asan_mac.cc revision 75b19ebf25af204cf209d108997272822241d6da
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) && 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
244extern "C"
245void asan_dispatch_call_block_and_release(void *block) {
246  GET_STACK_TRACE_HERE(kStackTraceMax);
247  asan_block_context_t *context = (asan_block_context_t*)block;
248  if (flags()->verbosity >= 2) {
249    Report("asan_dispatch_call_block_and_release(): "
250           "context: %p, pthread_self: %p\n",
251           block, pthread_self());
252  }
253  AsanThread *t = asanThreadRegistry().GetCurrent();
254  if (!t) {
255    t = AsanThread::Create(context->parent_tid, 0, 0, &stack);
256    asanThreadRegistry().RegisterThread(t);
257    t->Init();
258    asanThreadRegistry().SetCurrent(t);
259  }
260  // Call the original dispatcher for the block.
261  context->func(context->block);
262  asan_free(context, &stack);
263}
264
265}  // namespace __asan
266
267using namespace __asan;  // NOLINT
268
269// Wrap |ctxt| and |func| into an asan_block_context_t.
270// The caller retains control of the allocated context.
271extern "C"
272asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
273                                         AsanStackTrace *stack) {
274  asan_block_context_t *asan_ctxt =
275      (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
276  asan_ctxt->block = ctxt;
277  asan_ctxt->func = func;
278  asan_ctxt->parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid();
279  return asan_ctxt;
280}
281
282// TODO(glider): can we reduce code duplication by introducing a macro?
283INTERCEPTOR(void, dispatch_async_f, dispatch_queue_t dq, void *ctxt,
284                                    dispatch_function_t func) {
285  GET_STACK_TRACE_HERE(kStackTraceMax);
286  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
287  if (flags()->verbosity >= 2) {
288    Report("dispatch_async_f(): context: %p, pthread_self: %p\n",
289        asan_ctxt, pthread_self());
290    PRINT_CURRENT_STACK();
291  }
292  return REAL(dispatch_async_f)(dq, (void*)asan_ctxt,
293                                asan_dispatch_call_block_and_release);
294}
295
296INTERCEPTOR(void, dispatch_sync_f, dispatch_queue_t dq, void *ctxt,
297                                   dispatch_function_t func) {
298  GET_STACK_TRACE_HERE(kStackTraceMax);
299  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
300  if (flags()->verbosity >= 2) {
301    Report("dispatch_sync_f(): context: %p, pthread_self: %p\n",
302        asan_ctxt, pthread_self());
303    PRINT_CURRENT_STACK();
304  }
305  return REAL(dispatch_sync_f)(dq, (void*)asan_ctxt,
306                               asan_dispatch_call_block_and_release);
307}
308
309INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
310                                    dispatch_queue_t dq, void *ctxt,
311                                    dispatch_function_t func) {
312  GET_STACK_TRACE_HERE(kStackTraceMax);
313  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
314  if (flags()->verbosity >= 2) {
315    Report("dispatch_after_f: %p\n", asan_ctxt);
316    PRINT_CURRENT_STACK();
317  }
318  return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
319                                asan_dispatch_call_block_and_release);
320}
321
322INTERCEPTOR(void, dispatch_barrier_async_f, dispatch_queue_t dq, void *ctxt,
323                                            dispatch_function_t func) {
324  GET_STACK_TRACE_HERE(kStackTraceMax);
325  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
326  if (flags()->verbosity >= 2) {
327    Report("dispatch_barrier_async_f(): context: %p, pthread_self: %p\n",
328           asan_ctxt, pthread_self());
329    PRINT_CURRENT_STACK();
330  }
331  REAL(dispatch_barrier_async_f)(dq, (void*)asan_ctxt,
332                                 asan_dispatch_call_block_and_release);
333}
334
335INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
336                                          dispatch_queue_t dq, void *ctxt,
337                                          dispatch_function_t func) {
338  GET_STACK_TRACE_HERE(kStackTraceMax);
339  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
340  if (flags()->verbosity >= 2) {
341    Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
342           asan_ctxt, pthread_self());
343    PRINT_CURRENT_STACK();
344  }
345  REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
346                               asan_dispatch_call_block_and_release);
347}
348
349// The following stuff has been extremely helpful while looking for the
350// unhandled functions that spawned jobs on Chromium shutdown. If the verbosity
351// level is 2 or greater, we wrap pthread_workqueue_additem_np() in order to
352// find the points of worker thread creation (each of such threads may be used
353// to run several tasks, that's why this is not enough to support the whole
354// libdispatch API.
355extern "C"
356void *wrap_workitem_func(void *arg) {
357  if (flags()->verbosity >= 2) {
358    Report("wrap_workitem_func: %p, pthread_self: %p\n", arg, pthread_self());
359  }
360  asan_block_context_t *ctxt = (asan_block_context_t*)arg;
361  worker_t fn = (worker_t)(ctxt->func);
362  void *result =  fn(ctxt->block);
363  GET_STACK_TRACE_HERE(kStackTraceMax);
364  asan_free(arg, &stack);
365  return result;
366}
367
368INTERCEPTOR(int, pthread_workqueue_additem_np, pthread_workqueue_t workq,
369    void *(*workitem_func)(void *), void * workitem_arg,
370    pthread_workitem_handle_t * itemhandlep, unsigned int *gencountp) {
371  GET_STACK_TRACE_HERE(kStackTraceMax);
372  asan_block_context_t *asan_ctxt =
373      (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), &stack);
374  asan_ctxt->block = workitem_arg;
375  asan_ctxt->func = (dispatch_function_t)workitem_func;
376  asan_ctxt->parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid();
377  if (flags()->verbosity >= 2) {
378    Report("pthread_workqueue_additem_np: %p\n", asan_ctxt);
379    PRINT_CURRENT_STACK();
380  }
381  return REAL(pthread_workqueue_additem_np)(workq, wrap_workitem_func,
382                                            asan_ctxt, itemhandlep,
383                                            gencountp);
384}
385
386// See http://opensource.apple.com/source/CF/CF-635.15/CFString.c
387int __CFStrIsConstant(CFStringRef str) {
388  CFRuntimeBase *base = (CFRuntimeBase*)str;
389#if __LP64__
390  return base->_rc == 0;
391#else
392  return (base->_cfinfo[CF_RC_BITS]) == 0;
393#endif
394}
395
396INTERCEPTOR(CFStringRef, CFStringCreateCopy, CFAllocatorRef alloc,
397                                             CFStringRef str) {
398  if (__CFStrIsConstant(str)) {
399    return str;
400  } else {
401    return REAL(CFStringCreateCopy)(alloc, str);
402  }
403}
404
405DECLARE_REAL_AND_INTERCEPTOR(void, free, void *ptr)
406
407extern "C"
408void __CFInitialize();
409DECLARE_REAL_AND_INTERCEPTOR(void, __CFInitialize)
410
411namespace __asan {
412
413void InitializeMacInterceptors() {
414  CHECK(INTERCEPT_FUNCTION(dispatch_async_f));
415  CHECK(INTERCEPT_FUNCTION(dispatch_sync_f));
416  CHECK(INTERCEPT_FUNCTION(dispatch_after_f));
417  CHECK(INTERCEPT_FUNCTION(dispatch_barrier_async_f));
418  CHECK(INTERCEPT_FUNCTION(dispatch_group_async_f));
419  // We don't need to intercept pthread_workqueue_additem_np() to support the
420  // libdispatch API, but it helps us to debug the unsupported functions. Let's
421  // intercept it only during verbose runs.
422  if (flags()->verbosity >= 2) {
423    CHECK(INTERCEPT_FUNCTION(pthread_workqueue_additem_np));
424  }
425  // Normally CFStringCreateCopy should not copy constant CF strings.
426  // Replacing the default CFAllocator causes constant strings to be copied
427  // rather than just returned, which leads to bugs in big applications like
428  // Chromium and WebKit, see
429  // http://code.google.com/p/address-sanitizer/issues/detail?id=10
430  // Until this problem is fixed we need to check that the string is
431  // non-constant before calling CFStringCreateCopy.
432  CHECK(INTERCEPT_FUNCTION(CFStringCreateCopy));
433  // Some of the library functions call free() directly, so we have to
434  // intercept it.
435  CHECK(INTERCEPT_FUNCTION(free));
436  if (flags()->replace_cfallocator) {
437    CHECK(INTERCEPT_FUNCTION(__CFInitialize));
438  }
439}
440
441}  // namespace __asan
442
443#endif  // __APPLE__
444