asan_mac.cc revision def1be9b7ef4091ce465c0fbfb26cdb52128ade8
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#include "sanitizer_common/sanitizer_platform.h"
16#if SANITIZER_MAC
17
18#include "asan_interceptors.h"
19#include "asan_internal.h"
20#include "asan_mac.h"
21#include "asan_mapping.h"
22#include "asan_stack.h"
23#include "asan_thread.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  uptr 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      uptr 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 ((uptr)(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,
197        // append it to new_env.
198        if ((piece_len != fname_len) ||
199            (internal_strncmp(piece_start, info.dli_fname, fname_len) != 0)) {
200          if (new_env_pos != new_env + env_name_len + 1) {
201            new_env_pos[0] = ':';
202            new_env_pos++;
203          }
204          internal_strncpy(new_env_pos, piece_start, piece_len);
205        }
206        // Move on to the next piece.
207        new_env_pos += piece_len;
208        piece_start = piece_end;
209      } while (piece_start < old_env_end);
210
211      // Can't use setenv() here, because it requires the allocator to be
212      // initialized.
213      // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in
214      // a separate function called after InitializeAllocator().
215      LeakyResetEnv(kDyldInsertLibraries, new_env);
216    }
217  }
218}
219
220// No-op. Mac does not support static linkage anyway.
221void *AsanDoesNotSupportStaticLinkage() {
222  return 0;
223}
224
225bool AsanInterceptsSignal(int signum) {
226  return (signum == SIGSEGV || signum == SIGBUS) && flags()->handle_segv;
227}
228
229void AsanPlatformThreadInit() {
230}
231
232void GetStackTrace(StackTrace *stack, uptr max_s, uptr pc, uptr bp, bool fast) {
233  (void)fast;
234  stack->size = 0;
235  stack->trace[0] = pc;
236  if ((max_s) > 1) {
237    stack->max_size = max_s;
238    if (!asan_inited) return;
239    if (AsanThread *t = GetCurrentThread())
240      stack->FastUnwindStack(pc, bp, t->stack_top(), t->stack_bottom());
241  }
242}
243
244void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
245  UNIMPLEMENTED();
246}
247
248// Support for the following functions from libdispatch on Mac OS:
249//   dispatch_async_f()
250//   dispatch_async()
251//   dispatch_sync_f()
252//   dispatch_sync()
253//   dispatch_after_f()
254//   dispatch_after()
255//   dispatch_group_async_f()
256//   dispatch_group_async()
257// TODO(glider): libdispatch API contains other functions that we don't support
258// yet.
259//
260// dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
261// they can cause jobs to run on a thread different from the current one.
262// TODO(glider): if so, we need a test for this (otherwise we should remove
263// them).
264//
265// The following functions use dispatch_barrier_async_f() (which isn't a library
266// function but is exported) and are thus supported:
267//   dispatch_source_set_cancel_handler_f()
268//   dispatch_source_set_cancel_handler()
269//   dispatch_source_set_event_handler_f()
270//   dispatch_source_set_event_handler()
271//
272// The reference manual for Grand Central Dispatch is available at
273//   http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
274// The implementation details are at
275//   http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
276
277typedef void* dispatch_group_t;
278typedef void* dispatch_queue_t;
279typedef void* dispatch_source_t;
280typedef u64 dispatch_time_t;
281typedef void (*dispatch_function_t)(void *block);
282typedef void* (*worker_t)(void *block);
283
284// A wrapper for the ObjC blocks used to support libdispatch.
285typedef struct {
286  void *block;
287  dispatch_function_t func;
288  u32 parent_tid;
289} asan_block_context_t;
290
291static ALWAYS_INLINE
292void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
293  AsanThread *t = GetCurrentThread();
294  if (!t) {
295    t = AsanThread::Create(0, 0);
296    CreateThreadContextArgs args = { t, stack };
297    asanThreadRegistry().CreateThread(*(uptr*)t, true, parent_tid, &args);
298    t->Init();
299    asanThreadRegistry().StartThread(t->tid(), 0, 0);
300    SetCurrentThread(t);
301  }
302}
303
304// For use by only those functions that allocated the context via
305// alloc_asan_context().
306extern "C"
307void asan_dispatch_call_block_and_release(void *block) {
308  GET_STACK_TRACE_THREAD;
309  asan_block_context_t *context = (asan_block_context_t*)block;
310  if (flags()->verbosity >= 2) {
311    Report("asan_dispatch_call_block_and_release(): "
312           "context: %p, pthread_self: %p\n",
313           block, pthread_self());
314  }
315  asan_register_worker_thread(context->parent_tid, &stack);
316  // Call the original dispatcher for the block.
317  context->func(context->block);
318  asan_free(context, &stack, FROM_MALLOC);
319}
320
321}  // namespace __asan
322
323using namespace __asan;  // NOLINT
324
325// Wrap |ctxt| and |func| into an asan_block_context_t.
326// The caller retains control of the allocated context.
327extern "C"
328asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
329                                         StackTrace *stack) {
330  asan_block_context_t *asan_ctxt =
331      (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
332  asan_ctxt->block = ctxt;
333  asan_ctxt->func = func;
334  asan_ctxt->parent_tid = GetCurrentTidOrInvalid();
335  return asan_ctxt;
336}
337
338// Define interceptor for dispatch_*_f function with the three most common
339// parameters: dispatch_queue_t, context, dispatch_function_t.
340#define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f)                                \
341  INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt,            \
342                                  dispatch_function_t func) {                 \
343    GET_STACK_TRACE_THREAD;                                                   \
344    asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
345    if (flags()->verbosity >= 2) {                                            \
346      Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n",             \
347             asan_ctxt, pthread_self());                                      \
348       PRINT_CURRENT_STACK();                                                 \
349     }                                                                        \
350     return REAL(dispatch_x_f)(dq, (void*)asan_ctxt,                          \
351                               asan_dispatch_call_block_and_release);         \
352  }
353
354INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
355INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
356INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
357
358INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
359                                    dispatch_queue_t dq, void *ctxt,
360                                    dispatch_function_t func) {
361  GET_STACK_TRACE_THREAD;
362  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
363  if (flags()->verbosity >= 2) {
364    Report("dispatch_after_f: %p\n", asan_ctxt);
365    PRINT_CURRENT_STACK();
366  }
367  return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
368                                asan_dispatch_call_block_and_release);
369}
370
371INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
372                                          dispatch_queue_t dq, void *ctxt,
373                                          dispatch_function_t func) {
374  GET_STACK_TRACE_THREAD;
375  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
376  if (flags()->verbosity >= 2) {
377    Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
378           asan_ctxt, pthread_self());
379    PRINT_CURRENT_STACK();
380  }
381  REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
382                               asan_dispatch_call_block_and_release);
383}
384
385#if !defined(MISSING_BLOCKS_SUPPORT)
386extern "C" {
387// FIXME: consolidate these declarations with asan_intercepted_functions.h.
388void dispatch_async(dispatch_queue_t dq, void(^work)(void));
389void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
390                          void(^work)(void));
391void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
392                    void(^work)(void));
393void dispatch_source_set_cancel_handler(dispatch_source_t ds,
394                                        void(^work)(void));
395void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
396}
397
398#define GET_ASAN_BLOCK(work) \
399  void (^asan_block)(void);  \
400  int parent_tid = GetCurrentTidOrInvalid(); \
401  asan_block = ^(void) { \
402    GET_STACK_TRACE_THREAD; \
403    asan_register_worker_thread(parent_tid, &stack); \
404    work(); \
405  }
406
407INTERCEPTOR(void, dispatch_async,
408            dispatch_queue_t dq, void(^work)(void)) {
409  GET_ASAN_BLOCK(work);
410  REAL(dispatch_async)(dq, asan_block);
411}
412
413INTERCEPTOR(void, dispatch_group_async,
414            dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) {
415  GET_ASAN_BLOCK(work);
416  REAL(dispatch_group_async)(dg, dq, asan_block);
417}
418
419INTERCEPTOR(void, dispatch_after,
420            dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) {
421  GET_ASAN_BLOCK(work);
422  REAL(dispatch_after)(when, queue, asan_block);
423}
424
425INTERCEPTOR(void, dispatch_source_set_cancel_handler,
426            dispatch_source_t ds, void(^work)(void)) {
427  GET_ASAN_BLOCK(work);
428  REAL(dispatch_source_set_cancel_handler)(ds, asan_block);
429}
430
431INTERCEPTOR(void, dispatch_source_set_event_handler,
432            dispatch_source_t ds, void(^work)(void)) {
433  GET_ASAN_BLOCK(work);
434  REAL(dispatch_source_set_event_handler)(ds, asan_block);
435}
436#endif
437
438#endif  // __APPLE__
439