asan_mac.cc revision ec3a5a21fd261f5227b5ad0d76bc148c6d227297
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#include <CoreFoundation/CFString.h>
40
41namespace __asan {
42
43void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
44  ucontext_t *ucontext = (ucontext_t*)context;
45# if __WORDSIZE == 64
46  *pc = ucontext->uc_mcontext->__ss.__rip;
47  *bp = ucontext->uc_mcontext->__ss.__rbp;
48  *sp = ucontext->uc_mcontext->__ss.__rsp;
49# else
50  *pc = ucontext->uc_mcontext->__ss.__eip;
51  *bp = ucontext->uc_mcontext->__ss.__ebp;
52  *sp = ucontext->uc_mcontext->__ss.__esp;
53# endif  // __WORDSIZE
54}
55
56int GetMacosVersion() {
57  int mib[2] = { CTL_KERN, KERN_OSRELEASE };
58  char version[100];
59  uptr len = 0, maxlen = sizeof(version) / sizeof(version[0]);
60  for (uptr i = 0; i < maxlen; i++) version[i] = '\0';
61  // Get the version length.
62  CHECK(sysctl(mib, 2, 0, &len, 0, 0) != -1);
63  CHECK(len < maxlen);
64  CHECK(sysctl(mib, 2, version, &len, 0, 0) != -1);
65  switch (version[0]) {
66    case '9': return MACOS_VERSION_LEOPARD;
67    case '1': {
68      switch (version[1]) {
69        case '0': return MACOS_VERSION_SNOW_LEOPARD;
70        case '1': return MACOS_VERSION_LION;
71        case '2': return MACOS_VERSION_MOUNTAIN_LION;
72        default: return MACOS_VERSION_UNKNOWN;
73      }
74    }
75    default: return MACOS_VERSION_UNKNOWN;
76  }
77}
78
79bool PlatformHasDifferentMemcpyAndMemmove() {
80  // On OS X 10.7 memcpy() and memmove() are both resolved
81  // into memmove$VARIANT$sse42.
82  // See also http://code.google.com/p/address-sanitizer/issues/detail?id=34.
83  // TODO(glider): need to check dynamically that memcpy() and memmove() are
84  // actually the same function.
85  return GetMacosVersion() == MACOS_VERSION_SNOW_LEOPARD;
86}
87
88extern "C"
89void __asan_init();
90
91static const char kDyldInsertLibraries[] = "DYLD_INSERT_LIBRARIES";
92
93void MaybeReexec() {
94  if (!flags()->allow_reexec) return;
95#if MAC_INTERPOSE_FUNCTIONS
96  // If the program is linked with the dynamic ASan runtime library, make sure
97  // the library is preloaded so that the wrappers work. If it is not, set
98  // DYLD_INSERT_LIBRARIES and re-exec ourselves.
99  Dl_info info;
100  CHECK(dladdr((void*)((uptr)__asan_init), &info));
101  const char *dyld_insert_libraries = GetEnv(kDyldInsertLibraries);
102  if (!dyld_insert_libraries ||
103      !REAL(strstr)(dyld_insert_libraries, info.dli_fname)) {
104    // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
105    // library.
106    char program_name[1024];
107    uint32_t buf_size = sizeof(program_name);
108    _NSGetExecutablePath(program_name, &buf_size);
109    // Ok to use setenv() since the wrappers don't depend on the value of
110    // asan_inited.
111    setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0);
112    if (flags()->verbosity >= 1) {
113      Report("exec()-ing the program with\n");
114      Report("%s=%s\n", kDyldInsertLibraries, info.dli_fname);
115      Report("to enable ASan wrappers.\n");
116      Report("Set ASAN_OPTIONS=allow_reexec=0 to disable this.\n");
117    }
118    execv(program_name, *_NSGetArgv());
119  }
120#endif  // MAC_INTERPOSE_FUNCTIONS
121  // If we're not using the dynamic runtime, do nothing.
122}
123
124// No-op. Mac does not support static linkage anyway.
125void *AsanDoesNotSupportStaticLinkage() {
126  return 0;
127}
128
129bool AsanInterceptsSignal(int signum) {
130  return (signum == SIGSEGV || signum == SIGBUS) && flags()->handle_segv;
131}
132
133void AsanPlatformThreadInit() {
134  // For the first program thread, we can't replace the allocator before
135  // __CFInitialize() has been called. If it hasn't, we'll call
136  // MaybeReplaceCFAllocator() later on this thread.
137  // For other threads __CFInitialize() has been called before their creation.
138  // See also asan_malloc_mac.cc.
139  if (((CFRuntimeBase*)kCFAllocatorSystemDefault)->_cfisa) {
140    MaybeReplaceCFAllocator();
141  }
142}
143
144AsanLock::AsanLock(LinkerInitialized) {
145  // We assume that OS_SPINLOCK_INIT is zero
146}
147
148void AsanLock::Lock() {
149  CHECK(sizeof(OSSpinLock) <= sizeof(opaque_storage_));
150  CHECK(OS_SPINLOCK_INIT == 0);
151  CHECK(owner_ != (uptr)pthread_self());
152  OSSpinLockLock((OSSpinLock*)&opaque_storage_);
153  CHECK(!owner_);
154  owner_ = (uptr)pthread_self();
155}
156
157void AsanLock::Unlock() {
158  CHECK(owner_ == (uptr)pthread_self());
159  owner_ = 0;
160  OSSpinLockUnlock((OSSpinLock*)&opaque_storage_);
161}
162
163void GetStackTrace(StackTrace *stack, uptr max_s, uptr pc, uptr bp) {
164  stack->size = 0;
165  stack->trace[0] = pc;
166  if ((max_s) > 1) {
167    stack->max_size = max_s;
168    if (!asan_inited) return;
169    if (AsanThread *t = asanThreadRegistry().GetCurrent())
170      stack->FastUnwindStack(pc, bp, t->stack_top(), t->stack_bottom());
171  }
172}
173
174// The range of pages to be used for escape islands.
175// TODO(glider): instead of mapping a fixed range we must find a range of
176// unmapped pages in vmmap and take them.
177// These constants were chosen empirically and may not work if the shadow
178// memory layout changes. Unfortunately they do necessarily depend on
179// kHighMemBeg or kHighMemEnd.
180static void *island_allocator_pos = 0;
181
182#if __WORDSIZE == 32
183# define kIslandEnd (0xffdf0000 - kPageSize)
184# define kIslandBeg (kIslandEnd - 256 * kPageSize)
185#else
186# define kIslandEnd (0x7fffffdf0000 - kPageSize)
187# define kIslandBeg (kIslandEnd - 256 * kPageSize)
188#endif
189
190extern "C"
191mach_error_t __interception_allocate_island(void **ptr,
192                                            uptr unused_size,
193                                            void *unused_hint) {
194  if (!island_allocator_pos) {
195    island_allocator_pos =
196        internal_mmap((void*)kIslandBeg, kIslandEnd - kIslandBeg,
197                      PROT_READ | PROT_WRITE | PROT_EXEC,
198                      MAP_PRIVATE | MAP_ANON | MAP_FIXED,
199                      -1, 0);
200    if (island_allocator_pos != (void*)kIslandBeg) {
201      return KERN_NO_SPACE;
202    }
203    if (flags()->verbosity) {
204      Report("Mapped pages %p--%p for branch islands.\n",
205             (void*)kIslandBeg, (void*)kIslandEnd);
206    }
207    // Should not be very performance-critical.
208    internal_memset(island_allocator_pos, 0xCC, kIslandEnd - kIslandBeg);
209  };
210  *ptr = island_allocator_pos;
211  island_allocator_pos = (char*)island_allocator_pos + kPageSize;
212  if (flags()->verbosity) {
213    Report("Branch island allocated at %p\n", *ptr);
214  }
215  return err_none;
216}
217
218extern "C"
219mach_error_t __interception_deallocate_island(void *ptr) {
220  // Do nothing.
221  // TODO(glider): allow to free and reuse the island memory.
222  return err_none;
223}
224
225// Support for the following functions from libdispatch on Mac OS:
226//   dispatch_async_f()
227//   dispatch_async()
228//   dispatch_sync_f()
229//   dispatch_sync()
230//   dispatch_after_f()
231//   dispatch_after()
232//   dispatch_group_async_f()
233//   dispatch_group_async()
234// TODO(glider): libdispatch API contains other functions that we don't support
235// yet.
236//
237// dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
238// they can cause jobs to run on a thread different from the current one.
239// TODO(glider): if so, we need a test for this (otherwise we should remove
240// them).
241//
242// The following functions use dispatch_barrier_async_f() (which isn't a library
243// function but is exported) and are thus supported:
244//   dispatch_source_set_cancel_handler_f()
245//   dispatch_source_set_cancel_handler()
246//   dispatch_source_set_event_handler_f()
247//   dispatch_source_set_event_handler()
248//
249// The reference manual for Grand Central Dispatch is available at
250//   http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
251// The implementation details are at
252//   http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
253
254typedef void* pthread_workqueue_t;
255typedef void* pthread_workitem_handle_t;
256
257typedef void* dispatch_group_t;
258typedef void* dispatch_queue_t;
259typedef void* dispatch_source_t;
260typedef u64 dispatch_time_t;
261typedef void (*dispatch_function_t)(void *block);
262typedef void* (*worker_t)(void *block);
263
264// A wrapper for the ObjC blocks used to support libdispatch.
265typedef struct {
266  void *block;
267  dispatch_function_t func;
268  u32 parent_tid;
269} asan_block_context_t;
270
271// We use extern declarations of libdispatch functions here instead
272// of including <dispatch/dispatch.h>. This header is not present on
273// Mac OS X Leopard and eariler, and although we don't expect ASan to
274// work on legacy systems, it's bad to break the build of
275// LLVM compiler-rt there.
276extern "C" {
277void dispatch_async_f(dispatch_queue_t dq, void *ctxt,
278                      dispatch_function_t func);
279void dispatch_sync_f(dispatch_queue_t dq, void *ctxt,
280                     dispatch_function_t func);
281void dispatch_after_f(dispatch_time_t when, dispatch_queue_t dq, void *ctxt,
282                      dispatch_function_t func);
283void dispatch_barrier_async_f(dispatch_queue_t dq, void *ctxt,
284                              dispatch_function_t func);
285void dispatch_group_async_f(dispatch_group_t group, dispatch_queue_t dq,
286                            void *ctxt, dispatch_function_t func);
287int pthread_workqueue_additem_np(pthread_workqueue_t workq,
288    void *(*workitem_func)(void *), void * workitem_arg,
289    pthread_workitem_handle_t * itemhandlep, unsigned int *gencountp);
290}  // extern "C"
291
292static ALWAYS_INLINE
293void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
294  AsanThread *t = asanThreadRegistry().GetCurrent();
295  if (!t) {
296    t = AsanThread::Create(parent_tid, 0, 0, stack);
297    asanThreadRegistry().RegisterThread(t);
298    t->Init();
299    asanThreadRegistry().SetCurrent(t);
300  }
301}
302
303// For use by only those functions that allocated the context via
304// alloc_asan_context().
305extern "C"
306void asan_dispatch_call_block_and_release(void *block) {
307  GET_STACK_TRACE_HERE(kStackTraceMax);
308  asan_block_context_t *context = (asan_block_context_t*)block;
309  if (flags()->verbosity >= 2) {
310    Report("asan_dispatch_call_block_and_release(): "
311           "context: %p, pthread_self: %p\n",
312           block, pthread_self());
313  }
314  asan_register_worker_thread(context->parent_tid, &stack);
315  // Call the original dispatcher for the block.
316  context->func(context->block);
317  asan_free(context, &stack);
318}
319
320}  // namespace __asan
321
322using namespace __asan;  // NOLINT
323
324// Wrap |ctxt| and |func| into an asan_block_context_t.
325// The caller retains control of the allocated context.
326extern "C"
327asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
328                                         StackTrace *stack) {
329  asan_block_context_t *asan_ctxt =
330      (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
331  asan_ctxt->block = ctxt;
332  asan_ctxt->func = func;
333  asan_ctxt->parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid();
334  return asan_ctxt;
335}
336
337// Define interceptor for dispatch_*_f function with the three most common
338// parameters: dispatch_queue_t, context, dispatch_function_t.
339#define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f)                                \
340  INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt,            \
341                                  dispatch_function_t func) {                 \
342    GET_STACK_TRACE_HERE(kStackTraceMax);                                     \
343    asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
344    if (flags()->verbosity >= 2) {                                            \
345      Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n",             \
346             asan_ctxt, pthread_self());                                      \
347       PRINT_CURRENT_STACK();                                                 \
348     }                                                                        \
349     return REAL(dispatch_x_f)(dq, (void*)asan_ctxt,                          \
350                               asan_dispatch_call_block_and_release);         \
351  }
352
353INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
354INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
355INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
356
357INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
358                                    dispatch_queue_t dq, void *ctxt,
359                                    dispatch_function_t func) {
360  GET_STACK_TRACE_HERE(kStackTraceMax);
361  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
362  if (flags()->verbosity >= 2) {
363    Report("dispatch_after_f: %p\n", asan_ctxt);
364    PRINT_CURRENT_STACK();
365  }
366  return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
367                                asan_dispatch_call_block_and_release);
368}
369
370INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
371                                          dispatch_queue_t dq, void *ctxt,
372                                          dispatch_function_t func) {
373  GET_STACK_TRACE_HERE(kStackTraceMax);
374  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
375  if (flags()->verbosity >= 2) {
376    Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
377           asan_ctxt, pthread_self());
378    PRINT_CURRENT_STACK();
379  }
380  REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
381                               asan_dispatch_call_block_and_release);
382}
383
384#if MAC_INTERPOSE_FUNCTIONS
385// dispatch_async, dispatch_group_async and others tailcall the corresponding
386// dispatch_*_f functions. When wrapping functions with mach_override, those
387// dispatch_*_f are intercepted automatically. But with dylib interposition
388// this does not work, because the calls within the same library are not
389// interposed.
390// Therefore we need to re-implement dispatch_async and friends.
391
392extern "C" {
393// FIXME: consolidate these declarations with asan_intercepted_functions.h.
394void dispatch_async(dispatch_queue_t dq, void(^work)(void));
395void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
396                          void(^work)(void));
397void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
398                    void(^work)(void));
399void dispatch_source_set_cancel_handler(dispatch_source_t ds,
400                                        void(^work)(void));
401void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
402}
403
404#define GET_ASAN_BLOCK(work) \
405  void (^asan_block)(void);  \
406  int parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid(); \
407  asan_block = ^(void) { \
408    GET_STACK_TRACE_HERE(kStackTraceMax); \
409    asan_register_worker_thread(parent_tid, &stack); \
410    work(); \
411  }
412
413INTERCEPTOR(void, dispatch_async,
414            dispatch_queue_t dq, void(^work)(void)) {
415  GET_ASAN_BLOCK(work);
416  REAL(dispatch_async)(dq, asan_block);
417}
418
419INTERCEPTOR(void, dispatch_group_async,
420            dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) {
421  GET_ASAN_BLOCK(work);
422  REAL(dispatch_group_async)(dg, dq, asan_block);
423}
424
425INTERCEPTOR(void, dispatch_after,
426            dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) {
427  GET_ASAN_BLOCK(work);
428  REAL(dispatch_after)(when, queue, asan_block);
429}
430
431INTERCEPTOR(void, dispatch_source_set_cancel_handler,
432            dispatch_source_t ds, void(^work)(void)) {
433  GET_ASAN_BLOCK(work);
434  REAL(dispatch_source_set_cancel_handler)(ds, asan_block);
435}
436
437INTERCEPTOR(void, dispatch_source_set_event_handler,
438            dispatch_source_t ds, void(^work)(void)) {
439  GET_ASAN_BLOCK(work);
440  REAL(dispatch_source_set_event_handler)(ds, asan_block);
441}
442#endif
443
444// The following stuff has been extremely helpful while looking for the
445// unhandled functions that spawned jobs on Chromium shutdown. If the verbosity
446// level is 2 or greater, we wrap pthread_workqueue_additem_np() in order to
447// find the points of worker thread creation (each of such threads may be used
448// to run several tasks, that's why this is not enough to support the whole
449// libdispatch API.
450extern "C"
451void *wrap_workitem_func(void *arg) {
452  if (flags()->verbosity >= 2) {
453    Report("wrap_workitem_func: %p, pthread_self: %p\n", arg, pthread_self());
454  }
455  asan_block_context_t *ctxt = (asan_block_context_t*)arg;
456  worker_t fn = (worker_t)(ctxt->func);
457  void *result =  fn(ctxt->block);
458  GET_STACK_TRACE_HERE(kStackTraceMax);
459  asan_free(arg, &stack);
460  return result;
461}
462
463INTERCEPTOR(int, pthread_workqueue_additem_np, pthread_workqueue_t workq,
464    void *(*workitem_func)(void *), void * workitem_arg,
465    pthread_workitem_handle_t * itemhandlep, unsigned int *gencountp) {
466  GET_STACK_TRACE_HERE(kStackTraceMax);
467  asan_block_context_t *asan_ctxt =
468      (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), &stack);
469  asan_ctxt->block = workitem_arg;
470  asan_ctxt->func = (dispatch_function_t)workitem_func;
471  asan_ctxt->parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid();
472  if (flags()->verbosity >= 2) {
473    Report("pthread_workqueue_additem_np: %p\n", asan_ctxt);
474    PRINT_CURRENT_STACK();
475  }
476  return REAL(pthread_workqueue_additem_np)(workq, wrap_workitem_func,
477                                            asan_ctxt, itemhandlep,
478                                            gencountp);
479}
480
481// See http://opensource.apple.com/source/CF/CF-635.15/CFString.c
482int __CFStrIsConstant(CFStringRef str) {
483  CFRuntimeBase *base = (CFRuntimeBase*)str;
484#if __LP64__
485  return base->_rc == 0;
486#else
487  return (base->_cfinfo[CF_RC_BITS]) == 0;
488#endif
489}
490
491INTERCEPTOR(CFStringRef, CFStringCreateCopy, CFAllocatorRef alloc,
492                                             CFStringRef str) {
493  if (__CFStrIsConstant(str)) {
494    return str;
495  } else {
496    return REAL(CFStringCreateCopy)(alloc, str);
497  }
498}
499
500DECLARE_REAL_AND_INTERCEPTOR(void, free, void *ptr)
501
502DECLARE_REAL_AND_INTERCEPTOR(void, __CFInitialize, void)
503
504namespace __asan {
505
506void InitializeMacInterceptors() {
507  CHECK(INTERCEPT_FUNCTION(dispatch_async_f));
508  CHECK(INTERCEPT_FUNCTION(dispatch_sync_f));
509  CHECK(INTERCEPT_FUNCTION(dispatch_after_f));
510  CHECK(INTERCEPT_FUNCTION(dispatch_barrier_async_f));
511  CHECK(INTERCEPT_FUNCTION(dispatch_group_async_f));
512  // We don't need to intercept pthread_workqueue_additem_np() to support the
513  // libdispatch API, but it helps us to debug the unsupported functions. Let's
514  // intercept it only during verbose runs.
515  if (flags()->verbosity >= 2) {
516    CHECK(INTERCEPT_FUNCTION(pthread_workqueue_additem_np));
517  }
518  // Normally CFStringCreateCopy should not copy constant CF strings.
519  // Replacing the default CFAllocator causes constant strings to be copied
520  // rather than just returned, which leads to bugs in big applications like
521  // Chromium and WebKit, see
522  // http://code.google.com/p/address-sanitizer/issues/detail?id=10
523  // Until this problem is fixed we need to check that the string is
524  // non-constant before calling CFStringCreateCopy.
525  CHECK(INTERCEPT_FUNCTION(CFStringCreateCopy));
526  // Some of the library functions call free() directly, so we have to
527  // intercept it.
528  CHECK(INTERCEPT_FUNCTION(free));
529  if (flags()->replace_cfallocator) {
530    CHECK(INTERCEPT_FUNCTION(__CFInitialize));
531  }
532}
533
534}  // namespace __asan
535
536#endif  // __APPLE__
537