Home | History | Annotate | Download | only in asan
      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 
     40 namespace __asan {
     41 
     42 void 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 
     55 int 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 
     78 bool 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 
     87 extern "C"
     88 void __asan_init();
     89 
     90 static const char kDyldInsertLibraries[] = "DYLD_INSERT_LIBRARIES";
     91 LowLevelAllocator 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|.
     97 void 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 
    125 void 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.
    221 void *AsanDoesNotSupportStaticLinkage() {
    222   return 0;
    223 }
    224 
    225 bool AsanInterceptsSignal(int signum) {
    226   return (signum == SIGSEGV || signum == SIGBUS) && flags()->handle_segv;
    227 }
    228 
    229 void AsanPlatformThreadInit() {
    230 }
    231 
    232 void 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 = asanThreadRegistry().GetCurrent())
    240       stack->FastUnwindStack(pc, bp, t->stack_top(), t->stack_bottom());
    241   }
    242 }
    243 
    244 void 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 
    277 typedef void* dispatch_group_t;
    278 typedef void* dispatch_queue_t;
    279 typedef void* dispatch_source_t;
    280 typedef u64 dispatch_time_t;
    281 typedef void (*dispatch_function_t)(void *block);
    282 typedef void* (*worker_t)(void *block);
    283 
    284 // A wrapper for the ObjC blocks used to support libdispatch.
    285 typedef struct {
    286   void *block;
    287   dispatch_function_t func;
    288   u32 parent_tid;
    289 } asan_block_context_t;
    290 
    291 static ALWAYS_INLINE
    292 void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
    293   AsanThread *t = asanThreadRegistry().GetCurrent();
    294   if (!t) {
    295     t = AsanThread::Create(parent_tid, 0, 0, stack);
    296     asanThreadRegistry().RegisterThread(t);
    297     t->Init();
    298     asanThreadRegistry().SetCurrent(t);
    299   }
    300 }
    301 
    302 // For use by only those functions that allocated the context via
    303 // alloc_asan_context().
    304 extern "C"
    305 void asan_dispatch_call_block_and_release(void *block) {
    306   GET_STACK_TRACE_THREAD;
    307   asan_block_context_t *context = (asan_block_context_t*)block;
    308   if (flags()->verbosity >= 2) {
    309     Report("asan_dispatch_call_block_and_release(): "
    310            "context: %p, pthread_self: %p\n",
    311            block, pthread_self());
    312   }
    313   asan_register_worker_thread(context->parent_tid, &stack);
    314   // Call the original dispatcher for the block.
    315   context->func(context->block);
    316   asan_free(context, &stack, FROM_MALLOC);
    317 }
    318 
    319 }  // namespace __asan
    320 
    321 using namespace __asan;  // NOLINT
    322 
    323 // Wrap |ctxt| and |func| into an asan_block_context_t.
    324 // The caller retains control of the allocated context.
    325 extern "C"
    326 asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
    327                                          StackTrace *stack) {
    328   asan_block_context_t *asan_ctxt =
    329       (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
    330   asan_ctxt->block = ctxt;
    331   asan_ctxt->func = func;
    332   asan_ctxt->parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid();
    333   return asan_ctxt;
    334 }
    335 
    336 // Define interceptor for dispatch_*_f function with the three most common
    337 // parameters: dispatch_queue_t, context, dispatch_function_t.
    338 #define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f)                                \
    339   INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt,            \
    340                                   dispatch_function_t func) {                 \
    341     GET_STACK_TRACE_THREAD;                                                   \
    342     asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
    343     if (flags()->verbosity >= 2) {                                            \
    344       Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n",             \
    345              asan_ctxt, pthread_self());                                      \
    346        PRINT_CURRENT_STACK();                                                 \
    347      }                                                                        \
    348      return REAL(dispatch_x_f)(dq, (void*)asan_ctxt,                          \
    349                                asan_dispatch_call_block_and_release);         \
    350   }
    351 
    352 INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
    353 INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
    354 INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
    355 
    356 INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
    357                                     dispatch_queue_t dq, void *ctxt,
    358                                     dispatch_function_t func) {
    359   GET_STACK_TRACE_THREAD;
    360   asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
    361   if (flags()->verbosity >= 2) {
    362     Report("dispatch_after_f: %p\n", asan_ctxt);
    363     PRINT_CURRENT_STACK();
    364   }
    365   return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
    366                                 asan_dispatch_call_block_and_release);
    367 }
    368 
    369 INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
    370                                           dispatch_queue_t dq, void *ctxt,
    371                                           dispatch_function_t func) {
    372   GET_STACK_TRACE_THREAD;
    373   asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
    374   if (flags()->verbosity >= 2) {
    375     Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
    376            asan_ctxt, pthread_self());
    377     PRINT_CURRENT_STACK();
    378   }
    379   REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
    380                                asan_dispatch_call_block_and_release);
    381 }
    382 
    383 #if !defined(MISSING_BLOCKS_SUPPORT)
    384 extern "C" {
    385 // FIXME: consolidate these declarations with asan_intercepted_functions.h.
    386 void dispatch_async(dispatch_queue_t dq, void(^work)(void));
    387 void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
    388                           void(^work)(void));
    389 void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
    390                     void(^work)(void));
    391 void dispatch_source_set_cancel_handler(dispatch_source_t ds,
    392                                         void(^work)(void));
    393 void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
    394 }
    395 
    396 #define GET_ASAN_BLOCK(work) \
    397   void (^asan_block)(void);  \
    398   int parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid(); \
    399   asan_block = ^(void) { \
    400     GET_STACK_TRACE_THREAD; \
    401     asan_register_worker_thread(parent_tid, &stack); \
    402     work(); \
    403   }
    404 
    405 INTERCEPTOR(void, dispatch_async,
    406             dispatch_queue_t dq, void(^work)(void)) {
    407   GET_ASAN_BLOCK(work);
    408   REAL(dispatch_async)(dq, asan_block);
    409 }
    410 
    411 INTERCEPTOR(void, dispatch_group_async,
    412             dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) {
    413   GET_ASAN_BLOCK(work);
    414   REAL(dispatch_group_async)(dg, dq, asan_block);
    415 }
    416 
    417 INTERCEPTOR(void, dispatch_after,
    418             dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) {
    419   GET_ASAN_BLOCK(work);
    420   REAL(dispatch_after)(when, queue, asan_block);
    421 }
    422 
    423 INTERCEPTOR(void, dispatch_source_set_cancel_handler,
    424             dispatch_source_t ds, void(^work)(void)) {
    425   GET_ASAN_BLOCK(work);
    426   REAL(dispatch_source_set_cancel_handler)(ds, asan_block);
    427 }
    428 
    429 INTERCEPTOR(void, dispatch_source_set_event_handler,
    430             dispatch_source_t ds, void(^work)(void)) {
    431   GET_ASAN_BLOCK(work);
    432   REAL(dispatch_source_set_event_handler)(ds, asan_block);
    433 }
    434 #endif
    435 
    436 #endif  // __APPLE__
    437