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"
28 #include <crt_externs.h> // for _NSGetArgv and _NSGetEnviron
31 extern char ***_NSGetArgv(void);
35 #include <dlfcn.h> // for dladdr()
36 #include <mach-o/dyld.h>
37 #include <mach-o/loader.h>
39 #include <sys/resource.h>
40 #include <sys/sysctl.h>
41 #include <sys/ucontext.h>
44 #include <stdlib.h> // for free()
46 #include <libkern/OSAtomic.h>
50 void InitializePlatformInterceptors() {}
52 bool PlatformHasDifferentMemcpyAndMemmove() {
53 // On OS X 10.7 memcpy() and memmove() are both resolved
54 // into memmove$VARIANT$sse42.
55 // See also http://code.google.com/p/address-sanitizer/issues/detail?id=34.
56 // TODO(glider): need to check dynamically that memcpy() and memmove() are
57 // actually the same function.
58 return GetMacosVersion() == MACOS_VERSION_SNOW_LEOPARD;
64 static const char kDyldInsertLibraries[] = "DYLD_INSERT_LIBRARIES";
65 LowLevelAllocator allocator_for_env;
67 // Change the value of the env var |name|, leaking the original value.
68 // If |name_value| is NULL, the variable is deleted from the environment,
69 // otherwise the corresponding "NAME=value" string is replaced with
71 void LeakyResetEnv(const char *name, const char *name_value) {
72 char **env = GetEnviron();
73 uptr name_len = internal_strlen(name);
75 uptr len = internal_strlen(*env);
78 if (!internal_memcmp(p, name, name_len) && p[name_len] == '=') {
81 // Replace the old value with the new one.
82 *env = const_cast<char*>(name_value);
84 // Shift the subsequent pointers back.
96 static bool reexec_disabled = false;
98 void DisableReexec() {
99 reexec_disabled = true;
102 bool DyldNeedsEnvVariable() {
103 // If running on OS X 10.11+ or iOS 9.0+, dyld will interpose even if
104 // DYLD_INSERT_LIBRARIES is not set.
107 // GetMacosVersion will not work for the simulator, whose kernel version
108 // is tied to the host. Use a weak linking hack for the simulator.
109 // This API was introduced in the same version of the OS as the dyld
112 // Check for presence of a symbol that is available on OS X 10.11+, iOS 9.0+.
113 return (dlsym(RTLD_NEXT, "mach_memory_info") == nullptr);
115 return (GetMacosVersion() <= MACOS_VERSION_YOSEMITE);
120 if (reexec_disabled) return;
122 // Make sure the dynamic ASan runtime library is preloaded so that the
123 // wrappers work. If it is not, set DYLD_INSERT_LIBRARIES and re-exec
126 CHECK(dladdr((void*)((uptr)__asan_init), &info));
127 char *dyld_insert_libraries =
128 const_cast<char*>(GetEnv(kDyldInsertLibraries));
129 uptr old_env_len = dyld_insert_libraries ?
130 internal_strlen(dyld_insert_libraries) : 0;
131 uptr fname_len = internal_strlen(info.dli_fname);
132 const char *dylib_name = StripModuleName(info.dli_fname);
133 uptr dylib_name_len = internal_strlen(dylib_name);
136 dyld_insert_libraries && REAL(strstr)(dyld_insert_libraries, dylib_name);
137 if (DyldNeedsEnvVariable() && !lib_is_in_env) {
138 // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
140 char program_name[1024];
141 uint32_t buf_size = sizeof(program_name);
142 _NSGetExecutablePath(program_name, &buf_size);
143 char *new_env = const_cast<char*>(info.dli_fname);
144 if (dyld_insert_libraries) {
145 // Append the runtime dylib name to the existing value of
146 // DYLD_INSERT_LIBRARIES.
147 new_env = (char*)allocator_for_env.Allocate(old_env_len + fname_len + 2);
148 internal_strncpy(new_env, dyld_insert_libraries, old_env_len);
149 new_env[old_env_len] = ':';
150 // Copy fname_len and add a trailing zero.
151 internal_strncpy(new_env + old_env_len + 1, info.dli_fname,
153 // Ok to use setenv() since the wrappers don't depend on the value of
155 setenv(kDyldInsertLibraries, new_env, /*overwrite*/1);
157 // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name.
158 setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0);
160 VReport(1, "exec()-ing the program with\n");
161 VReport(1, "%s=%s\n", kDyldInsertLibraries, new_env);
162 VReport(1, "to enable ASan wrappers.\n");
163 execv(program_name, *_NSGetArgv());
165 // We get here only if execv() failed.
166 Report("ERROR: The process is launched without DYLD_INSERT_LIBRARIES, "
167 "which is required for ASan to work. ASan tried to set the "
168 "environment variable and re-execute itself, but execv() failed, "
169 "possibly because of sandbox restrictions. Make sure to launch the "
170 "executable with:\n%s=%s\n", kDyldInsertLibraries, new_env);
171 CHECK("execv failed" && 0);
177 // DYLD_INSERT_LIBRARIES is set and contains the runtime library. Let's remove
178 // the dylib from the environment variable, because interceptors are installed
179 // and we don't want our children to inherit the variable.
181 uptr env_name_len = internal_strlen(kDyldInsertLibraries);
182 // Allocate memory to hold the previous env var name, its value, the '='
183 // sign and the '\0' char.
184 char *new_env = (char*)allocator_for_env.Allocate(
185 old_env_len + 2 + env_name_len);
187 internal_memset(new_env, '\0', old_env_len + 2 + env_name_len);
188 internal_strncpy(new_env, kDyldInsertLibraries, env_name_len);
189 new_env[env_name_len] = '=';
190 char *new_env_pos = new_env + env_name_len + 1;
192 // Iterate over colon-separated pieces of |dyld_insert_libraries|.
193 char *piece_start = dyld_insert_libraries;
194 char *piece_end = NULL;
195 char *old_env_end = dyld_insert_libraries + old_env_len;
197 if (piece_start[0] == ':') piece_start++;
198 piece_end = REAL(strchr)(piece_start, ':');
199 if (!piece_end) piece_end = dyld_insert_libraries + old_env_len;
200 if ((uptr)(piece_start - dyld_insert_libraries) > old_env_len) break;
201 uptr piece_len = piece_end - piece_start;
203 char *filename_start =
204 (char *)internal_memrchr(piece_start, '/', piece_len);
205 uptr filename_len = piece_len;
206 if (filename_start) {
208 filename_len = piece_len - (filename_start - piece_start);
210 filename_start = piece_start;
213 // If the current piece isn't the runtime library name,
214 // append it to new_env.
215 if ((dylib_name_len != filename_len) ||
216 (internal_memcmp(filename_start, dylib_name, dylib_name_len) != 0)) {
217 if (new_env_pos != new_env + env_name_len + 1) {
218 new_env_pos[0] = ':';
221 internal_strncpy(new_env_pos, piece_start, piece_len);
222 new_env_pos += piece_len;
224 // Move on to the next piece.
225 piece_start = piece_end;
226 } while (piece_start < old_env_end);
228 // Can't use setenv() here, because it requires the allocator to be
230 // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in
231 // a separate function called after InitializeAllocator().
232 if (new_env_pos == new_env + env_name_len + 1) new_env = NULL;
233 LeakyResetEnv(kDyldInsertLibraries, new_env);
236 // No-op. Mac does not support static linkage anyway.
237 void *AsanDoesNotSupportStaticLinkage() {
241 // No-op. Mac does not support static linkage anyway.
242 void AsanCheckDynamicRTPrereqs() {}
244 // No-op. Mac does not support static linkage anyway.
245 void AsanCheckIncompatibleRT() {}
247 void AsanPlatformThreadInit() {
250 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
254 // Support for the following functions from libdispatch on Mac OS:
255 // dispatch_async_f()
259 // dispatch_after_f()
261 // dispatch_group_async_f()
262 // dispatch_group_async()
263 // TODO(glider): libdispatch API contains other functions that we don't support
266 // dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
267 // they can cause jobs to run on a thread different from the current one.
268 // TODO(glider): if so, we need a test for this (otherwise we should remove
271 // The following functions use dispatch_barrier_async_f() (which isn't a library
272 // function but is exported) and are thus supported:
273 // dispatch_source_set_cancel_handler_f()
274 // dispatch_source_set_cancel_handler()
275 // dispatch_source_set_event_handler_f()
276 // dispatch_source_set_event_handler()
278 // The reference manual for Grand Central Dispatch is available at
279 // http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
280 // The implementation details are at
281 // http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
283 typedef void* dispatch_group_t;
284 typedef void* dispatch_queue_t;
285 typedef void* dispatch_source_t;
286 typedef u64 dispatch_time_t;
287 typedef void (*dispatch_function_t)(void *block);
288 typedef void* (*worker_t)(void *block);
290 // A wrapper for the ObjC blocks used to support libdispatch.
293 dispatch_function_t func;
295 } asan_block_context_t;
298 void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
299 AsanThread *t = GetCurrentThread();
301 t = AsanThread::Create(/* start_routine */ nullptr, /* arg */ nullptr,
302 parent_tid, stack, /* detached */ true);
304 asanThreadRegistry().StartThread(t->tid(), 0, 0);
309 // For use by only those functions that allocated the context via
310 // alloc_asan_context().
312 void asan_dispatch_call_block_and_release(void *block) {
313 GET_STACK_TRACE_THREAD;
314 asan_block_context_t *context = (asan_block_context_t*)block;
316 "asan_dispatch_call_block_and_release(): "
317 "context: %p, pthread_self: %p\n",
318 block, pthread_self());
319 asan_register_worker_thread(context->parent_tid, &stack);
320 // Call the original dispatcher for the block.
321 context->func(context->block);
322 asan_free(context, &stack, FROM_MALLOC);
325 } // namespace __asan
327 using namespace __asan; // NOLINT
329 // Wrap |ctxt| and |func| into an asan_block_context_t.
330 // The caller retains control of the allocated context.
332 asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
333 BufferedStackTrace *stack) {
334 asan_block_context_t *asan_ctxt =
335 (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
336 asan_ctxt->block = ctxt;
337 asan_ctxt->func = func;
338 asan_ctxt->parent_tid = GetCurrentTidOrInvalid();
342 // Define interceptor for dispatch_*_f function with the three most common
343 // parameters: dispatch_queue_t, context, dispatch_function_t.
344 #define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f) \
345 INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt, \
346 dispatch_function_t func) { \
347 GET_STACK_TRACE_THREAD; \
348 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
349 if (Verbosity() >= 2) { \
350 Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n", \
351 asan_ctxt, pthread_self()); \
352 PRINT_CURRENT_STACK(); \
354 return REAL(dispatch_x_f)(dq, (void*)asan_ctxt, \
355 asan_dispatch_call_block_and_release); \
358 INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
359 INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
360 INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
362 INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
363 dispatch_queue_t dq, void *ctxt,
364 dispatch_function_t func) {
365 GET_STACK_TRACE_THREAD;
366 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
367 if (Verbosity() >= 2) {
368 Report("dispatch_after_f: %p\n", asan_ctxt);
369 PRINT_CURRENT_STACK();
371 return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
372 asan_dispatch_call_block_and_release);
375 INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
376 dispatch_queue_t dq, void *ctxt,
377 dispatch_function_t func) {
378 GET_STACK_TRACE_THREAD;
379 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
380 if (Verbosity() >= 2) {
381 Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
382 asan_ctxt, pthread_self());
383 PRINT_CURRENT_STACK();
385 REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
386 asan_dispatch_call_block_and_release);
389 #if !defined(MISSING_BLOCKS_SUPPORT)
391 void dispatch_async(dispatch_queue_t dq, void(^work)(void));
392 void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
394 void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
396 void dispatch_source_set_cancel_handler(dispatch_source_t ds,
398 void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
401 #define GET_ASAN_BLOCK(work) \
402 void (^asan_block)(void); \
403 int parent_tid = GetCurrentTidOrInvalid(); \
404 asan_block = ^(void) { \
405 GET_STACK_TRACE_THREAD; \
406 asan_register_worker_thread(parent_tid, &stack); \
410 INTERCEPTOR(void, dispatch_async,
411 dispatch_queue_t dq, void(^work)(void)) {
412 ENABLE_FRAME_POINTER;
413 GET_ASAN_BLOCK(work);
414 REAL(dispatch_async)(dq, asan_block);
417 INTERCEPTOR(void, dispatch_group_async,
418 dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) {
419 ENABLE_FRAME_POINTER;
420 GET_ASAN_BLOCK(work);
421 REAL(dispatch_group_async)(dg, dq, asan_block);
424 INTERCEPTOR(void, dispatch_after,
425 dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) {
426 ENABLE_FRAME_POINTER;
427 GET_ASAN_BLOCK(work);
428 REAL(dispatch_after)(when, queue, asan_block);
431 INTERCEPTOR(void, dispatch_source_set_cancel_handler,
432 dispatch_source_t ds, void(^work)(void)) {
434 REAL(dispatch_source_set_cancel_handler)(ds, work);
437 ENABLE_FRAME_POINTER;
438 GET_ASAN_BLOCK(work);
439 REAL(dispatch_source_set_cancel_handler)(ds, asan_block);
442 INTERCEPTOR(void, dispatch_source_set_event_handler,
443 dispatch_source_t ds, void(^work)(void)) {
444 ENABLE_FRAME_POINTER;
445 GET_ASAN_BLOCK(work);
446 REAL(dispatch_source_set_event_handler)(ds, asan_block);
450 #endif // SANITIZER_MAC