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