asan_mac.cc revision e6b91fdad54c4c9a711b5149d65ea6a6f368d9ab
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";
91LowLevelAllocator allocator_for_env;
92
93// Change the value of the env var |name|, leaking the original value.
94// If |name_value| is NULL, the variable is deleted from the environment,
95// otherwise the corresponding "NAME=value" string is replaced with
96// |name_value|.
97void LeakyResetEnv(const char *name, const char *name_value) {
98  char ***env_ptr = _NSGetEnviron();
99  CHECK(env_ptr);
100  char **environ = *env_ptr;
101  CHECK(environ);
102  uptr name_len = internal_strlen(name);
103  while (*environ != 0) {
104    uptr len = internal_strlen(*environ);
105    if (len > name_len) {
106      const char *p = *environ;
107      if (!internal_memcmp(p, name, name_len) && p[name_len] == '=') {
108        // Match.
109        if (name_value) {
110          // Replace the old value with the new one.
111          *environ = const_cast<char*>(name_value);
112        } else {
113          // Shift the subsequent pointers back.
114          char **del = environ;
115          do {
116            del[0] = del[1];
117          } while(*del++);
118        }
119      }
120    }
121    environ++;
122  }
123}
124
125void MaybeReexec() {
126  if (!flags()->allow_reexec) return;
127  // Make sure the dynamic ASan runtime library is preloaded so that the
128  // wrappers work. If it is not, set DYLD_INSERT_LIBRARIES and re-exec
129  // ourselves.
130  Dl_info info;
131  CHECK(dladdr((void*)((uptr)__asan_init), &info));
132  char *dyld_insert_libraries =
133      const_cast<char*>(GetEnv(kDyldInsertLibraries));
134  sptr old_env_len = dyld_insert_libraries ?
135      internal_strlen(dyld_insert_libraries) : 0;
136  uptr fname_len = internal_strlen(info.dli_fname);
137  if (!dyld_insert_libraries ||
138      !REAL(strstr)(dyld_insert_libraries, info.dli_fname)) {
139    // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
140    // library.
141    char program_name[1024];
142    uint32_t buf_size = sizeof(program_name);
143    _NSGetExecutablePath(program_name, &buf_size);
144    char *new_env = const_cast<char*>(info.dli_fname);
145    if (dyld_insert_libraries) {
146      // Append the runtime dylib name to the existing value of
147      // DYLD_INSERT_LIBRARIES.
148      new_env = (char*)allocator_for_env.Allocate(old_env_len + fname_len + 2);
149      internal_strncpy(new_env, dyld_insert_libraries, old_env_len);
150      new_env[old_env_len] = ':';
151      // Copy fname_len and add a trailing zero.
152      internal_strncpy(new_env + old_env_len + 1, info.dli_fname,
153                       fname_len + 1);
154      // Ok to use setenv() since the wrappers don't depend on the value of
155      // asan_inited.
156      setenv(kDyldInsertLibraries, new_env, /*overwrite*/1);
157    } else {
158      // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name.
159      setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0);
160    }
161    if (flags()->verbosity >= 1) {
162      Report("exec()-ing the program with\n");
163      Report("%s=%s\n", kDyldInsertLibraries, new_env);
164      Report("to enable ASan wrappers.\n");
165      Report("Set ASAN_OPTIONS=allow_reexec=0 to disable this.\n");
166    }
167    execv(program_name, *_NSGetArgv());
168  } else {
169    // DYLD_INSERT_LIBRARIES is set and contains the runtime library.
170    if (old_env_len == fname_len) {
171      // It's just the runtime library name - fine to unset the variable.
172      LeakyResetEnv(kDyldInsertLibraries, NULL);
173    } else {
174      sptr env_name_len = internal_strlen(kDyldInsertLibraries);
175      // Allocate memory to hold the previous env var name, its value, the '='
176      // sign and the '\0' char.
177      char *new_env = (char*)allocator_for_env.Allocate(
178          old_env_len + 2 + env_name_len);
179      CHECK(new_env);
180      internal_memset(new_env, '\0', old_env_len + 2 + env_name_len);
181      internal_strncpy(new_env, kDyldInsertLibraries, env_name_len);
182      new_env[env_name_len] = '=';
183      char *new_env_pos = new_env + env_name_len + 1;
184
185      // Iterate over colon-separated pieces of |dyld_insert_libraries|.
186      char *piece_start = dyld_insert_libraries;
187      char *piece_end = NULL;
188      char *old_env_end = dyld_insert_libraries + old_env_len;
189      do {
190        if (piece_start[0] == ':') piece_start++;
191        piece_end =  REAL(strchr)(piece_start, ':');
192        if (!piece_end) piece_end = dyld_insert_libraries + old_env_len;
193        if (piece_start - dyld_insert_libraries > old_env_len) break;
194        uptr piece_len = piece_end - piece_start;
195
196        // If the current piece isn't the runtime library name, append it to new_env.
197        if ((piece_len != fname_len) ||
198            (internal_strncmp(piece_start, info.dli_fname, fname_len) != 0)) {
199          if (new_env_pos != new_env + env_name_len + 1) {
200            new_env_pos[0] = ':';
201            new_env_pos++;
202          }
203          internal_strncpy(new_env_pos, piece_start, piece_len);
204        }
205        // Move on to the next piece.
206        new_env_pos += piece_len;
207        piece_start = piece_end;
208      } while (piece_start < old_env_end);
209
210      // Can't use setenv() here, because it requires the allocator to be
211      // initialized.
212      // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in
213      // a separate function called after InitializeAllocator().
214      LeakyResetEnv(kDyldInsertLibraries, new_env);
215    }
216  }
217}
218
219// No-op. Mac does not support static linkage anyway.
220void *AsanDoesNotSupportStaticLinkage() {
221  return 0;
222}
223
224bool AsanInterceptsSignal(int signum) {
225  return (signum == SIGSEGV || signum == SIGBUS) && flags()->handle_segv;
226}
227
228void AsanPlatformThreadInit() {
229}
230
231void GetStackTrace(StackTrace *stack, uptr max_s, uptr pc, uptr bp, bool fast) {
232  (void)fast;
233  stack->size = 0;
234  stack->trace[0] = pc;
235  if ((max_s) > 1) {
236    stack->max_size = max_s;
237    if (!asan_inited) return;
238    if (AsanThread *t = asanThreadRegistry().GetCurrent())
239      stack->FastUnwindStack(pc, bp, t->stack_top(), t->stack_bottom());
240  }
241}
242
243void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
244  UNIMPLEMENTED();
245}
246
247// Support for the following functions from libdispatch on Mac OS:
248//   dispatch_async_f()
249//   dispatch_async()
250//   dispatch_sync_f()
251//   dispatch_sync()
252//   dispatch_after_f()
253//   dispatch_after()
254//   dispatch_group_async_f()
255//   dispatch_group_async()
256// TODO(glider): libdispatch API contains other functions that we don't support
257// yet.
258//
259// dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
260// they can cause jobs to run on a thread different from the current one.
261// TODO(glider): if so, we need a test for this (otherwise we should remove
262// them).
263//
264// The following functions use dispatch_barrier_async_f() (which isn't a library
265// function but is exported) and are thus supported:
266//   dispatch_source_set_cancel_handler_f()
267//   dispatch_source_set_cancel_handler()
268//   dispatch_source_set_event_handler_f()
269//   dispatch_source_set_event_handler()
270//
271// The reference manual for Grand Central Dispatch is available at
272//   http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
273// The implementation details are at
274//   http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
275
276typedef void* dispatch_group_t;
277typedef void* dispatch_queue_t;
278typedef void* dispatch_source_t;
279typedef u64 dispatch_time_t;
280typedef void (*dispatch_function_t)(void *block);
281typedef void* (*worker_t)(void *block);
282
283// A wrapper for the ObjC blocks used to support libdispatch.
284typedef struct {
285  void *block;
286  dispatch_function_t func;
287  u32 parent_tid;
288} asan_block_context_t;
289
290// We use extern declarations of libdispatch functions here instead
291// of including <dispatch/dispatch.h>. This header is not present on
292// Mac OS X Leopard and eariler, and although we don't expect ASan to
293// work on legacy systems, it's bad to break the build of
294// LLVM compiler-rt there.
295extern "C" {
296void dispatch_async_f(dispatch_queue_t dq, void *ctxt,
297                      dispatch_function_t func);
298void dispatch_sync_f(dispatch_queue_t dq, void *ctxt,
299                     dispatch_function_t func);
300void dispatch_after_f(dispatch_time_t when, dispatch_queue_t dq, void *ctxt,
301                      dispatch_function_t func);
302void dispatch_barrier_async_f(dispatch_queue_t dq, void *ctxt,
303                              dispatch_function_t func);
304void dispatch_group_async_f(dispatch_group_t group, dispatch_queue_t dq,
305                            void *ctxt, dispatch_function_t func);
306}  // extern "C"
307
308static ALWAYS_INLINE
309void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
310  AsanThread *t = asanThreadRegistry().GetCurrent();
311  if (!t) {
312    t = AsanThread::Create(parent_tid, 0, 0, stack);
313    asanThreadRegistry().RegisterThread(t);
314    t->Init();
315    asanThreadRegistry().SetCurrent(t);
316  }
317}
318
319// For use by only those functions that allocated the context via
320// alloc_asan_context().
321extern "C"
322void asan_dispatch_call_block_and_release(void *block) {
323  GET_STACK_TRACE_THREAD;
324  asan_block_context_t *context = (asan_block_context_t*)block;
325  if (flags()->verbosity >= 2) {
326    Report("asan_dispatch_call_block_and_release(): "
327           "context: %p, pthread_self: %p\n",
328           block, pthread_self());
329  }
330  asan_register_worker_thread(context->parent_tid, &stack);
331  // Call the original dispatcher for the block.
332  context->func(context->block);
333  asan_free(context, &stack, FROM_MALLOC);
334}
335
336}  // namespace __asan
337
338using namespace __asan;  // NOLINT
339
340// Wrap |ctxt| and |func| into an asan_block_context_t.
341// The caller retains control of the allocated context.
342extern "C"
343asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
344                                         StackTrace *stack) {
345  asan_block_context_t *asan_ctxt =
346      (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
347  asan_ctxt->block = ctxt;
348  asan_ctxt->func = func;
349  asan_ctxt->parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid();
350  return asan_ctxt;
351}
352
353// Define interceptor for dispatch_*_f function with the three most common
354// parameters: dispatch_queue_t, context, dispatch_function_t.
355#define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f)                                \
356  INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt,            \
357                                  dispatch_function_t func) {                 \
358    GET_STACK_TRACE_THREAD;                                                   \
359    asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
360    if (flags()->verbosity >= 2) {                                            \
361      Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n",             \
362             asan_ctxt, pthread_self());                                      \
363       PRINT_CURRENT_STACK();                                                 \
364     }                                                                        \
365     return REAL(dispatch_x_f)(dq, (void*)asan_ctxt,                          \
366                               asan_dispatch_call_block_and_release);         \
367  }
368
369INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
370INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
371INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
372
373INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
374                                    dispatch_queue_t dq, void *ctxt,
375                                    dispatch_function_t func) {
376  GET_STACK_TRACE_THREAD;
377  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
378  if (flags()->verbosity >= 2) {
379    Report("dispatch_after_f: %p\n", asan_ctxt);
380    PRINT_CURRENT_STACK();
381  }
382  return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
383                                asan_dispatch_call_block_and_release);
384}
385
386INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
387                                          dispatch_queue_t dq, void *ctxt,
388                                          dispatch_function_t func) {
389  GET_STACK_TRACE_THREAD;
390  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
391  if (flags()->verbosity >= 2) {
392    Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
393           asan_ctxt, pthread_self());
394    PRINT_CURRENT_STACK();
395  }
396  REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
397                               asan_dispatch_call_block_and_release);
398}
399
400#if !defined(MISSING_BLOCKS_SUPPORT)
401extern "C" {
402// FIXME: consolidate these declarations with asan_intercepted_functions.h.
403void dispatch_async(dispatch_queue_t dq, void(^work)(void));
404void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
405                          void(^work)(void));
406void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
407                    void(^work)(void));
408void dispatch_source_set_cancel_handler(dispatch_source_t ds,
409                                        void(^work)(void));
410void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
411}
412
413#define GET_ASAN_BLOCK(work) \
414  void (^asan_block)(void);  \
415  int parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid(); \
416  asan_block = ^(void) { \
417    GET_STACK_TRACE_THREAD; \
418    asan_register_worker_thread(parent_tid, &stack); \
419    work(); \
420  }
421
422INTERCEPTOR(void, dispatch_async,
423            dispatch_queue_t dq, void(^work)(void)) {
424  GET_ASAN_BLOCK(work);
425  REAL(dispatch_async)(dq, asan_block);
426}
427
428INTERCEPTOR(void, dispatch_group_async,
429            dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) {
430  GET_ASAN_BLOCK(work);
431  REAL(dispatch_group_async)(dg, dq, asan_block);
432}
433
434INTERCEPTOR(void, dispatch_after,
435            dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) {
436  GET_ASAN_BLOCK(work);
437  REAL(dispatch_after)(when, queue, asan_block);
438}
439
440INTERCEPTOR(void, dispatch_source_set_cancel_handler,
441            dispatch_source_t ds, void(^work)(void)) {
442  GET_ASAN_BLOCK(work);
443  REAL(dispatch_source_set_cancel_handler)(ds, asan_block);
444}
445
446INTERCEPTOR(void, dispatch_source_set_event_handler,
447            dispatch_source_t ds, void(^work)(void)) {
448  GET_ASAN_BLOCK(work);
449  REAL(dispatch_source_set_event_handler)(ds, asan_block);
450}
451#endif
452
453#endif  // __APPLE__
454