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