libsanitizer merge from upstream r175733
[official-gcc.git] / libsanitizer / asan / asan_mac.cc
blobdd2657df1e25277506bc30eb252435690c872426
1 //===-- asan_mac.cc -------------------------------------------------------===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This file is a part of AddressSanitizer, an address sanity checker.
9 //
10 // Mac-specific details.
11 //===----------------------------------------------------------------------===//
13 #ifdef __APPLE__
15 #include "asan_interceptors.h"
16 #include "asan_internal.h"
17 #include "asan_mac.h"
18 #include "asan_mapping.h"
19 #include "asan_stack.h"
20 #include "asan_thread.h"
21 #include "asan_thread_registry.h"
22 #include "sanitizer_common/sanitizer_libc.h"
24 #include <crt_externs.h> // for _NSGetArgv
25 #include <dlfcn.h> // for dladdr()
26 #include <mach-o/dyld.h>
27 #include <mach-o/loader.h>
28 #include <sys/mman.h>
29 #include <sys/resource.h>
30 #include <sys/sysctl.h>
31 #include <sys/ucontext.h>
32 #include <fcntl.h>
33 #include <pthread.h>
34 #include <stdlib.h> // for free()
35 #include <unistd.h>
36 #include <libkern/OSAtomic.h>
38 namespace __asan {
40 void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
41 ucontext_t *ucontext = (ucontext_t*)context;
42 # if SANITIZER_WORDSIZE == 64
43 *pc = ucontext->uc_mcontext->__ss.__rip;
44 *bp = ucontext->uc_mcontext->__ss.__rbp;
45 *sp = ucontext->uc_mcontext->__ss.__rsp;
46 # else
47 *pc = ucontext->uc_mcontext->__ss.__eip;
48 *bp = ucontext->uc_mcontext->__ss.__ebp;
49 *sp = ucontext->uc_mcontext->__ss.__esp;
50 # endif // SANITIZER_WORDSIZE
53 int GetMacosVersion() {
54 int mib[2] = { CTL_KERN, KERN_OSRELEASE };
55 char version[100];
56 uptr len = 0, maxlen = sizeof(version) / sizeof(version[0]);
57 for (uptr i = 0; i < maxlen; i++) version[i] = '\0';
58 // Get the version length.
59 CHECK(sysctl(mib, 2, 0, &len, 0, 0) != -1);
60 CHECK(len < maxlen);
61 CHECK(sysctl(mib, 2, version, &len, 0, 0) != -1);
62 switch (version[0]) {
63 case '9': return MACOS_VERSION_LEOPARD;
64 case '1': {
65 switch (version[1]) {
66 case '0': return MACOS_VERSION_SNOW_LEOPARD;
67 case '1': return MACOS_VERSION_LION;
68 case '2': return MACOS_VERSION_MOUNTAIN_LION;
69 default: return MACOS_VERSION_UNKNOWN;
72 default: return MACOS_VERSION_UNKNOWN;
76 bool PlatformHasDifferentMemcpyAndMemmove() {
77 // On OS X 10.7 memcpy() and memmove() are both resolved
78 // into memmove$VARIANT$sse42.
79 // See also http://code.google.com/p/address-sanitizer/issues/detail?id=34.
80 // TODO(glider): need to check dynamically that memcpy() and memmove() are
81 // actually the same function.
82 return GetMacosVersion() == MACOS_VERSION_SNOW_LEOPARD;
85 extern "C"
86 void __asan_init();
88 static const char kDyldInsertLibraries[] = "DYLD_INSERT_LIBRARIES";
89 LowLevelAllocator allocator_for_env;
91 // Change the value of the env var |name|, leaking the original value.
92 // If |name_value| is NULL, the variable is deleted from the environment,
93 // otherwise the corresponding "NAME=value" string is replaced with
94 // |name_value|.
95 void LeakyResetEnv(const char *name, const char *name_value) {
96 char ***env_ptr = _NSGetEnviron();
97 CHECK(env_ptr);
98 char **environ = *env_ptr;
99 CHECK(environ);
100 uptr name_len = internal_strlen(name);
101 while (*environ != 0) {
102 uptr len = internal_strlen(*environ);
103 if (len > name_len) {
104 const char *p = *environ;
105 if (!internal_memcmp(p, name, name_len) && p[name_len] == '=') {
106 // Match.
107 if (name_value) {
108 // Replace the old value with the new one.
109 *environ = const_cast<char*>(name_value);
110 } else {
111 // Shift the subsequent pointers back.
112 char **del = environ;
113 do {
114 del[0] = del[1];
115 } while (*del++);
119 environ++;
123 void MaybeReexec() {
124 if (!flags()->allow_reexec) return;
125 // Make sure the dynamic ASan runtime library is preloaded so that the
126 // wrappers work. If it is not, set DYLD_INSERT_LIBRARIES and re-exec
127 // ourselves.
128 Dl_info info;
129 CHECK(dladdr((void*)((uptr)__asan_init), &info));
130 char *dyld_insert_libraries =
131 const_cast<char*>(GetEnv(kDyldInsertLibraries));
132 uptr old_env_len = dyld_insert_libraries ?
133 internal_strlen(dyld_insert_libraries) : 0;
134 uptr fname_len = internal_strlen(info.dli_fname);
135 if (!dyld_insert_libraries ||
136 !REAL(strstr)(dyld_insert_libraries, info.dli_fname)) {
137 // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
138 // library.
139 char program_name[1024];
140 uint32_t buf_size = sizeof(program_name);
141 _NSGetExecutablePath(program_name, &buf_size);
142 char *new_env = const_cast<char*>(info.dli_fname);
143 if (dyld_insert_libraries) {
144 // Append the runtime dylib name to the existing value of
145 // DYLD_INSERT_LIBRARIES.
146 new_env = (char*)allocator_for_env.Allocate(old_env_len + fname_len + 2);
147 internal_strncpy(new_env, dyld_insert_libraries, old_env_len);
148 new_env[old_env_len] = ':';
149 // Copy fname_len and add a trailing zero.
150 internal_strncpy(new_env + old_env_len + 1, info.dli_fname,
151 fname_len + 1);
152 // Ok to use setenv() since the wrappers don't depend on the value of
153 // asan_inited.
154 setenv(kDyldInsertLibraries, new_env, /*overwrite*/1);
155 } else {
156 // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name.
157 setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0);
159 if (flags()->verbosity >= 1) {
160 Report("exec()-ing the program with\n");
161 Report("%s=%s\n", kDyldInsertLibraries, new_env);
162 Report("to enable ASan wrappers.\n");
163 Report("Set ASAN_OPTIONS=allow_reexec=0 to disable this.\n");
165 execv(program_name, *_NSGetArgv());
166 } else {
167 // DYLD_INSERT_LIBRARIES is set and contains the runtime library.
168 if (old_env_len == fname_len) {
169 // It's just the runtime library name - fine to unset the variable.
170 LeakyResetEnv(kDyldInsertLibraries, NULL);
171 } else {
172 uptr env_name_len = internal_strlen(kDyldInsertLibraries);
173 // Allocate memory to hold the previous env var name, its value, the '='
174 // sign and the '\0' char.
175 char *new_env = (char*)allocator_for_env.Allocate(
176 old_env_len + 2 + env_name_len);
177 CHECK(new_env);
178 internal_memset(new_env, '\0', old_env_len + 2 + env_name_len);
179 internal_strncpy(new_env, kDyldInsertLibraries, env_name_len);
180 new_env[env_name_len] = '=';
181 char *new_env_pos = new_env + env_name_len + 1;
183 // Iterate over colon-separated pieces of |dyld_insert_libraries|.
184 char *piece_start = dyld_insert_libraries;
185 char *piece_end = NULL;
186 char *old_env_end = dyld_insert_libraries + old_env_len;
187 do {
188 if (piece_start[0] == ':') piece_start++;
189 piece_end = REAL(strchr)(piece_start, ':');
190 if (!piece_end) piece_end = dyld_insert_libraries + old_env_len;
191 if ((uptr)(piece_start - dyld_insert_libraries) > old_env_len) break;
192 uptr piece_len = piece_end - piece_start;
194 // If the current piece isn't the runtime library name,
195 // append it to new_env.
196 if ((piece_len != fname_len) ||
197 (internal_strncmp(piece_start, info.dli_fname, fname_len) != 0)) {
198 if (new_env_pos != new_env + env_name_len + 1) {
199 new_env_pos[0] = ':';
200 new_env_pos++;
202 internal_strncpy(new_env_pos, piece_start, piece_len);
204 // Move on to the next piece.
205 new_env_pos += piece_len;
206 piece_start = piece_end;
207 } while (piece_start < old_env_end);
209 // Can't use setenv() here, because it requires the allocator to be
210 // initialized.
211 // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in
212 // a separate function called after InitializeAllocator().
213 LeakyResetEnv(kDyldInsertLibraries, new_env);
218 // No-op. Mac does not support static linkage anyway.
219 void *AsanDoesNotSupportStaticLinkage() {
220 return 0;
223 bool AsanInterceptsSignal(int signum) {
224 return (signum == SIGSEGV || signum == SIGBUS) && flags()->handle_segv;
227 void AsanPlatformThreadInit() {
230 void GetStackTrace(StackTrace *stack, uptr max_s, uptr pc, uptr bp, bool fast) {
231 (void)fast;
232 stack->size = 0;
233 stack->trace[0] = pc;
234 if ((max_s) > 1) {
235 stack->max_size = max_s;
236 if (!asan_inited) return;
237 if (AsanThread *t = asanThreadRegistry().GetCurrent())
238 stack->FastUnwindStack(pc, bp, t->stack_top(), t->stack_bottom());
242 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
243 UNIMPLEMENTED();
246 // Support for the following functions from libdispatch on Mac OS:
247 // dispatch_async_f()
248 // dispatch_async()
249 // dispatch_sync_f()
250 // dispatch_sync()
251 // dispatch_after_f()
252 // dispatch_after()
253 // dispatch_group_async_f()
254 // dispatch_group_async()
255 // TODO(glider): libdispatch API contains other functions that we don't support
256 // yet.
258 // dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
259 // they can cause jobs to run on a thread different from the current one.
260 // TODO(glider): if so, we need a test for this (otherwise we should remove
261 // them).
263 // The following functions use dispatch_barrier_async_f() (which isn't a library
264 // function but is exported) and are thus supported:
265 // dispatch_source_set_cancel_handler_f()
266 // dispatch_source_set_cancel_handler()
267 // dispatch_source_set_event_handler_f()
268 // dispatch_source_set_event_handler()
270 // The reference manual for Grand Central Dispatch is available at
271 // http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
272 // The implementation details are at
273 // http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
275 typedef void* dispatch_group_t;
276 typedef void* dispatch_queue_t;
277 typedef void* dispatch_source_t;
278 typedef u64 dispatch_time_t;
279 typedef void (*dispatch_function_t)(void *block);
280 typedef void* (*worker_t)(void *block);
282 // A wrapper for the ObjC blocks used to support libdispatch.
283 typedef struct {
284 void *block;
285 dispatch_function_t func;
286 u32 parent_tid;
287 } asan_block_context_t;
289 // We use extern declarations of libdispatch functions here instead
290 // of including <dispatch/dispatch.h>. This header is not present on
291 // Mac OS X Leopard and eariler, and although we don't expect ASan to
292 // work on legacy systems, it's bad to break the build of
293 // LLVM compiler-rt there.
294 extern "C" {
295 void dispatch_async_f(dispatch_queue_t dq, void *ctxt,
296 dispatch_function_t func);
297 void dispatch_sync_f(dispatch_queue_t dq, void *ctxt,
298 dispatch_function_t func);
299 void dispatch_after_f(dispatch_time_t when, dispatch_queue_t dq, void *ctxt,
300 dispatch_function_t func);
301 void dispatch_barrier_async_f(dispatch_queue_t dq, void *ctxt,
302 dispatch_function_t func);
303 void dispatch_group_async_f(dispatch_group_t group, dispatch_queue_t dq,
304 void *ctxt, dispatch_function_t func);
305 } // extern "C"
307 static ALWAYS_INLINE
308 void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
309 AsanThread *t = asanThreadRegistry().GetCurrent();
310 if (!t) {
311 t = AsanThread::Create(parent_tid, 0, 0, stack);
312 asanThreadRegistry().RegisterThread(t);
313 t->Init();
314 asanThreadRegistry().SetCurrent(t);
318 // For use by only those functions that allocated the context via
319 // alloc_asan_context().
320 extern "C"
321 void asan_dispatch_call_block_and_release(void *block) {
322 GET_STACK_TRACE_THREAD;
323 asan_block_context_t *context = (asan_block_context_t*)block;
324 if (flags()->verbosity >= 2) {
325 Report("asan_dispatch_call_block_and_release(): "
326 "context: %p, pthread_self: %p\n",
327 block, pthread_self());
329 asan_register_worker_thread(context->parent_tid, &stack);
330 // Call the original dispatcher for the block.
331 context->func(context->block);
332 asan_free(context, &stack, FROM_MALLOC);
335 } // namespace __asan
337 using namespace __asan; // NOLINT
339 // Wrap |ctxt| and |func| into an asan_block_context_t.
340 // The caller retains control of the allocated context.
341 extern "C"
342 asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
343 StackTrace *stack) {
344 asan_block_context_t *asan_ctxt =
345 (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
346 asan_ctxt->block = ctxt;
347 asan_ctxt->func = func;
348 asan_ctxt->parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid();
349 return asan_ctxt;
352 // Define interceptor for dispatch_*_f function with the three most common
353 // parameters: dispatch_queue_t, context, dispatch_function_t.
354 #define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f) \
355 INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt, \
356 dispatch_function_t func) { \
357 GET_STACK_TRACE_THREAD; \
358 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
359 if (flags()->verbosity >= 2) { \
360 Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n", \
361 asan_ctxt, pthread_self()); \
362 PRINT_CURRENT_STACK(); \
364 return REAL(dispatch_x_f)(dq, (void*)asan_ctxt, \
365 asan_dispatch_call_block_and_release); \
368 INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
369 INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
370 INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
372 INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
373 dispatch_queue_t dq, void *ctxt,
374 dispatch_function_t func) {
375 GET_STACK_TRACE_THREAD;
376 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
377 if (flags()->verbosity >= 2) {
378 Report("dispatch_after_f: %p\n", asan_ctxt);
379 PRINT_CURRENT_STACK();
381 return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
382 asan_dispatch_call_block_and_release);
385 INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
386 dispatch_queue_t dq, void *ctxt,
387 dispatch_function_t func) {
388 GET_STACK_TRACE_THREAD;
389 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
390 if (flags()->verbosity >= 2) {
391 Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
392 asan_ctxt, pthread_self());
393 PRINT_CURRENT_STACK();
395 REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
396 asan_dispatch_call_block_and_release);
399 #if !defined(MISSING_BLOCKS_SUPPORT)
400 extern "C" {
401 // FIXME: consolidate these declarations with asan_intercepted_functions.h.
402 void dispatch_async(dispatch_queue_t dq, void(^work)(void));
403 void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
404 void(^work)(void));
405 void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
406 void(^work)(void));
407 void dispatch_source_set_cancel_handler(dispatch_source_t ds,
408 void(^work)(void));
409 void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
412 #define GET_ASAN_BLOCK(work) \
413 void (^asan_block)(void); \
414 int parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid(); \
415 asan_block = ^(void) { \
416 GET_STACK_TRACE_THREAD; \
417 asan_register_worker_thread(parent_tid, &stack); \
418 work(); \
421 INTERCEPTOR(void, dispatch_async,
422 dispatch_queue_t dq, void(^work)(void)) {
423 GET_ASAN_BLOCK(work);
424 REAL(dispatch_async)(dq, asan_block);
427 INTERCEPTOR(void, dispatch_group_async,
428 dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) {
429 GET_ASAN_BLOCK(work);
430 REAL(dispatch_group_async)(dg, dq, asan_block);
433 INTERCEPTOR(void, dispatch_after,
434 dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) {
435 GET_ASAN_BLOCK(work);
436 REAL(dispatch_after)(when, queue, asan_block);
439 INTERCEPTOR(void, dispatch_source_set_cancel_handler,
440 dispatch_source_t ds, void(^work)(void)) {
441 GET_ASAN_BLOCK(work);
442 REAL(dispatch_source_set_cancel_handler)(ds, asan_block);
445 INTERCEPTOR(void, dispatch_source_set_event_handler,
446 dispatch_source_t ds, void(^work)(void)) {
447 GET_ASAN_BLOCK(work);
448 REAL(dispatch_source_set_event_handler)(ds, asan_block);
450 #endif
452 #endif // __APPLE__