asan_mac.cc revision 736cf49a46b3cc5aa1856762f85e6f2799c24e5a
1//===-- asan_mac.cc -------------------------------------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file is a part of AddressSanitizer, an address sanity checker. 11// 12// Mac-specific details. 13//===----------------------------------------------------------------------===// 14 15#include "sanitizer_common/sanitizer_platform.h" 16#if SANITIZER_MAC 17 18#include "asan_interceptors.h" 19#include "asan_internal.h" 20#include "asan_mac.h" 21#include "asan_mapping.h" 22#include "asan_stack.h" 23#include "asan_thread.h" 24#include "sanitizer_common/sanitizer_libc.h" 25 26#include <crt_externs.h> // for _NSGetArgv 27#include <dlfcn.h> // for dladdr() 28#include <mach-o/dyld.h> 29#include <mach-o/loader.h> 30#include <sys/mman.h> 31#include <sys/resource.h> 32#include <sys/sysctl.h> 33#include <sys/ucontext.h> 34#include <fcntl.h> 35#include <pthread.h> 36#include <stdlib.h> // for free() 37#include <unistd.h> 38#include <libkern/OSAtomic.h> 39 40namespace __asan { 41 42void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) { 43 ucontext_t *ucontext = (ucontext_t*)context; 44# if SANITIZER_WORDSIZE == 64 45 *pc = ucontext->uc_mcontext->__ss.__rip; 46 *bp = ucontext->uc_mcontext->__ss.__rbp; 47 *sp = ucontext->uc_mcontext->__ss.__rsp; 48# else 49 *pc = ucontext->uc_mcontext->__ss.__eip; 50 *bp = ucontext->uc_mcontext->__ss.__ebp; 51 *sp = ucontext->uc_mcontext->__ss.__esp; 52# endif // SANITIZER_WORDSIZE 53} 54 55int GetMacosVersion() { 56 int mib[2] = { CTL_KERN, KERN_OSRELEASE }; 57 char version[100]; 58 uptr len = 0, maxlen = sizeof(version) / sizeof(version[0]); 59 for (uptr i = 0; i < maxlen; i++) version[i] = '\0'; 60 // Get the version length. 61 CHECK_NE(sysctl(mib, 2, 0, &len, 0, 0), -1); 62 CHECK_LT(len, maxlen); 63 CHECK_NE(sysctl(mib, 2, version, &len, 0, 0), -1); 64 switch (version[0]) { 65 case '9': return MACOS_VERSION_LEOPARD; 66 case '1': { 67 switch (version[1]) { 68 case '0': return MACOS_VERSION_SNOW_LEOPARD; 69 case '1': return MACOS_VERSION_LION; 70 case '2': return MACOS_VERSION_MOUNTAIN_LION; 71 default: return MACOS_VERSION_UNKNOWN; 72 } 73 } 74 default: return MACOS_VERSION_UNKNOWN; 75 } 76} 77 78bool PlatformHasDifferentMemcpyAndMemmove() { 79 // On OS X 10.7 memcpy() and memmove() are both resolved 80 // into memmove$VARIANT$sse42. 81 // See also http://code.google.com/p/address-sanitizer/issues/detail?id=34. 82 // TODO(glider): need to check dynamically that memcpy() and memmove() are 83 // actually the same function. 84 return GetMacosVersion() == MACOS_VERSION_SNOW_LEOPARD; 85} 86 87extern "C" 88void __asan_init(); 89 90static const char kDyldInsertLibraries[] = "DYLD_INSERT_LIBRARIES"; 91LowLevelAllocator allocator_for_env; 92 93// Change the value of the env var |name|, leaking the original value. 94// If |name_value| is NULL, the variable is deleted from the environment, 95// otherwise the corresponding "NAME=value" string is replaced with 96// |name_value|. 97void LeakyResetEnv(const char *name, const char *name_value) { 98 char ***env_ptr = _NSGetEnviron(); 99 CHECK(env_ptr); 100 char **environ = *env_ptr; 101 CHECK(environ); 102 uptr name_len = internal_strlen(name); 103 while (*environ != 0) { 104 uptr len = internal_strlen(*environ); 105 if (len > name_len) { 106 const char *p = *environ; 107 if (!internal_memcmp(p, name, name_len) && p[name_len] == '=') { 108 // Match. 109 if (name_value) { 110 // Replace the old value with the new one. 111 *environ = const_cast<char*>(name_value); 112 } else { 113 // Shift the subsequent pointers back. 114 char **del = environ; 115 do { 116 del[0] = del[1]; 117 } while (*del++); 118 } 119 } 120 } 121 environ++; 122 } 123} 124 125void MaybeReexec() { 126 if (!flags()->allow_reexec) return; 127 // Make sure the dynamic ASan runtime library is preloaded so that the 128 // wrappers work. If it is not, set DYLD_INSERT_LIBRARIES and re-exec 129 // ourselves. 130 Dl_info info; 131 CHECK(dladdr((void*)((uptr)__asan_init), &info)); 132 char *dyld_insert_libraries = 133 const_cast<char*>(GetEnv(kDyldInsertLibraries)); 134 uptr old_env_len = dyld_insert_libraries ? 135 internal_strlen(dyld_insert_libraries) : 0; 136 uptr fname_len = internal_strlen(info.dli_fname); 137 if (!dyld_insert_libraries || 138 !REAL(strstr)(dyld_insert_libraries, info.dli_fname)) { 139 // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime 140 // library. 141 char program_name[1024]; 142 uint32_t buf_size = sizeof(program_name); 143 _NSGetExecutablePath(program_name, &buf_size); 144 char *new_env = const_cast<char*>(info.dli_fname); 145 if (dyld_insert_libraries) { 146 // Append the runtime dylib name to the existing value of 147 // DYLD_INSERT_LIBRARIES. 148 new_env = (char*)allocator_for_env.Allocate(old_env_len + fname_len + 2); 149 internal_strncpy(new_env, dyld_insert_libraries, old_env_len); 150 new_env[old_env_len] = ':'; 151 // Copy fname_len and add a trailing zero. 152 internal_strncpy(new_env + old_env_len + 1, info.dli_fname, 153 fname_len + 1); 154 // Ok to use setenv() since the wrappers don't depend on the value of 155 // asan_inited. 156 setenv(kDyldInsertLibraries, new_env, /*overwrite*/1); 157 } else { 158 // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name. 159 setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0); 160 } 161 if (flags()->verbosity >= 1) { 162 Report("exec()-ing the program with\n"); 163 Report("%s=%s\n", kDyldInsertLibraries, new_env); 164 Report("to enable ASan wrappers.\n"); 165 Report("Set ASAN_OPTIONS=allow_reexec=0 to disable this.\n"); 166 } 167 execv(program_name, *_NSGetArgv()); 168 } else { 169 // DYLD_INSERT_LIBRARIES is set and contains the runtime library. 170 if (old_env_len == fname_len) { 171 // It's just the runtime library name - fine to unset the variable. 172 LeakyResetEnv(kDyldInsertLibraries, NULL); 173 } else { 174 uptr env_name_len = internal_strlen(kDyldInsertLibraries); 175 // Allocate memory to hold the previous env var name, its value, the '=' 176 // sign and the '\0' char. 177 char *new_env = (char*)allocator_for_env.Allocate( 178 old_env_len + 2 + env_name_len); 179 CHECK(new_env); 180 internal_memset(new_env, '\0', old_env_len + 2 + env_name_len); 181 internal_strncpy(new_env, kDyldInsertLibraries, env_name_len); 182 new_env[env_name_len] = '='; 183 char *new_env_pos = new_env + env_name_len + 1; 184 185 // Iterate over colon-separated pieces of |dyld_insert_libraries|. 186 char *piece_start = dyld_insert_libraries; 187 char *piece_end = NULL; 188 char *old_env_end = dyld_insert_libraries + old_env_len; 189 do { 190 if (piece_start[0] == ':') piece_start++; 191 piece_end = REAL(strchr)(piece_start, ':'); 192 if (!piece_end) piece_end = dyld_insert_libraries + old_env_len; 193 if ((uptr)(piece_start - dyld_insert_libraries) > old_env_len) break; 194 uptr piece_len = piece_end - piece_start; 195 196 // If the current piece isn't the runtime library name, 197 // append it to new_env. 198 if ((piece_len != fname_len) || 199 (internal_strncmp(piece_start, info.dli_fname, fname_len) != 0)) { 200 if (new_env_pos != new_env + env_name_len + 1) { 201 new_env_pos[0] = ':'; 202 new_env_pos++; 203 } 204 internal_strncpy(new_env_pos, piece_start, piece_len); 205 } 206 // Move on to the next piece. 207 new_env_pos += piece_len; 208 piece_start = piece_end; 209 } while (piece_start < old_env_end); 210 211 // Can't use setenv() here, because it requires the allocator to be 212 // initialized. 213 // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in 214 // a separate function called after InitializeAllocator(). 215 LeakyResetEnv(kDyldInsertLibraries, new_env); 216 } 217 } 218} 219 220// No-op. Mac does not support static linkage anyway. 221void *AsanDoesNotSupportStaticLinkage() { 222 return 0; 223} 224 225bool AsanInterceptsSignal(int signum) { 226 return (signum == SIGSEGV || signum == SIGBUS) && flags()->handle_segv; 227} 228 229void AsanPlatformThreadInit() { 230} 231 232void ReadContextStack(void *context, uptr *stack, uptr *ssize) { 233 UNIMPLEMENTED(); 234} 235 236// Support for the following functions from libdispatch on Mac OS: 237// dispatch_async_f() 238// dispatch_async() 239// dispatch_sync_f() 240// dispatch_sync() 241// dispatch_after_f() 242// dispatch_after() 243// dispatch_group_async_f() 244// dispatch_group_async() 245// TODO(glider): libdispatch API contains other functions that we don't support 246// yet. 247// 248// dispatch_sync() and dispatch_sync_f() are synchronous, although chances are 249// they can cause jobs to run on a thread different from the current one. 250// TODO(glider): if so, we need a test for this (otherwise we should remove 251// them). 252// 253// The following functions use dispatch_barrier_async_f() (which isn't a library 254// function but is exported) and are thus supported: 255// dispatch_source_set_cancel_handler_f() 256// dispatch_source_set_cancel_handler() 257// dispatch_source_set_event_handler_f() 258// dispatch_source_set_event_handler() 259// 260// The reference manual for Grand Central Dispatch is available at 261// http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html 262// The implementation details are at 263// http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c 264 265typedef void* dispatch_group_t; 266typedef void* dispatch_queue_t; 267typedef void* dispatch_source_t; 268typedef u64 dispatch_time_t; 269typedef void (*dispatch_function_t)(void *block); 270typedef void* (*worker_t)(void *block); 271 272// A wrapper for the ObjC blocks used to support libdispatch. 273typedef struct { 274 void *block; 275 dispatch_function_t func; 276 u32 parent_tid; 277} asan_block_context_t; 278 279ALWAYS_INLINE 280void asan_register_worker_thread(int parent_tid, StackTrace *stack) { 281 AsanThread *t = GetCurrentThread(); 282 if (!t) { 283 t = AsanThread::Create(0, 0); 284 CreateThreadContextArgs args = { t, stack }; 285 asanThreadRegistry().CreateThread(*(uptr*)t, true, parent_tid, &args); 286 t->Init(); 287 asanThreadRegistry().StartThread(t->tid(), 0, 0); 288 SetCurrentThread(t); 289 } 290} 291 292// For use by only those functions that allocated the context via 293// alloc_asan_context(). 294extern "C" 295void asan_dispatch_call_block_and_release(void *block) { 296 GET_STACK_TRACE_THREAD; 297 asan_block_context_t *context = (asan_block_context_t*)block; 298 if (flags()->verbosity >= 2) { 299 Report("asan_dispatch_call_block_and_release(): " 300 "context: %p, pthread_self: %p\n", 301 block, pthread_self()); 302 } 303 asan_register_worker_thread(context->parent_tid, &stack); 304 // Call the original dispatcher for the block. 305 context->func(context->block); 306 asan_free(context, &stack, FROM_MALLOC); 307} 308 309} // namespace __asan 310 311using namespace __asan; // NOLINT 312 313// Wrap |ctxt| and |func| into an asan_block_context_t. 314// The caller retains control of the allocated context. 315extern "C" 316asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func, 317 StackTrace *stack) { 318 asan_block_context_t *asan_ctxt = 319 (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack); 320 asan_ctxt->block = ctxt; 321 asan_ctxt->func = func; 322 asan_ctxt->parent_tid = GetCurrentTidOrInvalid(); 323 return asan_ctxt; 324} 325 326// Define interceptor for dispatch_*_f function with the three most common 327// parameters: dispatch_queue_t, context, dispatch_function_t. 328#define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f) \ 329 INTERCEPTOR(void, dispatch_x_f, 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 (flags()->verbosity >= 2) { \ 334 Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n", \ 335 asan_ctxt, pthread_self()); \ 336 PRINT_CURRENT_STACK(); \ 337 } \ 338 return REAL(dispatch_x_f)(dq, (void*)asan_ctxt, \ 339 asan_dispatch_call_block_and_release); \ 340 } 341 342INTERCEPT_DISPATCH_X_F_3(dispatch_async_f) 343INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f) 344INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f) 345 346INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when, 347 dispatch_queue_t dq, void *ctxt, 348 dispatch_function_t func) { 349 GET_STACK_TRACE_THREAD; 350 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); 351 if (flags()->verbosity >= 2) { 352 Report("dispatch_after_f: %p\n", asan_ctxt); 353 PRINT_CURRENT_STACK(); 354 } 355 return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt, 356 asan_dispatch_call_block_and_release); 357} 358 359INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group, 360 dispatch_queue_t dq, void *ctxt, 361 dispatch_function_t func) { 362 GET_STACK_TRACE_THREAD; 363 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); 364 if (flags()->verbosity >= 2) { 365 Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n", 366 asan_ctxt, pthread_self()); 367 PRINT_CURRENT_STACK(); 368 } 369 REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt, 370 asan_dispatch_call_block_and_release); 371} 372 373#if !defined(MISSING_BLOCKS_SUPPORT) 374extern "C" { 375// FIXME: consolidate these declarations with asan_intercepted_functions.h. 376void dispatch_async(dispatch_queue_t dq, void(^work)(void)); 377void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq, 378 void(^work)(void)); 379void dispatch_after(dispatch_time_t when, dispatch_queue_t queue, 380 void(^work)(void)); 381void dispatch_source_set_cancel_handler(dispatch_source_t ds, 382 void(^work)(void)); 383void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void)); 384} 385 386#define GET_ASAN_BLOCK(work) \ 387 void (^asan_block)(void); \ 388 int parent_tid = GetCurrentTidOrInvalid(); \ 389 asan_block = ^(void) { \ 390 GET_STACK_TRACE_THREAD; \ 391 asan_register_worker_thread(parent_tid, &stack); \ 392 work(); \ 393 } 394 395INTERCEPTOR(void, dispatch_async, 396 dispatch_queue_t dq, void(^work)(void)) { 397 GET_ASAN_BLOCK(work); 398 REAL(dispatch_async)(dq, asan_block); 399} 400 401INTERCEPTOR(void, dispatch_group_async, 402 dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) { 403 GET_ASAN_BLOCK(work); 404 REAL(dispatch_group_async)(dg, dq, asan_block); 405} 406 407INTERCEPTOR(void, dispatch_after, 408 dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) { 409 GET_ASAN_BLOCK(work); 410 REAL(dispatch_after)(when, queue, asan_block); 411} 412 413INTERCEPTOR(void, dispatch_source_set_cancel_handler, 414 dispatch_source_t ds, void(^work)(void)) { 415 GET_ASAN_BLOCK(work); 416 REAL(dispatch_source_set_cancel_handler)(ds, asan_block); 417} 418 419INTERCEPTOR(void, dispatch_source_set_event_handler, 420 dispatch_source_t ds, void(^work)(void)) { 421 GET_ASAN_BLOCK(work); 422 REAL(dispatch_source_set_event_handler)(ds, asan_block); 423} 424#endif 425 426#endif // SANITIZER_MAC 427