1 //===-- asan_mac.cc -------------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of AddressSanitizer, an address sanity checker.
12 // Mac-specific details.
13 //===----------------------------------------------------------------------===//
15 #include "sanitizer_common/sanitizer_platform.h"
18 #include "asan_interceptors.h"
19 #include "asan_internal.h"
20 #include "asan_mapping.h"
21 #include "asan_stack.h"
22 #include "asan_thread.h"
23 #include "sanitizer_common/sanitizer_atomic.h"
24 #include "sanitizer_common/sanitizer_libc.h"
25 #include "sanitizer_common/sanitizer_mac.h"
27 #include <crt_externs.h> // for _NSGetArgv
28 #include <dlfcn.h> // for dladdr()
29 #include <mach-o/dyld.h>
30 #include <mach-o/loader.h>
32 #include <sys/resource.h>
33 #include <sys/sysctl.h>
34 #include <sys/ucontext.h>
37 #include <stdlib.h> // for free()
39 #include <libkern/OSAtomic.h>
43 void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
44 ucontext_t *ucontext = (ucontext_t*)context;
45 # if SANITIZER_WORDSIZE == 64
46 *pc = ucontext->uc_mcontext->__ss.__rip;
47 *bp = ucontext->uc_mcontext->__ss.__rbp;
48 *sp = ucontext->uc_mcontext->__ss.__rsp;
50 *pc = ucontext->uc_mcontext->__ss.__eip;
51 *bp = ucontext->uc_mcontext->__ss.__ebp;
52 *sp = ucontext->uc_mcontext->__ss.__esp;
53 # endif // SANITIZER_WORDSIZE
57 bool PlatformHasDifferentMemcpyAndMemmove() {
58 // On OS X 10.7 memcpy() and memmove() are both resolved
59 // into memmove$VARIANT$sse42.
60 // See also http://code.google.com/p/address-sanitizer/issues/detail?id=34.
61 // TODO(glider): need to check dynamically that memcpy() and memmove() are
62 // actually the same function.
63 return GetMacosVersion() == MACOS_VERSION_SNOW_LEOPARD;
69 static const char kDyldInsertLibraries[] = "DYLD_INSERT_LIBRARIES";
70 LowLevelAllocator allocator_for_env;
72 // Change the value of the env var |name|, leaking the original value.
73 // If |name_value| is NULL, the variable is deleted from the environment,
74 // otherwise the corresponding "NAME=value" string is replaced with
76 void LeakyResetEnv(const char *name, const char *name_value) {
77 char ***env_ptr = _NSGetEnviron();
79 char **environ = *env_ptr;
81 uptr name_len = internal_strlen(name);
82 while (*environ != 0) {
83 uptr len = internal_strlen(*environ);
85 const char *p = *environ;
86 if (!internal_memcmp(p, name, name_len) && p[name_len] == '=') {
89 // Replace the old value with the new one.
90 *environ = const_cast<char*>(name_value);
92 // Shift the subsequent pointers back.
105 if (!flags()->allow_reexec) return;
106 // Make sure the dynamic ASan runtime library is preloaded so that the
107 // wrappers work. If it is not, set DYLD_INSERT_LIBRARIES and re-exec
110 CHECK(dladdr((void*)((uptr)__asan_init), &info));
111 char *dyld_insert_libraries =
112 const_cast<char*>(GetEnv(kDyldInsertLibraries));
113 uptr old_env_len = dyld_insert_libraries ?
114 internal_strlen(dyld_insert_libraries) : 0;
115 uptr fname_len = internal_strlen(info.dli_fname);
116 if (!dyld_insert_libraries ||
117 !REAL(strstr)(dyld_insert_libraries, StripModuleName(info.dli_fname))) {
118 // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
120 char program_name[1024];
121 uint32_t buf_size = sizeof(program_name);
122 _NSGetExecutablePath(program_name, &buf_size);
123 char *new_env = const_cast<char*>(info.dli_fname);
124 if (dyld_insert_libraries) {
125 // Append the runtime dylib name to the existing value of
126 // DYLD_INSERT_LIBRARIES.
127 new_env = (char*)allocator_for_env.Allocate(old_env_len + fname_len + 2);
128 internal_strncpy(new_env, dyld_insert_libraries, old_env_len);
129 new_env[old_env_len] = ':';
130 // Copy fname_len and add a trailing zero.
131 internal_strncpy(new_env + old_env_len + 1, info.dli_fname,
133 // Ok to use setenv() since the wrappers don't depend on the value of
135 setenv(kDyldInsertLibraries, new_env, /*overwrite*/1);
137 // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name.
138 setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0);
140 VReport(1, "exec()-ing the program with\n");
141 VReport(1, "%s=%s\n", kDyldInsertLibraries, new_env);
142 VReport(1, "to enable ASan wrappers.\n");
143 VReport(1, "Set ASAN_OPTIONS=allow_reexec=0 to disable this.\n");
144 execv(program_name, *_NSGetArgv());
146 // DYLD_INSERT_LIBRARIES is set and contains the runtime library.
147 if (old_env_len == fname_len) {
148 // It's just the runtime library name - fine to unset the variable.
149 LeakyResetEnv(kDyldInsertLibraries, NULL);
151 uptr env_name_len = internal_strlen(kDyldInsertLibraries);
152 // Allocate memory to hold the previous env var name, its value, the '='
153 // sign and the '\0' char.
154 char *new_env = (char*)allocator_for_env.Allocate(
155 old_env_len + 2 + env_name_len);
157 internal_memset(new_env, '\0', old_env_len + 2 + env_name_len);
158 internal_strncpy(new_env, kDyldInsertLibraries, env_name_len);
159 new_env[env_name_len] = '=';
160 char *new_env_pos = new_env + env_name_len + 1;
162 // Iterate over colon-separated pieces of |dyld_insert_libraries|.
163 char *piece_start = dyld_insert_libraries;
164 char *piece_end = NULL;
165 char *old_env_end = dyld_insert_libraries + old_env_len;
167 if (piece_start[0] == ':') piece_start++;
168 piece_end = REAL(strchr)(piece_start, ':');
169 if (!piece_end) piece_end = dyld_insert_libraries + old_env_len;
170 if ((uptr)(piece_start - dyld_insert_libraries) > old_env_len) break;
171 uptr piece_len = piece_end - piece_start;
173 // If the current piece isn't the runtime library name,
174 // append it to new_env.
175 if ((piece_len != fname_len) ||
176 (internal_strncmp(piece_start, info.dli_fname, fname_len) != 0)) {
177 if (new_env_pos != new_env + env_name_len + 1) {
178 new_env_pos[0] = ':';
181 internal_strncpy(new_env_pos, piece_start, piece_len);
183 // Move on to the next piece.
184 new_env_pos += piece_len;
185 piece_start = piece_end;
186 } while (piece_start < old_env_end);
188 // Can't use setenv() here, because it requires the allocator to be
190 // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in
191 // a separate function called after InitializeAllocator().
192 LeakyResetEnv(kDyldInsertLibraries, new_env);
197 // No-op. Mac does not support static linkage anyway.
198 void *AsanDoesNotSupportStaticLinkage() {
202 // No-op. Mac does not support static linkage anyway.
203 void AsanCheckDynamicRTPrereqs() {}
205 // No-op. Mac does not support static linkage anyway.
206 void AsanCheckIncompatibleRT() {}
208 bool AsanInterceptsSignal(int signum) {
209 return (signum == SIGSEGV || signum == SIGBUS) &&
210 common_flags()->handle_segv;
213 void AsanPlatformThreadInit() {
216 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
220 // Support for the following functions from libdispatch on Mac OS:
221 // dispatch_async_f()
225 // dispatch_after_f()
227 // dispatch_group_async_f()
228 // dispatch_group_async()
229 // TODO(glider): libdispatch API contains other functions that we don't support
232 // dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
233 // they can cause jobs to run on a thread different from the current one.
234 // TODO(glider): if so, we need a test for this (otherwise we should remove
237 // The following functions use dispatch_barrier_async_f() (which isn't a library
238 // function but is exported) and are thus supported:
239 // dispatch_source_set_cancel_handler_f()
240 // dispatch_source_set_cancel_handler()
241 // dispatch_source_set_event_handler_f()
242 // dispatch_source_set_event_handler()
244 // The reference manual for Grand Central Dispatch is available at
245 // http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
246 // The implementation details are at
247 // http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
249 typedef void* dispatch_group_t;
250 typedef void* dispatch_queue_t;
251 typedef void* dispatch_source_t;
252 typedef u64 dispatch_time_t;
253 typedef void (*dispatch_function_t)(void *block);
254 typedef void* (*worker_t)(void *block);
256 // A wrapper for the ObjC blocks used to support libdispatch.
259 dispatch_function_t func;
261 } asan_block_context_t;
264 void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
265 AsanThread *t = GetCurrentThread();
267 t = AsanThread::Create(/* start_routine */ nullptr, /* arg */ nullptr,
268 parent_tid, stack, /* detached */ true);
270 asanThreadRegistry().StartThread(t->tid(), 0, 0);
275 // For use by only those functions that allocated the context via
276 // alloc_asan_context().
278 void asan_dispatch_call_block_and_release(void *block) {
279 GET_STACK_TRACE_THREAD;
280 asan_block_context_t *context = (asan_block_context_t*)block;
282 "asan_dispatch_call_block_and_release(): "
283 "context: %p, pthread_self: %p\n",
284 block, pthread_self());
285 asan_register_worker_thread(context->parent_tid, &stack);
286 // Call the original dispatcher for the block.
287 context->func(context->block);
288 asan_free(context, &stack, FROM_MALLOC);
291 } // namespace __asan
293 using namespace __asan; // NOLINT
295 // Wrap |ctxt| and |func| into an asan_block_context_t.
296 // The caller retains control of the allocated context.
298 asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
299 BufferedStackTrace *stack) {
300 asan_block_context_t *asan_ctxt =
301 (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
302 asan_ctxt->block = ctxt;
303 asan_ctxt->func = func;
304 asan_ctxt->parent_tid = GetCurrentTidOrInvalid();
308 // Define interceptor for dispatch_*_f function with the three most common
309 // parameters: dispatch_queue_t, context, dispatch_function_t.
310 #define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f) \
311 INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt, \
312 dispatch_function_t func) { \
313 GET_STACK_TRACE_THREAD; \
314 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
315 if (common_flags()->verbosity >= 2) { \
316 Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n", \
317 asan_ctxt, pthread_self()); \
318 PRINT_CURRENT_STACK(); \
320 return REAL(dispatch_x_f)(dq, (void*)asan_ctxt, \
321 asan_dispatch_call_block_and_release); \
324 INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
325 INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
326 INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
328 INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
329 dispatch_queue_t dq, void *ctxt,
330 dispatch_function_t func) {
331 GET_STACK_TRACE_THREAD;
332 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
333 if (common_flags()->verbosity >= 2) {
334 Report("dispatch_after_f: %p\n", asan_ctxt);
335 PRINT_CURRENT_STACK();
337 return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
338 asan_dispatch_call_block_and_release);
341 INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
342 dispatch_queue_t dq, void *ctxt,
343 dispatch_function_t func) {
344 GET_STACK_TRACE_THREAD;
345 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
346 if (common_flags()->verbosity >= 2) {
347 Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
348 asan_ctxt, pthread_self());
349 PRINT_CURRENT_STACK();
351 REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
352 asan_dispatch_call_block_and_release);
355 #if !defined(MISSING_BLOCKS_SUPPORT)
357 void dispatch_async(dispatch_queue_t dq, void(^work)(void));
358 void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
360 void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
362 void dispatch_source_set_cancel_handler(dispatch_source_t ds,
364 void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
367 #define GET_ASAN_BLOCK(work) \
368 void (^asan_block)(void); \
369 int parent_tid = GetCurrentTidOrInvalid(); \
370 asan_block = ^(void) { \
371 GET_STACK_TRACE_THREAD; \
372 asan_register_worker_thread(parent_tid, &stack); \
376 // Forces the compiler to generate a frame pointer in the function.
377 #define ENABLE_FRAME_POINTER \
379 volatile uptr enable_fp; \
380 enable_fp = GET_CURRENT_FRAME(); \
383 INTERCEPTOR(void, dispatch_async,
384 dispatch_queue_t dq, void(^work)(void)) {
385 ENABLE_FRAME_POINTER;
386 GET_ASAN_BLOCK(work);
387 REAL(dispatch_async)(dq, asan_block);
390 INTERCEPTOR(void, dispatch_group_async,
391 dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) {
392 ENABLE_FRAME_POINTER;
393 GET_ASAN_BLOCK(work);
394 REAL(dispatch_group_async)(dg, dq, asan_block);
397 INTERCEPTOR(void, dispatch_after,
398 dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) {
399 ENABLE_FRAME_POINTER;
400 GET_ASAN_BLOCK(work);
401 REAL(dispatch_after)(when, queue, asan_block);
404 INTERCEPTOR(void, dispatch_source_set_cancel_handler,
405 dispatch_source_t ds, void(^work)(void)) {
406 ENABLE_FRAME_POINTER;
407 GET_ASAN_BLOCK(work);
408 REAL(dispatch_source_set_cancel_handler)(ds, asan_block);
411 INTERCEPTOR(void, dispatch_source_set_event_handler,
412 dispatch_source_t ds, void(^work)(void)) {
413 ENABLE_FRAME_POINTER;
414 GET_ASAN_BLOCK(work);
415 REAL(dispatch_source_set_event_handler)(ds, asan_block);
419 #endif // SANITIZER_MAC