asan_mac.cc revision 3dbeabb3446f203156ae03d957de9bdf50933ae4
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_mapping.h"
20#include "asan_stack.h"
21#include "asan_thread.h"
22#include "asan_thread_registry.h"
23#include "sanitizer_common/sanitizer_libc.h"
24
25#include <crt_externs.h>  // for _NSGetEnviron
26#include <mach-o/dyld.h>
27#include <mach-o/loader.h>
28#include <sys/mman.h>
29#include <sys/resource.h>
30#include <sys/sysctl.h>
31#include <sys/ucontext.h>
32#include <pthread.h>
33#include <fcntl.h>
34#include <unistd.h>
35#include <libkern/OSAtomic.h>
36#include <CoreFoundation/CFString.h>
37
38namespace __asan {
39
40void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
41  ucontext_t *ucontext = (ucontext_t*)context;
42# if __WORDSIZE == 64
43  *pc = ucontext->uc_mcontext->__ss.__rip;
44  *bp = ucontext->uc_mcontext->__ss.__rbp;
45  *sp = ucontext->uc_mcontext->__ss.__rsp;
46# else
47  *pc = ucontext->uc_mcontext->__ss.__eip;
48  *bp = ucontext->uc_mcontext->__ss.__ebp;
49  *sp = ucontext->uc_mcontext->__ss.__esp;
50# endif  // __WORDSIZE
51}
52
53enum {
54  MACOS_VERSION_UNKNOWN = 0,
55  MACOS_VERSION_LEOPARD,
56  MACOS_VERSION_SNOW_LEOPARD,
57  MACOS_VERSION_LION,
58};
59
60static int GetMacosVersion() {
61  int mib[2] = { CTL_KERN, KERN_OSRELEASE };
62  char version[100];
63  uptr len = 0, maxlen = sizeof(version) / sizeof(version[0]);
64  for (int i = 0; i < maxlen; i++) version[i] = '\0';
65  // Get the version length.
66  CHECK(sysctl(mib, 2, 0, &len, 0, 0) != -1);
67  CHECK(len < maxlen);
68  CHECK(sysctl(mib, 2, version, &len, 0, 0) != -1);
69  switch (version[0]) {
70    case '9': return MACOS_VERSION_LEOPARD;
71    case '1': {
72      switch (version[1]) {
73        case '0': return MACOS_VERSION_SNOW_LEOPARD;
74        case '1': return MACOS_VERSION_LION;
75        default: return MACOS_VERSION_UNKNOWN;
76      }
77    }
78    default: return MACOS_VERSION_UNKNOWN;
79  }
80}
81
82bool PlatformHasDifferentMemcpyAndMemmove() {
83  // On OS X 10.7 memcpy() and memmove() are both resolved
84  // into memmove$VARIANT$sse42.
85  // See also http://code.google.com/p/address-sanitizer/issues/detail?id=34.
86  // TODO(glider): need to check dynamically that memcpy() and memmove() are
87  // actually the same function.
88  return GetMacosVersion() == MACOS_VERSION_SNOW_LEOPARD;
89}
90
91// No-op. Mac does not support static linkage anyway.
92void *AsanDoesNotSupportStaticLinkage() {
93  return 0;
94}
95
96bool AsanInterceptsSignal(int signum) {
97  return (signum == SIGSEGV || signum == SIGBUS) && FLAG_handle_segv;
98}
99
100void *AsanMmapFixedNoReserve(uptr fixed_addr, uptr size) {
101  return internal_mmap((void*)fixed_addr, size,
102                      PROT_READ | PROT_WRITE,
103                      MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE,
104                      0, 0);
105}
106
107void *AsanMprotect(uptr fixed_addr, uptr size) {
108  return internal_mmap((void*)fixed_addr, size,
109                       PROT_NONE,
110                       MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE,
111                       0, 0);
112}
113
114AsanLock::AsanLock(LinkerInitialized) {
115  // We assume that OS_SPINLOCK_INIT is zero
116}
117
118void AsanLock::Lock() {
119  CHECK(sizeof(OSSpinLock) <= sizeof(opaque_storage_));
120  CHECK(OS_SPINLOCK_INIT == 0);
121  CHECK(owner_ != (uptr)pthread_self());
122  OSSpinLockLock((OSSpinLock*)&opaque_storage_);
123  CHECK(!owner_);
124  owner_ = (uptr)pthread_self();
125}
126
127void AsanLock::Unlock() {
128  CHECK(owner_ == (uptr)pthread_self());
129  owner_ = 0;
130  OSSpinLockUnlock((OSSpinLock*)&opaque_storage_);
131}
132
133void AsanStackTrace::GetStackTrace(uptr max_s, uptr pc, uptr bp) {
134  size = 0;
135  trace[0] = pc;
136  if ((max_s) > 1) {
137    max_size = max_s;
138    FastUnwindStack(pc, bp);
139  }
140}
141
142// The range of pages to be used for escape islands.
143// TODO(glider): instead of mapping a fixed range we must find a range of
144// unmapped pages in vmmap and take them.
145// These constants were chosen empirically and may not work if the shadow
146// memory layout changes. Unfortunately they do necessarily depend on
147// kHighMemBeg or kHighMemEnd.
148static void *island_allocator_pos = 0;
149
150#if __WORDSIZE == 32
151# define kIslandEnd (0xffdf0000 - kPageSize)
152# define kIslandBeg (kIslandEnd - 256 * kPageSize)
153#else
154# define kIslandEnd (0x7fffffdf0000 - kPageSize)
155# define kIslandBeg (kIslandEnd - 256 * kPageSize)
156#endif
157
158extern "C"
159mach_error_t __interception_allocate_island(void **ptr,
160                                            uptr unused_size,
161                                            void *unused_hint) {
162  if (!island_allocator_pos) {
163    island_allocator_pos =
164        internal_mmap((void*)kIslandBeg, kIslandEnd - kIslandBeg,
165                      PROT_READ | PROT_WRITE | PROT_EXEC,
166                      MAP_PRIVATE | MAP_ANON | MAP_FIXED,
167                      -1, 0);
168    if (island_allocator_pos != (void*)kIslandBeg) {
169      return KERN_NO_SPACE;
170    }
171    if (FLAG_v) {
172      Report("Mapped pages %p--%p for branch islands.\n",
173             (void*)kIslandBeg, (void*)kIslandEnd);
174    }
175    // Should not be very performance-critical.
176    internal_memset(island_allocator_pos, 0xCC, kIslandEnd - kIslandBeg);
177  };
178  *ptr = island_allocator_pos;
179  island_allocator_pos = (char*)island_allocator_pos + kPageSize;
180  if (FLAG_v) {
181    Report("Branch island allocated at %p\n", *ptr);
182  }
183  return err_none;
184}
185
186extern "C"
187mach_error_t __interception_deallocate_island(void *ptr) {
188  // Do nothing.
189  // TODO(glider): allow to free and reuse the island memory.
190  return err_none;
191}
192
193// Support for the following functions from libdispatch on Mac OS:
194//   dispatch_async_f()
195//   dispatch_async()
196//   dispatch_sync_f()
197//   dispatch_sync()
198//   dispatch_after_f()
199//   dispatch_after()
200//   dispatch_group_async_f()
201//   dispatch_group_async()
202// TODO(glider): libdispatch API contains other functions that we don't support
203// yet.
204//
205// dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
206// they can cause jobs to run on a thread different from the current one.
207// TODO(glider): if so, we need a test for this (otherwise we should remove
208// them).
209//
210// The following functions use dispatch_barrier_async_f() (which isn't a library
211// function but is exported) and are thus supported:
212//   dispatch_source_set_cancel_handler_f()
213//   dispatch_source_set_cancel_handler()
214//   dispatch_source_set_event_handler_f()
215//   dispatch_source_set_event_handler()
216//
217// The reference manual for Grand Central Dispatch is available at
218//   http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
219// The implementation details are at
220//   http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
221
222typedef void* pthread_workqueue_t;
223typedef void* pthread_workitem_handle_t;
224
225typedef void* dispatch_group_t;
226typedef void* dispatch_queue_t;
227typedef u64 dispatch_time_t;
228typedef void (*dispatch_function_t)(void *block);
229typedef void* (*worker_t)(void *block);
230
231// A wrapper for the ObjC blocks used to support libdispatch.
232typedef struct {
233  void *block;
234  dispatch_function_t func;
235  u32 parent_tid;
236} asan_block_context_t;
237
238// We use extern declarations of libdispatch functions here instead
239// of including <dispatch/dispatch.h>. This header is not present on
240// Mac OS X Leopard and eariler, and although we don't expect ASan to
241// work on legacy systems, it's bad to break the build of
242// LLVM compiler-rt there.
243extern "C" {
244void dispatch_async_f(dispatch_queue_t dq, void *ctxt,
245                      dispatch_function_t func);
246void dispatch_sync_f(dispatch_queue_t dq, void *ctxt,
247                     dispatch_function_t func);
248void dispatch_after_f(dispatch_time_t when, dispatch_queue_t dq, void *ctxt,
249                      dispatch_function_t func);
250void dispatch_barrier_async_f(dispatch_queue_t dq, void *ctxt,
251                              dispatch_function_t func);
252void dispatch_group_async_f(dispatch_group_t group, dispatch_queue_t dq,
253                            void *ctxt, dispatch_function_t func);
254int pthread_workqueue_additem_np(pthread_workqueue_t workq,
255    void *(*workitem_func)(void *), void * workitem_arg,
256    pthread_workitem_handle_t * itemhandlep, unsigned int *gencountp);
257}  // extern "C"
258
259extern "C"
260void asan_dispatch_call_block_and_release(void *block) {
261  GET_STACK_TRACE_HERE(kStackTraceMax);
262  asan_block_context_t *context = (asan_block_context_t*)block;
263  if (FLAG_v >= 2) {
264    Report("asan_dispatch_call_block_and_release(): "
265           "context: %p, pthread_self: %p\n",
266           block, pthread_self());
267  }
268  AsanThread *t = asanThreadRegistry().GetCurrent();
269  if (!t) {
270    t = AsanThread::Create(context->parent_tid, 0, 0, &stack);
271    asanThreadRegistry().RegisterThread(t);
272    t->Init();
273    asanThreadRegistry().SetCurrent(t);
274  }
275  // Call the original dispatcher for the block.
276  context->func(context->block);
277  asan_free(context, &stack);
278}
279
280}  // namespace __asan
281
282using namespace __asan;  // NOLINT
283
284// Wrap |ctxt| and |func| into an asan_block_context_t.
285// The caller retains control of the allocated context.
286extern "C"
287asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
288                                         AsanStackTrace *stack) {
289  asan_block_context_t *asan_ctxt =
290      (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
291  asan_ctxt->block = ctxt;
292  asan_ctxt->func = func;
293  asan_ctxt->parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid();
294  return asan_ctxt;
295}
296
297// TODO(glider): can we reduce code duplication by introducing a macro?
298INTERCEPTOR(void, dispatch_async_f, dispatch_queue_t dq, void *ctxt,
299                                    dispatch_function_t func) {
300  GET_STACK_TRACE_HERE(kStackTraceMax);
301  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
302  if (FLAG_v >= 2) {
303    Report("dispatch_async_f(): context: %p, pthread_self: %p\n",
304        asan_ctxt, pthread_self());
305    PRINT_CURRENT_STACK();
306  }
307  return REAL(dispatch_async_f)(dq, (void*)asan_ctxt,
308                                asan_dispatch_call_block_and_release);
309}
310
311INTERCEPTOR(void, dispatch_sync_f, dispatch_queue_t dq, void *ctxt,
312                                   dispatch_function_t func) {
313  GET_STACK_TRACE_HERE(kStackTraceMax);
314  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
315  if (FLAG_v >= 2) {
316    Report("dispatch_sync_f(): context: %p, pthread_self: %p\n",
317        asan_ctxt, pthread_self());
318    PRINT_CURRENT_STACK();
319  }
320  return REAL(dispatch_sync_f)(dq, (void*)asan_ctxt,
321                               asan_dispatch_call_block_and_release);
322}
323
324INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
325                                    dispatch_queue_t dq, void *ctxt,
326                                    dispatch_function_t func) {
327  GET_STACK_TRACE_HERE(kStackTraceMax);
328  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
329  if (FLAG_v >= 2) {
330    Report("dispatch_after_f: %p\n", asan_ctxt);
331    PRINT_CURRENT_STACK();
332  }
333  return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
334                                asan_dispatch_call_block_and_release);
335}
336
337INTERCEPTOR(void, dispatch_barrier_async_f, dispatch_queue_t dq, void *ctxt,
338                                            dispatch_function_t func) {
339  GET_STACK_TRACE_HERE(kStackTraceMax);
340  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
341  if (FLAG_v >= 2) {
342    Report("dispatch_barrier_async_f(): context: %p, pthread_self: %p\n",
343           asan_ctxt, pthread_self());
344    PRINT_CURRENT_STACK();
345  }
346  REAL(dispatch_barrier_async_f)(dq, (void*)asan_ctxt,
347                                 asan_dispatch_call_block_and_release);
348}
349
350INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
351                                          dispatch_queue_t dq, void *ctxt,
352                                          dispatch_function_t func) {
353  GET_STACK_TRACE_HERE(kStackTraceMax);
354  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
355  if (FLAG_v >= 2) {
356    Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
357           asan_ctxt, pthread_self());
358    PRINT_CURRENT_STACK();
359  }
360  REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
361                               asan_dispatch_call_block_and_release);
362}
363
364// The following stuff has been extremely helpful while looking for the
365// unhandled functions that spawned jobs on Chromium shutdown. If the verbosity
366// level is 2 or greater, we wrap pthread_workqueue_additem_np() in order to
367// find the points of worker thread creation (each of such threads may be used
368// to run several tasks, that's why this is not enough to support the whole
369// libdispatch API.
370extern "C"
371void *wrap_workitem_func(void *arg) {
372  if (FLAG_v >= 2) {
373    Report("wrap_workitem_func: %p, pthread_self: %p\n", arg, pthread_self());
374  }
375  asan_block_context_t *ctxt = (asan_block_context_t*)arg;
376  worker_t fn = (worker_t)(ctxt->func);
377  void *result =  fn(ctxt->block);
378  GET_STACK_TRACE_HERE(kStackTraceMax);
379  asan_free(arg, &stack);
380  return result;
381}
382
383INTERCEPTOR(int, pthread_workqueue_additem_np, pthread_workqueue_t workq,
384    void *(*workitem_func)(void *), void * workitem_arg,
385    pthread_workitem_handle_t * itemhandlep, unsigned int *gencountp) {
386  GET_STACK_TRACE_HERE(kStackTraceMax);
387  asan_block_context_t *asan_ctxt =
388      (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), &stack);
389  asan_ctxt->block = workitem_arg;
390  asan_ctxt->func = (dispatch_function_t)workitem_func;
391  asan_ctxt->parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid();
392  if (FLAG_v >= 2) {
393    Report("pthread_workqueue_additem_np: %p\n", asan_ctxt);
394    PRINT_CURRENT_STACK();
395  }
396  return REAL(pthread_workqueue_additem_np)(workq, wrap_workitem_func,
397                                            asan_ctxt, itemhandlep,
398                                            gencountp);
399}
400
401// CF_RC_BITS, the layout of CFRuntimeBase and __CFStrIsConstant are internal
402// and subject to change in further CoreFoundation versions. Apple does not
403// guarantee any binary compatibility from release to release.
404
405// See http://opensource.apple.com/source/CF/CF-635.15/CFInternal.h
406#if defined(__BIG_ENDIAN__)
407#define CF_RC_BITS 0
408#endif
409
410#if defined(__LITTLE_ENDIAN__)
411#define CF_RC_BITS 3
412#endif
413
414// See http://opensource.apple.com/source/CF/CF-635.15/CFRuntime.h
415typedef struct __CFRuntimeBase {
416  uptr _cfisa;
417  u8 _cfinfo[4];
418#if __LP64__
419  u32 _rc;
420#endif
421} CFRuntimeBase;
422
423// See http://opensource.apple.com/source/CF/CF-635.15/CFString.c
424int __CFStrIsConstant(CFStringRef str) {
425  CFRuntimeBase *base = (CFRuntimeBase*)str;
426#if __LP64__
427  return base->_rc == 0;
428#else
429  return (base->_cfinfo[CF_RC_BITS]) == 0;
430#endif
431}
432
433INTERCEPTOR(CFStringRef, CFStringCreateCopy, CFAllocatorRef alloc,
434                                             CFStringRef str) {
435  if (__CFStrIsConstant(str)) {
436    return str;
437  } else {
438    return REAL(CFStringCreateCopy)(alloc, str);
439  }
440}
441
442namespace __asan {
443
444void InitializeMacInterceptors() {
445  CHECK(INTERCEPT_FUNCTION(dispatch_async_f));
446  CHECK(INTERCEPT_FUNCTION(dispatch_sync_f));
447  CHECK(INTERCEPT_FUNCTION(dispatch_after_f));
448  CHECK(INTERCEPT_FUNCTION(dispatch_barrier_async_f));
449  CHECK(INTERCEPT_FUNCTION(dispatch_group_async_f));
450  // We don't need to intercept pthread_workqueue_additem_np() to support the
451  // libdispatch API, but it helps us to debug the unsupported functions. Let's
452  // intercept it only during verbose runs.
453  if (FLAG_v >= 2) {
454    CHECK(INTERCEPT_FUNCTION(pthread_workqueue_additem_np));
455  }
456  // Normally CFStringCreateCopy should not copy constant CF strings.
457  // Replacing the default CFAllocator causes constant strings to be copied
458  // rather than just returned, which leads to bugs in big applications like
459  // Chromium and WebKit, see
460  // http://code.google.com/p/address-sanitizer/issues/detail?id=10
461  // Until this problem is fixed we need to check that the string is
462  // non-constant before calling CFStringCreateCopy.
463  CHECK(INTERCEPT_FUNCTION(CFStringCreateCopy));
464}
465
466}  // namespace __asan
467
468#endif  // __APPLE__
469