asan_mac.cc revision 2483ce3e635515d907c0cd8c97db315142fb28db
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
244// For use by only those functions that allocated the context via
245// alloc_asan_context().
246extern "C"
247void asan_dispatch_call_block_and_release(void *block) {
248  GET_STACK_TRACE_HERE(kStackTraceMax);
249  asan_block_context_t *context = (asan_block_context_t*)block;
250  if (flags()->verbosity >= 2) {
251    Report("asan_dispatch_call_block_and_release(): "
252           "context: %p, pthread_self: %p\n",
253           block, pthread_self());
254  }
255  AsanThread *t = asanThreadRegistry().GetCurrent();
256  if (!t) {
257    t = AsanThread::Create(context->parent_tid, 0, 0, &stack);
258    asanThreadRegistry().RegisterThread(t);
259    t->Init();
260    asanThreadRegistry().SetCurrent(t);
261  }
262  // Call the original dispatcher for the block.
263  context->func(context->block);
264  asan_free(context, &stack);
265}
266
267}  // namespace __asan
268
269using namespace __asan;  // NOLINT
270
271// Wrap |ctxt| and |func| into an asan_block_context_t.
272// The caller retains control of the allocated context.
273extern "C"
274asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
275                                         AsanStackTrace *stack) {
276  asan_block_context_t *asan_ctxt =
277      (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
278  asan_ctxt->block = ctxt;
279  asan_ctxt->func = func;
280  asan_ctxt->parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid();
281  return asan_ctxt;
282}
283
284// Define interceptor for dispatch_*_f function with the three most common
285// parameters: dispatch_queue_t, context, dispatch_function_t.
286#define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f)                                \
287  INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt,            \
288                                  dispatch_function_t func) {                 \
289    GET_STACK_TRACE_HERE(kStackTraceMax);                                     \
290    asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
291    if (flags()->verbosity >= 2) {                                            \
292      Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n",             \
293             asan_ctxt, pthread_self());                                      \
294       PRINT_CURRENT_STACK();                                                 \
295     }                                                                        \
296     return REAL(dispatch_x_f)(dq, (void*)asan_ctxt,                          \
297                               asan_dispatch_call_block_and_release);         \
298   }
299
300INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
301INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
302INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
303
304INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
305                                    dispatch_queue_t dq, void *ctxt,
306                                    dispatch_function_t func) {
307  GET_STACK_TRACE_HERE(kStackTraceMax);
308  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
309  if (flags()->verbosity >= 2) {
310    Report("dispatch_after_f: %p\n", asan_ctxt);
311    PRINT_CURRENT_STACK();
312  }
313  return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
314                                asan_dispatch_call_block_and_release);
315}
316
317#if MAC_INTERPOSE_FUNCTIONS
318// dispatch_async and TODO tailcall the corresponding dispatch_*_f functions.
319// When wrapping functions with mach_override, they are intercepted
320// automatically. But with dylib interposition this does not work, because the
321// calls within the same library are not interposed.
322// Therefore we need to re-implement dispatch_async and friends.
323
324// See dispatch/dispatch.h.
325#define DISPATCH_TIME_FOREVER (~0ull)
326typedef void (^dispatch_block_t)(void);
327
328// See
329// http://www.opensource.apple.com/source/libdispatch/libdispatch-228.18/src/init.c
330// for the implementation of _dispatch_call_block_copy_and_release().
331static void _dispatch_call_block_and_release(void *block) {
332  void (^b)(void) = (dispatch_block_t)block;
333  b();
334  _Block_release(b);
335}
336
337// See
338// http://www.opensource.apple.com/source/libdispatch/libdispatch-228.18/src/internal.h
339#define fastpath(x) ((typeof(x))__builtin_expect((long)(x), ~0l))
340
341// See
342// http://www.opensource.apple.com/source/libdispatch/libdispatch-228.18/src/init.c
343static dispatch_block_t _dispatch_Block_copy(dispatch_block_t db) {
344  dispatch_block_t rval;
345  if (fastpath(db)) {
346    while (!fastpath(rval = Block_copy(db))) {
347      sleep(1);
348    }
349    return rval;
350  }
351  CHECK(0 && "NULL was passed where a block should have been");
352  return (dispatch_block_t)NULL;  // Unreachable.
353}
354
355// See
356// http://www.opensource.apple.com/source/libdispatch/libdispatch-228.18/src/queue.c
357// for the implementation of dispatch_async(), dispatch_sync(),
358// dispatch_after().
359INTERCEPTOR(void, dispatch_async,
360            dispatch_queue_t dq, dispatch_block_t work) {
361  WRAP(dispatch_async_f)(dq, _dispatch_Block_copy(work),
362                         _dispatch_call_block_and_release);
363}
364
365INTERCEPTOR(void, dispatch_after,
366            dispatch_time_t when, dispatch_queue_t queue,
367            dispatch_block_t work) {
368  if (when == DISPATCH_TIME_FOREVER) {
369    CHECK(0 && "dispatch_after() called with 'when' == infinity");
370    return;  // Unreachable.
371  }
372  WRAP(dispatch_after_f)(when, queue, _dispatch_Block_copy(work),
373                         _dispatch_call_block_and_release);
374}
375#endif
376
377INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
378                                          dispatch_queue_t dq, void *ctxt,
379                                          dispatch_function_t func) {
380  GET_STACK_TRACE_HERE(kStackTraceMax);
381  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
382  if (flags()->verbosity >= 2) {
383    Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
384           asan_ctxt, pthread_self());
385    PRINT_CURRENT_STACK();
386  }
387  REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
388                               asan_dispatch_call_block_and_release);
389}
390
391// The following stuff has been extremely helpful while looking for the
392// unhandled functions that spawned jobs on Chromium shutdown. If the verbosity
393// level is 2 or greater, we wrap pthread_workqueue_additem_np() in order to
394// find the points of worker thread creation (each of such threads may be used
395// to run several tasks, that's why this is not enough to support the whole
396// libdispatch API.
397extern "C"
398void *wrap_workitem_func(void *arg) {
399  if (flags()->verbosity >= 2) {
400    Report("wrap_workitem_func: %p, pthread_self: %p\n", arg, pthread_self());
401  }
402  asan_block_context_t *ctxt = (asan_block_context_t*)arg;
403  worker_t fn = (worker_t)(ctxt->func);
404  void *result =  fn(ctxt->block);
405  GET_STACK_TRACE_HERE(kStackTraceMax);
406  asan_free(arg, &stack);
407  return result;
408}
409
410INTERCEPTOR(int, pthread_workqueue_additem_np, pthread_workqueue_t workq,
411    void *(*workitem_func)(void *), void * workitem_arg,
412    pthread_workitem_handle_t * itemhandlep, unsigned int *gencountp) {
413  GET_STACK_TRACE_HERE(kStackTraceMax);
414  asan_block_context_t *asan_ctxt =
415      (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), &stack);
416  asan_ctxt->block = workitem_arg;
417  asan_ctxt->func = (dispatch_function_t)workitem_func;
418  asan_ctxt->parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid();
419  if (flags()->verbosity >= 2) {
420    Report("pthread_workqueue_additem_np: %p\n", asan_ctxt);
421    PRINT_CURRENT_STACK();
422  }
423  return REAL(pthread_workqueue_additem_np)(workq, wrap_workitem_func,
424                                            asan_ctxt, itemhandlep,
425                                            gencountp);
426}
427
428// See http://opensource.apple.com/source/CF/CF-635.15/CFString.c
429int __CFStrIsConstant(CFStringRef str) {
430  CFRuntimeBase *base = (CFRuntimeBase*)str;
431#if __LP64__
432  return base->_rc == 0;
433#else
434  return (base->_cfinfo[CF_RC_BITS]) == 0;
435#endif
436}
437
438INTERCEPTOR(CFStringRef, CFStringCreateCopy, CFAllocatorRef alloc,
439                                             CFStringRef str) {
440  if (__CFStrIsConstant(str)) {
441    return str;
442  } else {
443    return REAL(CFStringCreateCopy)(alloc, str);
444  }
445}
446
447DECLARE_REAL_AND_INTERCEPTOR(void, free, void *ptr)
448
449DECLARE_REAL_AND_INTERCEPTOR(void, __CFInitialize)
450
451namespace __asan {
452
453void InitializeMacInterceptors() {
454  CHECK(INTERCEPT_FUNCTION(dispatch_async_f));
455  CHECK(INTERCEPT_FUNCTION(dispatch_sync_f));
456  CHECK(INTERCEPT_FUNCTION(dispatch_after_f));
457  CHECK(INTERCEPT_FUNCTION(dispatch_barrier_async_f));
458  CHECK(INTERCEPT_FUNCTION(dispatch_group_async_f));
459  // We don't need to intercept pthread_workqueue_additem_np() to support the
460  // libdispatch API, but it helps us to debug the unsupported functions. Let's
461  // intercept it only during verbose runs.
462  if (flags()->verbosity >= 2) {
463    CHECK(INTERCEPT_FUNCTION(pthread_workqueue_additem_np));
464  }
465  // Normally CFStringCreateCopy should not copy constant CF strings.
466  // Replacing the default CFAllocator causes constant strings to be copied
467  // rather than just returned, which leads to bugs in big applications like
468  // Chromium and WebKit, see
469  // http://code.google.com/p/address-sanitizer/issues/detail?id=10
470  // Until this problem is fixed we need to check that the string is
471  // non-constant before calling CFStringCreateCopy.
472  CHECK(INTERCEPT_FUNCTION(CFStringCreateCopy));
473  // Some of the library functions call free() directly, so we have to
474  // intercept it.
475  CHECK(INTERCEPT_FUNCTION(free));
476  if (flags()->replace_cfallocator) {
477    CHECK(INTERCEPT_FUNCTION(__CFInitialize));
478  }
479}
480
481}  // namespace __asan
482
483#endif  // __APPLE__
484