asan_mac.cc revision fe6d91684bcda766593800f6307233f1a33d31f6
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 SANITIZER_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  // SANITIZER_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, bool fast) {
164  (void)fast;
165  stack->size = 0;
166  stack->trace[0] = pc;
167  if ((max_s) > 1) {
168    stack->max_size = max_s;
169    if (!asan_inited) return;
170    if (AsanThread *t = asanThreadRegistry().GetCurrent())
171      stack->FastUnwindStack(pc, bp, t->stack_top(), t->stack_bottom());
172  }
173}
174
175void ClearShadowMemoryForContext(void *context) {
176  UNIMPLEMENTED();
177}
178
179// The range of pages to be used for escape islands.
180// TODO(glider): instead of mapping a fixed range we must find a range of
181// unmapped pages in vmmap and take them.
182// These constants were chosen empirically and may not work if the shadow
183// memory layout changes. Unfortunately they do necessarily depend on
184// kHighMemBeg or kHighMemEnd.
185static void *island_allocator_pos = 0;
186
187#if SANITIZER_WORDSIZE == 32
188# define kIslandEnd (0xffdf0000 - GetPageSizeCached())
189# define kIslandBeg (kIslandEnd - 256 * GetPageSizeCached())
190#else
191# define kIslandEnd (0x7fffffdf0000 - GetPageSizeCached())
192# define kIslandBeg (kIslandEnd - 256 * GetPageSizeCached())
193#endif
194
195extern "C"
196mach_error_t __interception_allocate_island(void **ptr,
197                                            uptr unused_size,
198                                            void *unused_hint) {
199  if (!island_allocator_pos) {
200    island_allocator_pos =
201        internal_mmap((void*)kIslandBeg, kIslandEnd - kIslandBeg,
202                      PROT_READ | PROT_WRITE | PROT_EXEC,
203                      MAP_PRIVATE | MAP_ANON | MAP_FIXED,
204                      -1, 0);
205    if (island_allocator_pos != (void*)kIslandBeg) {
206      return KERN_NO_SPACE;
207    }
208    if (flags()->verbosity) {
209      Report("Mapped pages %p--%p for branch islands.\n",
210             (void*)kIslandBeg, (void*)kIslandEnd);
211    }
212    // Should not be very performance-critical.
213    internal_memset(island_allocator_pos, 0xCC, kIslandEnd - kIslandBeg);
214  };
215  *ptr = island_allocator_pos;
216  island_allocator_pos = (char*)island_allocator_pos + GetPageSizeCached();
217  if (flags()->verbosity) {
218    Report("Branch island allocated at %p\n", *ptr);
219  }
220  return err_none;
221}
222
223extern "C"
224mach_error_t __interception_deallocate_island(void *ptr) {
225  // Do nothing.
226  // TODO(glider): allow to free and reuse the island memory.
227  return err_none;
228}
229
230// Support for the following functions from libdispatch on Mac OS:
231//   dispatch_async_f()
232//   dispatch_async()
233//   dispatch_sync_f()
234//   dispatch_sync()
235//   dispatch_after_f()
236//   dispatch_after()
237//   dispatch_group_async_f()
238//   dispatch_group_async()
239// TODO(glider): libdispatch API contains other functions that we don't support
240// yet.
241//
242// dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
243// they can cause jobs to run on a thread different from the current one.
244// TODO(glider): if so, we need a test for this (otherwise we should remove
245// them).
246//
247// The following functions use dispatch_barrier_async_f() (which isn't a library
248// function but is exported) and are thus supported:
249//   dispatch_source_set_cancel_handler_f()
250//   dispatch_source_set_cancel_handler()
251//   dispatch_source_set_event_handler_f()
252//   dispatch_source_set_event_handler()
253//
254// The reference manual for Grand Central Dispatch is available at
255//   http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
256// The implementation details are at
257//   http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
258
259typedef void* pthread_workqueue_t;
260typedef void* pthread_workitem_handle_t;
261
262typedef void* dispatch_group_t;
263typedef void* dispatch_queue_t;
264typedef void* dispatch_source_t;
265typedef u64 dispatch_time_t;
266typedef void (*dispatch_function_t)(void *block);
267typedef void* (*worker_t)(void *block);
268
269// A wrapper for the ObjC blocks used to support libdispatch.
270typedef struct {
271  void *block;
272  dispatch_function_t func;
273  u32 parent_tid;
274} asan_block_context_t;
275
276// We use extern declarations of libdispatch functions here instead
277// of including <dispatch/dispatch.h>. This header is not present on
278// Mac OS X Leopard and eariler, and although we don't expect ASan to
279// work on legacy systems, it's bad to break the build of
280// LLVM compiler-rt there.
281extern "C" {
282void dispatch_async_f(dispatch_queue_t dq, void *ctxt,
283                      dispatch_function_t func);
284void dispatch_sync_f(dispatch_queue_t dq, void *ctxt,
285                     dispatch_function_t func);
286void dispatch_after_f(dispatch_time_t when, dispatch_queue_t dq, void *ctxt,
287                      dispatch_function_t func);
288void dispatch_barrier_async_f(dispatch_queue_t dq, void *ctxt,
289                              dispatch_function_t func);
290void dispatch_group_async_f(dispatch_group_t group, dispatch_queue_t dq,
291                            void *ctxt, dispatch_function_t func);
292int pthread_workqueue_additem_np(pthread_workqueue_t workq,
293    void *(*workitem_func)(void *), void * workitem_arg,
294    pthread_workitem_handle_t * itemhandlep, unsigned int *gencountp);
295}  // extern "C"
296
297static ALWAYS_INLINE
298void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
299  AsanThread *t = asanThreadRegistry().GetCurrent();
300  if (!t) {
301    t = AsanThread::Create(parent_tid, 0, 0, stack);
302    asanThreadRegistry().RegisterThread(t);
303    t->Init();
304    asanThreadRegistry().SetCurrent(t);
305  }
306}
307
308// For use by only those functions that allocated the context via
309// alloc_asan_context().
310extern "C"
311void asan_dispatch_call_block_and_release(void *block) {
312  GET_STACK_TRACE_THREAD;
313  asan_block_context_t *context = (asan_block_context_t*)block;
314  if (flags()->verbosity >= 2) {
315    Report("asan_dispatch_call_block_and_release(): "
316           "context: %p, pthread_self: %p\n",
317           block, pthread_self());
318  }
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);
323}
324
325}  // namespace __asan
326
327using namespace __asan;  // NOLINT
328
329// Wrap |ctxt| and |func| into an asan_block_context_t.
330// The caller retains control of the allocated context.
331extern "C"
332asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
333                                         StackTrace *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 = asanThreadRegistry().GetCurrentTidOrInvalid();
339  return asan_ctxt;
340}
341
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 (flags()->verbosity >= 2) {                                            \
350      Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n",             \
351             asan_ctxt, pthread_self());                                      \
352       PRINT_CURRENT_STACK();                                                 \
353     }                                                                        \
354     return REAL(dispatch_x_f)(dq, (void*)asan_ctxt,                          \
355                               asan_dispatch_call_block_and_release);         \
356  }
357
358INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
359INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
360INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
361
362INTERCEPTOR(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 (flags()->verbosity >= 2) {
368    Report("dispatch_after_f: %p\n", asan_ctxt);
369    PRINT_CURRENT_STACK();
370  }
371  return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
372                                asan_dispatch_call_block_and_release);
373}
374
375INTERCEPTOR(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 (flags()->verbosity >= 2) {
381    Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
382           asan_ctxt, pthread_self());
383    PRINT_CURRENT_STACK();
384  }
385  REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
386                               asan_dispatch_call_block_and_release);
387}
388
389#if MAC_INTERPOSE_FUNCTIONS && !defined(MISSING_BLOCKS_SUPPORT)
390// dispatch_async, dispatch_group_async and others tailcall the corresponding
391// dispatch_*_f functions. When wrapping functions with mach_override, those
392// dispatch_*_f are intercepted automatically. But with dylib interposition
393// this does not work, because the calls within the same library are not
394// interposed.
395// Therefore we need to re-implement dispatch_async and friends.
396
397extern "C" {
398// FIXME: consolidate these declarations with asan_intercepted_functions.h.
399void dispatch_async(dispatch_queue_t dq, void(^work)(void));
400void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
401                          void(^work)(void));
402void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
403                    void(^work)(void));
404void dispatch_source_set_cancel_handler(dispatch_source_t ds,
405                                        void(^work)(void));
406void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
407}
408
409#define GET_ASAN_BLOCK(work) \
410  void (^asan_block)(void);  \
411  int parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid(); \
412  asan_block = ^(void) { \
413    GET_STACK_TRACE_THREAD; \
414    asan_register_worker_thread(parent_tid, &stack); \
415    work(); \
416  }
417
418INTERCEPTOR(void, dispatch_async,
419            dispatch_queue_t dq, void(^work)(void)) {
420  GET_ASAN_BLOCK(work);
421  REAL(dispatch_async)(dq, asan_block);
422}
423
424INTERCEPTOR(void, dispatch_group_async,
425            dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) {
426  GET_ASAN_BLOCK(work);
427  REAL(dispatch_group_async)(dg, dq, asan_block);
428}
429
430INTERCEPTOR(void, dispatch_after,
431            dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) {
432  GET_ASAN_BLOCK(work);
433  REAL(dispatch_after)(when, queue, asan_block);
434}
435
436INTERCEPTOR(void, dispatch_source_set_cancel_handler,
437            dispatch_source_t ds, void(^work)(void)) {
438  GET_ASAN_BLOCK(work);
439  REAL(dispatch_source_set_cancel_handler)(ds, asan_block);
440}
441
442INTERCEPTOR(void, dispatch_source_set_event_handler,
443            dispatch_source_t ds, void(^work)(void)) {
444  GET_ASAN_BLOCK(work);
445  REAL(dispatch_source_set_event_handler)(ds, asan_block);
446}
447#endif
448
449// The following stuff has been extremely helpful while looking for the
450// unhandled functions that spawned jobs on Chromium shutdown. If the verbosity
451// level is 2 or greater, we wrap pthread_workqueue_additem_np() in order to
452// find the points of worker thread creation (each of such threads may be used
453// to run several tasks, that's why this is not enough to support the whole
454// libdispatch API.
455extern "C"
456void *wrap_workitem_func(void *arg) {
457  if (flags()->verbosity >= 2) {
458    Report("wrap_workitem_func: %p, pthread_self: %p\n", arg, pthread_self());
459  }
460  asan_block_context_t *ctxt = (asan_block_context_t*)arg;
461  worker_t fn = (worker_t)(ctxt->func);
462  void *result =  fn(ctxt->block);
463  GET_STACK_TRACE_THREAD;
464  asan_free(arg, &stack, FROM_MALLOC);
465  return result;
466}
467
468INTERCEPTOR(int, pthread_workqueue_additem_np, pthread_workqueue_t workq,
469    void *(*workitem_func)(void *), void * workitem_arg,
470    pthread_workitem_handle_t * itemhandlep, unsigned int *gencountp) {
471  GET_STACK_TRACE_THREAD;
472  asan_block_context_t *asan_ctxt =
473      (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), &stack);
474  asan_ctxt->block = workitem_arg;
475  asan_ctxt->func = (dispatch_function_t)workitem_func;
476  asan_ctxt->parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid();
477  if (flags()->verbosity >= 2) {
478    Report("pthread_workqueue_additem_np: %p\n", asan_ctxt);
479    PRINT_CURRENT_STACK();
480  }
481  return REAL(pthread_workqueue_additem_np)(workq, wrap_workitem_func,
482                                            asan_ctxt, itemhandlep,
483                                            gencountp);
484}
485
486// See http://opensource.apple.com/source/CF/CF-635.15/CFString.c
487int __CFStrIsConstant(CFStringRef str) {
488  CFRuntimeBase *base = (CFRuntimeBase*)str;
489#if __LP64__
490  return base->_rc == 0;
491#else
492  return (base->_cfinfo[CF_RC_BITS]) == 0;
493#endif
494}
495
496INTERCEPTOR(CFStringRef, CFStringCreateCopy, CFAllocatorRef alloc,
497                                             CFStringRef str) {
498  if (__CFStrIsConstant(str)) {
499    return str;
500  } else {
501    return REAL(CFStringCreateCopy)(alloc, str);
502  }
503}
504
505DECLARE_REAL_AND_INTERCEPTOR(void, free, void *ptr)
506
507DECLARE_REAL_AND_INTERCEPTOR(void, __CFInitialize, void)
508
509namespace __asan {
510
511void InitializeMacInterceptors() {
512  CHECK(INTERCEPT_FUNCTION(dispatch_async_f));
513  CHECK(INTERCEPT_FUNCTION(dispatch_sync_f));
514  CHECK(INTERCEPT_FUNCTION(dispatch_after_f));
515  CHECK(INTERCEPT_FUNCTION(dispatch_barrier_async_f));
516  CHECK(INTERCEPT_FUNCTION(dispatch_group_async_f));
517  // We don't need to intercept pthread_workqueue_additem_np() to support the
518  // libdispatch API, but it helps us to debug the unsupported functions. Let's
519  // intercept it only during verbose runs.
520  if (flags()->verbosity >= 2) {
521    CHECK(INTERCEPT_FUNCTION(pthread_workqueue_additem_np));
522  }
523  // Normally CFStringCreateCopy should not copy constant CF strings.
524  // Replacing the default CFAllocator causes constant strings to be copied
525  // rather than just returned, which leads to bugs in big applications like
526  // Chromium and WebKit, see
527  // http://code.google.com/p/address-sanitizer/issues/detail?id=10
528  // Until this problem is fixed we need to check that the string is
529  // non-constant before calling CFStringCreateCopy.
530  CHECK(INTERCEPT_FUNCTION(CFStringCreateCopy));
531  // Some of the library functions call free() directly, so we have to
532  // intercept it.
533  CHECK(INTERCEPT_FUNCTION(free));
534  if (flags()->replace_cfallocator) {
535    CHECK(INTERCEPT_FUNCTION(__CFInitialize));
536  }
537}
538
539}  // namespace __asan
540
541#endif  // __APPLE__
542