1 //===-- asan_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 AddressSanitizer, an address sanity checker.
10 //
11 // Mac-specific details.
12 //===----------------------------------------------------------------------===//
13 
14 #include "sanitizer_common/sanitizer_platform.h"
15 #if SANITIZER_APPLE
16 
17 #include "asan_interceptors.h"
18 #include "asan_internal.h"
19 #include "asan_mapping.h"
20 #include "asan_stack.h"
21 #include "asan_thread.h"
22 #include "sanitizer_common/sanitizer_atomic.h"
23 #include "sanitizer_common/sanitizer_libc.h"
24 #include "sanitizer_common/sanitizer_mac.h"
25 
26 #include <dlfcn.h>
27 #include <fcntl.h>
28 #include <libkern/OSAtomic.h>
29 #include <mach-o/dyld.h>
30 #include <mach-o/getsect.h>
31 #include <mach-o/loader.h>
32 #include <pthread.h>
33 #include <stdlib.h>  // for free()
34 #include <sys/mman.h>
35 #include <sys/resource.h>
36 #include <sys/sysctl.h>
37 #include <sys/ucontext.h>
38 #include <unistd.h>
39 
40 // from <crt_externs.h>, but we don't have that file on iOS
41 extern "C" {
42   extern char ***_NSGetArgv(void);
43   extern char ***_NSGetEnviron(void);
44 }
45 
46 namespace __asan {
47 
InitializePlatformInterceptors()48 void InitializePlatformInterceptors() {}
InitializePlatformExceptionHandlers()49 void InitializePlatformExceptionHandlers() {}
IsSystemHeapAddress(uptr addr)50 bool IsSystemHeapAddress (uptr addr) { return false; }
51 
52 // No-op. Mac does not support static linkage anyway.
AsanDoesNotSupportStaticLinkage()53 void *AsanDoesNotSupportStaticLinkage() {
54   return 0;
55 }
56 
FindDynamicShadowStart()57 uptr FindDynamicShadowStart() {
58   return MapDynamicShadow(MemToShadowSize(kHighMemEnd), ASAN_SHADOW_SCALE,
59                           /*min_shadow_base_alignment*/ 0, kHighMemEnd);
60 }
61 
62 // No-op. Mac does not support static linkage anyway.
AsanCheckDynamicRTPrereqs()63 void AsanCheckDynamicRTPrereqs() {}
64 
65 // No-op. Mac does not support static linkage anyway.
AsanCheckIncompatibleRT()66 void AsanCheckIncompatibleRT() {}
67 
AsanApplyToGlobals(globals_op_fptr op,const void * needle)68 void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
69   // Find the Mach-O header for the image containing the needle
70   Dl_info info;
71   int err = dladdr(needle, &info);
72   if (err == 0) return;
73 
74 #if __LP64__
75   const struct mach_header_64 *mh = (struct mach_header_64 *)info.dli_fbase;
76 #else
77   const struct mach_header *mh = (struct mach_header *)info.dli_fbase;
78 #endif
79 
80   // Look up the __asan_globals section in that image and register its globals
81   unsigned long size = 0;
82   __asan_global *globals = (__asan_global *)getsectiondata(
83       mh,
84       "__DATA", "__asan_globals",
85       &size);
86 
87   if (!globals) return;
88   if (size % sizeof(__asan_global) != 0) return;
89   op(globals, size / sizeof(__asan_global));
90 }
91 
FlushUnneededASanShadowMemory(uptr p,uptr size)92 void FlushUnneededASanShadowMemory(uptr p, uptr size) {
93   // Since asan's mapping is compacting, the shadow chunk may be
94   // not page-aligned, so we only flush the page-aligned portion.
95   ReleaseMemoryPagesToOS(MemToShadow(p), MemToShadow(p + size));
96 }
97 
98 // Support for the following functions from libdispatch on Mac OS:
99 //   dispatch_async_f()
100 //   dispatch_async()
101 //   dispatch_sync_f()
102 //   dispatch_sync()
103 //   dispatch_after_f()
104 //   dispatch_after()
105 //   dispatch_group_async_f()
106 //   dispatch_group_async()
107 // TODO(glider): libdispatch API contains other functions that we don't support
108 // yet.
109 //
110 // dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
111 // they can cause jobs to run on a thread different from the current one.
112 // TODO(glider): if so, we need a test for this (otherwise we should remove
113 // them).
114 //
115 // The following functions use dispatch_barrier_async_f() (which isn't a library
116 // function but is exported) and are thus supported:
117 //   dispatch_source_set_cancel_handler_f()
118 //   dispatch_source_set_cancel_handler()
119 //   dispatch_source_set_event_handler_f()
120 //   dispatch_source_set_event_handler()
121 //
122 // The reference manual for Grand Central Dispatch is available at
123 //   http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
124 // The implementation details are at
125 //   http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
126 
127 typedef void* dispatch_group_t;
128 typedef void* dispatch_queue_t;
129 typedef void* dispatch_source_t;
130 typedef u64 dispatch_time_t;
131 typedef void (*dispatch_function_t)(void *block);
132 typedef void* (*worker_t)(void *block);
133 typedef unsigned long dispatch_mach_reason;
134 typedef void *dispatch_mach_msg_t;
135 typedef int mach_error_t;
136 typedef void *dispatch_mach_t;
137 
138 typedef void (*dispatch_mach_handler_function_t)(void *context,
139                                                  dispatch_mach_reason reason,
140                                                  dispatch_mach_msg_t message,
141                                                  mach_error_t error);
142 #  if !defined(MISSING_BLOCKS_SUPPORT)
143 typedef void (^dispatch_mach_handler_t)(dispatch_mach_reason reason,
144                                         dispatch_mach_msg_t message,
145                                         mach_error_t error);
146 #  endif
147 
148 // A wrapper for the ObjC blocks used to support libdispatch.
149 typedef struct {
150   void *block;
151   dispatch_function_t func;
152   u32 parent_tid;
153 } asan_block_context_t;
154 
155 ALWAYS_INLINE
asan_register_worker_thread(int parent_tid,StackTrace * stack)156 void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
157   AsanThread *t = GetCurrentThread();
158   if (!t) {
159     t = AsanThread::Create(parent_tid, stack, /* detached */ true);
160     t->Init();
161     asanThreadRegistry().StartThread(t->tid(), GetTid(), ThreadType::Worker,
162                                      nullptr);
163     SetCurrentThread(t);
164   }
165 }
166 
167 // For use by only those functions that allocated the context via
168 // alloc_asan_context().
169 extern "C"
asan_dispatch_call_block_and_release(void * block)170 void asan_dispatch_call_block_and_release(void *block) {
171   GET_STACK_TRACE_THREAD;
172   asan_block_context_t *context = (asan_block_context_t*)block;
173   VReport(2,
174           "asan_dispatch_call_block_and_release(): "
175           "context: %p, pthread_self: %p\n",
176           block, (void*)pthread_self());
177   asan_register_worker_thread(context->parent_tid, &stack);
178   // Call the original dispatcher for the block.
179   context->func(context->block);
180   asan_free(context, &stack, FROM_MALLOC);
181 }
182 
183 }  // namespace __asan
184 
185 using namespace __asan;
186 
187 // Wrap |ctxt| and |func| into an asan_block_context_t.
188 // The caller retains control of the allocated context.
189 extern "C"
alloc_asan_context(void * ctxt,dispatch_function_t func,BufferedStackTrace * stack)190 asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
191                                          BufferedStackTrace *stack) {
192   asan_block_context_t *asan_ctxt =
193       (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
194   asan_ctxt->block = ctxt;
195   asan_ctxt->func = func;
196   asan_ctxt->parent_tid = GetCurrentTidOrInvalid();
197   return asan_ctxt;
198 }
199 
200 // Define interceptor for dispatch_*_f function with the three most common
201 // parameters: dispatch_queue_t, context, dispatch_function_t.
202 #define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f)                                \
203   INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt,            \
204                                   dispatch_function_t func) {                 \
205     GET_STACK_TRACE_THREAD;                                                   \
206     asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
207     if (Verbosity() >= 2) {                                     \
208       Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n",             \
209              (void*)asan_ctxt, (void*)pthread_self());                        \
210       PRINT_CURRENT_STACK();                                                  \
211     }                                                                         \
212     return REAL(dispatch_x_f)(dq, (void*)asan_ctxt,                           \
213                               asan_dispatch_call_block_and_release);          \
214   }
215 
216 INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)217 INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
218 INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
219 
220 INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
221                                     dispatch_queue_t dq, void *ctxt,
222                                     dispatch_function_t func) {
223   GET_STACK_TRACE_THREAD;
224   asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
225   if (Verbosity() >= 2) {
226     Report("dispatch_after_f: %p\n", (void*)asan_ctxt);
227     PRINT_CURRENT_STACK();
228   }
229   return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
230                                 asan_dispatch_call_block_and_release);
231 }
232 
INTERCEPTOR(void,dispatch_group_async_f,dispatch_group_t group,dispatch_queue_t dq,void * ctxt,dispatch_function_t func)233 INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
234                                           dispatch_queue_t dq, void *ctxt,
235                                           dispatch_function_t func) {
236   GET_STACK_TRACE_THREAD;
237   asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
238   if (Verbosity() >= 2) {
239     Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
240            (void*)asan_ctxt, (void*)pthread_self());
241     PRINT_CURRENT_STACK();
242   }
243   REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
244                                asan_dispatch_call_block_and_release);
245 }
246 
247 #if !defined(MISSING_BLOCKS_SUPPORT)
248 extern "C" {
249 void dispatch_async(dispatch_queue_t dq, void(^work)(void));
250 void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
251                           void(^work)(void));
252 void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
253                     void(^work)(void));
254 void dispatch_source_set_cancel_handler(dispatch_source_t ds,
255                                         void(^work)(void));
256 void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
257 dispatch_mach_t dispatch_mach_create(const char *label, dispatch_queue_t queue,
258                                      dispatch_mach_handler_t handler);
259 }
260 
261 #define GET_ASAN_BLOCK(work) \
262   void (^asan_block)(void);  \
263   int parent_tid = GetCurrentTidOrInvalid(); \
264   asan_block = ^(void) { \
265     GET_STACK_TRACE_THREAD; \
266     asan_register_worker_thread(parent_tid, &stack); \
267     work(); \
268   }
269 
270 INTERCEPTOR(void, dispatch_async,
271             dispatch_queue_t dq, void(^work)(void)) {
272   ENABLE_FRAME_POINTER;
273   GET_ASAN_BLOCK(work);
274   REAL(dispatch_async)(dq, asan_block);
275 }
276 
277 INTERCEPTOR(void, dispatch_group_async,
278             dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) {
279   ENABLE_FRAME_POINTER;
280   GET_ASAN_BLOCK(work);
281   REAL(dispatch_group_async)(dg, dq, asan_block);
282 }
283 
284 INTERCEPTOR(void, dispatch_after,
285             dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) {
286   ENABLE_FRAME_POINTER;
287   GET_ASAN_BLOCK(work);
288   REAL(dispatch_after)(when, queue, asan_block);
289 }
290 
291 INTERCEPTOR(void, dispatch_source_set_cancel_handler,
292             dispatch_source_t ds, void(^work)(void)) {
293   if (!work) {
294     REAL(dispatch_source_set_cancel_handler)(ds, work);
295     return;
296   }
297   ENABLE_FRAME_POINTER;
298   GET_ASAN_BLOCK(work);
299   REAL(dispatch_source_set_cancel_handler)(ds, asan_block);
300 }
301 
302 INTERCEPTOR(void, dispatch_source_set_event_handler,
303             dispatch_source_t ds, void(^work)(void)) {
304   ENABLE_FRAME_POINTER;
305   GET_ASAN_BLOCK(work);
306   REAL(dispatch_source_set_event_handler)(ds, asan_block);
307 }
308 
INTERCEPTOR(void *,dispatch_mach_create,const char * label,dispatch_queue_t dq,dispatch_mach_handler_t handler)309 INTERCEPTOR(void *, dispatch_mach_create, const char *label,
310             dispatch_queue_t dq, dispatch_mach_handler_t handler) {
311   int parent_tid = GetCurrentTidOrInvalid();
312   return REAL(dispatch_mach_create)(
313       label, dq,
314       ^(dispatch_mach_reason reason, dispatch_mach_msg_t message,
315         mach_error_t error) {
316         GET_STACK_TRACE_THREAD;
317         asan_register_worker_thread(parent_tid, &stack);
318         handler(reason, message, error);
319       });
320 }
321 
INTERCEPTOR(void *,dispatch_mach_create_f,const char * label,dispatch_queue_t dq,void * ctxt,dispatch_mach_handler_function_t handler)322 INTERCEPTOR(void *, dispatch_mach_create_f, const char *label,
323             dispatch_queue_t dq, void *ctxt,
324             dispatch_mach_handler_function_t handler) {
325   int parent_tid = GetCurrentTidOrInvalid();
326   return REAL(dispatch_mach_create)(
327       label, dq,
328       ^(dispatch_mach_reason reason, dispatch_mach_msg_t message,
329         mach_error_t error) {
330         GET_STACK_TRACE_THREAD;
331         asan_register_worker_thread(parent_tid, &stack);
332         handler(ctxt, reason, message, error);
333       });
334 }
335 
336 #endif
337 
338 #endif  // SANITIZER_APPLE
339