platform_thread_posix.cc 13 KB

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