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 #include "sanitizer_common/sanitizer_platform.h"
     16 #if SANITIZER_MAC
     17 
     18 #include "asan_interceptors.h"
     19 #include "asan_internal.h"
     20 #include "asan_mapping.h"
     21 #include "asan_stack.h"
     22 #include "asan_thread.h"
     23 #include "sanitizer_common/sanitizer_atomic.h"
     24 #include "sanitizer_common/sanitizer_libc.h"
     25 #include "sanitizer_common/sanitizer_mac.h"
     26 
     27 #include <crt_externs.h>  // for _NSGetArgv
     28 #include <dlfcn.h>  // for dladdr()
     29 #include <mach-o/dyld.h>
     30 #include <mach-o/loader.h>
     31 #include <sys/mman.h>
     32 #include <sys/resource.h>
     33 #include <sys/sysctl.h>
     34 #include <sys/ucontext.h>
     35 #include <fcntl.h>
     36 #include <pthread.h>
     37 #include <stdlib.h>  // for free()
     38 #include <unistd.h>
     39 #include <libkern/OSAtomic.h>
     40 
     41 namespace __asan {
     42 
     43 void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
     44   ucontext_t *ucontext = (ucontext_t*)context;
     45 # if SANITIZER_WORDSIZE == 64
     46   *pc = ucontext->uc_mcontext->__ss.__rip;
     47   *bp = ucontext->uc_mcontext->__ss.__rbp;
     48   *sp = ucontext->uc_mcontext->__ss.__rsp;
     49 # else
     50   *pc = ucontext->uc_mcontext->__ss.__eip;
     51   *bp = ucontext->uc_mcontext->__ss.__ebp;
     52   *sp = ucontext->uc_mcontext->__ss.__esp;
     53 # endif  // SANITIZER_WORDSIZE
     54 }
     55 
     56 
     57 bool PlatformHasDifferentMemcpyAndMemmove() {
     58   // On OS X 10.7 memcpy() and memmove() are both resolved
     59   // into memmove$VARIANT$sse42.
     60   // See also http://code.google.com/p/address-sanitizer/issues/detail?id=34.
     61   // TODO(glider): need to check dynamically that memcpy() and memmove() are
     62   // actually the same function.
     63   return GetMacosVersion() == MACOS_VERSION_SNOW_LEOPARD;
     64 }
     65 
     66 extern "C"
     67 void __asan_init();
     68 
     69 static const char kDyldInsertLibraries[] = "DYLD_INSERT_LIBRARIES";
     70 LowLevelAllocator allocator_for_env;
     71 
     72 // Change the value of the env var |name|, leaking the original value.
     73 // If |name_value| is NULL, the variable is deleted from the environment,
     74 // otherwise the corresponding "NAME=value" string is replaced with
     75 // |name_value|.
     76 void LeakyResetEnv(const char *name, const char *name_value) {
     77   char ***env_ptr = _NSGetEnviron();
     78   CHECK(env_ptr);
     79   char **environ = *env_ptr;
     80   CHECK(environ);
     81   uptr name_len = internal_strlen(name);
     82   while (*environ != 0) {
     83     uptr len = internal_strlen(*environ);
     84     if (len > name_len) {
     85       const char *p = *environ;
     86       if (!internal_memcmp(p, name, name_len) && p[name_len] == '=') {
     87         // Match.
     88         if (name_value) {
     89           // Replace the old value with the new one.
     90           *environ = const_cast<char*>(name_value);
     91         } else {
     92           // Shift the subsequent pointers back.
     93           char **del = environ;
     94           do {
     95             del[0] = del[1];
     96           } while (*del++);
     97         }
     98       }
     99     }
    100     environ++;
    101   }
    102 }
    103 
    104 void MaybeReexec() {
    105   if (!flags()->allow_reexec) return;
    106   // Make sure the dynamic ASan runtime library is preloaded so that the
    107   // wrappers work. If it is not, set DYLD_INSERT_LIBRARIES and re-exec
    108   // ourselves.
    109   Dl_info info;
    110   CHECK(dladdr((void*)((uptr)__asan_init), &info));
    111   char *dyld_insert_libraries =
    112       const_cast<char*>(GetEnv(kDyldInsertLibraries));
    113   uptr old_env_len = dyld_insert_libraries ?
    114       internal_strlen(dyld_insert_libraries) : 0;
    115   uptr fname_len = internal_strlen(info.dli_fname);
    116   if (!dyld_insert_libraries ||
    117       !REAL(strstr)(dyld_insert_libraries, info.dli_fname)) {
    118     // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
    119     // library.
    120     char program_name[1024];
    121     uint32_t buf_size = sizeof(program_name);
    122     _NSGetExecutablePath(program_name, &buf_size);
    123     char *new_env = const_cast<char*>(info.dli_fname);
    124     if (dyld_insert_libraries) {
    125       // Append the runtime dylib name to the existing value of
    126       // DYLD_INSERT_LIBRARIES.
    127       new_env = (char*)allocator_for_env.Allocate(old_env_len + fname_len + 2);
    128       internal_strncpy(new_env, dyld_insert_libraries, old_env_len);
    129       new_env[old_env_len] = ':';
    130       // Copy fname_len and add a trailing zero.
    131       internal_strncpy(new_env + old_env_len + 1, info.dli_fname,
    132                        fname_len + 1);
    133       // Ok to use setenv() since the wrappers don't depend on the value of
    134       // asan_inited.
    135       setenv(kDyldInsertLibraries, new_env, /*overwrite*/1);
    136     } else {
    137       // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name.
    138       setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0);
    139     }
    140     VReport(1, "exec()-ing the program with\n");
    141     VReport(1, "%s=%s\n", kDyldInsertLibraries, new_env);
    142     VReport(1, "to enable ASan wrappers.\n");
    143     VReport(1, "Set ASAN_OPTIONS=allow_reexec=0 to disable this.\n");
    144     execv(program_name, *_NSGetArgv());
    145   } else {
    146     // DYLD_INSERT_LIBRARIES is set and contains the runtime library.
    147     if (old_env_len == fname_len) {
    148       // It's just the runtime library name - fine to unset the variable.
    149       LeakyResetEnv(kDyldInsertLibraries, NULL);
    150     } else {
    151       uptr env_name_len = internal_strlen(kDyldInsertLibraries);
    152       // Allocate memory to hold the previous env var name, its value, the '='
    153       // sign and the '\0' char.
    154       char *new_env = (char*)allocator_for_env.Allocate(
    155           old_env_len + 2 + env_name_len);
    156       CHECK(new_env);
    157       internal_memset(new_env, '\0', old_env_len + 2 + env_name_len);
    158       internal_strncpy(new_env, kDyldInsertLibraries, env_name_len);
    159       new_env[env_name_len] = '=';
    160       char *new_env_pos = new_env + env_name_len + 1;
    161 
    162       // Iterate over colon-separated pieces of |dyld_insert_libraries|.
    163       char *piece_start = dyld_insert_libraries;
    164       char *piece_end = NULL;
    165       char *old_env_end = dyld_insert_libraries + old_env_len;
    166       do {
    167         if (piece_start[0] == ':') piece_start++;
    168         piece_end =  REAL(strchr)(piece_start, ':');
    169         if (!piece_end) piece_end = dyld_insert_libraries + old_env_len;
    170         if ((uptr)(piece_start - dyld_insert_libraries) > old_env_len) break;
    171         uptr piece_len = piece_end - piece_start;
    172 
    173         // If the current piece isn't the runtime library name,
    174         // append it to new_env.
    175         if ((piece_len != fname_len) ||
    176             (internal_strncmp(piece_start, info.dli_fname, fname_len) != 0)) {
    177           if (new_env_pos != new_env + env_name_len + 1) {
    178             new_env_pos[0] = ':';
    179             new_env_pos++;
    180           }
    181           internal_strncpy(new_env_pos, piece_start, piece_len);
    182         }
    183         // Move on to the next piece.
    184         new_env_pos += piece_len;
    185         piece_start = piece_end;
    186       } while (piece_start < old_env_end);
    187 
    188       // Can't use setenv() here, because it requires the allocator to be
    189       // initialized.
    190       // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in
    191       // a separate function called after InitializeAllocator().
    192       LeakyResetEnv(kDyldInsertLibraries, new_env);
    193     }
    194   }
    195 }
    196 
    197 // No-op. Mac does not support static linkage anyway.
    198 void *AsanDoesNotSupportStaticLinkage() {
    199   return 0;
    200 }
    201 
    202 // No-op. Mac does not support static linkage anyway.
    203 void AsanCheckDynamicRTPrereqs() {}
    204 
    205 // No-op. Mac does not support static linkage anyway.
    206 void AsanCheckIncompatibleRT() {}
    207 
    208 bool AsanInterceptsSignal(int signum) {
    209   return (signum == SIGSEGV || signum == SIGBUS) &&
    210          common_flags()->handle_segv;
    211 }
    212 
    213 void AsanPlatformThreadInit() {
    214 }
    215 
    216 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
    217   UNIMPLEMENTED();
    218 }
    219 
    220 // Support for the following functions from libdispatch on Mac OS:
    221 //   dispatch_async_f()
    222 //   dispatch_async()
    223 //   dispatch_sync_f()
    224 //   dispatch_sync()
    225 //   dispatch_after_f()
    226 //   dispatch_after()
    227 //   dispatch_group_async_f()
    228 //   dispatch_group_async()
    229 // TODO(glider): libdispatch API contains other functions that we don't support
    230 // yet.
    231 //
    232 // dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
    233 // they can cause jobs to run on a thread different from the current one.
    234 // TODO(glider): if so, we need a test for this (otherwise we should remove
    235 // them).
    236 //
    237 // The following functions use dispatch_barrier_async_f() (which isn't a library
    238 // function but is exported) and are thus supported:
    239 //   dispatch_source_set_cancel_handler_f()
    240 //   dispatch_source_set_cancel_handler()
    241 //   dispatch_source_set_event_handler_f()
    242 //   dispatch_source_set_event_handler()
    243 //
    244 // The reference manual for Grand Central Dispatch is available at
    245 //   http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
    246 // The implementation details are at
    247 //   http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
    248 
    249 typedef void* dispatch_group_t;
    250 typedef void* dispatch_queue_t;
    251 typedef void* dispatch_source_t;
    252 typedef u64 dispatch_time_t;
    253 typedef void (*dispatch_function_t)(void *block);
    254 typedef void* (*worker_t)(void *block);
    255 
    256 // A wrapper for the ObjC blocks used to support libdispatch.
    257 typedef struct {
    258   void *block;
    259   dispatch_function_t func;
    260   u32 parent_tid;
    261 } asan_block_context_t;
    262 
    263 ALWAYS_INLINE
    264 void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
    265   AsanThread *t = GetCurrentThread();
    266   if (!t) {
    267     t = AsanThread::Create(0, 0);
    268     CreateThreadContextArgs args = { t, stack };
    269     asanThreadRegistry().CreateThread(*(uptr*)t, true, parent_tid, &args);
    270     t->Init();
    271     asanThreadRegistry().StartThread(t->tid(), 0, 0);
    272     SetCurrentThread(t);
    273   }
    274 }
    275 
    276 // For use by only those functions that allocated the context via
    277 // alloc_asan_context().
    278 extern "C"
    279 void asan_dispatch_call_block_and_release(void *block) {
    280   GET_STACK_TRACE_THREAD;
    281   asan_block_context_t *context = (asan_block_context_t*)block;
    282   VReport(2,
    283           "asan_dispatch_call_block_and_release(): "
    284           "context: %p, pthread_self: %p\n",
    285           block, pthread_self());
    286   asan_register_worker_thread(context->parent_tid, &stack);
    287   // Call the original dispatcher for the block.
    288   context->func(context->block);
    289   asan_free(context, &stack, FROM_MALLOC);
    290 }
    291 
    292 }  // namespace __asan
    293 
    294 using namespace __asan;  // NOLINT
    295 
    296 // Wrap |ctxt| and |func| into an asan_block_context_t.
    297 // The caller retains control of the allocated context.
    298 extern "C"
    299 asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
    300                                          StackTrace *stack) {
    301   asan_block_context_t *asan_ctxt =
    302       (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
    303   asan_ctxt->block = ctxt;
    304   asan_ctxt->func = func;
    305   asan_ctxt->parent_tid = GetCurrentTidOrInvalid();
    306   return asan_ctxt;
    307 }
    308 
    309 // Define interceptor for dispatch_*_f function with the three most common
    310 // parameters: dispatch_queue_t, context, dispatch_function_t.
    311 #define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f)                                \
    312   INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt,            \
    313                                   dispatch_function_t func) {                 \
    314     GET_STACK_TRACE_THREAD;                                                   \
    315     asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
    316     if (common_flags()->verbosity >= 2) {                                     \
    317       Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n",             \
    318              asan_ctxt, pthread_self());                                      \
    319       PRINT_CURRENT_STACK();                                                  \
    320     }                                                                         \
    321     return REAL(dispatch_x_f)(dq, (void*)asan_ctxt,                           \
    322                               asan_dispatch_call_block_and_release);          \
    323   }
    324 
    325 INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
    326 INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
    327 INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
    328 
    329 INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
    330                                     dispatch_queue_t dq, void *ctxt,
    331                                     dispatch_function_t func) {
    332   GET_STACK_TRACE_THREAD;
    333   asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
    334   if (common_flags()->verbosity >= 2) {
    335     Report("dispatch_after_f: %p\n", asan_ctxt);
    336     PRINT_CURRENT_STACK();
    337   }
    338   return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
    339                                 asan_dispatch_call_block_and_release);
    340 }
    341 
    342 INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
    343                                           dispatch_queue_t dq, void *ctxt,
    344                                           dispatch_function_t func) {
    345   GET_STACK_TRACE_THREAD;
    346   asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
    347   if (common_flags()->verbosity >= 2) {
    348     Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
    349            asan_ctxt, pthread_self());
    350     PRINT_CURRENT_STACK();
    351   }
    352   REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
    353                                asan_dispatch_call_block_and_release);
    354 }
    355 
    356 #if !defined(MISSING_BLOCKS_SUPPORT)
    357 extern "C" {
    358 void dispatch_async(dispatch_queue_t dq, void(^work)(void));
    359 void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
    360                           void(^work)(void));
    361 void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
    362                     void(^work)(void));
    363 void dispatch_source_set_cancel_handler(dispatch_source_t ds,
    364                                         void(^work)(void));
    365 void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
    366 }
    367 
    368 #define GET_ASAN_BLOCK(work) \
    369   void (^asan_block)(void);  \
    370   int parent_tid = GetCurrentTidOrInvalid(); \
    371   asan_block = ^(void) { \
    372     GET_STACK_TRACE_THREAD; \
    373     asan_register_worker_thread(parent_tid, &stack); \
    374     work(); \
    375   }
    376 
    377 // Forces the compiler to generate a frame pointer in the function.
    378 #define ENABLE_FRAME_POINTER                                       \
    379   do {                                                             \
    380     volatile uptr enable_fp;                                       \
    381     enable_fp = GET_CURRENT_FRAME();                               \
    382   } while (0)
    383 
    384 INTERCEPTOR(void, dispatch_async,
    385             dispatch_queue_t dq, void(^work)(void)) {
    386   ENABLE_FRAME_POINTER;
    387   GET_ASAN_BLOCK(work);
    388   REAL(dispatch_async)(dq, asan_block);
    389 }
    390 
    391 INTERCEPTOR(void, dispatch_group_async,
    392             dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) {
    393   ENABLE_FRAME_POINTER;
    394   GET_ASAN_BLOCK(work);
    395   REAL(dispatch_group_async)(dg, dq, asan_block);
    396 }
    397 
    398 INTERCEPTOR(void, dispatch_after,
    399             dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) {
    400   ENABLE_FRAME_POINTER;
    401   GET_ASAN_BLOCK(work);
    402   REAL(dispatch_after)(when, queue, asan_block);
    403 }
    404 
    405 INTERCEPTOR(void, dispatch_source_set_cancel_handler,
    406             dispatch_source_t ds, void(^work)(void)) {
    407   ENABLE_FRAME_POINTER;
    408   GET_ASAN_BLOCK(work);
    409   REAL(dispatch_source_set_cancel_handler)(ds, asan_block);
    410 }
    411 
    412 INTERCEPTOR(void, dispatch_source_set_event_handler,
    413             dispatch_source_t ds, void(^work)(void)) {
    414   ENABLE_FRAME_POINTER;
    415   GET_ASAN_BLOCK(work);
    416   REAL(dispatch_source_set_event_handler)(ds, asan_block);
    417 }
    418 #endif
    419 
    420 #endif  // SANITIZER_MAC
    421