1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "sandbox/linux/services/thread_helpers.h"
15 #include "base/basictypes.h"
16 #include "base/logging.h"
17 #include "base/posix/eintr_wrapper.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/threading/platform_thread.h"
20 #include "base/threading/thread.h"
24 bool ThreadHelpers::IsSingleThreaded(int proc_self_task) {
25 CHECK_LE(0, proc_self_task);
26 struct stat task_stat;
27 int fstat_ret = fstat(proc_self_task, &task_stat);
28 PCHECK(0 == fstat_ret);
30 // At least "..", "." and the current thread should be present.
31 CHECK_LE(3UL, task_stat.st_nlink);
32 // Counting threads via /proc/self/task could be racy. For the purpose of
33 // determining if the current proces is monothreaded it works: if at any
34 // time it becomes monothreaded, it'll stay so.
35 return task_stat.st_nlink == 3;
38 bool ThreadHelpers::StopThreadAndWatchProcFS(int proc_self_task,
39 base::Thread* thread) {
40 DCHECK_LE(0, proc_self_task);
42 const base::PlatformThreadId thread_id = thread->thread_id();
43 const std::string thread_id_dir_str = base::IntToString(thread_id) + "/";
45 // The kernel is at liberty to wake the thread id futex before updating
46 // /proc. Following Stop(), the thread is joined, but entries in /proc may
47 // not have been updated.
50 unsigned int iterations = 0;
51 bool thread_present_in_procfs = true;
52 // Poll /proc with an exponential back-off, sleeping 2^iterations nanoseconds
54 // Note: the clock may not allow for nanosecond granularity, in this case the
55 // first iterations would sleep a tiny bit more instead, which would not
56 // change the calculations significantly.
57 while (thread_present_in_procfs) {
58 struct stat task_stat;
60 fstatat(proc_self_task, thread_id_dir_str.c_str(), &task_stat, 0);
62 PCHECK(ENOENT == errno);
63 // The thread disappeared from /proc, we're done.
64 thread_present_in_procfs = false;
67 // Increase the waiting time exponentially.
68 struct timespec ts = {0, 1L << iterations /* nanoseconds */};
69 PCHECK(0 == HANDLE_EINTR(nanosleep(&ts, &ts)));
72 // Crash after 30 iterations, which means having spent roughly 2s in
73 // nanosleep(2) cumulatively.
74 CHECK_GT(30U, iterations);
75 // In practice, this never goes through more than a couple iterations. In
76 // debug mode, crash after 64ms (+ eventually 25 times the granularity of
77 // the clock) in nanosleep(2).
78 DCHECK_GT(25U, iterations);
84 } // namespace sandbox