asan_mac.cc revision 8da17ea3bc3ba0a28844642921247a3b9a1a3bcd
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    if (dyld_insert_libraries) {
110      // Append the runtime dylib name to the existing value of
111      // DYLD_INSERT_LIBRARIES.
112      uptr old_env_len = internal_strlen(dyld_insert_libraries);
113      uptr fname_len = internal_strlen(info.dli_fname);
114      LowLevelAllocator allocator_for_env;
115      char *new_env =
116          (char*)allocator_for_env.Allocate(old_env_len + fname_len + 2);
117      internal_strncpy(new_env, dyld_insert_libraries, old_env_len);
118      new_env[old_env_len] = ':';
119      // Copy fname_len and add a trailing zero.
120      internal_strncpy(new_env + old_env_len + 1, info.dli_fname,
121                       fname_len + 1);
122      setenv(kDyldInsertLibraries, new_env, /*overwrite*/1);
123    } else {
124      // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name.
125      setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0);
126    }
127    if (flags()->verbosity >= 1) {
128      Report("exec()-ing the program with\n");
129      Report("%s=%s\n", kDyldInsertLibraries, info.dli_fname);
130      Report("to enable ASan wrappers.\n");
131      Report("Set ASAN_OPTIONS=allow_reexec=0 to disable this.\n");
132    }
133    execv(program_name, *_NSGetArgv());
134  }
135}
136
137// No-op. Mac does not support static linkage anyway.
138void *AsanDoesNotSupportStaticLinkage() {
139  return 0;
140}
141
142bool AsanInterceptsSignal(int signum) {
143  return (signum == SIGSEGV || signum == SIGBUS) && flags()->handle_segv;
144}
145
146void AsanPlatformThreadInit() {
147}
148
149void GetStackTrace(StackTrace *stack, uptr max_s, uptr pc, uptr bp, bool fast) {
150  (void)fast;
151  stack->size = 0;
152  stack->trace[0] = pc;
153  if ((max_s) > 1) {
154    stack->max_size = max_s;
155    if (!asan_inited) return;
156    if (AsanThread *t = asanThreadRegistry().GetCurrent())
157      stack->FastUnwindStack(pc, bp, t->stack_top(), t->stack_bottom());
158  }
159}
160
161void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
162  UNIMPLEMENTED();
163}
164
165// Support for the following functions from libdispatch on Mac OS:
166//   dispatch_async_f()
167//   dispatch_async()
168//   dispatch_sync_f()
169//   dispatch_sync()
170//   dispatch_after_f()
171//   dispatch_after()
172//   dispatch_group_async_f()
173//   dispatch_group_async()
174// TODO(glider): libdispatch API contains other functions that we don't support
175// yet.
176//
177// dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
178// they can cause jobs to run on a thread different from the current one.
179// TODO(glider): if so, we need a test for this (otherwise we should remove
180// them).
181//
182// The following functions use dispatch_barrier_async_f() (which isn't a library
183// function but is exported) and are thus supported:
184//   dispatch_source_set_cancel_handler_f()
185//   dispatch_source_set_cancel_handler()
186//   dispatch_source_set_event_handler_f()
187//   dispatch_source_set_event_handler()
188//
189// The reference manual for Grand Central Dispatch is available at
190//   http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
191// The implementation details are at
192//   http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
193
194typedef void* dispatch_group_t;
195typedef void* dispatch_queue_t;
196typedef void* dispatch_source_t;
197typedef u64 dispatch_time_t;
198typedef void (*dispatch_function_t)(void *block);
199typedef void* (*worker_t)(void *block);
200
201// A wrapper for the ObjC blocks used to support libdispatch.
202typedef struct {
203  void *block;
204  dispatch_function_t func;
205  u32 parent_tid;
206} asan_block_context_t;
207
208// We use extern declarations of libdispatch functions here instead
209// of including <dispatch/dispatch.h>. This header is not present on
210// Mac OS X Leopard and eariler, and although we don't expect ASan to
211// work on legacy systems, it's bad to break the build of
212// LLVM compiler-rt there.
213extern "C" {
214void dispatch_async_f(dispatch_queue_t dq, void *ctxt,
215                      dispatch_function_t func);
216void dispatch_sync_f(dispatch_queue_t dq, void *ctxt,
217                     dispatch_function_t func);
218void dispatch_after_f(dispatch_time_t when, dispatch_queue_t dq, void *ctxt,
219                      dispatch_function_t func);
220void dispatch_barrier_async_f(dispatch_queue_t dq, void *ctxt,
221                              dispatch_function_t func);
222void dispatch_group_async_f(dispatch_group_t group, dispatch_queue_t dq,
223                            void *ctxt, dispatch_function_t func);
224}  // extern "C"
225
226static ALWAYS_INLINE
227void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
228  AsanThread *t = asanThreadRegistry().GetCurrent();
229  if (!t) {
230    t = AsanThread::Create(parent_tid, 0, 0, stack);
231    asanThreadRegistry().RegisterThread(t);
232    t->Init();
233    asanThreadRegistry().SetCurrent(t);
234  }
235}
236
237// For use by only those functions that allocated the context via
238// alloc_asan_context().
239extern "C"
240void asan_dispatch_call_block_and_release(void *block) {
241  GET_STACK_TRACE_THREAD;
242  asan_block_context_t *context = (asan_block_context_t*)block;
243  if (flags()->verbosity >= 2) {
244    Report("asan_dispatch_call_block_and_release(): "
245           "context: %p, pthread_self: %p\n",
246           block, pthread_self());
247  }
248  asan_register_worker_thread(context->parent_tid, &stack);
249  // Call the original dispatcher for the block.
250  context->func(context->block);
251  asan_free(context, &stack, FROM_MALLOC);
252}
253
254}  // namespace __asan
255
256using namespace __asan;  // NOLINT
257
258// Wrap |ctxt| and |func| into an asan_block_context_t.
259// The caller retains control of the allocated context.
260extern "C"
261asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
262                                         StackTrace *stack) {
263  asan_block_context_t *asan_ctxt =
264      (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
265  asan_ctxt->block = ctxt;
266  asan_ctxt->func = func;
267  asan_ctxt->parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid();
268  return asan_ctxt;
269}
270
271// Define interceptor for dispatch_*_f function with the three most common
272// parameters: dispatch_queue_t, context, dispatch_function_t.
273#define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f)                                \
274  INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt,            \
275                                  dispatch_function_t func) {                 \
276    GET_STACK_TRACE_THREAD;                                                   \
277    asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
278    if (flags()->verbosity >= 2) {                                            \
279      Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n",             \
280             asan_ctxt, pthread_self());                                      \
281       PRINT_CURRENT_STACK();                                                 \
282     }                                                                        \
283     return REAL(dispatch_x_f)(dq, (void*)asan_ctxt,                          \
284                               asan_dispatch_call_block_and_release);         \
285  }
286
287INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
288INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
289INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
290
291INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
292                                    dispatch_queue_t dq, void *ctxt,
293                                    dispatch_function_t func) {
294  GET_STACK_TRACE_THREAD;
295  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
296  if (flags()->verbosity >= 2) {
297    Report("dispatch_after_f: %p\n", asan_ctxt);
298    PRINT_CURRENT_STACK();
299  }
300  return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
301                                asan_dispatch_call_block_and_release);
302}
303
304INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
305                                          dispatch_queue_t dq, void *ctxt,
306                                          dispatch_function_t func) {
307  GET_STACK_TRACE_THREAD;
308  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
309  if (flags()->verbosity >= 2) {
310    Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
311           asan_ctxt, pthread_self());
312    PRINT_CURRENT_STACK();
313  }
314  REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
315                               asan_dispatch_call_block_and_release);
316}
317
318#if !defined(MISSING_BLOCKS_SUPPORT)
319extern "C" {
320// FIXME: consolidate these declarations with asan_intercepted_functions.h.
321void dispatch_async(dispatch_queue_t dq, void(^work)(void));
322void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
323                          void(^work)(void));
324void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
325                    void(^work)(void));
326void dispatch_source_set_cancel_handler(dispatch_source_t ds,
327                                        void(^work)(void));
328void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
329}
330
331#define GET_ASAN_BLOCK(work) \
332  void (^asan_block)(void);  \
333  int parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid(); \
334  asan_block = ^(void) { \
335    GET_STACK_TRACE_THREAD; \
336    asan_register_worker_thread(parent_tid, &stack); \
337    work(); \
338  }
339
340INTERCEPTOR(void, dispatch_async,
341            dispatch_queue_t dq, void(^work)(void)) {
342  GET_ASAN_BLOCK(work);
343  REAL(dispatch_async)(dq, asan_block);
344}
345
346INTERCEPTOR(void, dispatch_group_async,
347            dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) {
348  GET_ASAN_BLOCK(work);
349  REAL(dispatch_group_async)(dg, dq, asan_block);
350}
351
352INTERCEPTOR(void, dispatch_after,
353            dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) {
354  GET_ASAN_BLOCK(work);
355  REAL(dispatch_after)(when, queue, asan_block);
356}
357
358INTERCEPTOR(void, dispatch_source_set_cancel_handler,
359            dispatch_source_t ds, void(^work)(void)) {
360  GET_ASAN_BLOCK(work);
361  REAL(dispatch_source_set_cancel_handler)(ds, asan_block);
362}
363
364INTERCEPTOR(void, dispatch_source_set_event_handler,
365            dispatch_source_t ds, void(^work)(void)) {
366  GET_ASAN_BLOCK(work);
367  REAL(dispatch_source_set_event_handler)(ds, asan_block);
368}
369#endif
370
371#endif  // __APPLE__
372