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