• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/notreached.h"
6 #include "base/threading/platform_thread.h"
7 
8 #include <errno.h>
9 #include <pthread.h>
10 #include <sched.h>
11 #include <stddef.h>
12 #include <stdint.h>
13 #include <sys/time.h>
14 #include <sys/types.h>
15 #include <unistd.h>
16 
17 #include <memory>
18 #include <tuple>
19 
20 #include "base/allocator/partition_allocator/src/partition_alloc/partition_alloc_buildflags.h"
21 #include "base/compiler_specific.h"
22 #include "base/lazy_instance.h"
23 #include "base/logging.h"
24 #include "base/memory/raw_ptr.h"
25 #include "base/threading/platform_thread_internal_posix.h"
26 #include "base/threading/scoped_blocking_call.h"
27 #include "base/threading/thread_id_name_manager.h"
28 #include "base/threading/thread_restrictions.h"
29 #include "build/build_config.h"
30 
31 #if !BUILDFLAG(IS_APPLE) && !BUILDFLAG(IS_FUCHSIA) && !BUILDFLAG(IS_NACL)
32 #include "base/posix/can_lower_nice_to.h"
33 #endif
34 
35 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
36 #include <sys/syscall.h>
37 #include <atomic>
38 #endif
39 
40 #if BUILDFLAG(IS_FUCHSIA)
41 #include <zircon/process.h>
42 #else
43 #include <sys/resource.h>
44 #endif
45 
46 #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(USE_STARSCAN)
47 #include "base/allocator/partition_allocator/src/partition_alloc/starscan/pcscan.h"
48 #include "base/allocator/partition_allocator/src/partition_alloc/starscan/stack/stack.h"
49 #endif
50 
51 namespace base {
52 
53 void InitThreading();
54 void TerminateOnThread();
55 size_t GetDefaultThreadStackSize(const pthread_attr_t& attributes);
56 
57 namespace {
58 
59 struct ThreadParams {
60   ThreadParams() = default;
61 
62   raw_ptr<PlatformThread::Delegate> delegate = nullptr;
63   bool joinable = false;
64   ThreadType thread_type = ThreadType::kDefault;
65   MessagePumpType message_pump_type = MessagePumpType::DEFAULT;
66 };
67 
ThreadFunc(void * params)68 void* ThreadFunc(void* params) {
69   PlatformThread::Delegate* delegate = nullptr;
70 
71   {
72     std::unique_ptr<ThreadParams> thread_params(
73         static_cast<ThreadParams*>(params));
74 
75     delegate = thread_params->delegate;
76     if (!thread_params->joinable)
77       base::DisallowSingleton();
78 
79 #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(USE_STARSCAN)
80     partition_alloc::internal::PCScan::NotifyThreadCreated(
81         partition_alloc::internal::GetStackPointer());
82 #endif
83 
84 #if !BUILDFLAG(IS_NACL)
85 #if BUILDFLAG(IS_APPLE)
86     PlatformThread::SetCurrentThreadRealtimePeriodValue(
87         delegate->GetRealtimePeriod());
88 #endif
89 
90     // Threads on linux/android may inherit their priority from the thread
91     // where they were created. This explicitly sets the priority of all new
92     // threads.
93     PlatformThread::SetCurrentThreadType(thread_params->thread_type);
94 #endif  //  !BUILDFLAG(IS_NACL)
95   }
96 
97   ThreadIdNameManager::GetInstance()->RegisterThread(
98       PlatformThread::CurrentHandle().platform_handle(),
99       PlatformThread::CurrentId());
100 
101   delegate->ThreadMain();
102 
103   ThreadIdNameManager::GetInstance()->RemoveName(
104       PlatformThread::CurrentHandle().platform_handle(),
105       PlatformThread::CurrentId());
106 
107 #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(USE_STARSCAN)
108   partition_alloc::internal::PCScan::NotifyThreadDestroyed();
109 #endif
110 
111   base::TerminateOnThread();
112   return nullptr;
113 }
114 
CreateThread(size_t stack_size,bool joinable,PlatformThread::Delegate * delegate,PlatformThreadHandle * thread_handle,ThreadType thread_type,MessagePumpType message_pump_type)115 bool CreateThread(size_t stack_size,
116                   bool joinable,
117                   PlatformThread::Delegate* delegate,
118                   PlatformThreadHandle* thread_handle,
119                   ThreadType thread_type,
120                   MessagePumpType message_pump_type) {
121   DCHECK(thread_handle);
122   base::InitThreading();
123 
124   pthread_attr_t attributes;
125   pthread_attr_init(&attributes);
126 
127   // Pthreads are joinable by default, so only specify the detached
128   // attribute if the thread should be non-joinable.
129   if (!joinable)
130     pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);
131 
132   // Get a better default if available.
133   if (stack_size == 0)
134     stack_size = base::GetDefaultThreadStackSize(attributes);
135 
136   if (stack_size > 0)
137     pthread_attr_setstacksize(&attributes, stack_size);
138 
139   std::unique_ptr<ThreadParams> params(new ThreadParams);
140   params->delegate = delegate;
141   params->joinable = joinable;
142   params->thread_type = thread_type;
143   params->message_pump_type = message_pump_type;
144 
145   pthread_t handle;
146   int err = pthread_create(&handle, &attributes, ThreadFunc, params.get());
147   bool success = !err;
148   if (success) {
149     // ThreadParams should be deleted on the created thread after used.
150     std::ignore = params.release();
151   } else {
152     // Value of |handle| is undefined if pthread_create fails.
153     handle = 0;
154     errno = err;
155     PLOG(ERROR) << "pthread_create";
156   }
157   *thread_handle = PlatformThreadHandle(handle);
158 
159   pthread_attr_destroy(&attributes);
160 
161   return success;
162 }
163 
164 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
165 
166 // Store the thread ids in local storage since calling the SWI can be
167 // expensive and PlatformThread::CurrentId is used liberally.
168 thread_local pid_t g_thread_id = -1;
169 
170 // A boolean value that indicates that the value stored in |g_thread_id| on the
171 // main thread is invalid, because it hasn't been updated since the process
172 // forked.
173 //
174 // This used to work by setting |g_thread_id| to -1 in a pthread_atfork handler.
175 // However, when a multithreaded process forks, it is only allowed to call
176 // async-signal-safe functions until it calls an exec() syscall. However,
177 // accessing TLS may allocate (see crbug.com/1275748), which is not
178 // async-signal-safe and therefore causes deadlocks, corruption, and crashes.
179 //
180 // It's Atomic to placate TSAN.
181 std::atomic<bool> g_main_thread_tid_cache_valid = false;
182 
183 // Tracks whether the current thread is the main thread, and therefore whether
184 // |g_main_thread_tid_cache_valid| is relevant for the current thread. This is
185 // also updated by PlatformThread::CurrentId().
186 thread_local bool g_is_main_thread = true;
187 
188 class InitAtFork {
189  public:
InitAtFork()190   InitAtFork() {
191     pthread_atfork(nullptr, nullptr, internal::InvalidateTidCache);
192   }
193 };
194 
195 #endif  // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
196 
197 }  // namespace
198 
199 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
200 
201 namespace internal {
202 
InvalidateTidCache()203 void InvalidateTidCache() {
204   g_main_thread_tid_cache_valid.store(false, std::memory_order_relaxed);
205 }
206 
207 }  // namespace internal
208 
209 #endif  // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
210 
211 // static
CurrentId()212 PlatformThreadId PlatformThreadBase::CurrentId() {
213   // Pthreads doesn't have the concept of a thread ID, so we have to reach down
214   // into the kernel.
215 #if BUILDFLAG(IS_APPLE)
216   return pthread_mach_thread_np(pthread_self());
217 #elif BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
218   // Workaround false-positive MSAN use-of-uninitialized-value on
219   // thread_local storage for loaded libraries:
220   // https://github.com/google/sanitizers/issues/1265
221   MSAN_UNPOISON(&g_thread_id, sizeof(pid_t));
222   MSAN_UNPOISON(&g_is_main_thread, sizeof(bool));
223   static InitAtFork init_at_fork;
224   if (g_thread_id == -1 ||
225       (g_is_main_thread &&
226        !g_main_thread_tid_cache_valid.load(std::memory_order_relaxed))) {
227     // Update the cached tid.
228     g_thread_id = static_cast<pid_t>(syscall(__NR_gettid));
229     // If this is the main thread, we can mark the tid_cache as valid.
230     // Otherwise, stop the current thread from always entering this slow path.
231     if (g_thread_id == getpid()) {
232       g_main_thread_tid_cache_valid.store(true, std::memory_order_relaxed);
233     } else {
234       g_is_main_thread = false;
235     }
236   } else {
237 #if DCHECK_IS_ON()
238     if (g_thread_id != syscall(__NR_gettid)) {
239       RAW_LOG(
240           FATAL,
241           "Thread id stored in TLS is different from thread id returned by "
242           "the system. It is likely that the process was forked without going "
243           "through fork().");
244     }
245 #endif
246   }
247   return g_thread_id;
248 #elif BUILDFLAG(IS_ANDROID)
249   // Note: do not cache the return value inside a thread_local variable on
250   // Android (as above). The reasons are:
251   // - thread_local is slow on Android (goes through emutls)
252   // - gettid() is fast, since its return value is cached in pthread (in the
253   //   thread control block of pthread). See gettid.c in bionic.
254   return gettid();
255 #elif BUILDFLAG(IS_FUCHSIA)
256   return zx_thread_self();
257 #elif BUILDFLAG(IS_SOLARIS) || BUILDFLAG(IS_QNX)
258   return pthread_self();
259 #elif BUILDFLAG(IS_NACL) && defined(__GLIBC__)
260   return pthread_self();
261 #elif BUILDFLAG(IS_NACL) && !defined(__GLIBC__)
262   // Pointers are 32-bits in NaCl.
263   return reinterpret_cast<int32_t>(pthread_self());
264 #elif BUILDFLAG(IS_POSIX) && BUILDFLAG(IS_AIX)
265   return pthread_self();
266 #elif BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_AIX)
267   return reinterpret_cast<int64_t>(pthread_self());
268 #endif
269 }
270 
271 // static
CurrentRef()272 PlatformThreadRef PlatformThreadBase::CurrentRef() {
273   return PlatformThreadRef(pthread_self());
274 }
275 
276 // static
CurrentHandle()277 PlatformThreadHandle PlatformThreadBase::CurrentHandle() {
278   return PlatformThreadHandle(pthread_self());
279 }
280 
281 #if !BUILDFLAG(IS_APPLE)
282 // static
YieldCurrentThread()283 void PlatformThreadBase::YieldCurrentThread() {
284   sched_yield();
285 }
286 #endif  // !BUILDFLAG(IS_APPLE)
287 
288 // static
Sleep(TimeDelta duration)289 void PlatformThreadBase::Sleep(TimeDelta duration) {
290   struct timespec sleep_time, remaining;
291 
292   // Break the duration into seconds and nanoseconds.
293   // NOTE: TimeDelta's microseconds are int64s while timespec's
294   // nanoseconds are longs, so this unpacking must prevent overflow.
295   sleep_time.tv_sec = static_cast<time_t>(duration.InSeconds());
296   duration -= Seconds(sleep_time.tv_sec);
297   sleep_time.tv_nsec = static_cast<long>(duration.InMicroseconds() * 1000);
298 
299   while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR)
300     sleep_time = remaining;
301 }
302 
303 // static
GetName()304 const char* PlatformThreadBase::GetName() {
305   return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
306 }
307 
308 // static
CreateWithType(size_t stack_size,Delegate * delegate,PlatformThreadHandle * thread_handle,ThreadType thread_type,MessagePumpType pump_type_hint)309 bool PlatformThreadBase::CreateWithType(size_t stack_size,
310                                     Delegate* delegate,
311                                     PlatformThreadHandle* thread_handle,
312                                     ThreadType thread_type,
313                                     MessagePumpType pump_type_hint) {
314   return CreateThread(stack_size, true /* joinable thread */, delegate,
315                       thread_handle, thread_type, pump_type_hint);
316 }
317 
318 // static
CreateNonJoinable(size_t stack_size,Delegate * delegate)319 bool PlatformThreadBase::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
320   return CreateNonJoinableWithType(stack_size, delegate, ThreadType::kDefault);
321 }
322 
323 // static
CreateNonJoinableWithType(size_t stack_size,Delegate * delegate,ThreadType thread_type,MessagePumpType pump_type_hint)324 bool PlatformThreadBase::CreateNonJoinableWithType(size_t stack_size,
325                                                Delegate* delegate,
326                                                ThreadType thread_type,
327                                                MessagePumpType pump_type_hint) {
328   PlatformThreadHandle unused;
329 
330   bool result = CreateThread(stack_size, false /* non-joinable thread */,
331                              delegate, &unused, thread_type, pump_type_hint);
332   return result;
333 }
334 
335 // static
Join(PlatformThreadHandle thread_handle)336 void PlatformThreadBase::Join(PlatformThreadHandle thread_handle) {
337   // Joining another thread may block the current thread for a long time, since
338   // the thread referred to by |thread_handle| may still be running long-lived /
339   // blocking tasks.
340   base::internal::ScopedBlockingCallWithBaseSyncPrimitives scoped_blocking_call(
341       FROM_HERE, base::BlockingType::MAY_BLOCK);
342   CHECK_EQ(0, pthread_join(thread_handle.platform_handle(), nullptr));
343 }
344 
345 // static
Detach(PlatformThreadHandle thread_handle)346 void PlatformThreadBase::Detach(PlatformThreadHandle thread_handle) {
347   CHECK_EQ(0, pthread_detach(thread_handle.platform_handle()));
348 }
349 
350 // Mac and Fuchsia have their own SetCurrentThreadType() and
351 // GetCurrentThreadPriorityForTest() implementations.
352 #if !BUILDFLAG(IS_APPLE) && !BUILDFLAG(IS_FUCHSIA)
353 
354 // static
CanChangeThreadType(ThreadType from,ThreadType to)355 bool PlatformThreadBase::CanChangeThreadType(ThreadType from, ThreadType to) {
356 #if BUILDFLAG(IS_NACL)
357   return false;
358 #else
359   if (from >= to) {
360     // Decreasing thread priority on POSIX is always allowed.
361     return true;
362   }
363   if (to == ThreadType::kRealtimeAudio) {
364     return internal::CanSetThreadTypeToRealtimeAudio();
365   }
366 
367   return internal::CanLowerNiceTo(internal::ThreadTypeToNiceValue(to));
368 #endif  // BUILDFLAG(IS_NACL)
369 }
370 
371 namespace internal {
372 
SetCurrentThreadTypeImpl(ThreadType thread_type,MessagePumpType pump_type_hint)373 void SetCurrentThreadTypeImpl(ThreadType thread_type,
374                               MessagePumpType pump_type_hint) {
375 #if BUILDFLAG(IS_NACL)
376   NOTIMPLEMENTED();
377 #else
378   if (internal::SetCurrentThreadTypeForPlatform(thread_type, pump_type_hint))
379     return;
380 
381   // setpriority(2) should change the whole thread group's (i.e. process)
382   // priority. However, as stated in the bugs section of
383   // http://man7.org/linux/man-pages/man2/getpriority.2.html: "under the current
384   // Linux/NPTL implementation of POSIX threads, the nice value is a per-thread
385   // attribute". Also, 0 is prefered to the current thread id since it is
386   // equivalent but makes sandboxing easier (https://crbug.com/399473).
387   const int nice_setting = internal::ThreadTypeToNiceValue(thread_type);
388   if (setpriority(PRIO_PROCESS, 0, nice_setting)) {
389     DVPLOG(1) << "Failed to set nice value of thread ("
390               << PlatformThread::CurrentId() << ") to " << nice_setting;
391   }
392 #endif  // BUILDFLAG(IS_NACL)
393 }
394 
395 }  // namespace internal
396 
397 // static
GetCurrentThreadPriorityForTest()398 ThreadPriorityForTest PlatformThreadBase::GetCurrentThreadPriorityForTest() {
399 #if BUILDFLAG(IS_NACL)
400   NOTIMPLEMENTED();
401   return ThreadPriorityForTest::kNormal;
402 #else
403   // Mirrors SetCurrentThreadPriority()'s implementation.
404   auto platform_specific_priority =
405       internal::GetCurrentThreadPriorityForPlatformForTest();  // IN-TEST
406   if (platform_specific_priority)
407     return platform_specific_priority.value();
408 
409   int nice_value = internal::GetCurrentThreadNiceValue();
410 
411   return internal::NiceValueToThreadPriorityForTest(nice_value);  // IN-TEST
412 #endif  // !BUILDFLAG(IS_NACL)
413 }
414 
415 #endif  // !BUILDFLAG(IS_APPLE) && !BUILDFLAG(IS_FUCHSIA)
416 
417 // static
GetDefaultThreadStackSize()418 size_t PlatformThreadBase::GetDefaultThreadStackSize() {
419   pthread_attr_t attributes;
420   pthread_attr_init(&attributes);
421   return base::GetDefaultThreadStackSize(attributes);
422 }
423 
424 }  // namespace base
425