1 //===-- asan_mac.cc -------------------------------------------------------===//
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
6 //===----------------------------------------------------------------------===//
8 // This file is a part of AddressSanitizer, an address sanity checker.
10 // Mac-specific details.
11 //===----------------------------------------------------------------------===//
13 #include "sanitizer_common/sanitizer_platform.h"
16 #include "asan_interceptors.h"
17 #include "asan_internal.h"
18 #include "asan_mapping.h"
19 #include "asan_stack.h"
20 #include "asan_thread.h"
21 #include "sanitizer_common/sanitizer_atomic.h"
22 #include "sanitizer_common/sanitizer_libc.h"
23 #include "sanitizer_common/sanitizer_mac.h"
25 #include <crt_externs.h> // for _NSGetArgv
26 #include <dlfcn.h> // for dladdr()
27 #include <mach-o/dyld.h>
28 #include <mach-o/loader.h>
30 #include <sys/resource.h>
31 #include <sys/sysctl.h>
32 #include <sys/ucontext.h>
35 #include <stdlib.h> // for free()
37 #include <libkern/OSAtomic.h>
41 void GetPcSpBp(void *context
, uptr
*pc
, uptr
*sp
, uptr
*bp
) {
42 ucontext_t
*ucontext
= (ucontext_t
*)context
;
43 # if SANITIZER_WORDSIZE == 64
44 *pc
= ucontext
->uc_mcontext
->__ss
.__rip
;
45 *bp
= ucontext
->uc_mcontext
->__ss
.__rbp
;
46 *sp
= ucontext
->uc_mcontext
->__ss
.__rsp
;
48 *pc
= ucontext
->uc_mcontext
->__ss
.__eip
;
49 *bp
= ucontext
->uc_mcontext
->__ss
.__ebp
;
50 *sp
= ucontext
->uc_mcontext
->__ss
.__esp
;
51 # endif // SANITIZER_WORDSIZE
55 bool PlatformHasDifferentMemcpyAndMemmove() {
56 // On OS X 10.7 memcpy() and memmove() are both resolved
57 // into memmove$VARIANT$sse42.
58 // See also http://code.google.com/p/address-sanitizer/issues/detail?id=34.
59 // TODO(glider): need to check dynamically that memcpy() and memmove() are
60 // actually the same function.
61 return GetMacosVersion() == MACOS_VERSION_SNOW_LEOPARD
;
67 static const char kDyldInsertLibraries
[] = "DYLD_INSERT_LIBRARIES";
68 LowLevelAllocator allocator_for_env
;
70 // Change the value of the env var |name|, leaking the original value.
71 // If |name_value| is NULL, the variable is deleted from the environment,
72 // otherwise the corresponding "NAME=value" string is replaced with
74 void LeakyResetEnv(const char *name
, const char *name_value
) {
75 char ***env_ptr
= _NSGetEnviron();
77 char **environ
= *env_ptr
;
79 uptr name_len
= internal_strlen(name
);
80 while (*environ
!= 0) {
81 uptr len
= internal_strlen(*environ
);
83 const char *p
= *environ
;
84 if (!internal_memcmp(p
, name
, name_len
) && p
[name_len
] == '=') {
87 // Replace the old value with the new one.
88 *environ
= const_cast<char*>(name_value
);
90 // Shift the subsequent pointers back.
103 if (!flags()->allow_reexec
) return;
104 // Make sure the dynamic ASan runtime library is preloaded so that the
105 // wrappers work. If it is not, set DYLD_INSERT_LIBRARIES and re-exec
108 CHECK(dladdr((void*)((uptr
)__asan_init
), &info
));
109 char *dyld_insert_libraries
=
110 const_cast<char*>(GetEnv(kDyldInsertLibraries
));
111 uptr old_env_len
= dyld_insert_libraries
?
112 internal_strlen(dyld_insert_libraries
) : 0;
113 uptr fname_len
= internal_strlen(info
.dli_fname
);
114 if (!dyld_insert_libraries
||
115 !REAL(strstr
)(dyld_insert_libraries
, info
.dli_fname
)) {
116 // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
118 char program_name
[1024];
119 uint32_t buf_size
= sizeof(program_name
);
120 _NSGetExecutablePath(program_name
, &buf_size
);
121 char *new_env
= const_cast<char*>(info
.dli_fname
);
122 if (dyld_insert_libraries
) {
123 // Append the runtime dylib name to the existing value of
124 // DYLD_INSERT_LIBRARIES.
125 new_env
= (char*)allocator_for_env
.Allocate(old_env_len
+ fname_len
+ 2);
126 internal_strncpy(new_env
, dyld_insert_libraries
, old_env_len
);
127 new_env
[old_env_len
] = ':';
128 // Copy fname_len and add a trailing zero.
129 internal_strncpy(new_env
+ old_env_len
+ 1, info
.dli_fname
,
131 // Ok to use setenv() since the wrappers don't depend on the value of
133 setenv(kDyldInsertLibraries
, new_env
, /*overwrite*/1);
135 // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name.
136 setenv(kDyldInsertLibraries
, info
.dli_fname
, /*overwrite*/0);
138 VReport(1, "exec()-ing the program with\n");
139 VReport(1, "%s=%s\n", kDyldInsertLibraries
, new_env
);
140 VReport(1, "to enable ASan wrappers.\n");
141 VReport(1, "Set ASAN_OPTIONS=allow_reexec=0 to disable this.\n");
142 execv(program_name
, *_NSGetArgv());
144 // DYLD_INSERT_LIBRARIES is set and contains the runtime library.
145 if (old_env_len
== fname_len
) {
146 // It's just the runtime library name - fine to unset the variable.
147 LeakyResetEnv(kDyldInsertLibraries
, NULL
);
149 uptr env_name_len
= internal_strlen(kDyldInsertLibraries
);
150 // Allocate memory to hold the previous env var name, its value, the '='
151 // sign and the '\0' char.
152 char *new_env
= (char*)allocator_for_env
.Allocate(
153 old_env_len
+ 2 + env_name_len
);
155 internal_memset(new_env
, '\0', old_env_len
+ 2 + env_name_len
);
156 internal_strncpy(new_env
, kDyldInsertLibraries
, env_name_len
);
157 new_env
[env_name_len
] = '=';
158 char *new_env_pos
= new_env
+ env_name_len
+ 1;
160 // Iterate over colon-separated pieces of |dyld_insert_libraries|.
161 char *piece_start
= dyld_insert_libraries
;
162 char *piece_end
= NULL
;
163 char *old_env_end
= dyld_insert_libraries
+ old_env_len
;
165 if (piece_start
[0] == ':') piece_start
++;
166 piece_end
= REAL(strchr
)(piece_start
, ':');
167 if (!piece_end
) piece_end
= dyld_insert_libraries
+ old_env_len
;
168 if ((uptr
)(piece_start
- dyld_insert_libraries
) > old_env_len
) break;
169 uptr piece_len
= piece_end
- piece_start
;
171 // If the current piece isn't the runtime library name,
172 // append it to new_env.
173 if ((piece_len
!= fname_len
) ||
174 (internal_strncmp(piece_start
, info
.dli_fname
, fname_len
) != 0)) {
175 if (new_env_pos
!= new_env
+ env_name_len
+ 1) {
176 new_env_pos
[0] = ':';
179 internal_strncpy(new_env_pos
, piece_start
, piece_len
);
181 // Move on to the next piece.
182 new_env_pos
+= piece_len
;
183 piece_start
= piece_end
;
184 } while (piece_start
< old_env_end
);
186 // Can't use setenv() here, because it requires the allocator to be
188 // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in
189 // a separate function called after InitializeAllocator().
190 LeakyResetEnv(kDyldInsertLibraries
, new_env
);
195 // No-op. Mac does not support static linkage anyway.
196 void *AsanDoesNotSupportStaticLinkage() {
200 // No-op. Mac does not support static linkage anyway.
201 void AsanCheckDynamicRTPrereqs() {}
203 // No-op. Mac does not support static linkage anyway.
204 void AsanCheckIncompatibleRT() {}
206 bool AsanInterceptsSignal(int signum
) {
207 return (signum
== SIGSEGV
|| signum
== SIGBUS
) &&
208 common_flags()->handle_segv
;
211 void AsanPlatformThreadInit() {
214 void ReadContextStack(void *context
, uptr
*stack
, uptr
*ssize
) {
218 // Support for the following functions from libdispatch on Mac OS:
219 // dispatch_async_f()
223 // dispatch_after_f()
225 // dispatch_group_async_f()
226 // dispatch_group_async()
227 // TODO(glider): libdispatch API contains other functions that we don't support
230 // dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
231 // they can cause jobs to run on a thread different from the current one.
232 // TODO(glider): if so, we need a test for this (otherwise we should remove
235 // The following functions use dispatch_barrier_async_f() (which isn't a library
236 // function but is exported) and are thus supported:
237 // dispatch_source_set_cancel_handler_f()
238 // dispatch_source_set_cancel_handler()
239 // dispatch_source_set_event_handler_f()
240 // dispatch_source_set_event_handler()
242 // The reference manual for Grand Central Dispatch is available at
243 // http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
244 // The implementation details are at
245 // http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
247 typedef void* dispatch_group_t
;
248 typedef void* dispatch_queue_t
;
249 typedef void* dispatch_source_t
;
250 typedef u64 dispatch_time_t
;
251 typedef void (*dispatch_function_t
)(void *block
);
252 typedef void* (*worker_t
)(void *block
);
254 // A wrapper for the ObjC blocks used to support libdispatch.
257 dispatch_function_t func
;
259 } asan_block_context_t
;
262 void asan_register_worker_thread(int parent_tid
, StackTrace
*stack
) {
263 AsanThread
*t
= GetCurrentThread();
265 t
= AsanThread::Create(0, 0);
266 CreateThreadContextArgs args
= { t
, stack
};
267 asanThreadRegistry().CreateThread(*(uptr
*)t
, true, parent_tid
, &args
);
269 asanThreadRegistry().StartThread(t
->tid(), 0, 0);
274 // For use by only those functions that allocated the context via
275 // alloc_asan_context().
277 void asan_dispatch_call_block_and_release(void *block
) {
278 GET_STACK_TRACE_THREAD
;
279 asan_block_context_t
*context
= (asan_block_context_t
*)block
;
281 "asan_dispatch_call_block_and_release(): "
282 "context: %p, pthread_self: %p\n",
283 block
, pthread_self());
284 asan_register_worker_thread(context
->parent_tid
, &stack
);
285 // Call the original dispatcher for the block.
286 context
->func(context
->block
);
287 asan_free(context
, &stack
, FROM_MALLOC
);
290 } // namespace __asan
292 using namespace __asan
; // NOLINT
294 // Wrap |ctxt| and |func| into an asan_block_context_t.
295 // The caller retains control of the allocated context.
297 asan_block_context_t
*alloc_asan_context(void *ctxt
, dispatch_function_t func
,
298 BufferedStackTrace
*stack
) {
299 asan_block_context_t
*asan_ctxt
=
300 (asan_block_context_t
*) asan_malloc(sizeof(asan_block_context_t
), stack
);
301 asan_ctxt
->block
= ctxt
;
302 asan_ctxt
->func
= func
;
303 asan_ctxt
->parent_tid
= GetCurrentTidOrInvalid();
307 // Define interceptor for dispatch_*_f function with the three most common
308 // parameters: dispatch_queue_t, context, dispatch_function_t.
309 #define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f) \
310 INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt, \
311 dispatch_function_t func) { \
312 GET_STACK_TRACE_THREAD; \
313 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
314 if (common_flags()->verbosity >= 2) { \
315 Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n", \
316 asan_ctxt, pthread_self()); \
317 PRINT_CURRENT_STACK(); \
319 return REAL(dispatch_x_f)(dq, (void*)asan_ctxt, \
320 asan_dispatch_call_block_and_release); \
323 INTERCEPT_DISPATCH_X_F_3(dispatch_async_f
)
324 INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f
)
325 INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f
)
327 INTERCEPTOR(void, dispatch_after_f
, dispatch_time_t when
,
328 dispatch_queue_t dq
, void *ctxt
,
329 dispatch_function_t func
) {
330 GET_STACK_TRACE_THREAD
;
331 asan_block_context_t
*asan_ctxt
= alloc_asan_context(ctxt
, func
, &stack
);
332 if (common_flags()->verbosity
>= 2) {
333 Report("dispatch_after_f: %p\n", asan_ctxt
);
334 PRINT_CURRENT_STACK();
336 return REAL(dispatch_after_f
)(when
, dq
, (void*)asan_ctxt
,
337 asan_dispatch_call_block_and_release
);
340 INTERCEPTOR(void, dispatch_group_async_f
, dispatch_group_t group
,
341 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 (common_flags()->verbosity
>= 2) {
346 Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
347 asan_ctxt
, pthread_self());
348 PRINT_CURRENT_STACK();
350 REAL(dispatch_group_async_f
)(group
, dq
, (void*)asan_ctxt
,
351 asan_dispatch_call_block_and_release
);
354 #if !defined(MISSING_BLOCKS_SUPPORT)
356 void dispatch_async(dispatch_queue_t dq
, void(^work
)(void));
357 void dispatch_group_async(dispatch_group_t dg
, dispatch_queue_t dq
,
359 void dispatch_after(dispatch_time_t when
, dispatch_queue_t queue
,
361 void dispatch_source_set_cancel_handler(dispatch_source_t ds
,
363 void dispatch_source_set_event_handler(dispatch_source_t ds
, void(^work
)(void));
366 #define GET_ASAN_BLOCK(work) \
367 void (^asan_block)(void); \
368 int parent_tid = GetCurrentTidOrInvalid(); \
369 asan_block = ^(void) { \
370 GET_STACK_TRACE_THREAD; \
371 asan_register_worker_thread(parent_tid, &stack); \
375 // Forces the compiler to generate a frame pointer in the function.
376 #define ENABLE_FRAME_POINTER \
378 volatile uptr enable_fp; \
379 enable_fp = GET_CURRENT_FRAME(); \
382 INTERCEPTOR(void, dispatch_async
,
383 dispatch_queue_t dq
, void(^work
)(void)) {
384 ENABLE_FRAME_POINTER
;
385 GET_ASAN_BLOCK(work
);
386 REAL(dispatch_async
)(dq
, asan_block
);
389 INTERCEPTOR(void, dispatch_group_async
,
390 dispatch_group_t dg
, dispatch_queue_t dq
, void(^work
)(void)) {
391 ENABLE_FRAME_POINTER
;
392 GET_ASAN_BLOCK(work
);
393 REAL(dispatch_group_async
)(dg
, dq
, asan_block
);
396 INTERCEPTOR(void, dispatch_after
,
397 dispatch_time_t when
, dispatch_queue_t queue
, void(^work
)(void)) {
398 ENABLE_FRAME_POINTER
;
399 GET_ASAN_BLOCK(work
);
400 REAL(dispatch_after
)(when
, queue
, asan_block
);
403 INTERCEPTOR(void, dispatch_source_set_cancel_handler
,
404 dispatch_source_t ds
, void(^work
)(void)) {
405 ENABLE_FRAME_POINTER
;
406 GET_ASAN_BLOCK(work
);
407 REAL(dispatch_source_set_cancel_handler
)(ds
, asan_block
);
410 INTERCEPTOR(void, dispatch_source_set_event_handler
,
411 dispatch_source_t ds
, void(^work
)(void)) {
412 ENABLE_FRAME_POINTER
;
413 GET_ASAN_BLOCK(work
);
414 REAL(dispatch_source_set_event_handler
)(ds
, asan_block
);
418 #endif // SANITIZER_MAC