xref: /aosp_15_r20/external/cronet/base/threading/platform_thread_posix.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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/threading/platform_thread.h"
6 
7 #include <errno.h>
8 #include <pthread.h>
9 #include <sched.h>
10 #include <stddef.h>
11 #include <stdint.h>
12 #include <sys/time.h>
13 #include <sys/types.h>
14 #include <unistd.h>
15 
16 #include <memory>
17 #include <tuple>
18 
19 #include "base/compiler_specific.h"
20 #include "base/lazy_instance.h"
21 #include "base/logging.h"
22 #include "base/memory/raw_ptr.h"
23 #include "base/notimplemented.h"
24 #include "base/threading/platform_thread_internal_posix.h"
25 #include "base/threading/scoped_blocking_call.h"
26 #include "base/threading/thread_id_name_manager.h"
27 #include "base/threading/thread_restrictions.h"
28 #include "build/build_config.h"
29 #include "partition_alloc/partition_alloc_buildflags.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 <lib/zx/thread.h>
42 
43 #include "base/fuchsia/koid.h"
44 #else
45 #include <sys/resource.h>
46 #endif
47 
48 #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
49 #include "partition_alloc/stack/stack.h"
50 #endif
51 
52 namespace base {
53 
54 void InitThreading();
55 void TerminateOnThread();
56 size_t GetDefaultThreadStackSize(const pthread_attr_t& attributes);
57 
58 namespace {
59 
60 struct ThreadParams {
61   ThreadParams() = default;
62 
63   raw_ptr<PlatformThread::Delegate> delegate = nullptr;
64   bool joinable = false;
65   ThreadType thread_type = ThreadType::kDefault;
66   MessagePumpType message_pump_type = MessagePumpType::DEFAULT;
67 };
68 
ThreadFunc(void * params)69 void* ThreadFunc(void* params) {
70   PlatformThread::Delegate* delegate = nullptr;
71 
72   {
73     std::unique_ptr<ThreadParams> thread_params(
74         static_cast<ThreadParams*>(params));
75 
76     delegate = thread_params->delegate;
77     if (!thread_params->joinable)
78       base::DisallowSingleton();
79 
80 #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
81     partition_alloc::internal::StackTopRegistry::Get().NotifyThreadCreated();
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)
108   partition_alloc::internal::StackTopRegistry::Get().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   thread_local static zx_koid_t id =
257       GetKoid(*zx::thread::self()).value_or(ZX_KOID_INVALID);
258   return id;
259 #elif BUILDFLAG(IS_SOLARIS) || BUILDFLAG(IS_QNX)
260   return pthread_self();
261 #elif BUILDFLAG(IS_NACL) && defined(__GLIBC__)
262   return pthread_self();
263 #elif BUILDFLAG(IS_NACL) && !defined(__GLIBC__)
264   // Pointers are 32-bits in NaCl.
265   return reinterpret_cast<int32_t>(pthread_self());
266 #elif BUILDFLAG(IS_POSIX) && BUILDFLAG(IS_AIX)
267   return pthread_self();
268 #elif BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_AIX)
269   return reinterpret_cast<int64_t>(pthread_self());
270 #endif
271 }
272 
273 // static
CurrentRef()274 PlatformThreadRef PlatformThreadBase::CurrentRef() {
275   return PlatformThreadRef(pthread_self());
276 }
277 
278 // static
CurrentHandle()279 PlatformThreadHandle PlatformThreadBase::CurrentHandle() {
280   return PlatformThreadHandle(pthread_self());
281 }
282 
283 #if !BUILDFLAG(IS_APPLE)
284 // static
YieldCurrentThread()285 void PlatformThreadBase::YieldCurrentThread() {
286   sched_yield();
287 }
288 #endif  // !BUILDFLAG(IS_APPLE)
289 
290 // static
Sleep(TimeDelta duration)291 void PlatformThreadBase::Sleep(TimeDelta duration) {
292   struct timespec sleep_time, remaining;
293 
294   // Break the duration into seconds and nanoseconds.
295   // NOTE: TimeDelta's microseconds are int64s while timespec's
296   // nanoseconds are longs, so this unpacking must prevent overflow.
297   sleep_time.tv_sec = static_cast<time_t>(duration.InSeconds());
298   duration -= Seconds(sleep_time.tv_sec);
299   sleep_time.tv_nsec = static_cast<long>(duration.InMicroseconds() * 1000);
300 
301   while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR)
302     sleep_time = remaining;
303 }
304 
305 // static
GetName()306 const char* PlatformThreadBase::GetName() {
307   return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
308 }
309 
310 // static
CreateWithType(size_t stack_size,Delegate * delegate,PlatformThreadHandle * thread_handle,ThreadType thread_type,MessagePumpType pump_type_hint)311 bool PlatformThreadBase::CreateWithType(size_t stack_size,
312                                     Delegate* delegate,
313                                     PlatformThreadHandle* thread_handle,
314                                     ThreadType thread_type,
315                                     MessagePumpType pump_type_hint) {
316   return CreateThread(stack_size, true /* joinable thread */, delegate,
317                       thread_handle, thread_type, pump_type_hint);
318 }
319 
320 // static
CreateNonJoinable(size_t stack_size,Delegate * delegate)321 bool PlatformThreadBase::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
322   return CreateNonJoinableWithType(stack_size, delegate, ThreadType::kDefault);
323 }
324 
325 // static
CreateNonJoinableWithType(size_t stack_size,Delegate * delegate,ThreadType thread_type,MessagePumpType pump_type_hint)326 bool PlatformThreadBase::CreateNonJoinableWithType(size_t stack_size,
327                                                Delegate* delegate,
328                                                ThreadType thread_type,
329                                                MessagePumpType pump_type_hint) {
330   PlatformThreadHandle unused;
331 
332   bool result = CreateThread(stack_size, false /* non-joinable thread */,
333                              delegate, &unused, thread_type, pump_type_hint);
334   return result;
335 }
336 
337 // static
Join(PlatformThreadHandle thread_handle)338 void PlatformThreadBase::Join(PlatformThreadHandle thread_handle) {
339   // Joining another thread may block the current thread for a long time, since
340   // the thread referred to by |thread_handle| may still be running long-lived /
341   // blocking tasks.
342   base::internal::ScopedBlockingCallWithBaseSyncPrimitives scoped_blocking_call(
343       FROM_HERE, base::BlockingType::MAY_BLOCK);
344   CHECK_EQ(0, pthread_join(thread_handle.platform_handle(), nullptr));
345 }
346 
347 // static
Detach(PlatformThreadHandle thread_handle)348 void PlatformThreadBase::Detach(PlatformThreadHandle thread_handle) {
349   CHECK_EQ(0, pthread_detach(thread_handle.platform_handle()));
350 }
351 
352 // Mac and Fuchsia have their own SetCurrentThreadType() and
353 // GetCurrentThreadPriorityForTest() implementations.
354 #if !BUILDFLAG(IS_APPLE) && !BUILDFLAG(IS_FUCHSIA)
355 
356 // static
CanChangeThreadType(ThreadType from,ThreadType to)357 bool PlatformThreadBase::CanChangeThreadType(ThreadType from, ThreadType to) {
358 #if BUILDFLAG(IS_NACL)
359   return false;
360 #else
361   if (from >= to) {
362     // Decreasing thread priority on POSIX is always allowed.
363     return true;
364   }
365   if (to == ThreadType::kRealtimeAudio) {
366     return internal::CanSetThreadTypeToRealtimeAudio();
367   }
368 
369   return internal::CanLowerNiceTo(internal::ThreadTypeToNiceValue(to));
370 #endif  // BUILDFLAG(IS_NACL)
371 }
372 
373 namespace internal {
374 
SetCurrentThreadTypeImpl(ThreadType thread_type,MessagePumpType pump_type_hint)375 void SetCurrentThreadTypeImpl(ThreadType thread_type,
376                               MessagePumpType pump_type_hint) {
377 #if BUILDFLAG(IS_NACL)
378   NOTIMPLEMENTED();
379 #else
380   if (internal::SetCurrentThreadTypeForPlatform(thread_type, pump_type_hint))
381     return;
382 
383   // setpriority(2) should change the whole thread group's (i.e. process)
384   // priority. However, as stated in the bugs section of
385   // http://man7.org/linux/man-pages/man2/getpriority.2.html: "under the current
386   // Linux/NPTL implementation of POSIX threads, the nice value is a per-thread
387   // attribute". Also, 0 is prefered to the current thread id since it is
388   // equivalent but makes sandboxing easier (https://crbug.com/399473).
389   const int nice_setting = internal::ThreadTypeToNiceValue(thread_type);
390   if (setpriority(PRIO_PROCESS, 0, nice_setting)) {
391     DVPLOG(1) << "Failed to set nice value of thread ("
392               << PlatformThread::CurrentId() << ") to " << nice_setting;
393   }
394 #endif  // BUILDFLAG(IS_NACL)
395 }
396 
397 }  // namespace internal
398 
399 // static
GetCurrentThreadPriorityForTest()400 ThreadPriorityForTest PlatformThreadBase::GetCurrentThreadPriorityForTest() {
401 #if BUILDFLAG(IS_NACL)
402   NOTIMPLEMENTED();
403   return ThreadPriorityForTest::kNormal;
404 #else
405   // Mirrors SetCurrentThreadPriority()'s implementation.
406   auto platform_specific_priority =
407       internal::GetCurrentThreadPriorityForPlatformForTest();  // IN-TEST
408   if (platform_specific_priority)
409     return platform_specific_priority.value();
410 
411   int nice_value = internal::GetCurrentThreadNiceValue();
412 
413   return internal::NiceValueToThreadPriorityForTest(nice_value);  // IN-TEST
414 #endif  // !BUILDFLAG(IS_NACL)
415 }
416 
417 #endif  // !BUILDFLAG(IS_APPLE) && !BUILDFLAG(IS_FUCHSIA)
418 
419 // static
GetDefaultThreadStackSize()420 size_t PlatformThreadBase::GetDefaultThreadStackSize() {
421   pthread_attr_t attributes;
422   pthread_attr_init(&attributes);
423   return base::GetDefaultThreadStackSize(attributes);
424 }
425 
426 }  // namespace base
427