Remove assert in get_def_bb_for_const
[official-gcc.git] / libsanitizer / asan / asan_mac.cc
blobab3c6560825bd6ffa89d9f8fae9e16699f999b83
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 #include "sanitizer_common/sanitizer_platform.h"
14 #if SANITIZER_MAC
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 #if !SANITIZER_IOS
26 #include <crt_externs.h> // for _NSGetArgv and _NSGetEnviron
27 #else
28 extern "C" {
29 extern char ***_NSGetArgv(void);
31 #endif
33 #include <dlfcn.h> // for dladdr()
34 #include <fcntl.h>
35 #include <libkern/OSAtomic.h>
36 #include <mach-o/dyld.h>
37 #include <mach-o/loader.h>
38 #include <pthread.h>
39 #include <stdlib.h> // for free()
40 #include <sys/mman.h>
41 #include <sys/resource.h>
42 #include <sys/sysctl.h>
43 #include <sys/ucontext.h>
44 #include <unistd.h>
46 namespace __asan {
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;
59 extern "C"
60 void __asan_init();
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
68 // |name_value|.
69 void LeakyResetEnv(const char *name, const char *name_value) {
70 char **env = GetEnviron();
71 uptr name_len = internal_strlen(name);
72 while (*env != 0) {
73 uptr len = internal_strlen(*env);
74 if (len > name_len) {
75 const char *p = *env;
76 if (!internal_memcmp(p, name, name_len) && p[name_len] == '=') {
77 // Match.
78 if (name_value) {
79 // Replace the old value with the new one.
80 *env = const_cast<char*>(name_value);
81 } else {
82 // Shift the subsequent pointers back.
83 char **del = env;
84 do {
85 del[0] = del[1];
86 } while (*del++);
90 env++;
94 static bool reexec_disabled = false;
96 void DisableReexec() {
97 reexec_disabled = true;
100 extern "C" SANITIZER_WEAK_ATTRIBUTE double dyldVersionNumber;
101 static const double kMinDyldVersionWithAutoInterposition = 360.0;
103 bool DyldNeedsEnvVariable() {
104 // Although sanitizer support was added to LLVM on OS X 10.7+, GCC users
105 // still may want use them on older systems. On older Darwin platforms, dyld
106 // doesn't export dyldVersionNumber symbol and we simply return true.
107 if (!&dyldVersionNumber) return true;
108 // If running on OS X 10.11+ or iOS 9.0+, dyld will interpose even if
109 // DYLD_INSERT_LIBRARIES is not set. However, checking OS version via
110 // GetMacosVersion() doesn't work for the simulator. Let's instead check
111 // `dyldVersionNumber`, which is exported by dyld, against a known version
112 // number from the first OS release where this appeared.
113 return dyldVersionNumber < kMinDyldVersionWithAutoInterposition;
116 void MaybeReexec() {
117 if (reexec_disabled) return;
119 // Make sure the dynamic ASan runtime library is preloaded so that the
120 // wrappers work. If it is not, set DYLD_INSERT_LIBRARIES and re-exec
121 // ourselves.
122 Dl_info info;
123 CHECK(dladdr((void*)((uptr)__asan_init), &info));
124 char *dyld_insert_libraries =
125 const_cast<char*>(GetEnv(kDyldInsertLibraries));
126 uptr old_env_len = dyld_insert_libraries ?
127 internal_strlen(dyld_insert_libraries) : 0;
128 uptr fname_len = internal_strlen(info.dli_fname);
129 const char *dylib_name = StripModuleName(info.dli_fname);
130 uptr dylib_name_len = internal_strlen(dylib_name);
132 bool lib_is_in_env =
133 dyld_insert_libraries && REAL(strstr)(dyld_insert_libraries, dylib_name);
134 if (DyldNeedsEnvVariable() && !lib_is_in_env) {
135 // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
136 // library.
137 char program_name[1024];
138 uint32_t buf_size = sizeof(program_name);
139 _NSGetExecutablePath(program_name, &buf_size);
140 char *new_env = const_cast<char*>(info.dli_fname);
141 if (dyld_insert_libraries) {
142 // Append the runtime dylib name to the existing value of
143 // DYLD_INSERT_LIBRARIES.
144 new_env = (char*)allocator_for_env.Allocate(old_env_len + fname_len + 2);
145 internal_strncpy(new_env, dyld_insert_libraries, old_env_len);
146 new_env[old_env_len] = ':';
147 // Copy fname_len and add a trailing zero.
148 internal_strncpy(new_env + old_env_len + 1, info.dli_fname,
149 fname_len + 1);
150 // Ok to use setenv() since the wrappers don't depend on the value of
151 // asan_inited.
152 setenv(kDyldInsertLibraries, new_env, /*overwrite*/1);
153 } else {
154 // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name.
155 setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0);
157 VReport(1, "exec()-ing the program with\n");
158 VReport(1, "%s=%s\n", kDyldInsertLibraries, new_env);
159 VReport(1, "to enable ASan wrappers.\n");
160 execv(program_name, *_NSGetArgv());
162 // We get here only if execv() failed.
163 Report("ERROR: The process is launched without DYLD_INSERT_LIBRARIES, "
164 "which is required for ASan to work. ASan tried to set the "
165 "environment variable and re-execute itself, but execv() failed, "
166 "possibly because of sandbox restrictions. Make sure to launch the "
167 "executable with:\n%s=%s\n", kDyldInsertLibraries, new_env);
168 CHECK("execv failed" && 0);
171 if (!lib_is_in_env)
172 return;
174 // DYLD_INSERT_LIBRARIES is set and contains the runtime library. Let's remove
175 // the dylib from the environment variable, because interceptors are installed
176 // and we don't want our children to inherit the variable.
178 uptr env_name_len = internal_strlen(kDyldInsertLibraries);
179 // Allocate memory to hold the previous env var name, its value, the '='
180 // sign and the '\0' char.
181 char *new_env = (char*)allocator_for_env.Allocate(
182 old_env_len + 2 + env_name_len);
183 CHECK(new_env);
184 internal_memset(new_env, '\0', old_env_len + 2 + env_name_len);
185 internal_strncpy(new_env, kDyldInsertLibraries, env_name_len);
186 new_env[env_name_len] = '=';
187 char *new_env_pos = new_env + env_name_len + 1;
189 // Iterate over colon-separated pieces of |dyld_insert_libraries|.
190 char *piece_start = dyld_insert_libraries;
191 char *piece_end = NULL;
192 char *old_env_end = dyld_insert_libraries + old_env_len;
193 do {
194 if (piece_start[0] == ':') piece_start++;
195 piece_end = REAL(strchr)(piece_start, ':');
196 if (!piece_end) piece_end = dyld_insert_libraries + old_env_len;
197 if ((uptr)(piece_start - dyld_insert_libraries) > old_env_len) break;
198 uptr piece_len = piece_end - piece_start;
200 char *filename_start =
201 (char *)internal_memrchr(piece_start, '/', piece_len);
202 uptr filename_len = piece_len;
203 if (filename_start) {
204 filename_start += 1;
205 filename_len = piece_len - (filename_start - piece_start);
206 } else {
207 filename_start = piece_start;
210 // If the current piece isn't the runtime library name,
211 // append it to new_env.
212 if ((dylib_name_len != filename_len) ||
213 (internal_memcmp(filename_start, dylib_name, dylib_name_len) != 0)) {
214 if (new_env_pos != new_env + env_name_len + 1) {
215 new_env_pos[0] = ':';
216 new_env_pos++;
218 internal_strncpy(new_env_pos, piece_start, piece_len);
219 new_env_pos += piece_len;
221 // Move on to the next piece.
222 piece_start = piece_end;
223 } while (piece_start < old_env_end);
225 // Can't use setenv() here, because it requires the allocator to be
226 // initialized.
227 // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in
228 // a separate function called after InitializeAllocator().
229 if (new_env_pos == new_env + env_name_len + 1) new_env = NULL;
230 LeakyResetEnv(kDyldInsertLibraries, new_env);
233 // No-op. Mac does not support static linkage anyway.
234 void *AsanDoesNotSupportStaticLinkage() {
235 return 0;
238 // No-op. Mac does not support static linkage anyway.
239 void AsanCheckDynamicRTPrereqs() {}
241 // No-op. Mac does not support static linkage anyway.
242 void AsanCheckIncompatibleRT() {}
244 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
245 UNIMPLEMENTED();
248 // Support for the following functions from libdispatch on Mac OS:
249 // dispatch_async_f()
250 // dispatch_async()
251 // dispatch_sync_f()
252 // dispatch_sync()
253 // dispatch_after_f()
254 // dispatch_after()
255 // dispatch_group_async_f()
256 // dispatch_group_async()
257 // TODO(glider): libdispatch API contains other functions that we don't support
258 // yet.
260 // dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
261 // they can cause jobs to run on a thread different from the current one.
262 // TODO(glider): if so, we need a test for this (otherwise we should remove
263 // them).
265 // The following functions use dispatch_barrier_async_f() (which isn't a library
266 // function but is exported) and are thus supported:
267 // dispatch_source_set_cancel_handler_f()
268 // dispatch_source_set_cancel_handler()
269 // dispatch_source_set_event_handler_f()
270 // dispatch_source_set_event_handler()
272 // The reference manual for Grand Central Dispatch is available at
273 // http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
274 // The implementation details are at
275 // http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
277 typedef void* dispatch_group_t;
278 typedef void* dispatch_queue_t;
279 typedef void* dispatch_source_t;
280 typedef u64 dispatch_time_t;
281 typedef void (*dispatch_function_t)(void *block);
282 typedef void* (*worker_t)(void *block);
284 // A wrapper for the ObjC blocks used to support libdispatch.
285 typedef struct {
286 void *block;
287 dispatch_function_t func;
288 u32 parent_tid;
289 } asan_block_context_t;
291 ALWAYS_INLINE
292 void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
293 AsanThread *t = GetCurrentThread();
294 if (!t) {
295 t = AsanThread::Create(/* start_routine */ nullptr, /* arg */ nullptr,
296 parent_tid, stack, /* detached */ true);
297 t->Init();
298 asanThreadRegistry().StartThread(t->tid(), 0, 0);
299 SetCurrentThread(t);
303 // For use by only those functions that allocated the context via
304 // alloc_asan_context().
305 extern "C"
306 void asan_dispatch_call_block_and_release(void *block) {
307 GET_STACK_TRACE_THREAD;
308 asan_block_context_t *context = (asan_block_context_t*)block;
309 VReport(2,
310 "asan_dispatch_call_block_and_release(): "
311 "context: %p, pthread_self: %p\n",
312 block, pthread_self());
313 asan_register_worker_thread(context->parent_tid, &stack);
314 // Call the original dispatcher for the block.
315 context->func(context->block);
316 asan_free(context, &stack, FROM_MALLOC);
319 } // namespace __asan
321 using namespace __asan; // NOLINT
323 // Wrap |ctxt| and |func| into an asan_block_context_t.
324 // The caller retains control of the allocated context.
325 extern "C"
326 asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
327 BufferedStackTrace *stack) {
328 asan_block_context_t *asan_ctxt =
329 (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
330 asan_ctxt->block = ctxt;
331 asan_ctxt->func = func;
332 asan_ctxt->parent_tid = GetCurrentTidOrInvalid();
333 return asan_ctxt;
336 // Define interceptor for dispatch_*_f function with the three most common
337 // parameters: dispatch_queue_t, context, dispatch_function_t.
338 #define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f) \
339 INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt, \
340 dispatch_function_t func) { \
341 GET_STACK_TRACE_THREAD; \
342 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
343 if (Verbosity() >= 2) { \
344 Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n", \
345 asan_ctxt, pthread_self()); \
346 PRINT_CURRENT_STACK(); \
348 return REAL(dispatch_x_f)(dq, (void*)asan_ctxt, \
349 asan_dispatch_call_block_and_release); \
352 INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
353 INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
354 INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
356 INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
357 dispatch_queue_t dq, void *ctxt,
358 dispatch_function_t func) {
359 GET_STACK_TRACE_THREAD;
360 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
361 if (Verbosity() >= 2) {
362 Report("dispatch_after_f: %p\n", asan_ctxt);
363 PRINT_CURRENT_STACK();
365 return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
366 asan_dispatch_call_block_and_release);
369 INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
370 dispatch_queue_t dq, void *ctxt,
371 dispatch_function_t func) {
372 GET_STACK_TRACE_THREAD;
373 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
374 if (Verbosity() >= 2) {
375 Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
376 asan_ctxt, pthread_self());
377 PRINT_CURRENT_STACK();
379 REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
380 asan_dispatch_call_block_and_release);
383 #if !defined(MISSING_BLOCKS_SUPPORT)
384 extern "C" {
385 void dispatch_async(dispatch_queue_t dq, void(^work)(void));
386 void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
387 void(^work)(void));
388 void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
389 void(^work)(void));
390 void dispatch_source_set_cancel_handler(dispatch_source_t ds,
391 void(^work)(void));
392 void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
395 #define GET_ASAN_BLOCK(work) \
396 void (^asan_block)(void); \
397 int parent_tid = GetCurrentTidOrInvalid(); \
398 asan_block = ^(void) { \
399 GET_STACK_TRACE_THREAD; \
400 asan_register_worker_thread(parent_tid, &stack); \
401 work(); \
404 INTERCEPTOR(void, dispatch_async,
405 dispatch_queue_t dq, void(^work)(void)) {
406 ENABLE_FRAME_POINTER;
407 GET_ASAN_BLOCK(work);
408 REAL(dispatch_async)(dq, asan_block);
411 INTERCEPTOR(void, dispatch_group_async,
412 dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) {
413 ENABLE_FRAME_POINTER;
414 GET_ASAN_BLOCK(work);
415 REAL(dispatch_group_async)(dg, dq, asan_block);
418 INTERCEPTOR(void, dispatch_after,
419 dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) {
420 ENABLE_FRAME_POINTER;
421 GET_ASAN_BLOCK(work);
422 REAL(dispatch_after)(when, queue, asan_block);
425 INTERCEPTOR(void, dispatch_source_set_cancel_handler,
426 dispatch_source_t ds, void(^work)(void)) {
427 if (!work) {
428 REAL(dispatch_source_set_cancel_handler)(ds, work);
429 return;
431 ENABLE_FRAME_POINTER;
432 GET_ASAN_BLOCK(work);
433 REAL(dispatch_source_set_cancel_handler)(ds, asan_block);
436 INTERCEPTOR(void, dispatch_source_set_event_handler,
437 dispatch_source_t ds, void(^work)(void)) {
438 ENABLE_FRAME_POINTER;
439 GET_ASAN_BLOCK(work);
440 REAL(dispatch_source_set_event_handler)(ds, asan_block);
442 #endif
444 #endif // SANITIZER_MAC