tsan_platform_mac.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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 <mach/mach.h>
  26. #include <pthread.h>
  27. #include <signal.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <stdarg.h>
  32. #include <sys/mman.h>
  33. #include <sys/syscall.h>
  34. #include <sys/time.h>
  35. #include <sys/types.h>
  36. #include <sys/resource.h>
  37. #include <sys/stat.h>
  38. #include <unistd.h>
  39. #include <errno.h>
  40. #include <sched.h>
  41. namespace __tsan {
  42. #if !SANITIZER_GO
  43. static void *SignalSafeGetOrAllocate(uptr *dst, uptr size) {
  44. atomic_uintptr_t *a = (atomic_uintptr_t *)dst;
  45. void *val = (void *)atomic_load_relaxed(a);
  46. atomic_signal_fence(memory_order_acquire); // Turns the previous load into
  47. // acquire wrt signals.
  48. if (UNLIKELY(val == nullptr)) {
  49. val = (void *)internal_mmap(nullptr, size, PROT_READ | PROT_WRITE,
  50. MAP_PRIVATE | MAP_ANON, -1, 0);
  51. CHECK(val);
  52. void *cmp = nullptr;
  53. if (!atomic_compare_exchange_strong(a, (uintptr_t *)&cmp, (uintptr_t)val,
  54. memory_order_acq_rel)) {
  55. internal_munmap(val, size);
  56. val = cmp;
  57. }
  58. }
  59. return val;
  60. }
  61. // On OS X, accessing TLVs via __thread or manually by using pthread_key_* is
  62. // problematic, because there are several places where interceptors are called
  63. // when TLVs are not accessible (early process startup, thread cleanup, ...).
  64. // The following provides a "poor man's TLV" implementation, where we use the
  65. // shadow memory of the pointer returned by pthread_self() to store a pointer to
  66. // the ThreadState object. The main thread's ThreadState is stored separately
  67. // in a static variable, because we need to access it even before the
  68. // shadow memory is set up.
  69. static uptr main_thread_identity = 0;
  70. ALIGNED(64) static char main_thread_state[sizeof(ThreadState)];
  71. static ThreadState *main_thread_state_loc = (ThreadState *)main_thread_state;
  72. // We cannot use pthread_self() before libpthread has been initialized. Our
  73. // current heuristic for guarding this is checking `main_thread_identity` which
  74. // is only assigned in `__tsan::InitializePlatform`.
  75. static ThreadState **cur_thread_location() {
  76. if (main_thread_identity == 0)
  77. return &main_thread_state_loc;
  78. uptr thread_identity = (uptr)pthread_self();
  79. if (thread_identity == main_thread_identity)
  80. return &main_thread_state_loc;
  81. return (ThreadState **)MemToShadow(thread_identity);
  82. }
  83. ThreadState *cur_thread() {
  84. return (ThreadState *)SignalSafeGetOrAllocate(
  85. (uptr *)cur_thread_location(), sizeof(ThreadState));
  86. }
  87. void set_cur_thread(ThreadState *thr) {
  88. *cur_thread_location() = thr;
  89. }
  90. // TODO(kuba.brecka): This is not async-signal-safe. In particular, we call
  91. // munmap first and then clear `fake_tls`; if we receive a signal in between,
  92. // handler will try to access the unmapped ThreadState.
  93. void cur_thread_finalize() {
  94. ThreadState **thr_state_loc = cur_thread_location();
  95. if (thr_state_loc == &main_thread_state_loc) {
  96. // Calling dispatch_main() or xpc_main() actually invokes pthread_exit to
  97. // exit the main thread. Let's keep the main thread's ThreadState.
  98. return;
  99. }
  100. internal_munmap(*thr_state_loc, sizeof(ThreadState));
  101. *thr_state_loc = nullptr;
  102. }
  103. #endif
  104. void FlushShadowMemory() {
  105. }
  106. static void RegionMemUsage(uptr start, uptr end, uptr *res, uptr *dirty) {
  107. vm_address_t address = start;
  108. vm_address_t end_address = end;
  109. uptr resident_pages = 0;
  110. uptr dirty_pages = 0;
  111. while (address < end_address) {
  112. vm_size_t vm_region_size;
  113. mach_msg_type_number_t count = VM_REGION_EXTENDED_INFO_COUNT;
  114. vm_region_extended_info_data_t vm_region_info;
  115. mach_port_t object_name;
  116. kern_return_t ret = vm_region_64(
  117. mach_task_self(), &address, &vm_region_size, VM_REGION_EXTENDED_INFO,
  118. (vm_region_info_t)&vm_region_info, &count, &object_name);
  119. if (ret != KERN_SUCCESS) break;
  120. resident_pages += vm_region_info.pages_resident;
  121. dirty_pages += vm_region_info.pages_dirtied;
  122. address += vm_region_size;
  123. }
  124. *res = resident_pages * GetPageSizeCached();
  125. *dirty = dirty_pages * GetPageSizeCached();
  126. }
  127. void WriteMemoryProfile(char *buf, uptr buf_size, u64 uptime_ns) {
  128. uptr shadow_res, shadow_dirty;
  129. uptr meta_res, meta_dirty;
  130. uptr trace_res, trace_dirty;
  131. RegionMemUsage(ShadowBeg(), ShadowEnd(), &shadow_res, &shadow_dirty);
  132. RegionMemUsage(MetaShadowBeg(), MetaShadowEnd(), &meta_res, &meta_dirty);
  133. RegionMemUsage(TraceMemBeg(), TraceMemEnd(), &trace_res, &trace_dirty);
  134. #if !SANITIZER_GO
  135. uptr low_res, low_dirty;
  136. uptr high_res, high_dirty;
  137. uptr heap_res, heap_dirty;
  138. RegionMemUsage(LoAppMemBeg(), LoAppMemEnd(), &low_res, &low_dirty);
  139. RegionMemUsage(HiAppMemBeg(), HiAppMemEnd(), &high_res, &high_dirty);
  140. RegionMemUsage(HeapMemBeg(), HeapMemEnd(), &heap_res, &heap_dirty);
  141. #else // !SANITIZER_GO
  142. uptr app_res, app_dirty;
  143. RegionMemUsage(LoAppMemBeg(), LoAppMemEnd(), &app_res, &app_dirty);
  144. #endif
  145. StackDepotStats stacks = StackDepotGetStats();
  146. uptr nthread, nlive;
  147. ctx->thread_registry.GetNumberOfThreads(&nthread, &nlive);
  148. internal_snprintf(
  149. buf, buf_size,
  150. "shadow (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
  151. "meta (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
  152. "traces (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
  153. # if !SANITIZER_GO
  154. "low app (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
  155. "high app (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
  156. "heap (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
  157. # else // !SANITIZER_GO
  158. "app (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
  159. # endif
  160. "stacks: %zd unique IDs, %zd kB allocated\n"
  161. "threads: %zd total, %zd live\n"
  162. "------------------------------\n",
  163. ShadowBeg(), ShadowEnd(), shadow_res / 1024, shadow_dirty / 1024,
  164. MetaShadowBeg(), MetaShadowEnd(), meta_res / 1024, meta_dirty / 1024,
  165. TraceMemBeg(), TraceMemEnd(), trace_res / 1024, trace_dirty / 1024,
  166. # if !SANITIZER_GO
  167. LoAppMemBeg(), LoAppMemEnd(), low_res / 1024, low_dirty / 1024,
  168. HiAppMemBeg(), HiAppMemEnd(), high_res / 1024, high_dirty / 1024,
  169. HeapMemBeg(), HeapMemEnd(), heap_res / 1024, heap_dirty / 1024,
  170. # else // !SANITIZER_GO
  171. LoAppMemBeg(), LoAppMemEnd(), app_res / 1024, app_dirty / 1024,
  172. # endif
  173. stacks.n_uniq_ids, stacks.allocated / 1024, nthread, nlive);
  174. }
  175. # if !SANITIZER_GO
  176. void InitializeShadowMemoryPlatform() { }
  177. // On OS X, GCD worker threads are created without a call to pthread_create. We
  178. // need to properly register these threads with ThreadCreate and ThreadStart.
  179. // These threads don't have a parent thread, as they are created "spuriously".
  180. // We're using a libpthread API that notifies us about a newly created thread.
  181. // The `thread == pthread_self()` check indicates this is actually a worker
  182. // thread. If it's just a regular thread, this hook is called on the parent
  183. // thread.
  184. typedef void (*pthread_introspection_hook_t)(unsigned int event,
  185. pthread_t thread, void *addr,
  186. size_t size);
  187. extern "C" pthread_introspection_hook_t pthread_introspection_hook_install(
  188. pthread_introspection_hook_t hook);
  189. static const uptr PTHREAD_INTROSPECTION_THREAD_CREATE = 1;
  190. static const uptr PTHREAD_INTROSPECTION_THREAD_TERMINATE = 3;
  191. static pthread_introspection_hook_t prev_pthread_introspection_hook;
  192. static void my_pthread_introspection_hook(unsigned int event, pthread_t thread,
  193. void *addr, size_t size) {
  194. if (event == PTHREAD_INTROSPECTION_THREAD_CREATE) {
  195. if (thread == pthread_self()) {
  196. // The current thread is a newly created GCD worker thread.
  197. ThreadState *thr = cur_thread();
  198. Processor *proc = ProcCreate();
  199. ProcWire(proc, thr);
  200. ThreadState *parent_thread_state = nullptr; // No parent.
  201. Tid tid = ThreadCreate(parent_thread_state, 0, (uptr)thread, true);
  202. CHECK_NE(tid, kMainTid);
  203. ThreadStart(thr, tid, GetTid(), ThreadType::Worker);
  204. }
  205. } else if (event == PTHREAD_INTROSPECTION_THREAD_TERMINATE) {
  206. if (thread == pthread_self()) {
  207. ThreadState *thr = cur_thread();
  208. if (thr->tctx) {
  209. DestroyThreadState();
  210. }
  211. }
  212. }
  213. if (prev_pthread_introspection_hook != nullptr)
  214. prev_pthread_introspection_hook(event, thread, addr, size);
  215. }
  216. #endif
  217. void InitializePlatformEarly() {
  218. # if !SANITIZER_GO && SANITIZER_IOS
  219. uptr max_vm = GetMaxUserVirtualAddress() + 1;
  220. if (max_vm != HiAppMemEnd()) {
  221. Printf("ThreadSanitizer: unsupported vm address limit %p, expected %p.\n",
  222. (void *)max_vm, (void *)HiAppMemEnd());
  223. Die();
  224. }
  225. #endif
  226. }
  227. static uptr longjmp_xor_key = 0;
  228. void InitializePlatform() {
  229. DisableCoreDumperIfNecessary();
  230. #if !SANITIZER_GO
  231. CheckAndProtect();
  232. CHECK_EQ(main_thread_identity, 0);
  233. main_thread_identity = (uptr)pthread_self();
  234. prev_pthread_introspection_hook =
  235. pthread_introspection_hook_install(&my_pthread_introspection_hook);
  236. #endif
  237. if (GetMacosAlignedVersion() >= MacosVersion(10, 14)) {
  238. // Libsystem currently uses a process-global key; this might change.
  239. const unsigned kTLSLongjmpXorKeySlot = 0x7;
  240. longjmp_xor_key = (uptr)pthread_getspecific(kTLSLongjmpXorKeySlot);
  241. }
  242. }
  243. #ifdef __aarch64__
  244. # define LONG_JMP_SP_ENV_SLOT \
  245. ((GetMacosAlignedVersion() >= MacosVersion(10, 14)) ? 12 : 13)
  246. #else
  247. # define LONG_JMP_SP_ENV_SLOT 2
  248. #endif
  249. uptr ExtractLongJmpSp(uptr *env) {
  250. uptr mangled_sp = env[LONG_JMP_SP_ENV_SLOT];
  251. uptr sp = mangled_sp ^ longjmp_xor_key;
  252. sp = (uptr)ptrauth_auth_data((void *)sp, ptrauth_key_asdb,
  253. ptrauth_string_discriminator("sp"));
  254. return sp;
  255. }
  256. #if !SANITIZER_GO
  257. extern "C" void __tsan_tls_initialization() {}
  258. void ImitateTlsWrite(ThreadState *thr, uptr tls_addr, uptr tls_size) {
  259. // The pointer to the ThreadState object is stored in the shadow memory
  260. // of the tls.
  261. uptr tls_end = tls_addr + tls_size;
  262. uptr thread_identity = (uptr)pthread_self();
  263. const uptr pc = StackTrace::GetNextInstructionPc(
  264. reinterpret_cast<uptr>(__tsan_tls_initialization));
  265. if (thread_identity == main_thread_identity) {
  266. MemoryRangeImitateWrite(thr, pc, tls_addr, tls_size);
  267. } else {
  268. uptr thr_state_start = thread_identity;
  269. uptr thr_state_end = thr_state_start + sizeof(uptr);
  270. CHECK_GE(thr_state_start, tls_addr);
  271. CHECK_LE(thr_state_start, tls_addr + tls_size);
  272. CHECK_GE(thr_state_end, tls_addr);
  273. CHECK_LE(thr_state_end, tls_addr + tls_size);
  274. MemoryRangeImitateWrite(thr, pc, tls_addr, thr_state_start - tls_addr);
  275. MemoryRangeImitateWrite(thr, pc, thr_state_end, tls_end - thr_state_end);
  276. }
  277. }
  278. #endif
  279. #if !SANITIZER_GO
  280. // Note: this function runs with async signals enabled,
  281. // so it must not touch any tsan state.
  282. int call_pthread_cancel_with_cleanup(int (*fn)(void *arg),
  283. void (*cleanup)(void *arg), void *arg) {
  284. // pthread_cleanup_push/pop are hardcore macros mess.
  285. // We can't intercept nor call them w/o including pthread.h.
  286. int res;
  287. pthread_cleanup_push(cleanup, arg);
  288. res = fn(arg);
  289. pthread_cleanup_pop(0);
  290. return res;
  291. }
  292. #endif
  293. } // namespace __tsan
  294. #endif // SANITIZER_MAC