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