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"
26 #include <crt_externs.h> // for _NSGetArgv and _NSGetEnviron
29 extern char ***_NSGetArgv(void);
33 #include <dlfcn.h> // for dladdr()
35 #include <libkern/OSAtomic.h>
36 #include <mach-o/dyld.h>
37 #include <mach-o/loader.h>
39 #include <stdlib.h> // for free()
41 #include <sys/resource.h>
42 #include <sys/sysctl.h>
43 #include <sys/ucontext.h>
48 void InitializePlatformInterceptors() {}
50 bool PlatformHasDifferentMemcpyAndMemmove() {
51 // On OS X 10.7 memcpy() and memmove() are both resolved
52 // into memmove$VARIANT$sse42.
53 // See also http://code.google.com/p/address-sanitizer/issues/detail?id=34.
54 // TODO(glider): need to check dynamically that memcpy() and memmove() are
55 // actually the same function.
56 return GetMacosVersion() == MACOS_VERSION_SNOW_LEOPARD
;
62 static const char kDyldInsertLibraries
[] = "DYLD_INSERT_LIBRARIES";
63 LowLevelAllocator allocator_for_env
;
65 // Change the value of the env var |name|, leaking the original value.
66 // If |name_value| is NULL, the variable is deleted from the environment,
67 // otherwise the corresponding "NAME=value" string is replaced with
69 void LeakyResetEnv(const char *name
, const char *name_value
) {
70 char **env
= GetEnviron();
71 uptr name_len
= internal_strlen(name
);
73 uptr len
= internal_strlen(*env
);
76 if (!internal_memcmp(p
, name
, name_len
) && p
[name_len
] == '=') {
79 // Replace the old value with the new one.
80 *env
= const_cast<char*>(name_value
);
82 // Shift the subsequent pointers back.
94 static bool reexec_disabled
= false;
96 void DisableReexec() {
97 reexec_disabled
= true;
100 extern "C" double dyldVersionNumber
;
101 static const double kMinDyldVersionWithAutoInterposition
= 360.0;
103 bool DyldNeedsEnvVariable() {
104 // If running on OS X 10.11+ or iOS 9.0+, dyld will interpose even if
105 // DYLD_INSERT_LIBRARIES is not set. However, checking OS version via
106 // GetMacosVersion() doesn't work for the simulator. Let's instead check
107 // `dyldVersionNumber`, which is exported by dyld, against a known version
108 // number from the first OS release where this appeared.
109 return dyldVersionNumber
< kMinDyldVersionWithAutoInterposition
;
113 if (reexec_disabled
) return;
115 // Make sure the dynamic ASan runtime library is preloaded so that the
116 // wrappers work. If it is not, set DYLD_INSERT_LIBRARIES and re-exec
119 CHECK(dladdr((void*)((uptr
)__asan_init
), &info
));
120 char *dyld_insert_libraries
=
121 const_cast<char*>(GetEnv(kDyldInsertLibraries
));
122 uptr old_env_len
= dyld_insert_libraries
?
123 internal_strlen(dyld_insert_libraries
) : 0;
124 uptr fname_len
= internal_strlen(info
.dli_fname
);
125 const char *dylib_name
= StripModuleName(info
.dli_fname
);
126 uptr dylib_name_len
= internal_strlen(dylib_name
);
129 dyld_insert_libraries
&& REAL(strstr
)(dyld_insert_libraries
, dylib_name
);
130 if (DyldNeedsEnvVariable() && !lib_is_in_env
) {
131 // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
133 char program_name
[1024];
134 uint32_t buf_size
= sizeof(program_name
);
135 _NSGetExecutablePath(program_name
, &buf_size
);
136 char *new_env
= const_cast<char*>(info
.dli_fname
);
137 if (dyld_insert_libraries
) {
138 // Append the runtime dylib name to the existing value of
139 // DYLD_INSERT_LIBRARIES.
140 new_env
= (char*)allocator_for_env
.Allocate(old_env_len
+ fname_len
+ 2);
141 internal_strncpy(new_env
, dyld_insert_libraries
, old_env_len
);
142 new_env
[old_env_len
] = ':';
143 // Copy fname_len and add a trailing zero.
144 internal_strncpy(new_env
+ old_env_len
+ 1, info
.dli_fname
,
146 // Ok to use setenv() since the wrappers don't depend on the value of
148 setenv(kDyldInsertLibraries
, new_env
, /*overwrite*/1);
150 // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name.
151 setenv(kDyldInsertLibraries
, info
.dli_fname
, /*overwrite*/0);
153 VReport(1, "exec()-ing the program with\n");
154 VReport(1, "%s=%s\n", kDyldInsertLibraries
, new_env
);
155 VReport(1, "to enable ASan wrappers.\n");
156 execv(program_name
, *_NSGetArgv());
158 // We get here only if execv() failed.
159 Report("ERROR: The process is launched without DYLD_INSERT_LIBRARIES, "
160 "which is required for ASan to work. ASan tried to set the "
161 "environment variable and re-execute itself, but execv() failed, "
162 "possibly because of sandbox restrictions. Make sure to launch the "
163 "executable with:\n%s=%s\n", kDyldInsertLibraries
, new_env
);
164 CHECK("execv failed" && 0);
170 // DYLD_INSERT_LIBRARIES is set and contains the runtime library. Let's remove
171 // the dylib from the environment variable, because interceptors are installed
172 // and we don't want our children to inherit the variable.
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
);
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;
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
;
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
;
196 char *filename_start
=
197 (char *)internal_memrchr(piece_start
, '/', piece_len
);
198 uptr filename_len
= piece_len
;
199 if (filename_start
) {
201 filename_len
= piece_len
- (filename_start
- piece_start
);
203 filename_start
= piece_start
;
206 // If the current piece isn't the runtime library name,
207 // append it to new_env.
208 if ((dylib_name_len
!= filename_len
) ||
209 (internal_memcmp(filename_start
, dylib_name
, dylib_name_len
) != 0)) {
210 if (new_env_pos
!= new_env
+ env_name_len
+ 1) {
211 new_env_pos
[0] = ':';
214 internal_strncpy(new_env_pos
, piece_start
, piece_len
);
215 new_env_pos
+= piece_len
;
217 // Move on to the next piece.
218 piece_start
= piece_end
;
219 } while (piece_start
< old_env_end
);
221 // Can't use setenv() here, because it requires the allocator to be
223 // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in
224 // a separate function called after InitializeAllocator().
225 if (new_env_pos
== new_env
+ env_name_len
+ 1) new_env
= NULL
;
226 LeakyResetEnv(kDyldInsertLibraries
, new_env
);
229 // No-op. Mac does not support static linkage anyway.
230 void *AsanDoesNotSupportStaticLinkage() {
234 // No-op. Mac does not support static linkage anyway.
235 void AsanCheckDynamicRTPrereqs() {}
237 // No-op. Mac does not support static linkage anyway.
238 void AsanCheckIncompatibleRT() {}
240 void ReadContextStack(void *context
, uptr
*stack
, uptr
*ssize
) {
244 // Support for the following functions from libdispatch on Mac OS:
245 // dispatch_async_f()
249 // dispatch_after_f()
251 // dispatch_group_async_f()
252 // dispatch_group_async()
253 // TODO(glider): libdispatch API contains other functions that we don't support
256 // dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
257 // they can cause jobs to run on a thread different from the current one.
258 // TODO(glider): if so, we need a test for this (otherwise we should remove
261 // The following functions use dispatch_barrier_async_f() (which isn't a library
262 // function but is exported) and are thus supported:
263 // dispatch_source_set_cancel_handler_f()
264 // dispatch_source_set_cancel_handler()
265 // dispatch_source_set_event_handler_f()
266 // dispatch_source_set_event_handler()
268 // The reference manual for Grand Central Dispatch is available at
269 // http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
270 // The implementation details are at
271 // http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
273 typedef void* dispatch_group_t
;
274 typedef void* dispatch_queue_t
;
275 typedef void* dispatch_source_t
;
276 typedef u64 dispatch_time_t
;
277 typedef void (*dispatch_function_t
)(void *block
);
278 typedef void* (*worker_t
)(void *block
);
280 // A wrapper for the ObjC blocks used to support libdispatch.
283 dispatch_function_t func
;
285 } asan_block_context_t
;
288 void asan_register_worker_thread(int parent_tid
, StackTrace
*stack
) {
289 AsanThread
*t
= GetCurrentThread();
291 t
= AsanThread::Create(/* start_routine */ nullptr, /* arg */ nullptr,
292 parent_tid
, stack
, /* detached */ true);
294 asanThreadRegistry().StartThread(t
->tid(), 0, 0);
299 // For use by only those functions that allocated the context via
300 // alloc_asan_context().
302 void asan_dispatch_call_block_and_release(void *block
) {
303 GET_STACK_TRACE_THREAD
;
304 asan_block_context_t
*context
= (asan_block_context_t
*)block
;
306 "asan_dispatch_call_block_and_release(): "
307 "context: %p, pthread_self: %p\n",
308 block
, pthread_self());
309 asan_register_worker_thread(context
->parent_tid
, &stack
);
310 // Call the original dispatcher for the block.
311 context
->func(context
->block
);
312 asan_free(context
, &stack
, FROM_MALLOC
);
315 } // namespace __asan
317 using namespace __asan
; // NOLINT
319 // Wrap |ctxt| and |func| into an asan_block_context_t.
320 // The caller retains control of the allocated context.
322 asan_block_context_t
*alloc_asan_context(void *ctxt
, dispatch_function_t func
,
323 BufferedStackTrace
*stack
) {
324 asan_block_context_t
*asan_ctxt
=
325 (asan_block_context_t
*) asan_malloc(sizeof(asan_block_context_t
), stack
);
326 asan_ctxt
->block
= ctxt
;
327 asan_ctxt
->func
= func
;
328 asan_ctxt
->parent_tid
= GetCurrentTidOrInvalid();
332 // Define interceptor for dispatch_*_f function with the three most common
333 // parameters: dispatch_queue_t, context, dispatch_function_t.
334 #define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f) \
335 INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt, \
336 dispatch_function_t func) { \
337 GET_STACK_TRACE_THREAD; \
338 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
339 if (Verbosity() >= 2) { \
340 Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n", \
341 asan_ctxt, pthread_self()); \
342 PRINT_CURRENT_STACK(); \
344 return REAL(dispatch_x_f)(dq, (void*)asan_ctxt, \
345 asan_dispatch_call_block_and_release); \
348 INTERCEPT_DISPATCH_X_F_3(dispatch_async_f
)
349 INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f
)
350 INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f
)
352 INTERCEPTOR(void, dispatch_after_f
, dispatch_time_t when
,
353 dispatch_queue_t dq
, void *ctxt
,
354 dispatch_function_t func
) {
355 GET_STACK_TRACE_THREAD
;
356 asan_block_context_t
*asan_ctxt
= alloc_asan_context(ctxt
, func
, &stack
);
357 if (Verbosity() >= 2) {
358 Report("dispatch_after_f: %p\n", asan_ctxt
);
359 PRINT_CURRENT_STACK();
361 return REAL(dispatch_after_f
)(when
, dq
, (void*)asan_ctxt
,
362 asan_dispatch_call_block_and_release
);
365 INTERCEPTOR(void, dispatch_group_async_f
, dispatch_group_t group
,
366 dispatch_queue_t dq
, void *ctxt
,
367 dispatch_function_t func
) {
368 GET_STACK_TRACE_THREAD
;
369 asan_block_context_t
*asan_ctxt
= alloc_asan_context(ctxt
, func
, &stack
);
370 if (Verbosity() >= 2) {
371 Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
372 asan_ctxt
, pthread_self());
373 PRINT_CURRENT_STACK();
375 REAL(dispatch_group_async_f
)(group
, dq
, (void*)asan_ctxt
,
376 asan_dispatch_call_block_and_release
);
379 #if !defined(MISSING_BLOCKS_SUPPORT)
381 void dispatch_async(dispatch_queue_t dq
, void(^work
)(void));
382 void dispatch_group_async(dispatch_group_t dg
, dispatch_queue_t dq
,
384 void dispatch_after(dispatch_time_t when
, dispatch_queue_t queue
,
386 void dispatch_source_set_cancel_handler(dispatch_source_t ds
,
388 void dispatch_source_set_event_handler(dispatch_source_t ds
, void(^work
)(void));
391 #define GET_ASAN_BLOCK(work) \
392 void (^asan_block)(void); \
393 int parent_tid = GetCurrentTidOrInvalid(); \
394 asan_block = ^(void) { \
395 GET_STACK_TRACE_THREAD; \
396 asan_register_worker_thread(parent_tid, &stack); \
400 INTERCEPTOR(void, dispatch_async
,
401 dispatch_queue_t dq
, void(^work
)(void)) {
402 ENABLE_FRAME_POINTER
;
403 GET_ASAN_BLOCK(work
);
404 REAL(dispatch_async
)(dq
, asan_block
);
407 INTERCEPTOR(void, dispatch_group_async
,
408 dispatch_group_t dg
, dispatch_queue_t dq
, void(^work
)(void)) {
409 ENABLE_FRAME_POINTER
;
410 GET_ASAN_BLOCK(work
);
411 REAL(dispatch_group_async
)(dg
, dq
, asan_block
);
414 INTERCEPTOR(void, dispatch_after
,
415 dispatch_time_t when
, dispatch_queue_t queue
, void(^work
)(void)) {
416 ENABLE_FRAME_POINTER
;
417 GET_ASAN_BLOCK(work
);
418 REAL(dispatch_after
)(when
, queue
, asan_block
);
421 INTERCEPTOR(void, dispatch_source_set_cancel_handler
,
422 dispatch_source_t ds
, void(^work
)(void)) {
424 REAL(dispatch_source_set_cancel_handler
)(ds
, work
);
427 ENABLE_FRAME_POINTER
;
428 GET_ASAN_BLOCK(work
);
429 REAL(dispatch_source_set_cancel_handler
)(ds
, asan_block
);
432 INTERCEPTOR(void, dispatch_source_set_event_handler
,
433 dispatch_source_t ds
, void(^work
)(void)) {
434 ENABLE_FRAME_POINTER
;
435 GET_ASAN_BLOCK(work
);
436 REAL(dispatch_source_set_event_handler
)(ds
, asan_block
);
440 #endif // SANITIZER_MAC