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