asan_mac.cc revision bc459cccc292df02314302890a4330840865982f
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#ifdef __APPLE__ 16 17#include "asan_interceptors.h" 18#include "asan_internal.h" 19#include "asan_mac.h" 20#include "asan_mapping.h" 21#include "asan_stack.h" 22#include "asan_thread.h" 23#include "asan_thread_registry.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(sysctl(mib, 2, 0, &len, 0, 0) != -1); 62 CHECK(len < maxlen); 63 CHECK(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"; 91 92void MaybeReexec() { 93 if (!flags()->allow_reexec) return; 94#if MAC_INTERPOSE_FUNCTIONS 95 // If the program is linked with the dynamic ASan runtime library, make sure 96 // the library is preloaded so that the wrappers work. If it is not, set 97 // DYLD_INSERT_LIBRARIES and re-exec ourselves. 98 Dl_info info; 99 CHECK(dladdr((void*)((uptr)__asan_init), &info)); 100 const char *dyld_insert_libraries = GetEnv(kDyldInsertLibraries); 101 if (!dyld_insert_libraries || 102 !REAL(strstr)(dyld_insert_libraries, info.dli_fname)) { 103 // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime 104 // library. 105 char program_name[1024]; 106 uint32_t buf_size = sizeof(program_name); 107 _NSGetExecutablePath(program_name, &buf_size); 108 // Ok to use setenv() since the wrappers don't depend on the value of 109 // asan_inited. 110 setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0); 111 if (flags()->verbosity >= 1) { 112 Report("exec()-ing the program with\n"); 113 Report("%s=%s\n", kDyldInsertLibraries, info.dli_fname); 114 Report("to enable ASan wrappers.\n"); 115 Report("Set ASAN_OPTIONS=allow_reexec=0 to disable this.\n"); 116 } 117 execv(program_name, *_NSGetArgv()); 118 } 119#endif // MAC_INTERPOSE_FUNCTIONS 120 // If we're not using the dynamic runtime, do nothing. 121} 122 123// No-op. Mac does not support static linkage anyway. 124void *AsanDoesNotSupportStaticLinkage() { 125 return 0; 126} 127 128bool AsanInterceptsSignal(int signum) { 129 return (signum == SIGSEGV || signum == SIGBUS) && flags()->handle_segv; 130} 131 132void AsanPlatformThreadInit() { 133} 134 135void GetStackTrace(StackTrace *stack, uptr max_s, uptr pc, uptr bp, bool fast) { 136 (void)fast; 137 stack->size = 0; 138 stack->trace[0] = pc; 139 if ((max_s) > 1) { 140 stack->max_size = max_s; 141 if (!asan_inited) return; 142 if (AsanThread *t = asanThreadRegistry().GetCurrent()) 143 stack->FastUnwindStack(pc, bp, t->stack_top(), t->stack_bottom()); 144 } 145} 146 147void ReadContextStack(void *context, uptr *stack, uptr *ssize) { 148 UNIMPLEMENTED(); 149} 150 151// The range of pages to be used for escape islands. 152// TODO(glider): instead of mapping a fixed range we must find a range of 153// unmapped pages in vmmap and take them. 154// These constants were chosen empirically and may not work if the shadow 155// memory layout changes. Unfortunately they do necessarily depend on 156// kHighMemBeg or kHighMemEnd. 157static void *island_allocator_pos = 0; 158 159#if SANITIZER_WORDSIZE == 32 160# define kIslandEnd (0xffdf0000 - GetPageSizeCached()) 161# define kIslandBeg (kIslandEnd - 256 * GetPageSizeCached()) 162#else 163# define kIslandEnd (0x7fffffdf0000 - GetPageSizeCached()) 164# define kIslandBeg (kIslandEnd - 256 * GetPageSizeCached()) 165#endif 166 167extern "C" 168mach_error_t __interception_allocate_island(void **ptr, 169 uptr unused_size, 170 void *unused_hint) { 171 if (!island_allocator_pos) { 172 island_allocator_pos = 173 internal_mmap((void*)kIslandBeg, kIslandEnd - kIslandBeg, 174 PROT_READ | PROT_WRITE | PROT_EXEC, 175 MAP_PRIVATE | MAP_ANON | MAP_FIXED, 176 -1, 0); 177 if (island_allocator_pos != (void*)kIslandBeg) { 178 return KERN_NO_SPACE; 179 } 180 if (flags()->verbosity) { 181 Report("Mapped pages %p--%p for branch islands.\n", 182 (void*)kIslandBeg, (void*)kIslandEnd); 183 } 184 // Should not be very performance-critical. 185 internal_memset(island_allocator_pos, 0xCC, kIslandEnd - kIslandBeg); 186 }; 187 *ptr = island_allocator_pos; 188 island_allocator_pos = (char*)island_allocator_pos + GetPageSizeCached(); 189 if (flags()->verbosity) { 190 Report("Branch island allocated at %p\n", *ptr); 191 } 192 return err_none; 193} 194 195extern "C" 196mach_error_t __interception_deallocate_island(void *ptr) { 197 // Do nothing. 198 // TODO(glider): allow to free and reuse the island memory. 199 return err_none; 200} 201 202// Support for the following functions from libdispatch on Mac OS: 203// dispatch_async_f() 204// dispatch_async() 205// dispatch_sync_f() 206// dispatch_sync() 207// dispatch_after_f() 208// dispatch_after() 209// dispatch_group_async_f() 210// dispatch_group_async() 211// TODO(glider): libdispatch API contains other functions that we don't support 212// yet. 213// 214// dispatch_sync() and dispatch_sync_f() are synchronous, although chances are 215// they can cause jobs to run on a thread different from the current one. 216// TODO(glider): if so, we need a test for this (otherwise we should remove 217// them). 218// 219// The following functions use dispatch_barrier_async_f() (which isn't a library 220// function but is exported) and are thus supported: 221// dispatch_source_set_cancel_handler_f() 222// dispatch_source_set_cancel_handler() 223// dispatch_source_set_event_handler_f() 224// dispatch_source_set_event_handler() 225// 226// The reference manual for Grand Central Dispatch is available at 227// http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html 228// The implementation details are at 229// http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c 230 231typedef void* dispatch_group_t; 232typedef void* dispatch_queue_t; 233typedef void* dispatch_source_t; 234typedef u64 dispatch_time_t; 235typedef void (*dispatch_function_t)(void *block); 236typedef void* (*worker_t)(void *block); 237 238// A wrapper for the ObjC blocks used to support libdispatch. 239typedef struct { 240 void *block; 241 dispatch_function_t func; 242 u32 parent_tid; 243} asan_block_context_t; 244 245// We use extern declarations of libdispatch functions here instead 246// of including <dispatch/dispatch.h>. This header is not present on 247// Mac OS X Leopard and eariler, and although we don't expect ASan to 248// work on legacy systems, it's bad to break the build of 249// LLVM compiler-rt there. 250extern "C" { 251void dispatch_async_f(dispatch_queue_t dq, void *ctxt, 252 dispatch_function_t func); 253void dispatch_sync_f(dispatch_queue_t dq, void *ctxt, 254 dispatch_function_t func); 255void dispatch_after_f(dispatch_time_t when, dispatch_queue_t dq, void *ctxt, 256 dispatch_function_t func); 257void dispatch_barrier_async_f(dispatch_queue_t dq, void *ctxt, 258 dispatch_function_t func); 259void dispatch_group_async_f(dispatch_group_t group, dispatch_queue_t dq, 260 void *ctxt, dispatch_function_t func); 261} // extern "C" 262 263static ALWAYS_INLINE 264void asan_register_worker_thread(int parent_tid, StackTrace *stack) { 265 AsanThread *t = asanThreadRegistry().GetCurrent(); 266 if (!t) { 267 t = AsanThread::Create(parent_tid, 0, 0, stack); 268 asanThreadRegistry().RegisterThread(t); 269 t->Init(); 270 asanThreadRegistry().SetCurrent(t); 271 } 272} 273 274// For use by only those functions that allocated the context via 275// alloc_asan_context(). 276extern "C" 277void asan_dispatch_call_block_and_release(void *block) { 278 GET_STACK_TRACE_THREAD; 279 asan_block_context_t *context = (asan_block_context_t*)block; 280 if (flags()->verbosity >= 2) { 281 Report("asan_dispatch_call_block_and_release(): " 282 "context: %p, pthread_self: %p\n", 283 block, pthread_self()); 284 } 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); 289} 290 291} // namespace __asan 292 293using namespace __asan; // NOLINT 294 295// Wrap |ctxt| and |func| into an asan_block_context_t. 296// The caller retains control of the allocated context. 297extern "C" 298asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func, 299 StackTrace *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 = asanThreadRegistry().GetCurrentTidOrInvalid(); 305 return asan_ctxt; 306} 307 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 (flags()->verbosity >= 2) { \ 316 Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n", \ 317 asan_ctxt, pthread_self()); \ 318 PRINT_CURRENT_STACK(); \ 319 } \ 320 return REAL(dispatch_x_f)(dq, (void*)asan_ctxt, \ 321 asan_dispatch_call_block_and_release); \ 322 } 323 324INTERCEPT_DISPATCH_X_F_3(dispatch_async_f) 325INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f) 326INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f) 327 328INTERCEPTOR(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 (flags()->verbosity >= 2) { 334 Report("dispatch_after_f: %p\n", asan_ctxt); 335 PRINT_CURRENT_STACK(); 336 } 337 return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt, 338 asan_dispatch_call_block_and_release); 339} 340 341INTERCEPTOR(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 (flags()->verbosity >= 2) { 347 Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n", 348 asan_ctxt, pthread_self()); 349 PRINT_CURRENT_STACK(); 350 } 351 REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt, 352 asan_dispatch_call_block_and_release); 353} 354 355#if MAC_INTERPOSE_FUNCTIONS && !defined(MISSING_BLOCKS_SUPPORT) 356// dispatch_async, dispatch_group_async and others tailcall the corresponding 357// dispatch_*_f functions. When wrapping functions with mach_override, those 358// dispatch_*_f are intercepted automatically. But with dylib interposition 359// this does not work, because the calls within the same library are not 360// interposed. 361// Therefore we need to re-implement dispatch_async and friends. 362 363extern "C" { 364// FIXME: consolidate these declarations with asan_intercepted_functions.h. 365void dispatch_async(dispatch_queue_t dq, void(^work)(void)); 366void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq, 367 void(^work)(void)); 368void dispatch_after(dispatch_time_t when, dispatch_queue_t queue, 369 void(^work)(void)); 370void dispatch_source_set_cancel_handler(dispatch_source_t ds, 371 void(^work)(void)); 372void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void)); 373} 374 375#define GET_ASAN_BLOCK(work) \ 376 void (^asan_block)(void); \ 377 int parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid(); \ 378 asan_block = ^(void) { \ 379 GET_STACK_TRACE_THREAD; \ 380 asan_register_worker_thread(parent_tid, &stack); \ 381 work(); \ 382 } 383 384INTERCEPTOR(void, dispatch_async, 385 dispatch_queue_t dq, void(^work)(void)) { 386 GET_ASAN_BLOCK(work); 387 REAL(dispatch_async)(dq, asan_block); 388} 389 390INTERCEPTOR(void, dispatch_group_async, 391 dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) { 392 GET_ASAN_BLOCK(work); 393 REAL(dispatch_group_async)(dg, dq, asan_block); 394} 395 396INTERCEPTOR(void, dispatch_after, 397 dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) { 398 GET_ASAN_BLOCK(work); 399 REAL(dispatch_after)(when, queue, asan_block); 400} 401 402INTERCEPTOR(void, dispatch_source_set_cancel_handler, 403 dispatch_source_t ds, void(^work)(void)) { 404 GET_ASAN_BLOCK(work); 405 REAL(dispatch_source_set_cancel_handler)(ds, asan_block); 406} 407 408INTERCEPTOR(void, dispatch_source_set_event_handler, 409 dispatch_source_t ds, void(^work)(void)) { 410 GET_ASAN_BLOCK(work); 411 REAL(dispatch_source_set_event_handler)(ds, asan_block); 412} 413#endif 414 415namespace __asan { 416 417void InitializeMacInterceptors() { 418 CHECK(INTERCEPT_FUNCTION(dispatch_async_f)); 419 CHECK(INTERCEPT_FUNCTION(dispatch_sync_f)); 420 CHECK(INTERCEPT_FUNCTION(dispatch_after_f)); 421 CHECK(INTERCEPT_FUNCTION(dispatch_barrier_async_f)); 422 CHECK(INTERCEPT_FUNCTION(dispatch_group_async_f)); 423} 424 425} // namespace __asan 426 427#endif // __APPLE__ 428