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.
104 static bool reexec_disabled = false;
106 void DisableReexec() {
107 reexec_disabled = true;
111 if (reexec_disabled) return;
113 // Make sure the dynamic ASan runtime library is preloaded so that the
114 // wrappers work. If it is not, set DYLD_INSERT_LIBRARIES and re-exec
117 CHECK(dladdr((void*)((uptr)__asan_init), &info));
118 char *dyld_insert_libraries =
119 const_cast<char*>(GetEnv(kDyldInsertLibraries));
120 uptr old_env_len = dyld_insert_libraries ?
121 internal_strlen(dyld_insert_libraries) : 0;
122 uptr fname_len = internal_strlen(info.dli_fname);
123 const char *dylib_name = StripModuleName(info.dli_fname);
124 uptr dylib_name_len = internal_strlen(dylib_name);
125 if (!dyld_insert_libraries ||
126 !REAL(strstr)(dyld_insert_libraries, dylib_name)) {
127 // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
129 char program_name[1024];
130 uint32_t buf_size = sizeof(program_name);
131 _NSGetExecutablePath(program_name, &buf_size);
132 char *new_env = const_cast<char*>(info.dli_fname);
133 if (dyld_insert_libraries) {
134 // Append the runtime dylib name to the existing value of
135 // DYLD_INSERT_LIBRARIES.
136 new_env = (char*)allocator_for_env.Allocate(old_env_len + fname_len + 2);
137 internal_strncpy(new_env, dyld_insert_libraries, old_env_len);
138 new_env[old_env_len] = ':';
139 // Copy fname_len and add a trailing zero.
140 internal_strncpy(new_env + old_env_len + 1, info.dli_fname,
142 // Ok to use setenv() since the wrappers don't depend on the value of
144 setenv(kDyldInsertLibraries, new_env, /*overwrite*/1);
146 // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name.
147 setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0);
149 VReport(1, "exec()-ing the program with\n");
150 VReport(1, "%s=%s\n", kDyldInsertLibraries, new_env);
151 VReport(1, "to enable ASan wrappers.\n");
152 execv(program_name, *_NSGetArgv());
154 // We get here only if execv() failed.
155 Report("ERROR: The process is launched without DYLD_INSERT_LIBRARIES, "
156 "which is required for ASan to work. ASan tried to set the "
157 "environment variable and re-execute itself, but execv() failed, "
158 "possibly because of sandbox restrictions. Make sure to launch the "
159 "executable with:\n%s=%s\n", kDyldInsertLibraries, new_env);
160 CHECK("execv failed" && 0);
163 // DYLD_INSERT_LIBRARIES is set and contains the runtime library. Let's remove
164 // the dylib from the environment variable, because interceptors are installed
165 // and we don't want our children to inherit the variable.
167 uptr env_name_len = internal_strlen(kDyldInsertLibraries);
168 // Allocate memory to hold the previous env var name, its value, the '='
169 // sign and the '\0' char.
170 char *new_env = (char*)allocator_for_env.Allocate(
171 old_env_len + 2 + env_name_len);
173 internal_memset(new_env, '\0', old_env_len + 2 + env_name_len);
174 internal_strncpy(new_env, kDyldInsertLibraries, env_name_len);
175 new_env[env_name_len] = '=';
176 char *new_env_pos = new_env + env_name_len + 1;
178 // Iterate over colon-separated pieces of |dyld_insert_libraries|.
179 char *piece_start = dyld_insert_libraries;
180 char *piece_end = NULL;
181 char *old_env_end = dyld_insert_libraries + old_env_len;
183 if (piece_start[0] == ':') piece_start++;
184 piece_end = REAL(strchr)(piece_start, ':');
185 if (!piece_end) piece_end = dyld_insert_libraries + old_env_len;
186 if ((uptr)(piece_start - dyld_insert_libraries) > old_env_len) break;
187 uptr piece_len = piece_end - piece_start;
189 char *filename_start =
190 (char *)internal_memrchr(piece_start, '/', piece_len);
191 uptr filename_len = piece_len;
192 if (filename_start) {
194 filename_len = piece_len - (filename_start - piece_start);
196 filename_start = piece_start;
199 // If the current piece isn't the runtime library name,
200 // append it to new_env.
201 if ((dylib_name_len != filename_len) ||
202 (internal_memcmp(filename_start, dylib_name, dylib_name_len) != 0)) {
203 if (new_env_pos != new_env + env_name_len + 1) {
204 new_env_pos[0] = ':';
207 internal_strncpy(new_env_pos, piece_start, piece_len);
208 new_env_pos += piece_len;
210 // Move on to the next piece.
211 piece_start = piece_end;
212 } while (piece_start < old_env_end);
214 // Can't use setenv() here, because it requires the allocator to be
216 // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in
217 // a separate function called after InitializeAllocator().
218 if (new_env_pos == new_env + env_name_len + 1) new_env = NULL;
219 LeakyResetEnv(kDyldInsertLibraries, new_env);
222 // No-op. Mac does not support static linkage anyway.
223 void *AsanDoesNotSupportStaticLinkage() {
227 // No-op. Mac does not support static linkage anyway.
228 void AsanCheckDynamicRTPrereqs() {}
230 // No-op. Mac does not support static linkage anyway.
231 void AsanCheckIncompatibleRT() {}
233 void AsanPlatformThreadInit() {
236 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
240 // Support for the following functions from libdispatch on Mac OS:
241 // dispatch_async_f()
245 // dispatch_after_f()
247 // dispatch_group_async_f()
248 // dispatch_group_async()
249 // TODO(glider): libdispatch API contains other functions that we don't support
252 // dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
253 // they can cause jobs to run on a thread different from the current one.
254 // TODO(glider): if so, we need a test for this (otherwise we should remove
257 // The following functions use dispatch_barrier_async_f() (which isn't a library
258 // function but is exported) and are thus supported:
259 // dispatch_source_set_cancel_handler_f()
260 // dispatch_source_set_cancel_handler()
261 // dispatch_source_set_event_handler_f()
262 // dispatch_source_set_event_handler()
264 // The reference manual for Grand Central Dispatch is available at
265 // http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
266 // The implementation details are at
267 // http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
269 typedef void* dispatch_group_t;
270 typedef void* dispatch_queue_t;
271 typedef void* dispatch_source_t;
272 typedef u64 dispatch_time_t;
273 typedef void (*dispatch_function_t)(void *block);
274 typedef void* (*worker_t)(void *block);
276 // A wrapper for the ObjC blocks used to support libdispatch.
279 dispatch_function_t func;
281 } asan_block_context_t;
284 void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
285 AsanThread *t = GetCurrentThread();
287 t = AsanThread::Create(/* start_routine */ nullptr, /* arg */ nullptr,
288 parent_tid, stack, /* detached */ true);
290 asanThreadRegistry().StartThread(t->tid(), 0, 0);
295 // For use by only those functions that allocated the context via
296 // alloc_asan_context().
298 void asan_dispatch_call_block_and_release(void *block) {
299 GET_STACK_TRACE_THREAD;
300 asan_block_context_t *context = (asan_block_context_t*)block;
302 "asan_dispatch_call_block_and_release(): "
303 "context: %p, pthread_self: %p\n",
304 block, pthread_self());
305 asan_register_worker_thread(context->parent_tid, &stack);
306 // Call the original dispatcher for the block.
307 context->func(context->block);
308 asan_free(context, &stack, FROM_MALLOC);
311 } // namespace __asan
313 using namespace __asan; // NOLINT
315 // Wrap |ctxt| and |func| into an asan_block_context_t.
316 // The caller retains control of the allocated context.
318 asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
319 BufferedStackTrace *stack) {
320 asan_block_context_t *asan_ctxt =
321 (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
322 asan_ctxt->block = ctxt;
323 asan_ctxt->func = func;
324 asan_ctxt->parent_tid = GetCurrentTidOrInvalid();
328 // Define interceptor for dispatch_*_f function with the three most common
329 // parameters: dispatch_queue_t, context, dispatch_function_t.
330 #define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f) \
331 INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt, \
332 dispatch_function_t func) { \
333 GET_STACK_TRACE_THREAD; \
334 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
335 if (Verbosity() >= 2) { \
336 Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n", \
337 asan_ctxt, pthread_self()); \
338 PRINT_CURRENT_STACK(); \
340 return REAL(dispatch_x_f)(dq, (void*)asan_ctxt, \
341 asan_dispatch_call_block_and_release); \
344 INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
345 INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
346 INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
348 INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
349 dispatch_queue_t dq, void *ctxt,
350 dispatch_function_t func) {
351 GET_STACK_TRACE_THREAD;
352 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
353 if (Verbosity() >= 2) {
354 Report("dispatch_after_f: %p\n", asan_ctxt);
355 PRINT_CURRENT_STACK();
357 return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
358 asan_dispatch_call_block_and_release);
361 INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
362 dispatch_queue_t dq, void *ctxt,
363 dispatch_function_t func) {
364 GET_STACK_TRACE_THREAD;
365 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
366 if (Verbosity() >= 2) {
367 Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
368 asan_ctxt, pthread_self());
369 PRINT_CURRENT_STACK();
371 REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
372 asan_dispatch_call_block_and_release);
375 #if !defined(MISSING_BLOCKS_SUPPORT)
377 void dispatch_async(dispatch_queue_t dq, void(^work)(void));
378 void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
380 void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
382 void dispatch_source_set_cancel_handler(dispatch_source_t ds,
384 void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
387 #define GET_ASAN_BLOCK(work) \
388 void (^asan_block)(void); \
389 int parent_tid = GetCurrentTidOrInvalid(); \
390 asan_block = ^(void) { \
391 GET_STACK_TRACE_THREAD; \
392 asan_register_worker_thread(parent_tid, &stack); \
396 INTERCEPTOR(void, dispatch_async,
397 dispatch_queue_t dq, void(^work)(void)) {
398 ENABLE_FRAME_POINTER;
399 GET_ASAN_BLOCK(work);
400 REAL(dispatch_async)(dq, asan_block);
403 INTERCEPTOR(void, dispatch_group_async,
404 dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) {
405 ENABLE_FRAME_POINTER;
406 GET_ASAN_BLOCK(work);
407 REAL(dispatch_group_async)(dg, dq, asan_block);
410 INTERCEPTOR(void, dispatch_after,
411 dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) {
412 ENABLE_FRAME_POINTER;
413 GET_ASAN_BLOCK(work);
414 REAL(dispatch_after)(when, queue, asan_block);
417 INTERCEPTOR(void, dispatch_source_set_cancel_handler,
418 dispatch_source_t ds, void(^work)(void)) {
420 REAL(dispatch_source_set_cancel_handler)(ds, work);
423 ENABLE_FRAME_POINTER;
424 GET_ASAN_BLOCK(work);
425 REAL(dispatch_source_set_cancel_handler)(ds, asan_block);
428 INTERCEPTOR(void, dispatch_source_set_event_handler,
429 dispatch_source_t ds, void(^work)(void)) {
430 ENABLE_FRAME_POINTER;
431 GET_ASAN_BLOCK(work);
432 REAL(dispatch_source_set_event_handler)(ds, asan_block);
436 #endif // SANITIZER_MAC