2013-02-04 Paul Thomas <pault@gcc.gnu.org>
[official-gcc.git] / libsanitizer / asan / asan_mac.cc
bloba49d5c5ab8f9df39e0cf1819145667a47c1d8dfb
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";
90 void MaybeReexec() {
91 if (!flags()->allow_reexec) return;
92 #if MAC_INTERPOSE_FUNCTIONS
93 // If the program is linked with the dynamic ASan runtime library, make sure
94 // the library is preloaded so that the wrappers work. If it is not, set
95 // DYLD_INSERT_LIBRARIES and re-exec ourselves.
96 Dl_info info;
97 CHECK(dladdr((void*)((uptr)__asan_init), &info));
98 const char *dyld_insert_libraries = GetEnv(kDyldInsertLibraries);
99 if (!dyld_insert_libraries ||
100 !REAL(strstr)(dyld_insert_libraries, info.dli_fname)) {
101 // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
102 // library.
103 char program_name[1024];
104 uint32_t buf_size = sizeof(program_name);
105 _NSGetExecutablePath(program_name, &buf_size);
106 // Ok to use setenv() since the wrappers don't depend on the value of
107 // asan_inited.
108 setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0);
109 if (flags()->verbosity >= 1) {
110 Report("exec()-ing the program with\n");
111 Report("%s=%s\n", kDyldInsertLibraries, info.dli_fname);
112 Report("to enable ASan wrappers.\n");
113 Report("Set ASAN_OPTIONS=allow_reexec=0 to disable this.\n");
115 execv(program_name, *_NSGetArgv());
117 #endif // MAC_INTERPOSE_FUNCTIONS
118 // If we're not using the dynamic runtime, do nothing.
121 // No-op. Mac does not support static linkage anyway.
122 void *AsanDoesNotSupportStaticLinkage() {
123 return 0;
126 bool AsanInterceptsSignal(int signum) {
127 return (signum == SIGSEGV || signum == SIGBUS) && flags()->handle_segv;
130 void AsanPlatformThreadInit() {
133 void GetStackTrace(StackTrace *stack, uptr max_s, uptr pc, uptr bp, bool fast) {
134 (void)fast;
135 stack->size = 0;
136 stack->trace[0] = pc;
137 if ((max_s) > 1) {
138 stack->max_size = max_s;
139 if (!asan_inited) return;
140 if (AsanThread *t = asanThreadRegistry().GetCurrent())
141 stack->FastUnwindStack(pc, bp, t->stack_top(), t->stack_bottom());
145 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
146 UNIMPLEMENTED();
149 // The range of pages to be used for escape islands.
150 // TODO(glider): instead of mapping a fixed range we must find a range of
151 // unmapped pages in vmmap and take them.
152 // These constants were chosen empirically and may not work if the shadow
153 // memory layout changes. Unfortunately they do necessarily depend on
154 // kHighMemBeg or kHighMemEnd.
155 static void *island_allocator_pos = 0;
157 #if SANITIZER_WORDSIZE == 32
158 # define kIslandEnd (0xffdf0000 - GetPageSizeCached())
159 # define kIslandBeg (kIslandEnd - 256 * GetPageSizeCached())
160 #else
161 # define kIslandEnd (0x7fffffdf0000 - GetPageSizeCached())
162 # define kIslandBeg (kIslandEnd - 256 * GetPageSizeCached())
163 #endif
165 extern "C"
166 mach_error_t __interception_allocate_island(void **ptr,
167 uptr unused_size,
168 void *unused_hint) {
169 if (!island_allocator_pos) {
170 island_allocator_pos =
171 internal_mmap((void*)kIslandBeg, kIslandEnd - kIslandBeg,
172 PROT_READ | PROT_WRITE | PROT_EXEC,
173 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
174 -1, 0);
175 if (island_allocator_pos != (void*)kIslandBeg) {
176 return KERN_NO_SPACE;
178 if (flags()->verbosity) {
179 Report("Mapped pages %p--%p for branch islands.\n",
180 (void*)kIslandBeg, (void*)kIslandEnd);
182 // Should not be very performance-critical.
183 internal_memset(island_allocator_pos, 0xCC, kIslandEnd - kIslandBeg);
185 *ptr = island_allocator_pos;
186 island_allocator_pos = (char*)island_allocator_pos + GetPageSizeCached();
187 if (flags()->verbosity) {
188 Report("Branch island allocated at %p\n", *ptr);
190 return err_none;
193 extern "C"
194 mach_error_t __interception_deallocate_island(void *ptr) {
195 // Do nothing.
196 // TODO(glider): allow to free and reuse the island memory.
197 return err_none;
200 // Support for the following functions from libdispatch on Mac OS:
201 // dispatch_async_f()
202 // dispatch_async()
203 // dispatch_sync_f()
204 // dispatch_sync()
205 // dispatch_after_f()
206 // dispatch_after()
207 // dispatch_group_async_f()
208 // dispatch_group_async()
209 // TODO(glider): libdispatch API contains other functions that we don't support
210 // yet.
212 // dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
213 // they can cause jobs to run on a thread different from the current one.
214 // TODO(glider): if so, we need a test for this (otherwise we should remove
215 // them).
217 // The following functions use dispatch_barrier_async_f() (which isn't a library
218 // function but is exported) and are thus supported:
219 // dispatch_source_set_cancel_handler_f()
220 // dispatch_source_set_cancel_handler()
221 // dispatch_source_set_event_handler_f()
222 // dispatch_source_set_event_handler()
224 // The reference manual for Grand Central Dispatch is available at
225 // http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
226 // The implementation details are at
227 // http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
229 typedef void* dispatch_group_t;
230 typedef void* dispatch_queue_t;
231 typedef void* dispatch_source_t;
232 typedef u64 dispatch_time_t;
233 typedef void (*dispatch_function_t)(void *block);
234 typedef void* (*worker_t)(void *block);
236 // A wrapper for the ObjC blocks used to support libdispatch.
237 typedef struct {
238 void *block;
239 dispatch_function_t func;
240 u32 parent_tid;
241 } asan_block_context_t;
243 // We use extern declarations of libdispatch functions here instead
244 // of including <dispatch/dispatch.h>. This header is not present on
245 // Mac OS X Leopard and eariler, and although we don't expect ASan to
246 // work on legacy systems, it's bad to break the build of
247 // LLVM compiler-rt there.
248 extern "C" {
249 void dispatch_async_f(dispatch_queue_t dq, void *ctxt,
250 dispatch_function_t func);
251 void dispatch_sync_f(dispatch_queue_t dq, void *ctxt,
252 dispatch_function_t func);
253 void dispatch_after_f(dispatch_time_t when, dispatch_queue_t dq, void *ctxt,
254 dispatch_function_t func);
255 void dispatch_barrier_async_f(dispatch_queue_t dq, void *ctxt,
256 dispatch_function_t func);
257 void dispatch_group_async_f(dispatch_group_t group, dispatch_queue_t dq,
258 void *ctxt, dispatch_function_t func);
259 } // extern "C"
261 static ALWAYS_INLINE
262 void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
263 AsanThread *t = asanThreadRegistry().GetCurrent();
264 if (!t) {
265 t = AsanThread::Create(parent_tid, 0, 0, stack);
266 asanThreadRegistry().RegisterThread(t);
267 t->Init();
268 asanThreadRegistry().SetCurrent(t);
272 // For use by only those functions that allocated the context via
273 // alloc_asan_context().
274 extern "C"
275 void asan_dispatch_call_block_and_release(void *block) {
276 GET_STACK_TRACE_THREAD;
277 asan_block_context_t *context = (asan_block_context_t*)block;
278 if (flags()->verbosity >= 2) {
279 Report("asan_dispatch_call_block_and_release(): "
280 "context: %p, pthread_self: %p\n",
281 block, pthread_self());
283 asan_register_worker_thread(context->parent_tid, &stack);
284 // Call the original dispatcher for the block.
285 context->func(context->block);
286 asan_free(context, &stack, FROM_MALLOC);
289 } // namespace __asan
291 using namespace __asan; // NOLINT
293 // Wrap |ctxt| and |func| into an asan_block_context_t.
294 // The caller retains control of the allocated context.
295 extern "C"
296 asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
297 StackTrace *stack) {
298 asan_block_context_t *asan_ctxt =
299 (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
300 asan_ctxt->block = ctxt;
301 asan_ctxt->func = func;
302 asan_ctxt->parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid();
303 return asan_ctxt;
306 // Define interceptor for dispatch_*_f function with the three most common
307 // parameters: dispatch_queue_t, context, dispatch_function_t.
308 #define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f) \
309 INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt, \
310 dispatch_function_t func) { \
311 GET_STACK_TRACE_THREAD; \
312 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
313 if (flags()->verbosity >= 2) { \
314 Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n", \
315 asan_ctxt, pthread_self()); \
316 PRINT_CURRENT_STACK(); \
318 return REAL(dispatch_x_f)(dq, (void*)asan_ctxt, \
319 asan_dispatch_call_block_and_release); \
322 INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
323 INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
324 INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
326 INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
327 dispatch_queue_t dq, void *ctxt,
328 dispatch_function_t func) {
329 GET_STACK_TRACE_THREAD;
330 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
331 if (flags()->verbosity >= 2) {
332 Report("dispatch_after_f: %p\n", asan_ctxt);
333 PRINT_CURRENT_STACK();
335 return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
336 asan_dispatch_call_block_and_release);
339 INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
340 dispatch_queue_t dq, void *ctxt,
341 dispatch_function_t func) {
342 GET_STACK_TRACE_THREAD;
343 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
344 if (flags()->verbosity >= 2) {
345 Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
346 asan_ctxt, pthread_self());
347 PRINT_CURRENT_STACK();
349 REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
350 asan_dispatch_call_block_and_release);
353 #if MAC_INTERPOSE_FUNCTIONS && !defined(MISSING_BLOCKS_SUPPORT)
354 // dispatch_async, dispatch_group_async and others tailcall the corresponding
355 // dispatch_*_f functions. When wrapping functions with mach_override, those
356 // dispatch_*_f are intercepted automatically. But with dylib interposition
357 // this does not work, because the calls within the same library are not
358 // interposed.
359 // Therefore we need to re-implement dispatch_async and friends.
361 extern "C" {
362 // FIXME: consolidate these declarations with asan_intercepted_functions.h.
363 void dispatch_async(dispatch_queue_t dq, void(^work)(void));
364 void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
365 void(^work)(void));
366 void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
367 void(^work)(void));
368 void dispatch_source_set_cancel_handler(dispatch_source_t ds,
369 void(^work)(void));
370 void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
373 #define GET_ASAN_BLOCK(work) \
374 void (^asan_block)(void); \
375 int parent_tid = asanThreadRegistry().GetCurrentTidOrInvalid(); \
376 asan_block = ^(void) { \
377 GET_STACK_TRACE_THREAD; \
378 asan_register_worker_thread(parent_tid, &stack); \
379 work(); \
382 INTERCEPTOR(void, dispatch_async,
383 dispatch_queue_t dq, void(^work)(void)) {
384 GET_ASAN_BLOCK(work);
385 REAL(dispatch_async)(dq, asan_block);
388 INTERCEPTOR(void, dispatch_group_async,
389 dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) {
390 GET_ASAN_BLOCK(work);
391 REAL(dispatch_group_async)(dg, dq, asan_block);
394 INTERCEPTOR(void, dispatch_after,
395 dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) {
396 GET_ASAN_BLOCK(work);
397 REAL(dispatch_after)(when, queue, asan_block);
400 INTERCEPTOR(void, dispatch_source_set_cancel_handler,
401 dispatch_source_t ds, void(^work)(void)) {
402 GET_ASAN_BLOCK(work);
403 REAL(dispatch_source_set_cancel_handler)(ds, asan_block);
406 INTERCEPTOR(void, dispatch_source_set_event_handler,
407 dispatch_source_t ds, void(^work)(void)) {
408 GET_ASAN_BLOCK(work);
409 REAL(dispatch_source_set_event_handler)(ds, asan_block);
411 #endif
413 namespace __asan {
415 void InitializeMacInterceptors() {
416 CHECK(INTERCEPT_FUNCTION(dispatch_async_f));
417 CHECK(INTERCEPT_FUNCTION(dispatch_sync_f));
418 CHECK(INTERCEPT_FUNCTION(dispatch_after_f));
419 CHECK(INTERCEPT_FUNCTION(dispatch_barrier_async_f));
420 CHECK(INTERCEPT_FUNCTION(dispatch_group_async_f));
423 } // namespace __asan
425 #endif // __APPLE__