1 //===-- asan_mac.cc -------------------------------------------------------===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This file is a part of AddressSanitizer, an address sanity checker.
9 //
10 // Mac-specific details.
11 //===----------------------------------------------------------------------===//
12 
13 #include "sanitizer_common/sanitizer_platform.h"
14 #if SANITIZER_MAC
15 
16 #include "asan_interceptors.h"
17 #include "asan_internal.h"
18 #include "asan_mapping.h"
19 #include "asan_stack.h"
20 #include "asan_thread.h"
21 #include "sanitizer_common/sanitizer_atomic.h"
22 #include "sanitizer_common/sanitizer_libc.h"
23 #include "sanitizer_common/sanitizer_mac.h"
24 
25 #include <dlfcn.h>
26 #include <fcntl.h>
27 #include <libkern/OSAtomic.h>
28 #include <mach-o/dyld.h>
29 #include <mach-o/getsect.h>
30 #include <mach-o/loader.h>
31 #include <pthread.h>
32 #include <stdlib.h>  // for free()
33 #include <sys/mman.h>
34 #include <sys/resource.h>
35 #include <sys/sysctl.h>
36 #include <sys/ucontext.h>
37 #include <unistd.h>
38 
39 // from <crt_externs.h>, but we don't have that file on iOS
40 extern "C" {
41   extern char ***_NSGetArgv(void);
42   extern char ***_NSGetEnviron(void);
43 }
44 
45 namespace __asan {
46 
InitializePlatformInterceptors()47 void InitializePlatformInterceptors() {}
InitializePlatformExceptionHandlers()48 void InitializePlatformExceptionHandlers() {}
IsSystemHeapAddress(uptr addr)49 bool IsSystemHeapAddress (uptr addr) { return false; }
50 
51 // No-op. Mac does not support static linkage anyway.
AsanDoesNotSupportStaticLinkage()52 void *AsanDoesNotSupportStaticLinkage() {
53   return 0;
54 }
55 
FindDynamicShadowStart()56 uptr FindDynamicShadowStart() {
57   uptr granularity = GetMmapGranularity();
58   uptr alignment = 8 * granularity;
59   uptr left_padding = granularity;
60   uptr space_size = kHighShadowEnd + left_padding;
61 
62   uptr largest_gap_found = 0;
63   uptr shadow_start = FindAvailableMemoryRange(space_size, alignment,
64                                                granularity, &largest_gap_found);
65   // If the shadow doesn't fit, restrict the address space to make it fit.
66   if (shadow_start == 0) {
67     uptr new_max_vm = RoundDownTo(largest_gap_found << SHADOW_SCALE, alignment);
68     RestrictMemoryToMaxAddress(new_max_vm);
69     kHighMemEnd = new_max_vm - 1;
70     space_size = kHighShadowEnd + left_padding;
71     shadow_start =
72         FindAvailableMemoryRange(space_size, alignment, granularity, nullptr);
73   }
74   CHECK_NE((uptr)0, shadow_start);
75   CHECK(IsAligned(shadow_start, alignment));
76   return shadow_start;
77 }
78 
79 // No-op. Mac does not support static linkage anyway.
AsanCheckDynamicRTPrereqs()80 void AsanCheckDynamicRTPrereqs() {}
81 
82 // No-op. Mac does not support static linkage anyway.
AsanCheckIncompatibleRT()83 void AsanCheckIncompatibleRT() {}
84 
AsanApplyToGlobals(globals_op_fptr op,const void * needle)85 void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
86   // Find the Mach-O header for the image containing the needle
87   Dl_info info;
88   int err = dladdr(needle, &info);
89   if (err == 0) return;
90 
91 #if __LP64__
92   const struct mach_header_64 *mh = (struct mach_header_64 *)info.dli_fbase;
93 #else
94   const struct mach_header *mh = (struct mach_header *)info.dli_fbase;
95 #endif
96 
97   // Look up the __asan_globals section in that image and register its globals
98   unsigned long size = 0;
99   __asan_global *globals = (__asan_global *)getsectiondata(
100       mh,
101       "__DATA", "__asan_globals",
102       &size);
103 
104   if (!globals) return;
105   if (size % sizeof(__asan_global) != 0) return;
106   op(globals, size / sizeof(__asan_global));
107 }
108 
ReadContextStack(void * context,uptr * stack,uptr * ssize)109 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
110   UNIMPLEMENTED();
111 }
112 
113 // Support for the following functions from libdispatch on Mac OS:
114 //   dispatch_async_f()
115 //   dispatch_async()
116 //   dispatch_sync_f()
117 //   dispatch_sync()
118 //   dispatch_after_f()
119 //   dispatch_after()
120 //   dispatch_group_async_f()
121 //   dispatch_group_async()
122 // TODO(glider): libdispatch API contains other functions that we don't support
123 // yet.
124 //
125 // dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
126 // they can cause jobs to run on a thread different from the current one.
127 // TODO(glider): if so, we need a test for this (otherwise we should remove
128 // them).
129 //
130 // The following functions use dispatch_barrier_async_f() (which isn't a library
131 // function but is exported) and are thus supported:
132 //   dispatch_source_set_cancel_handler_f()
133 //   dispatch_source_set_cancel_handler()
134 //   dispatch_source_set_event_handler_f()
135 //   dispatch_source_set_event_handler()
136 //
137 // The reference manual for Grand Central Dispatch is available at
138 //   http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
139 // The implementation details are at
140 //   http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
141 
142 typedef void* dispatch_group_t;
143 typedef void* dispatch_queue_t;
144 typedef void* dispatch_source_t;
145 typedef u64 dispatch_time_t;
146 typedef void (*dispatch_function_t)(void *block);
147 typedef void* (*worker_t)(void *block);
148 
149 // A wrapper for the ObjC blocks used to support libdispatch.
150 typedef struct {
151   void *block;
152   dispatch_function_t func;
153   u32 parent_tid;
154 } asan_block_context_t;
155 
156 ALWAYS_INLINE
asan_register_worker_thread(int parent_tid,StackTrace * stack)157 void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
158   AsanThread *t = GetCurrentThread();
159   if (!t) {
160     t = AsanThread::Create(/* start_routine */ nullptr, /* arg */ nullptr,
161                            parent_tid, stack, /* detached */ true);
162     t->Init();
163     asanThreadRegistry().StartThread(t->tid(), GetTid(),
164                                      /* workerthread */ true, 0);
165     SetCurrentThread(t);
166   }
167 }
168 
169 // For use by only those functions that allocated the context via
170 // alloc_asan_context().
171 extern "C"
asan_dispatch_call_block_and_release(void * block)172 void asan_dispatch_call_block_and_release(void *block) {
173   GET_STACK_TRACE_THREAD;
174   asan_block_context_t *context = (asan_block_context_t*)block;
175   VReport(2,
176           "asan_dispatch_call_block_and_release(): "
177           "context: %p, pthread_self: %p\n",
178           block, pthread_self());
179   asan_register_worker_thread(context->parent_tid, &stack);
180   // Call the original dispatcher for the block.
181   context->func(context->block);
182   asan_free(context, &stack, FROM_MALLOC);
183 }
184 
185 }  // namespace __asan
186 
187 using namespace __asan;  // NOLINT
188 
189 // Wrap |ctxt| and |func| into an asan_block_context_t.
190 // The caller retains control of the allocated context.
191 extern "C"
alloc_asan_context(void * ctxt,dispatch_function_t func,BufferedStackTrace * stack)192 asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
193                                          BufferedStackTrace *stack) {
194   asan_block_context_t *asan_ctxt =
195       (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
196   asan_ctxt->block = ctxt;
197   asan_ctxt->func = func;
198   asan_ctxt->parent_tid = GetCurrentTidOrInvalid();
199   return asan_ctxt;
200 }
201 
202 // Define interceptor for dispatch_*_f function with the three most common
203 // parameters: dispatch_queue_t, context, dispatch_function_t.
204 #define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f)                                \
205   INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt,            \
206                                   dispatch_function_t func) {                 \
207     GET_STACK_TRACE_THREAD;                                                   \
208     asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
209     if (Verbosity() >= 2) {                                     \
210       Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n",             \
211              asan_ctxt, pthread_self());                                      \
212       PRINT_CURRENT_STACK();                                                  \
213     }                                                                         \
214     return REAL(dispatch_x_f)(dq, (void*)asan_ctxt,                           \
215                               asan_dispatch_call_block_and_release);          \
216   }
217 
218 INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)219 INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
220 INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
221 
222 INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
223                                     dispatch_queue_t dq, void *ctxt,
224                                     dispatch_function_t func) {
225   GET_STACK_TRACE_THREAD;
226   asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
227   if (Verbosity() >= 2) {
228     Report("dispatch_after_f: %p\n", asan_ctxt);
229     PRINT_CURRENT_STACK();
230   }
231   return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
232                                 asan_dispatch_call_block_and_release);
233 }
234 
INTERCEPTOR(void,dispatch_group_async_f,dispatch_group_t group,dispatch_queue_t dq,void * ctxt,dispatch_function_t func)235 INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
236                                           dispatch_queue_t dq, void *ctxt,
237                                           dispatch_function_t func) {
238   GET_STACK_TRACE_THREAD;
239   asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
240   if (Verbosity() >= 2) {
241     Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
242            asan_ctxt, pthread_self());
243     PRINT_CURRENT_STACK();
244   }
245   REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
246                                asan_dispatch_call_block_and_release);
247 }
248 
249 #if !defined(MISSING_BLOCKS_SUPPORT)
250 extern "C" {
251 void dispatch_async(dispatch_queue_t dq, void(^work)(void));
252 void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
253                           void(^work)(void));
254 void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
255                     void(^work)(void));
256 void dispatch_source_set_cancel_handler(dispatch_source_t ds,
257                                         void(^work)(void));
258 void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
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 #endif
309 
310 #endif  // SANITIZER_MAC
311