asan_mac.cc revision 69563986ca570ce750111a82264d51ddbf4107ba
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 _NSGetArgv
27#include <dlfcn.h>  // for dladdr()
28#include <mach-o/dyld.h>
29#include <mach-o/loader.h>
30#include <sys/mman.h>
31#include <sys/resource.h>
32#include <sys/sysctl.h>
33#include <sys/ucontext.h>
34#include <fcntl.h>
35#include <pthread.h>
36#include <stdlib.h>  // for free()
37#include <unistd.h>
38#include <libkern/OSAtomic.h>
39
40namespace __asan {
41
42void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
43  ucontext_t *ucontext = (ucontext_t*)context;
44# if SANITIZER_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  // SANITIZER_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        case '2': return MACOS_VERSION_MOUNTAIN_LION;
71        default: return MACOS_VERSION_UNKNOWN;
72      }
73    }
74    default: return MACOS_VERSION_UNKNOWN;
75  }
76}
77
78bool PlatformHasDifferentMemcpyAndMemmove() {
79  // On OS X 10.7 memcpy() and memmove() are both resolved
80  // into memmove$VARIANT$sse42.
81  // See also http://code.google.com/p/address-sanitizer/issues/detail?id=34.
82  // TODO(glider): need to check dynamically that memcpy() and memmove() are
83  // actually the same function.
84  return GetMacosVersion() == MACOS_VERSION_SNOW_LEOPARD;
85}
86
87extern "C"
88void __asan_init();
89
90static const char kDyldInsertLibraries[] = "DYLD_INSERT_LIBRARIES";
91
92void MaybeReexec() {
93  if (!flags()->allow_reexec) return;
94  // Make sure the dynamic ASan runtime library is preloaded so that the
95  // wrappers work. If it is not, set DYLD_INSERT_LIBRARIES and re-exec
96  // ourselves.
97  Dl_info info;
98  CHECK(dladdr((void*)((uptr)__asan_init), &info));
99  const char *dyld_insert_libraries = GetEnv(kDyldInsertLibraries);
100  if (!dyld_insert_libraries ||
101      !REAL(strstr)(dyld_insert_libraries, info.dli_fname)) {
102    // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
103    // library.
104    char program_name[1024];
105    uint32_t buf_size = sizeof(program_name);
106    _NSGetExecutablePath(program_name, &buf_size);
107    // Ok to use setenv() since the wrappers don't depend on the value of
108    // asan_inited.
109    setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0);
110    if (flags()->verbosity >= 1) {
111      Report("exec()-ing the program with\n");
112      Report("%s=%s\n", kDyldInsertLibraries, info.dli_fname);
113      Report("to enable ASan wrappers.\n");
114      Report("Set ASAN_OPTIONS=allow_reexec=0 to disable this.\n");
115    }
116    execv(program_name, *_NSGetArgv());
117  }
118}
119
120// No-op. Mac does not support static linkage anyway.
121void *AsanDoesNotSupportStaticLinkage() {
122  return 0;
123}
124
125bool AsanInterceptsSignal(int signum) {
126  return (signum == SIGSEGV || signum == SIGBUS) && flags()->handle_segv;
127}
128
129void AsanPlatformThreadInit() {
130}
131
132void GetStackTrace(StackTrace *stack, uptr max_s, uptr pc, uptr bp, bool fast) {
133  (void)fast;
134  stack->size = 0;
135  stack->trace[0] = pc;
136  if ((max_s) > 1) {
137    stack->max_size = max_s;
138    if (!asan_inited) return;
139    if (AsanThread *t = asanThreadRegistry().GetCurrent())
140      stack->FastUnwindStack(pc, bp, t->stack_top(), t->stack_bottom());
141  }
142}
143
144void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
145  UNIMPLEMENTED();
146}
147
148// Support for the following functions from libdispatch on Mac OS:
149//   dispatch_async_f()
150//   dispatch_async()
151//   dispatch_sync_f()
152//   dispatch_sync()
153//   dispatch_after_f()
154//   dispatch_after()
155//   dispatch_group_async_f()
156//   dispatch_group_async()
157// TODO(glider): libdispatch API contains other functions that we don't support
158// yet.
159//
160// dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
161// they can cause jobs to run on a thread different from the current one.
162// TODO(glider): if so, we need a test for this (otherwise we should remove
163// them).
164//
165// The following functions use dispatch_barrier_async_f() (which isn't a library
166// function but is exported) and are thus supported:
167//   dispatch_source_set_cancel_handler_f()
168//   dispatch_source_set_cancel_handler()
169//   dispatch_source_set_event_handler_f()
170//   dispatch_source_set_event_handler()
171//
172// The reference manual for Grand Central Dispatch is available at
173//   http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
174// The implementation details are at
175//   http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
176
177typedef void* dispatch_group_t;
178typedef void* dispatch_queue_t;
179typedef void* dispatch_source_t;
180typedef u64 dispatch_time_t;
181typedef void (*dispatch_function_t)(void *block);
182typedef void* (*worker_t)(void *block);
183
184// A wrapper for the ObjC blocks used to support libdispatch.
185typedef struct {
186  void *block;
187  dispatch_function_t func;
188  u32 parent_tid;
189} asan_block_context_t;
190
191// We use extern declarations of libdispatch functions here instead
192// of including <dispatch/dispatch.h>. This header is not present on
193// Mac OS X Leopard and eariler, and although we don't expect ASan to
194// work on legacy systems, it's bad to break the build of
195// LLVM compiler-rt there.
196extern "C" {
197void dispatch_async_f(dispatch_queue_t dq, void *ctxt,
198                      dispatch_function_t func);
199void dispatch_sync_f(dispatch_queue_t dq, void *ctxt,
200                     dispatch_function_t func);
201void dispatch_after_f(dispatch_time_t when, dispatch_queue_t dq, void *ctxt,
202                      dispatch_function_t func);
203void dispatch_barrier_async_f(dispatch_queue_t dq, void *ctxt,
204                              dispatch_function_t func);
205void dispatch_group_async_f(dispatch_group_t group, dispatch_queue_t dq,
206                            void *ctxt, dispatch_function_t func);
207}  // extern "C"
208
209static ALWAYS_INLINE
210void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
211  AsanThread *t = asanThreadRegistry().GetCurrent();
212  if (!t) {
213    t = AsanThread::Create(parent_tid, 0, 0, stack);
214    asanThreadRegistry().RegisterThread(t);
215    t->Init();
216    asanThreadRegistry().SetCurrent(t);
217  }
218}
219
220// For use by only those functions that allocated the context via
221// alloc_asan_context().
222extern "C"
223void asan_dispatch_call_block_and_release(void *block) {
224  GET_STACK_TRACE_THREAD;
225  asan_block_context_t *context = (asan_block_context_t*)block;
226  if (flags()->verbosity >= 2) {
227    Report("asan_dispatch_call_block_and_release(): "
228           "context: %p, pthread_self: %p\n",
229           block, pthread_self());
230  }
231  asan_register_worker_thread(context->parent_tid, &stack);
232  // Call the original dispatcher for the block.
233  context->func(context->block);
234  asan_free(context, &stack, FROM_MALLOC);
235}
236
237}  // namespace __asan
238
239using namespace __asan;  // NOLINT
240
241// Wrap |ctxt| and |func| into an asan_block_context_t.
242// The caller retains control of the allocated context.
243extern "C"
244asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
245                                         StackTrace *stack) {
246  asan_block_context_t *asan_ctxt =
247      (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
248  asan_ctxt->block = ctxt;
249  asan_ctxt->func = func;
250  asan_ctxt->parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid();
251  return asan_ctxt;
252}
253
254// Define interceptor for dispatch_*_f function with the three most common
255// parameters: dispatch_queue_t, context, dispatch_function_t.
256#define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f)                                \
257  INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt,            \
258                                  dispatch_function_t func) {                 \
259    GET_STACK_TRACE_THREAD;                                                   \
260    asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
261    if (flags()->verbosity >= 2) {                                            \
262      Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n",             \
263             asan_ctxt, pthread_self());                                      \
264       PRINT_CURRENT_STACK();                                                 \
265     }                                                                        \
266     return REAL(dispatch_x_f)(dq, (void*)asan_ctxt,                          \
267                               asan_dispatch_call_block_and_release);         \
268  }
269
270INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
271INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
272INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
273
274INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
275                                    dispatch_queue_t dq, void *ctxt,
276                                    dispatch_function_t func) {
277  GET_STACK_TRACE_THREAD;
278  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
279  if (flags()->verbosity >= 2) {
280    Report("dispatch_after_f: %p\n", asan_ctxt);
281    PRINT_CURRENT_STACK();
282  }
283  return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
284                                asan_dispatch_call_block_and_release);
285}
286
287INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
288                                          dispatch_queue_t dq, void *ctxt,
289                                          dispatch_function_t func) {
290  GET_STACK_TRACE_THREAD;
291  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
292  if (flags()->verbosity >= 2) {
293    Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
294           asan_ctxt, pthread_self());
295    PRINT_CURRENT_STACK();
296  }
297  REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
298                               asan_dispatch_call_block_and_release);
299}
300
301#if !defined(MISSING_BLOCKS_SUPPORT)
302extern "C" {
303// FIXME: consolidate these declarations with asan_intercepted_functions.h.
304void dispatch_async(dispatch_queue_t dq, void(^work)(void));
305void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
306                          void(^work)(void));
307void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
308                    void(^work)(void));
309void dispatch_source_set_cancel_handler(dispatch_source_t ds,
310                                        void(^work)(void));
311void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
312}
313
314#define GET_ASAN_BLOCK(work) \
315  void (^asan_block)(void);  \
316  int parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid(); \
317  asan_block = ^(void) { \
318    GET_STACK_TRACE_THREAD; \
319    asan_register_worker_thread(parent_tid, &stack); \
320    work(); \
321  }
322
323INTERCEPTOR(void, dispatch_async,
324            dispatch_queue_t dq, void(^work)(void)) {
325  GET_ASAN_BLOCK(work);
326  REAL(dispatch_async)(dq, asan_block);
327}
328
329INTERCEPTOR(void, dispatch_group_async,
330            dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) {
331  GET_ASAN_BLOCK(work);
332  REAL(dispatch_group_async)(dg, dq, asan_block);
333}
334
335INTERCEPTOR(void, dispatch_after,
336            dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) {
337  GET_ASAN_BLOCK(work);
338  REAL(dispatch_after)(when, queue, asan_block);
339}
340
341INTERCEPTOR(void, dispatch_source_set_cancel_handler,
342            dispatch_source_t ds, void(^work)(void)) {
343  GET_ASAN_BLOCK(work);
344  REAL(dispatch_source_set_cancel_handler)(ds, asan_block);
345}
346
347INTERCEPTOR(void, dispatch_source_set_event_handler,
348            dispatch_source_t ds, void(^work)(void)) {
349  GET_ASAN_BLOCK(work);
350  REAL(dispatch_source_set_event_handler)(ds, asan_block);
351}
352#endif
353
354#endif  // __APPLE__
355