asan_mac.cc revision b09dd34786713a150fed5c5ab1529f01de0e2bc0
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 _NSGetEnviron 27#include <mach-o/dyld.h> 28#include <mach-o/loader.h> 29#include <sys/mman.h> 30#include <sys/resource.h> 31#include <sys/sysctl.h> 32#include <sys/ucontext.h> 33#include <fcntl.h> 34#include <pthread.h> 35#include <stdlib.h> // for free() 36#include <unistd.h> 37#include <libkern/OSAtomic.h> 38#include <CoreFoundation/CFString.h> 39 40namespace __asan { 41 42void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) { 43 ucontext_t *ucontext = (ucontext_t*)context; 44# if __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 // __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 default: return MACOS_VERSION_UNKNOWN; 71 } 72 } 73 default: return MACOS_VERSION_UNKNOWN; 74 } 75} 76 77bool PlatformHasDifferentMemcpyAndMemmove() { 78 // On OS X 10.7 memcpy() and memmove() are both resolved 79 // into memmove$VARIANT$sse42. 80 // See also http://code.google.com/p/address-sanitizer/issues/detail?id=34. 81 // TODO(glider): need to check dynamically that memcpy() and memmove() are 82 // actually the same function. 83 return GetMacosVersion() == MACOS_VERSION_SNOW_LEOPARD; 84} 85 86// No-op. Mac does not support static linkage anyway. 87void *AsanDoesNotSupportStaticLinkage() { 88 return 0; 89} 90 91bool AsanInterceptsSignal(int signum) { 92 return (signum == SIGSEGV || signum == SIGBUS) && flags()->handle_segv; 93} 94 95void AsanPlatformThreadInit() { 96 ReplaceCFAllocator(); 97} 98 99AsanLock::AsanLock(LinkerInitialized) { 100 // We assume that OS_SPINLOCK_INIT is zero 101} 102 103void AsanLock::Lock() { 104 CHECK(sizeof(OSSpinLock) <= sizeof(opaque_storage_)); 105 CHECK(OS_SPINLOCK_INIT == 0); 106 CHECK(owner_ != (uptr)pthread_self()); 107 OSSpinLockLock((OSSpinLock*)&opaque_storage_); 108 CHECK(!owner_); 109 owner_ = (uptr)pthread_self(); 110} 111 112void AsanLock::Unlock() { 113 CHECK(owner_ == (uptr)pthread_self()); 114 owner_ = 0; 115 OSSpinLockUnlock((OSSpinLock*)&opaque_storage_); 116} 117 118void AsanStackTrace::GetStackTrace(uptr max_s, uptr pc, uptr bp) { 119 size = 0; 120 trace[0] = pc; 121 if ((max_s) > 1) { 122 max_size = max_s; 123 FastUnwindStack(pc, bp); 124 } 125} 126 127// The range of pages to be used for escape islands. 128// TODO(glider): instead of mapping a fixed range we must find a range of 129// unmapped pages in vmmap and take them. 130// These constants were chosen empirically and may not work if the shadow 131// memory layout changes. Unfortunately they do necessarily depend on 132// kHighMemBeg or kHighMemEnd. 133static void *island_allocator_pos = 0; 134 135#if __WORDSIZE == 32 136# define kIslandEnd (0xffdf0000 - kPageSize) 137# define kIslandBeg (kIslandEnd - 256 * kPageSize) 138#else 139# define kIslandEnd (0x7fffffdf0000 - kPageSize) 140# define kIslandBeg (kIslandEnd - 256 * kPageSize) 141#endif 142 143extern "C" 144mach_error_t __interception_allocate_island(void **ptr, 145 uptr unused_size, 146 void *unused_hint) { 147 if (!island_allocator_pos) { 148 island_allocator_pos = 149 internal_mmap((void*)kIslandBeg, kIslandEnd - kIslandBeg, 150 PROT_READ | PROT_WRITE | PROT_EXEC, 151 MAP_PRIVATE | MAP_ANON | MAP_FIXED, 152 -1, 0); 153 if (island_allocator_pos != (void*)kIslandBeg) { 154 return KERN_NO_SPACE; 155 } 156 if (flags()->verbosity) { 157 Report("Mapped pages %p--%p for branch islands.\n", 158 (void*)kIslandBeg, (void*)kIslandEnd); 159 } 160 // Should not be very performance-critical. 161 internal_memset(island_allocator_pos, 0xCC, kIslandEnd - kIslandBeg); 162 }; 163 *ptr = island_allocator_pos; 164 island_allocator_pos = (char*)island_allocator_pos + kPageSize; 165 if (flags()->verbosity) { 166 Report("Branch island allocated at %p\n", *ptr); 167 } 168 return err_none; 169} 170 171extern "C" 172mach_error_t __interception_deallocate_island(void *ptr) { 173 // Do nothing. 174 // TODO(glider): allow to free and reuse the island memory. 175 return err_none; 176} 177 178// Support for the following functions from libdispatch on Mac OS: 179// dispatch_async_f() 180// dispatch_async() 181// dispatch_sync_f() 182// dispatch_sync() 183// dispatch_after_f() 184// dispatch_after() 185// dispatch_group_async_f() 186// dispatch_group_async() 187// TODO(glider): libdispatch API contains other functions that we don't support 188// yet. 189// 190// dispatch_sync() and dispatch_sync_f() are synchronous, although chances are 191// they can cause jobs to run on a thread different from the current one. 192// TODO(glider): if so, we need a test for this (otherwise we should remove 193// them). 194// 195// The following functions use dispatch_barrier_async_f() (which isn't a library 196// function but is exported) and are thus supported: 197// dispatch_source_set_cancel_handler_f() 198// dispatch_source_set_cancel_handler() 199// dispatch_source_set_event_handler_f() 200// dispatch_source_set_event_handler() 201// 202// The reference manual for Grand Central Dispatch is available at 203// http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html 204// The implementation details are at 205// http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c 206 207typedef void* pthread_workqueue_t; 208typedef void* pthread_workitem_handle_t; 209 210typedef void* dispatch_group_t; 211typedef void* dispatch_queue_t; 212typedef u64 dispatch_time_t; 213typedef void (*dispatch_function_t)(void *block); 214typedef void* (*worker_t)(void *block); 215 216// A wrapper for the ObjC blocks used to support libdispatch. 217typedef struct { 218 void *block; 219 dispatch_function_t func; 220 u32 parent_tid; 221} asan_block_context_t; 222 223// We use extern declarations of libdispatch functions here instead 224// of including <dispatch/dispatch.h>. This header is not present on 225// Mac OS X Leopard and eariler, and although we don't expect ASan to 226// work on legacy systems, it's bad to break the build of 227// LLVM compiler-rt there. 228extern "C" { 229void dispatch_async_f(dispatch_queue_t dq, void *ctxt, 230 dispatch_function_t func); 231void dispatch_sync_f(dispatch_queue_t dq, void *ctxt, 232 dispatch_function_t func); 233void dispatch_after_f(dispatch_time_t when, dispatch_queue_t dq, void *ctxt, 234 dispatch_function_t func); 235void dispatch_barrier_async_f(dispatch_queue_t dq, void *ctxt, 236 dispatch_function_t func); 237void dispatch_group_async_f(dispatch_group_t group, dispatch_queue_t dq, 238 void *ctxt, dispatch_function_t func); 239int pthread_workqueue_additem_np(pthread_workqueue_t workq, 240 void *(*workitem_func)(void *), void * workitem_arg, 241 pthread_workitem_handle_t * itemhandlep, unsigned int *gencountp); 242} // extern "C" 243 244extern "C" 245void asan_dispatch_call_block_and_release(void *block) { 246 GET_STACK_TRACE_HERE(kStackTraceMax); 247 asan_block_context_t *context = (asan_block_context_t*)block; 248 if (flags()->verbosity >= 2) { 249 Report("asan_dispatch_call_block_and_release(): " 250 "context: %p, pthread_self: %p\n", 251 block, pthread_self()); 252 } 253 AsanThread *t = asanThreadRegistry().GetCurrent(); 254 if (!t) { 255 t = AsanThread::Create(context->parent_tid, 0, 0, &stack); 256 asanThreadRegistry().RegisterThread(t); 257 t->Init(); 258 asanThreadRegistry().SetCurrent(t); 259 } 260 // Call the original dispatcher for the block. 261 context->func(context->block); 262 asan_free(context, &stack); 263} 264 265} // namespace __asan 266 267using namespace __asan; // NOLINT 268 269// Wrap |ctxt| and |func| into an asan_block_context_t. 270// The caller retains control of the allocated context. 271extern "C" 272asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func, 273 AsanStackTrace *stack) { 274 asan_block_context_t *asan_ctxt = 275 (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack); 276 asan_ctxt->block = ctxt; 277 asan_ctxt->func = func; 278 asan_ctxt->parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid(); 279 return asan_ctxt; 280} 281 282// Define interceptor for dispatch_*_f function with the three most common 283// parameters: dispatch_queue_t, context, dispatch_function_t. 284#define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f) \ 285 INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt, \ 286 dispatch_function_t func) { \ 287 GET_STACK_TRACE_HERE(kStackTraceMax); \ 288 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \ 289 if (flags()->verbosity >= 2) { \ 290 Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n", \ 291 asan_ctxt, pthread_self()); \ 292 PRINT_CURRENT_STACK(); \ 293 } \ 294 return REAL(dispatch_x_f)(dq, (void*)asan_ctxt, \ 295 asan_dispatch_call_block_and_release); \ 296 } 297 298INTERCEPT_DISPATCH_X_F_3(dispatch_async_f) 299INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f) 300INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f) 301 302INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when, 303 dispatch_queue_t dq, void *ctxt, 304 dispatch_function_t func) { 305 GET_STACK_TRACE_HERE(kStackTraceMax); 306 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); 307 if (flags()->verbosity >= 2) { 308 Report("dispatch_after_f: %p\n", asan_ctxt); 309 PRINT_CURRENT_STACK(); 310 } 311 return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt, 312 asan_dispatch_call_block_and_release); 313} 314 315INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group, 316 dispatch_queue_t dq, void *ctxt, 317 dispatch_function_t func) { 318 GET_STACK_TRACE_HERE(kStackTraceMax); 319 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); 320 if (flags()->verbosity >= 2) { 321 Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n", 322 asan_ctxt, pthread_self()); 323 PRINT_CURRENT_STACK(); 324 } 325 REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt, 326 asan_dispatch_call_block_and_release); 327} 328 329// The following stuff has been extremely helpful while looking for the 330// unhandled functions that spawned jobs on Chromium shutdown. If the verbosity 331// level is 2 or greater, we wrap pthread_workqueue_additem_np() in order to 332// find the points of worker thread creation (each of such threads may be used 333// to run several tasks, that's why this is not enough to support the whole 334// libdispatch API. 335extern "C" 336void *wrap_workitem_func(void *arg) { 337 if (flags()->verbosity >= 2) { 338 Report("wrap_workitem_func: %p, pthread_self: %p\n", arg, pthread_self()); 339 } 340 asan_block_context_t *ctxt = (asan_block_context_t*)arg; 341 worker_t fn = (worker_t)(ctxt->func); 342 void *result = fn(ctxt->block); 343 GET_STACK_TRACE_HERE(kStackTraceMax); 344 asan_free(arg, &stack); 345 return result; 346} 347 348INTERCEPTOR(int, pthread_workqueue_additem_np, pthread_workqueue_t workq, 349 void *(*workitem_func)(void *), void * workitem_arg, 350 pthread_workitem_handle_t * itemhandlep, unsigned int *gencountp) { 351 GET_STACK_TRACE_HERE(kStackTraceMax); 352 asan_block_context_t *asan_ctxt = 353 (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), &stack); 354 asan_ctxt->block = workitem_arg; 355 asan_ctxt->func = (dispatch_function_t)workitem_func; 356 asan_ctxt->parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid(); 357 if (flags()->verbosity >= 2) { 358 Report("pthread_workqueue_additem_np: %p\n", asan_ctxt); 359 PRINT_CURRENT_STACK(); 360 } 361 return REAL(pthread_workqueue_additem_np)(workq, wrap_workitem_func, 362 asan_ctxt, itemhandlep, 363 gencountp); 364} 365 366// See http://opensource.apple.com/source/CF/CF-635.15/CFString.c 367int __CFStrIsConstant(CFStringRef str) { 368 CFRuntimeBase *base = (CFRuntimeBase*)str; 369#if __LP64__ 370 return base->_rc == 0; 371#else 372 return (base->_cfinfo[CF_RC_BITS]) == 0; 373#endif 374} 375 376INTERCEPTOR(CFStringRef, CFStringCreateCopy, CFAllocatorRef alloc, 377 CFStringRef str) { 378 if (__CFStrIsConstant(str)) { 379 return str; 380 } else { 381 return REAL(CFStringCreateCopy)(alloc, str); 382 } 383} 384 385DECLARE_REAL_AND_INTERCEPTOR(void, free, void *ptr) 386 387DECLARE_REAL_AND_INTERCEPTOR(void, __CFInitialize) 388 389namespace __asan { 390 391void InitializeMacInterceptors() { 392 CHECK(INTERCEPT_FUNCTION(dispatch_async_f)); 393 CHECK(INTERCEPT_FUNCTION(dispatch_sync_f)); 394 CHECK(INTERCEPT_FUNCTION(dispatch_after_f)); 395 CHECK(INTERCEPT_FUNCTION(dispatch_barrier_async_f)); 396 CHECK(INTERCEPT_FUNCTION(dispatch_group_async_f)); 397 // We don't need to intercept pthread_workqueue_additem_np() to support the 398 // libdispatch API, but it helps us to debug the unsupported functions. Let's 399 // intercept it only during verbose runs. 400 if (flags()->verbosity >= 2) { 401 CHECK(INTERCEPT_FUNCTION(pthread_workqueue_additem_np)); 402 } 403 // Normally CFStringCreateCopy should not copy constant CF strings. 404 // Replacing the default CFAllocator causes constant strings to be copied 405 // rather than just returned, which leads to bugs in big applications like 406 // Chromium and WebKit, see 407 // http://code.google.com/p/address-sanitizer/issues/detail?id=10 408 // Until this problem is fixed we need to check that the string is 409 // non-constant before calling CFStringCreateCopy. 410 CHECK(INTERCEPT_FUNCTION(CFStringCreateCopy)); 411 // Some of the library functions call free() directly, so we have to 412 // intercept it. 413 CHECK(INTERCEPT_FUNCTION(free)); 414 if (flags()->replace_cfallocator) { 415 CHECK(INTERCEPT_FUNCTION(__CFInitialize)); 416 } 417} 418 419} // namespace __asan 420 421#endif // __APPLE__ 422