blob: 6743b440207cf93f6f7d91f18b3c2f0e46819a43 [file] [log] [blame]
Kaido Kert25902c62024-06-17 17:10:28 -07001// Copyright 2012 The Chromium Authors
Andrew Top0d1858f2019-05-15 22:01:47 -07002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Kaido Kert25902c62024-06-17 17:10:28 -07005#include "base/notreached.h"
Andrew Top0d1858f2019-05-15 22:01:47 -07006#include "base/threading/platform_thread.h"
7
8#include <errno.h>
9#include <pthread.h>
10#include <sched.h>
Kaido Kert25902c62024-06-17 17:10:28 -070011#include <stddef.h>
12#include <stdint.h>
Andrew Top0d1858f2019-05-15 22:01:47 -070013#include <sys/time.h>
14#include <sys/types.h>
15#include <unistd.h>
16
17#include <memory>
Kaido Kert25902c62024-06-17 17:10:28 -070018#include <tuple>
Andrew Top0d1858f2019-05-15 22:01:47 -070019
Kaido Kert25902c62024-06-17 17:10:28 -070020#include "base/allocator/partition_allocator/partition_alloc_buildflags.h"
21#include "base/compiler_specific.h"
Andrew Top0d1858f2019-05-15 22:01:47 -070022#include "base/lazy_instance.h"
23#include "base/logging.h"
Kaido Kert25902c62024-06-17 17:10:28 -070024#include "base/memory/raw_ptr.h"
Andrew Top0d1858f2019-05-15 22:01:47 -070025#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"
Kaido Kert25902c62024-06-17 17:10:28 -070028#include "base/threading/thread_restrictions.h"
Andrew Top0d1858f2019-05-15 22:01:47 -070029#include "build/build_config.h"
30
Kaido Kert25902c62024-06-17 17:10:28 -070031#if !BUILDFLAG(IS_APPLE) && !BUILDFLAG(IS_FUCHSIA) && !BUILDFLAG(IS_NACL)
Andrew Top0d1858f2019-05-15 22:01:47 -070032#include "base/posix/can_lower_nice_to.h"
33#endif
34
Kaido Kert25902c62024-06-17 17:10:28 -070035#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
Andrew Top0d1858f2019-05-15 22:01:47 -070036#include <sys/syscall.h>
Kaido Kert25902c62024-06-17 17:10:28 -070037#include <atomic>
Andrew Top0d1858f2019-05-15 22:01:47 -070038#endif
39
Kaido Kert25902c62024-06-17 17:10:28 -070040#if BUILDFLAG(IS_FUCHSIA)
Andrew Top0d1858f2019-05-15 22:01:47 -070041#include <zircon/process.h>
42#else
43#include <sys/resource.h>
44#endif
45
Kaido Kert25902c62024-06-17 17:10:28 -070046#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(USE_STARSCAN)
47#include "base/allocator/partition_allocator/starscan/pcscan.h"
48#include "base/allocator/partition_allocator/starscan/stack/stack.h"
49#endif
50
Andrew Top0d1858f2019-05-15 22:01:47 -070051namespace base {
52
53void InitThreading();
54void TerminateOnThread();
55size_t GetDefaultThreadStackSize(const pthread_attr_t& attributes);
56
57namespace {
58
59struct ThreadParams {
Kaido Kert25902c62024-06-17 17:10:28 -070060 ThreadParams() = default;
Andrew Top0d1858f2019-05-15 22:01:47 -070061
Kaido Kert25902c62024-06-17 17:10:28 -070062 raw_ptr<PlatformThread::Delegate> delegate = nullptr;
63 bool joinable = false;
64 ThreadType thread_type = ThreadType::kDefault;
65 MessagePumpType message_pump_type = MessagePumpType::DEFAULT;
Andrew Top0d1858f2019-05-15 22:01:47 -070066};
67
68void* 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)
Kaido Kert25902c62024-06-17 17:10:28 -070077 base::DisallowSingleton();
Andrew Top0d1858f2019-05-15 22:01:47 -070078
Kaido Kert25902c62024-06-17 17:10:28 -070079#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
Andrew Top0d1858f2019-05-15 22:01:47 -070090 // 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.
Kaido Kert25902c62024-06-17 17:10:28 -070093 PlatformThread::SetCurrentThreadType(thread_params->thread_type);
94#endif // !BUILDFLAG(IS_NACL)
Andrew Top0d1858f2019-05-15 22:01:47 -070095 }
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
Kaido Kert25902c62024-06-17 17:10:28 -0700107#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(USE_STARSCAN)
108 partition_alloc::internal::PCScan::NotifyThreadDestroyed();
109#endif
110
Andrew Top0d1858f2019-05-15 22:01:47 -0700111 base::TerminateOnThread();
112 return nullptr;
113}
114
115bool CreateThread(size_t stack_size,
116 bool joinable,
117 PlatformThread::Delegate* delegate,
118 PlatformThreadHandle* thread_handle,
Kaido Kert25902c62024-06-17 17:10:28 -0700119 ThreadType thread_type,
120 MessagePumpType message_pump_type) {
Andrew Top0d1858f2019-05-15 22:01:47 -0700121 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;
Kaido Kert25902c62024-06-17 17:10:28 -0700142 params->thread_type = thread_type;
143 params->message_pump_type = message_pump_type;
Andrew Top0d1858f2019-05-15 22:01:47 -0700144
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.
Kaido Kert25902c62024-06-17 17:10:28 -0700150 std::ignore = params.release();
Andrew Top0d1858f2019-05-15 22:01:47 -0700151 } 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
Kaido Kert25902c62024-06-17 17:10:28 -0700164#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.
168thread_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.
181std::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().
186thread_local bool g_is_main_thread = true;
187
188class InitAtFork {
189 public:
190 InitAtFork() {
191 pthread_atfork(nullptr, nullptr, internal::InvalidateTidCache);
192 }
193};
194
195#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
196
Andrew Top0d1858f2019-05-15 22:01:47 -0700197} // namespace
198
Kaido Kert25902c62024-06-17 17:10:28 -0700199#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
200
201namespace internal {
202
203void 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
Andrew Top0d1858f2019-05-15 22:01:47 -0700211// static
212PlatformThreadId PlatformThread::CurrentId() {
213 // Pthreads doesn't have the concept of a thread ID, so we have to reach down
214 // into the kernel.
Kaido Kert25902c62024-06-17 17:10:28 -0700215#if BUILDFLAG(IS_APPLE)
Andrew Top0d1858f2019-05-15 22:01:47 -0700216 return pthread_mach_thread_np(pthread_self());
Kaido Kert25902c62024-06-17 17:10:28 -0700217#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.
Andrew Top0d1858f2019-05-15 22:01:47 -0700254 return gettid();
Kaido Kert25902c62024-06-17 17:10:28 -0700255#elif BUILDFLAG(IS_FUCHSIA)
Andrew Top0d1858f2019-05-15 22:01:47 -0700256 return zx_thread_self();
Kaido Kert25902c62024-06-17 17:10:28 -0700257#elif BUILDFLAG(IS_SOLARIS) || BUILDFLAG(IS_QNX)
Andrew Top0d1858f2019-05-15 22:01:47 -0700258 return pthread_self();
Kaido Kert25902c62024-06-17 17:10:28 -0700259#elif BUILDFLAG(IS_NACL) && defined(__GLIBC__)
Andrew Top0d1858f2019-05-15 22:01:47 -0700260 return pthread_self();
Kaido Kert25902c62024-06-17 17:10:28 -0700261#elif BUILDFLAG(IS_NACL) && !defined(__GLIBC__)
Andrew Top0d1858f2019-05-15 22:01:47 -0700262 // Pointers are 32-bits in NaCl.
263 return reinterpret_cast<int32_t>(pthread_self());
Kaido Kert25902c62024-06-17 17:10:28 -0700264#elif BUILDFLAG(IS_POSIX) && BUILDFLAG(IS_AIX)
Andrew Top0d1858f2019-05-15 22:01:47 -0700265 return pthread_self();
Kaido Kert25902c62024-06-17 17:10:28 -0700266#elif BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_AIX)
Andrew Top0d1858f2019-05-15 22:01:47 -0700267 return reinterpret_cast<int64_t>(pthread_self());
268#endif
269}
270
271// static
272PlatformThreadRef PlatformThread::CurrentRef() {
273 return PlatformThreadRef(pthread_self());
274}
275
276// static
277PlatformThreadHandle PlatformThread::CurrentHandle() {
278 return PlatformThreadHandle(pthread_self());
279}
280
Kaido Kert25902c62024-06-17 17:10:28 -0700281#if !BUILDFLAG(IS_APPLE)
Andrew Top0d1858f2019-05-15 22:01:47 -0700282// static
283void PlatformThread::YieldCurrentThread() {
284 sched_yield();
285}
Kaido Kert25902c62024-06-17 17:10:28 -0700286#endif // !BUILDFLAG(IS_APPLE)
Andrew Top0d1858f2019-05-15 22:01:47 -0700287
288// static
289void PlatformThread::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.
Kaido Kert25902c62024-06-17 17:10:28 -0700295 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);
Andrew Top0d1858f2019-05-15 22:01:47 -0700298
299 while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR)
300 sleep_time = remaining;
301}
302
303// static
304const char* PlatformThread::GetName() {
305 return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
306}
307
308// static
Kaido Kert25902c62024-06-17 17:10:28 -0700309bool PlatformThread::CreateWithType(size_t stack_size,
310 Delegate* delegate,
311 PlatformThreadHandle* thread_handle,
312 ThreadType thread_type,
313 MessagePumpType pump_type_hint) {
Andrew Top0d1858f2019-05-15 22:01:47 -0700314 return CreateThread(stack_size, true /* joinable thread */, delegate,
Kaido Kert25902c62024-06-17 17:10:28 -0700315 thread_handle, thread_type, pump_type_hint);
Andrew Top0d1858f2019-05-15 22:01:47 -0700316}
317
318// static
319bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
Kaido Kert25902c62024-06-17 17:10:28 -0700320 return CreateNonJoinableWithType(stack_size, delegate, ThreadType::kDefault);
Andrew Top0d1858f2019-05-15 22:01:47 -0700321}
322
323// static
Kaido Kert25902c62024-06-17 17:10:28 -0700324bool PlatformThread::CreateNonJoinableWithType(size_t stack_size,
325 Delegate* delegate,
326 ThreadType thread_type,
327 MessagePumpType pump_type_hint) {
Andrew Top0d1858f2019-05-15 22:01:47 -0700328 PlatformThreadHandle unused;
329
330 bool result = CreateThread(stack_size, false /* non-joinable thread */,
Kaido Kert25902c62024-06-17 17:10:28 -0700331 delegate, &unused, thread_type, pump_type_hint);
Andrew Top0d1858f2019-05-15 22:01:47 -0700332 return result;
333}
334
335// static
336void PlatformThread::Join(PlatformThreadHandle thread_handle) {
Andrew Top0d1858f2019-05-15 22:01:47 -0700337 // 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.
Kaido Kert25902c62024-06-17 17:10:28 -0700340 base::internal::ScopedBlockingCallWithBaseSyncPrimitives scoped_blocking_call(
341 FROM_HERE, base::BlockingType::MAY_BLOCK);
Andrew Top0d1858f2019-05-15 22:01:47 -0700342 CHECK_EQ(0, pthread_join(thread_handle.platform_handle(), nullptr));
343}
344
345// static
346void PlatformThread::Detach(PlatformThreadHandle thread_handle) {
347 CHECK_EQ(0, pthread_detach(thread_handle.platform_handle()));
348}
349
Kaido Kert25902c62024-06-17 17:10:28 -0700350// Mac and Fuchsia have their own SetCurrentThreadType() and
351// GetCurrentThreadPriorityForTest() implementations.
352#if !BUILDFLAG(IS_APPLE) && !BUILDFLAG(IS_FUCHSIA)
Andrew Top0d1858f2019-05-15 22:01:47 -0700353
354// static
Kaido Kert25902c62024-06-17 17:10:28 -0700355bool PlatformThread::CanChangeThreadType(ThreadType from, ThreadType to) {
356#if BUILDFLAG(IS_NACL)
Andrew Top0d1858f2019-05-15 22:01:47 -0700357 return false;
358#else
Kaido Kert25902c62024-06-17 17:10:28 -0700359 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)
Andrew Top0d1858f2019-05-15 22:01:47 -0700369}
370
Kaido Kert25902c62024-06-17 17:10:28 -0700371namespace internal {
372
373void SetCurrentThreadTypeImpl(ThreadType thread_type,
374 MessagePumpType pump_type_hint) {
375#if BUILDFLAG(IS_NACL)
Andrew Top0d1858f2019-05-15 22:01:47 -0700376 NOTIMPLEMENTED();
377#else
Kaido Kert25902c62024-06-17 17:10:28 -0700378 if (internal::SetCurrentThreadTypeForPlatform(thread_type, pump_type_hint))
Andrew Top0d1858f2019-05-15 22:01:47 -0700379 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).
Kaido Kert25902c62024-06-17 17:10:28 -0700387 const int nice_setting = internal::ThreadTypeToNiceValue(thread_type);
Andrew Top0d1858f2019-05-15 22:01:47 -0700388 if (setpriority(PRIO_PROCESS, 0, nice_setting)) {
389 DVPLOG(1) << "Failed to set nice value of thread ("
390 << PlatformThread::CurrentId() << ") to " << nice_setting;
391 }
Kaido Kert25902c62024-06-17 17:10:28 -0700392#endif // BUILDFLAG(IS_NACL)
Andrew Top0d1858f2019-05-15 22:01:47 -0700393}
394
Kaido Kert25902c62024-06-17 17:10:28 -0700395} // namespace internal
396
Andrew Top0d1858f2019-05-15 22:01:47 -0700397// static
Kaido Kert25902c62024-06-17 17:10:28 -0700398ThreadPriorityForTest PlatformThread::GetCurrentThreadPriorityForTest() {
399#if BUILDFLAG(IS_NACL)
Andrew Top0d1858f2019-05-15 22:01:47 -0700400 NOTIMPLEMENTED();
Kaido Kert25902c62024-06-17 17:10:28 -0700401 return ThreadPriorityForTest::kNormal;
Andrew Top0d1858f2019-05-15 22:01:47 -0700402#else
403 // Mirrors SetCurrentThreadPriority()'s implementation.
Kaido Kert25902c62024-06-17 17:10:28 -0700404 auto platform_specific_priority =
405 internal::GetCurrentThreadPriorityForPlatformForTest(); // IN-TEST
406 if (platform_specific_priority)
407 return platform_specific_priority.value();
Andrew Top0d1858f2019-05-15 22:01:47 -0700408
Kaido Kert25902c62024-06-17 17:10:28 -0700409 int nice_value = internal::GetCurrentThreadNiceValue();
Andrew Top0d1858f2019-05-15 22:01:47 -0700410
Kaido Kert25902c62024-06-17 17:10:28 -0700411 return internal::NiceValueToThreadPriorityForTest(nice_value); // IN-TEST
412#endif // !BUILDFLAG(IS_NACL)
Andrew Top0d1858f2019-05-15 22:01:47 -0700413}
414
Kaido Kert25902c62024-06-17 17:10:28 -0700415#endif // !BUILDFLAG(IS_APPLE) && !BUILDFLAG(IS_FUCHSIA)
416
417// static
418size_t PlatformThread::GetDefaultThreadStackSize() {
419 pthread_attr_t attributes;
420 pthread_attr_init(&attributes);
421 return base::GetDefaultThreadStackSize(attributes);
422}
Andrew Top0d1858f2019-05-15 22:01:47 -0700423
424} // namespace base