libsanitizer merge from upstream r250806.
[gcc.git] / libsanitizer / asan / asan_mac.cc
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 //===----------------------------------------------------------------------===//
12
13 #include "sanitizer_common/sanitizer_platform.h"
14 #if SANITIZER_MAC
15
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"
24
25 #if !SANITIZER_IOS
26 #include <crt_externs.h> // for _NSGetArgv and _NSGetEnviron
27 #else
28 extern "C" {
29 extern char ***_NSGetArgv(void);
30 }
31 #endif
32
33 #include <dlfcn.h> // for dladdr()
34 #include <mach-o/dyld.h>
35 #include <mach-o/loader.h>
36 #include <sys/mman.h>
37 #include <sys/resource.h>
38 #include <sys/sysctl.h>
39 #include <sys/ucontext.h>
40 #include <fcntl.h>
41 #include <pthread.h>
42 #include <stdlib.h> // for free()
43 #include <unistd.h>
44 #include <libkern/OSAtomic.h>
45
46 namespace __asan {
47
48 void InitializePlatformInterceptors() {}
49
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;
57 }
58
59 extern "C"
60 void __asan_init();
61
62 static const char kDyldInsertLibraries[] = "DYLD_INSERT_LIBRARIES";
63 LowLevelAllocator allocator_for_env;
64
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++);
87 }
88 }
89 }
90 env++;
91 }
92 }
93
94 static bool reexec_disabled = false;
95
96 void DisableReexec() {
97 reexec_disabled = true;
98 }
99
100 extern "C" double dyldVersionNumber;
101 static const double kMinDyldVersionWithAutoInterposition = 360.0;
102
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;
110 }
111
112 void MaybeReexec() {
113 if (reexec_disabled) return;
114
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
117 // ourselves.
118 Dl_info info;
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);
127
128 bool lib_is_in_env =
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
132 // library.
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,
145 fname_len + 1);
146 // Ok to use setenv() since the wrappers don't depend on the value of
147 // asan_inited.
148 setenv(kDyldInsertLibraries, new_env, /*overwrite*/1);
149 } else {
150 // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name.
151 setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0);
152 }
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());
157
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);
165 }
166
167 if (!lib_is_in_env)
168 return;
169
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.
173
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);
179 CHECK(new_env);
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;
184
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;
189 do {
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;
195
196 char *filename_start =
197 (char *)internal_memrchr(piece_start, '/', piece_len);
198 uptr filename_len = piece_len;
199 if (filename_start) {
200 filename_start += 1;
201 filename_len = piece_len - (filename_start - piece_start);
202 } else {
203 filename_start = piece_start;
204 }
205
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] = ':';
212 new_env_pos++;
213 }
214 internal_strncpy(new_env_pos, piece_start, piece_len);
215 new_env_pos += piece_len;
216 }
217 // Move on to the next piece.
218 piece_start = piece_end;
219 } while (piece_start < old_env_end);
220
221 // Can't use setenv() here, because it requires the allocator to be
222 // initialized.
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);
227 }
228
229 // No-op. Mac does not support static linkage anyway.
230 void *AsanDoesNotSupportStaticLinkage() {
231 return 0;
232 }
233
234 // No-op. Mac does not support static linkage anyway.
235 void AsanCheckDynamicRTPrereqs() {}
236
237 // No-op. Mac does not support static linkage anyway.
238 void AsanCheckIncompatibleRT() {}
239
240 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
241 UNIMPLEMENTED();
242 }
243
244 // Support for the following functions from libdispatch on Mac OS:
245 // dispatch_async_f()
246 // dispatch_async()
247 // dispatch_sync_f()
248 // dispatch_sync()
249 // dispatch_after_f()
250 // dispatch_after()
251 // dispatch_group_async_f()
252 // dispatch_group_async()
253 // TODO(glider): libdispatch API contains other functions that we don't support
254 // yet.
255 //
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
259 // them).
260 //
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()
267 //
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
272
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);
279
280 // A wrapper for the ObjC blocks used to support libdispatch.
281 typedef struct {
282 void *block;
283 dispatch_function_t func;
284 u32 parent_tid;
285 } asan_block_context_t;
286
287 ALWAYS_INLINE
288 void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
289 AsanThread *t = GetCurrentThread();
290 if (!t) {
291 t = AsanThread::Create(/* start_routine */ nullptr, /* arg */ nullptr,
292 parent_tid, stack, /* detached */ true);
293 t->Init();
294 asanThreadRegistry().StartThread(t->tid(), 0, 0);
295 SetCurrentThread(t);
296 }
297 }
298
299 // For use by only those functions that allocated the context via
300 // alloc_asan_context().
301 extern "C"
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;
305 VReport(2,
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);
313 }
314
315 } // namespace __asan
316
317 using namespace __asan; // NOLINT
318
319 // Wrap |ctxt| and |func| into an asan_block_context_t.
320 // The caller retains control of the allocated context.
321 extern "C"
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();
329 return asan_ctxt;
330 }
331
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(); \
343 } \
344 return REAL(dispatch_x_f)(dq, (void*)asan_ctxt, \
345 asan_dispatch_call_block_and_release); \
346 }
347
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)
351
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();
360 }
361 return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
362 asan_dispatch_call_block_and_release);
363 }
364
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();
374 }
375 REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
376 asan_dispatch_call_block_and_release);
377 }
378
379 #if !defined(MISSING_BLOCKS_SUPPORT)
380 extern "C" {
381 void dispatch_async(dispatch_queue_t dq, void(^work)(void));
382 void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
383 void(^work)(void));
384 void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
385 void(^work)(void));
386 void dispatch_source_set_cancel_handler(dispatch_source_t ds,
387 void(^work)(void));
388 void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
389 }
390
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); \
397 work(); \
398 }
399
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);
405 }
406
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);
412 }
413
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);
419 }
420
421 INTERCEPTOR(void, dispatch_source_set_cancel_handler,
422 dispatch_source_t ds, void(^work)(void)) {
423 if (!work) {
424 REAL(dispatch_source_set_cancel_handler)(ds, work);
425 return;
426 }
427 ENABLE_FRAME_POINTER;
428 GET_ASAN_BLOCK(work);
429 REAL(dispatch_source_set_cancel_handler)(ds, asan_block);
430 }
431
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);
437 }
438 #endif
439
440 #endif // SANITIZER_MAC