tsan_platform_mac.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. //===-- tsan_platform_mac.cpp ---------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file is a part of ThreadSanitizer (TSan), a race detector.
  10. //
  11. // Mac-specific code.
  12. //===----------------------------------------------------------------------===//
  13. #include "sanitizer_common/sanitizer_platform.h"
  14. #if SANITIZER_MAC
  15. #include "sanitizer_common/sanitizer_atomic.h"
  16. #include "sanitizer_common/sanitizer_common.h"
  17. #include "sanitizer_common/sanitizer_libc.h"
  18. #include "sanitizer_common/sanitizer_posix.h"
  19. #include "sanitizer_common/sanitizer_procmaps.h"
  20. #include "sanitizer_common/sanitizer_ptrauth.h"
  21. #include "sanitizer_common/sanitizer_stackdepot.h"
  22. #include "tsan_platform.h"
  23. #include "tsan_rtl.h"
  24. #include "tsan_flags.h"
  25. #include <limits.h>
  26. #include <mach/mach.h>
  27. #include <pthread.h>
  28. #include <signal.h>
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <string.h>
  32. #include <stdarg.h>
  33. #include <sys/mman.h>
  34. #include <sys/syscall.h>
  35. #include <sys/time.h>
  36. #include <sys/types.h>
  37. #include <sys/resource.h>
  38. #include <sys/stat.h>
  39. #include <unistd.h>
  40. #include <errno.h>
  41. #include <sched.h>
  42. namespace __tsan {
  43. #if !SANITIZER_GO
  44. static char main_thread_state[sizeof(ThreadState)] ALIGNED(
  45. SANITIZER_CACHE_LINE_SIZE);
  46. static ThreadState *dead_thread_state;
  47. static pthread_key_t thread_state_key;
  48. // We rely on the following documented, but Darwin-specific behavior to keep the
  49. // reference to the ThreadState object alive in TLS:
  50. // pthread_key_create man page:
  51. // If, after all the destructors have been called for all non-NULL values with
  52. // associated destructors, there are still some non-NULL values with
  53. // associated destructors, then the process is repeated. If, after at least
  54. // [PTHREAD_DESTRUCTOR_ITERATIONS] iterations of destructor calls for
  55. // outstanding non-NULL values, there are still some non-NULL values with
  56. // associated destructors, the implementation stops calling destructors.
  57. static_assert(PTHREAD_DESTRUCTOR_ITERATIONS == 4, "Small number of iterations");
  58. static void ThreadStateDestructor(void *thr) {
  59. int res = pthread_setspecific(thread_state_key, thr);
  60. CHECK_EQ(res, 0);
  61. }
  62. static void InitializeThreadStateStorage() {
  63. int res;
  64. CHECK_EQ(thread_state_key, 0);
  65. res = pthread_key_create(&thread_state_key, ThreadStateDestructor);
  66. CHECK_EQ(res, 0);
  67. res = pthread_setspecific(thread_state_key, main_thread_state);
  68. CHECK_EQ(res, 0);
  69. auto dts = (ThreadState *)MmapOrDie(sizeof(ThreadState), "ThreadState");
  70. dts->fast_state.SetIgnoreBit();
  71. dts->ignore_interceptors = 1;
  72. dts->is_dead = true;
  73. const_cast<Tid &>(dts->tid) = kInvalidTid;
  74. res = internal_mprotect(dts, sizeof(ThreadState), PROT_READ); // immutable
  75. CHECK_EQ(res, 0);
  76. dead_thread_state = dts;
  77. }
  78. ThreadState *cur_thread() {
  79. // Some interceptors get called before libpthread has been initialized and in
  80. // these cases we must avoid calling any pthread APIs.
  81. if (UNLIKELY(!thread_state_key)) {
  82. return (ThreadState *)main_thread_state;
  83. }
  84. // We only reach this line after InitializeThreadStateStorage() ran, i.e,
  85. // after TSan (and therefore libpthread) have been initialized.
  86. ThreadState *thr = (ThreadState *)pthread_getspecific(thread_state_key);
  87. if (UNLIKELY(!thr)) {
  88. thr = (ThreadState *)MmapOrDie(sizeof(ThreadState), "ThreadState");
  89. int res = pthread_setspecific(thread_state_key, thr);
  90. CHECK_EQ(res, 0);
  91. }
  92. return thr;
  93. }
  94. void set_cur_thread(ThreadState *thr) {
  95. int res = pthread_setspecific(thread_state_key, thr);
  96. CHECK_EQ(res, 0);
  97. }
  98. void cur_thread_finalize() {
  99. ThreadState *thr = (ThreadState *)pthread_getspecific(thread_state_key);
  100. CHECK(thr);
  101. if (thr == (ThreadState *)main_thread_state) {
  102. // Calling dispatch_main() or xpc_main() actually invokes pthread_exit to
  103. // exit the main thread. Let's keep the main thread's ThreadState.
  104. return;
  105. }
  106. // Intercepted functions can still get called after cur_thread_finalize()
  107. // (called from DestroyThreadState()), so put a fake thread state for "dead"
  108. // threads. An alternative solution would be to release the ThreadState
  109. // object from THREAD_DESTROY (which is delivered later and on the parent
  110. // thread) instead of THREAD_TERMINATE.
  111. int res = pthread_setspecific(thread_state_key, dead_thread_state);
  112. CHECK_EQ(res, 0);
  113. UnmapOrDie(thr, sizeof(ThreadState));
  114. }
  115. #endif
  116. static void RegionMemUsage(uptr start, uptr end, uptr *res, uptr *dirty) {
  117. vm_address_t address = start;
  118. vm_address_t end_address = end;
  119. uptr resident_pages = 0;
  120. uptr dirty_pages = 0;
  121. while (address < end_address) {
  122. vm_size_t vm_region_size;
  123. mach_msg_type_number_t count = VM_REGION_EXTENDED_INFO_COUNT;
  124. vm_region_extended_info_data_t vm_region_info;
  125. mach_port_t object_name;
  126. kern_return_t ret = vm_region_64(
  127. mach_task_self(), &address, &vm_region_size, VM_REGION_EXTENDED_INFO,
  128. (vm_region_info_t)&vm_region_info, &count, &object_name);
  129. if (ret != KERN_SUCCESS) break;
  130. resident_pages += vm_region_info.pages_resident;
  131. dirty_pages += vm_region_info.pages_dirtied;
  132. address += vm_region_size;
  133. }
  134. *res = resident_pages * GetPageSizeCached();
  135. *dirty = dirty_pages * GetPageSizeCached();
  136. }
  137. void WriteMemoryProfile(char *buf, uptr buf_size, u64 uptime_ns) {
  138. uptr shadow_res, shadow_dirty;
  139. uptr meta_res, meta_dirty;
  140. RegionMemUsage(ShadowBeg(), ShadowEnd(), &shadow_res, &shadow_dirty);
  141. RegionMemUsage(MetaShadowBeg(), MetaShadowEnd(), &meta_res, &meta_dirty);
  142. # if !SANITIZER_GO
  143. uptr low_res, low_dirty;
  144. uptr high_res, high_dirty;
  145. uptr heap_res, heap_dirty;
  146. RegionMemUsage(LoAppMemBeg(), LoAppMemEnd(), &low_res, &low_dirty);
  147. RegionMemUsage(HiAppMemBeg(), HiAppMemEnd(), &high_res, &high_dirty);
  148. RegionMemUsage(HeapMemBeg(), HeapMemEnd(), &heap_res, &heap_dirty);
  149. #else // !SANITIZER_GO
  150. uptr app_res, app_dirty;
  151. RegionMemUsage(LoAppMemBeg(), LoAppMemEnd(), &app_res, &app_dirty);
  152. #endif
  153. StackDepotStats stacks = StackDepotGetStats();
  154. uptr nthread, nlive;
  155. ctx->thread_registry.GetNumberOfThreads(&nthread, &nlive);
  156. internal_snprintf(
  157. buf, buf_size,
  158. "shadow (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
  159. "meta (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
  160. # if !SANITIZER_GO
  161. "low app (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
  162. "high app (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
  163. "heap (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
  164. # else // !SANITIZER_GO
  165. "app (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
  166. # endif
  167. "stacks: %zd unique IDs, %zd kB allocated\n"
  168. "threads: %zd total, %zd live\n"
  169. "------------------------------\n",
  170. ShadowBeg(), ShadowEnd(), shadow_res / 1024, shadow_dirty / 1024,
  171. MetaShadowBeg(), MetaShadowEnd(), meta_res / 1024, meta_dirty / 1024,
  172. # if !SANITIZER_GO
  173. LoAppMemBeg(), LoAppMemEnd(), low_res / 1024, low_dirty / 1024,
  174. HiAppMemBeg(), HiAppMemEnd(), high_res / 1024, high_dirty / 1024,
  175. HeapMemBeg(), HeapMemEnd(), heap_res / 1024, heap_dirty / 1024,
  176. # else // !SANITIZER_GO
  177. LoAppMemBeg(), LoAppMemEnd(), app_res / 1024, app_dirty / 1024,
  178. # endif
  179. stacks.n_uniq_ids, stacks.allocated / 1024, nthread, nlive);
  180. }
  181. # if !SANITIZER_GO
  182. void InitializeShadowMemoryPlatform() { }
  183. // On OS X, GCD worker threads are created without a call to pthread_create. We
  184. // need to properly register these threads with ThreadCreate and ThreadStart.
  185. // These threads don't have a parent thread, as they are created "spuriously".
  186. // We're using a libpthread API that notifies us about a newly created thread.
  187. // The `thread == pthread_self()` check indicates this is actually a worker
  188. // thread. If it's just a regular thread, this hook is called on the parent
  189. // thread.
  190. typedef void (*pthread_introspection_hook_t)(unsigned int event,
  191. pthread_t thread, void *addr,
  192. size_t size);
  193. extern "C" pthread_introspection_hook_t pthread_introspection_hook_install(
  194. pthread_introspection_hook_t hook);
  195. static const uptr PTHREAD_INTROSPECTION_THREAD_CREATE = 1;
  196. static const uptr PTHREAD_INTROSPECTION_THREAD_TERMINATE = 3;
  197. static pthread_introspection_hook_t prev_pthread_introspection_hook;
  198. static void my_pthread_introspection_hook(unsigned int event, pthread_t thread,
  199. void *addr, size_t size) {
  200. if (event == PTHREAD_INTROSPECTION_THREAD_CREATE) {
  201. if (thread == pthread_self()) {
  202. // The current thread is a newly created GCD worker thread.
  203. ThreadState *thr = cur_thread();
  204. Processor *proc = ProcCreate();
  205. ProcWire(proc, thr);
  206. ThreadState *parent_thread_state = nullptr; // No parent.
  207. Tid tid = ThreadCreate(parent_thread_state, 0, (uptr)thread, true);
  208. CHECK_NE(tid, kMainTid);
  209. ThreadStart(thr, tid, GetTid(), ThreadType::Worker);
  210. }
  211. } else if (event == PTHREAD_INTROSPECTION_THREAD_TERMINATE) {
  212. CHECK_EQ(thread, pthread_self());
  213. ThreadState *thr = cur_thread();
  214. if (thr->tctx) {
  215. DestroyThreadState();
  216. }
  217. }
  218. if (prev_pthread_introspection_hook != nullptr)
  219. prev_pthread_introspection_hook(event, thread, addr, size);
  220. }
  221. #endif
  222. void InitializePlatformEarly() {
  223. # if !SANITIZER_GO && SANITIZER_IOS
  224. uptr max_vm = GetMaxUserVirtualAddress() + 1;
  225. if (max_vm != HiAppMemEnd()) {
  226. Printf("ThreadSanitizer: unsupported vm address limit %p, expected %p.\n",
  227. (void *)max_vm, (void *)HiAppMemEnd());
  228. Die();
  229. }
  230. #endif
  231. }
  232. static uptr longjmp_xor_key = 0;
  233. void InitializePlatform() {
  234. DisableCoreDumperIfNecessary();
  235. #if !SANITIZER_GO
  236. CheckAndProtect();
  237. InitializeThreadStateStorage();
  238. prev_pthread_introspection_hook =
  239. pthread_introspection_hook_install(&my_pthread_introspection_hook);
  240. #endif
  241. if (GetMacosAlignedVersion() >= MacosVersion(10, 14)) {
  242. // Libsystem currently uses a process-global key; this might change.
  243. const unsigned kTLSLongjmpXorKeySlot = 0x7;
  244. longjmp_xor_key = (uptr)pthread_getspecific(kTLSLongjmpXorKeySlot);
  245. }
  246. }
  247. #ifdef __aarch64__
  248. # define LONG_JMP_SP_ENV_SLOT \
  249. ((GetMacosAlignedVersion() >= MacosVersion(10, 14)) ? 12 : 13)
  250. #else
  251. # define LONG_JMP_SP_ENV_SLOT 2
  252. #endif
  253. uptr ExtractLongJmpSp(uptr *env) {
  254. uptr mangled_sp = env[LONG_JMP_SP_ENV_SLOT];
  255. uptr sp = mangled_sp ^ longjmp_xor_key;
  256. sp = (uptr)ptrauth_auth_data((void *)sp, ptrauth_key_asdb,
  257. ptrauth_string_discriminator("sp"));
  258. return sp;
  259. }
  260. #if !SANITIZER_GO
  261. extern "C" void __tsan_tls_initialization() {}
  262. void ImitateTlsWrite(ThreadState *thr, uptr tls_addr, uptr tls_size) {
  263. const uptr pc = StackTrace::GetNextInstructionPc(
  264. reinterpret_cast<uptr>(__tsan_tls_initialization));
  265. // Unlike Linux, we only store a pointer to the ThreadState object in TLS;
  266. // just mark the entire range as written to.
  267. MemoryRangeImitateWrite(thr, pc, tls_addr, tls_size);
  268. }
  269. #endif
  270. #if !SANITIZER_GO
  271. // Note: this function runs with async signals enabled,
  272. // so it must not touch any tsan state.
  273. int call_pthread_cancel_with_cleanup(int (*fn)(void *arg),
  274. void (*cleanup)(void *arg), void *arg) {
  275. // pthread_cleanup_push/pop are hardcore macros mess.
  276. // We can't intercept nor call them w/o including pthread.h.
  277. int res;
  278. pthread_cleanup_push(cleanup, arg);
  279. res = fn(arg);
  280. pthread_cleanup_pop(0);
  281. return res;
  282. }
  283. #endif
  284. } // namespace __tsan
  285. #endif // SANITIZER_MAC