]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/asan/asan_mac.cc
Merge ACPICA 20150619.
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / asan / asan_mac.cc
1 //===-- asan_mac.cc -------------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file is a part of AddressSanitizer, an address sanity checker.
11 //
12 // Mac-specific details.
13 //===----------------------------------------------------------------------===//
14
15 #include "sanitizer_common/sanitizer_platform.h"
16 #if SANITIZER_MAC
17
18 #include "asan_interceptors.h"
19 #include "asan_internal.h"
20 #include "asan_mapping.h"
21 #include "asan_stack.h"
22 #include "asan_thread.h"
23 #include "sanitizer_common/sanitizer_atomic.h"
24 #include "sanitizer_common/sanitizer_libc.h"
25 #include "sanitizer_common/sanitizer_mac.h"
26
27 #include <crt_externs.h>  // for _NSGetArgv
28 #include <dlfcn.h>  // for dladdr()
29 #include <mach-o/dyld.h>
30 #include <mach-o/loader.h>
31 #include <sys/mman.h>
32 #include <sys/resource.h>
33 #include <sys/sysctl.h>
34 #include <sys/ucontext.h>
35 #include <fcntl.h>
36 #include <pthread.h>
37 #include <stdlib.h>  // for free()
38 #include <unistd.h>
39 #include <libkern/OSAtomic.h>
40
41 namespace __asan {
42
43 void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
44   ucontext_t *ucontext = (ucontext_t*)context;
45 # if SANITIZER_WORDSIZE == 64
46   *pc = ucontext->uc_mcontext->__ss.__rip;
47   *bp = ucontext->uc_mcontext->__ss.__rbp;
48   *sp = ucontext->uc_mcontext->__ss.__rsp;
49 # else
50   *pc = ucontext->uc_mcontext->__ss.__eip;
51   *bp = ucontext->uc_mcontext->__ss.__ebp;
52   *sp = ucontext->uc_mcontext->__ss.__esp;
53 # endif  // SANITIZER_WORDSIZE
54 }
55
56
57 bool PlatformHasDifferentMemcpyAndMemmove() {
58   // On OS X 10.7 memcpy() and memmove() are both resolved
59   // into memmove$VARIANT$sse42.
60   // See also http://code.google.com/p/address-sanitizer/issues/detail?id=34.
61   // TODO(glider): need to check dynamically that memcpy() and memmove() are
62   // actually the same function.
63   return GetMacosVersion() == MACOS_VERSION_SNOW_LEOPARD;
64 }
65
66 extern "C"
67 void __asan_init();
68
69 static const char kDyldInsertLibraries[] = "DYLD_INSERT_LIBRARIES";
70 LowLevelAllocator allocator_for_env;
71
72 // Change the value of the env var |name|, leaking the original value.
73 // If |name_value| is NULL, the variable is deleted from the environment,
74 // otherwise the corresponding "NAME=value" string is replaced with
75 // |name_value|.
76 void LeakyResetEnv(const char *name, const char *name_value) {
77   char ***env_ptr = _NSGetEnviron();
78   CHECK(env_ptr);
79   char **environ = *env_ptr;
80   CHECK(environ);
81   uptr name_len = internal_strlen(name);
82   while (*environ != 0) {
83     uptr len = internal_strlen(*environ);
84     if (len > name_len) {
85       const char *p = *environ;
86       if (!internal_memcmp(p, name, name_len) && p[name_len] == '=') {
87         // Match.
88         if (name_value) {
89           // Replace the old value with the new one.
90           *environ = const_cast<char*>(name_value);
91         } else {
92           // Shift the subsequent pointers back.
93           char **del = environ;
94           do {
95             del[0] = del[1];
96           } while (*del++);
97         }
98       }
99     }
100     environ++;
101   }
102 }
103
104 static bool reexec_disabled = false;
105
106 void DisableReexec() {
107   reexec_disabled = true;
108 }
109
110 void MaybeReexec() {
111   if (reexec_disabled) return;
112
113   // Make sure the dynamic ASan runtime library is preloaded so that the
114   // wrappers work. If it is not, set DYLD_INSERT_LIBRARIES and re-exec
115   // ourselves.
116   Dl_info info;
117   CHECK(dladdr((void*)((uptr)__asan_init), &info));
118   char *dyld_insert_libraries =
119       const_cast<char*>(GetEnv(kDyldInsertLibraries));
120   uptr old_env_len = dyld_insert_libraries ?
121       internal_strlen(dyld_insert_libraries) : 0;
122   uptr fname_len = internal_strlen(info.dli_fname);
123   const char *dylib_name = StripModuleName(info.dli_fname);
124   uptr dylib_name_len = internal_strlen(dylib_name);
125   if (!dyld_insert_libraries ||
126       !REAL(strstr)(dyld_insert_libraries, dylib_name)) {
127     // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
128     // library.
129     char program_name[1024];
130     uint32_t buf_size = sizeof(program_name);
131     _NSGetExecutablePath(program_name, &buf_size);
132     char *new_env = const_cast<char*>(info.dli_fname);
133     if (dyld_insert_libraries) {
134       // Append the runtime dylib name to the existing value of
135       // DYLD_INSERT_LIBRARIES.
136       new_env = (char*)allocator_for_env.Allocate(old_env_len + fname_len + 2);
137       internal_strncpy(new_env, dyld_insert_libraries, old_env_len);
138       new_env[old_env_len] = ':';
139       // Copy fname_len and add a trailing zero.
140       internal_strncpy(new_env + old_env_len + 1, info.dli_fname,
141                        fname_len + 1);
142       // Ok to use setenv() since the wrappers don't depend on the value of
143       // asan_inited.
144       setenv(kDyldInsertLibraries, new_env, /*overwrite*/1);
145     } else {
146       // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name.
147       setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0);
148     }
149     VReport(1, "exec()-ing the program with\n");
150     VReport(1, "%s=%s\n", kDyldInsertLibraries, new_env);
151     VReport(1, "to enable ASan wrappers.\n");
152     execv(program_name, *_NSGetArgv());
153
154     // We get here only if execv() failed.
155     Report("ERROR: The process is launched without DYLD_INSERT_LIBRARIES, "
156            "which is required for ASan to work. ASan tried to set the "
157            "environment variable and re-execute itself, but execv() failed, "
158            "possibly because of sandbox restrictions. Make sure to launch the "
159            "executable with:\n%s=%s\n", kDyldInsertLibraries, new_env);
160     CHECK("execv failed" && 0);
161   }
162
163   // DYLD_INSERT_LIBRARIES is set and contains the runtime library. Let's remove
164   // the dylib from the environment variable, because interceptors are installed
165   // and we don't want our children to inherit the variable.
166
167   uptr env_name_len = internal_strlen(kDyldInsertLibraries);
168   // Allocate memory to hold the previous env var name, its value, the '='
169   // sign and the '\0' char.
170   char *new_env = (char*)allocator_for_env.Allocate(
171       old_env_len + 2 + env_name_len);
172   CHECK(new_env);
173   internal_memset(new_env, '\0', old_env_len + 2 + env_name_len);
174   internal_strncpy(new_env, kDyldInsertLibraries, env_name_len);
175   new_env[env_name_len] = '=';
176   char *new_env_pos = new_env + env_name_len + 1;
177
178   // Iterate over colon-separated pieces of |dyld_insert_libraries|.
179   char *piece_start = dyld_insert_libraries;
180   char *piece_end = NULL;
181   char *old_env_end = dyld_insert_libraries + old_env_len;
182   do {
183     if (piece_start[0] == ':') piece_start++;
184     piece_end = REAL(strchr)(piece_start, ':');
185     if (!piece_end) piece_end = dyld_insert_libraries + old_env_len;
186     if ((uptr)(piece_start - dyld_insert_libraries) > old_env_len) break;
187     uptr piece_len = piece_end - piece_start;
188
189     char *filename_start =
190         (char *)internal_memrchr(piece_start, '/', piece_len);
191     uptr filename_len = piece_len;
192     if (filename_start) {
193       filename_start += 1;
194       filename_len = piece_len - (filename_start - piece_start);
195     } else {
196       filename_start = piece_start;
197     }
198
199     // If the current piece isn't the runtime library name,
200     // append it to new_env.
201     if ((dylib_name_len != filename_len) ||
202         (internal_memcmp(filename_start, dylib_name, dylib_name_len) != 0)) {
203       if (new_env_pos != new_env + env_name_len + 1) {
204         new_env_pos[0] = ':';
205         new_env_pos++;
206       }
207       internal_strncpy(new_env_pos, piece_start, piece_len);
208       new_env_pos += piece_len;
209     }
210     // Move on to the next piece.
211     piece_start = piece_end;
212   } while (piece_start < old_env_end);
213
214   // Can't use setenv() here, because it requires the allocator to be
215   // initialized.
216   // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in
217   // a separate function called after InitializeAllocator().
218   if (new_env_pos == new_env + env_name_len + 1) new_env = NULL;
219   LeakyResetEnv(kDyldInsertLibraries, new_env);
220 }
221
222 // No-op. Mac does not support static linkage anyway.
223 void *AsanDoesNotSupportStaticLinkage() {
224   return 0;
225 }
226
227 // No-op. Mac does not support static linkage anyway.
228 void AsanCheckDynamicRTPrereqs() {}
229
230 // No-op. Mac does not support static linkage anyway.
231 void AsanCheckIncompatibleRT() {}
232
233 void AsanPlatformThreadInit() {
234 }
235
236 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
237   UNIMPLEMENTED();
238 }
239
240 // Support for the following functions from libdispatch on Mac OS:
241 //   dispatch_async_f()
242 //   dispatch_async()
243 //   dispatch_sync_f()
244 //   dispatch_sync()
245 //   dispatch_after_f()
246 //   dispatch_after()
247 //   dispatch_group_async_f()
248 //   dispatch_group_async()
249 // TODO(glider): libdispatch API contains other functions that we don't support
250 // yet.
251 //
252 // dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
253 // they can cause jobs to run on a thread different from the current one.
254 // TODO(glider): if so, we need a test for this (otherwise we should remove
255 // them).
256 //
257 // The following functions use dispatch_barrier_async_f() (which isn't a library
258 // function but is exported) and are thus supported:
259 //   dispatch_source_set_cancel_handler_f()
260 //   dispatch_source_set_cancel_handler()
261 //   dispatch_source_set_event_handler_f()
262 //   dispatch_source_set_event_handler()
263 //
264 // The reference manual for Grand Central Dispatch is available at
265 //   http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
266 // The implementation details are at
267 //   http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
268
269 typedef void* dispatch_group_t;
270 typedef void* dispatch_queue_t;
271 typedef void* dispatch_source_t;
272 typedef u64 dispatch_time_t;
273 typedef void (*dispatch_function_t)(void *block);
274 typedef void* (*worker_t)(void *block);
275
276 // A wrapper for the ObjC blocks used to support libdispatch.
277 typedef struct {
278   void *block;
279   dispatch_function_t func;
280   u32 parent_tid;
281 } asan_block_context_t;
282
283 ALWAYS_INLINE
284 void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
285   AsanThread *t = GetCurrentThread();
286   if (!t) {
287     t = AsanThread::Create(/* start_routine */ nullptr, /* arg */ nullptr,
288                            parent_tid, stack, /* detached */ true);
289     t->Init();
290     asanThreadRegistry().StartThread(t->tid(), 0, 0);
291     SetCurrentThread(t);
292   }
293 }
294
295 // For use by only those functions that allocated the context via
296 // alloc_asan_context().
297 extern "C"
298 void asan_dispatch_call_block_and_release(void *block) {
299   GET_STACK_TRACE_THREAD;
300   asan_block_context_t *context = (asan_block_context_t*)block;
301   VReport(2,
302           "asan_dispatch_call_block_and_release(): "
303           "context: %p, pthread_self: %p\n",
304           block, pthread_self());
305   asan_register_worker_thread(context->parent_tid, &stack);
306   // Call the original dispatcher for the block.
307   context->func(context->block);
308   asan_free(context, &stack, FROM_MALLOC);
309 }
310
311 }  // namespace __asan
312
313 using namespace __asan;  // NOLINT
314
315 // Wrap |ctxt| and |func| into an asan_block_context_t.
316 // The caller retains control of the allocated context.
317 extern "C"
318 asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
319                                          BufferedStackTrace *stack) {
320   asan_block_context_t *asan_ctxt =
321       (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
322   asan_ctxt->block = ctxt;
323   asan_ctxt->func = func;
324   asan_ctxt->parent_tid = GetCurrentTidOrInvalid();
325   return asan_ctxt;
326 }
327
328 // Define interceptor for dispatch_*_f function with the three most common
329 // parameters: dispatch_queue_t, context, dispatch_function_t.
330 #define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f)                                \
331   INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt,            \
332                                   dispatch_function_t func) {                 \
333     GET_STACK_TRACE_THREAD;                                                   \
334     asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
335     if (Verbosity() >= 2) {                                     \
336       Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n",             \
337              asan_ctxt, pthread_self());                                      \
338       PRINT_CURRENT_STACK();                                                  \
339     }                                                                         \
340     return REAL(dispatch_x_f)(dq, (void*)asan_ctxt,                           \
341                               asan_dispatch_call_block_and_release);          \
342   }
343
344 INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
345 INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
346 INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
347
348 INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
349                                     dispatch_queue_t dq, void *ctxt,
350                                     dispatch_function_t func) {
351   GET_STACK_TRACE_THREAD;
352   asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
353   if (Verbosity() >= 2) {
354     Report("dispatch_after_f: %p\n", asan_ctxt);
355     PRINT_CURRENT_STACK();
356   }
357   return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
358                                 asan_dispatch_call_block_and_release);
359 }
360
361 INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
362                                           dispatch_queue_t dq, void *ctxt,
363                                           dispatch_function_t func) {
364   GET_STACK_TRACE_THREAD;
365   asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
366   if (Verbosity() >= 2) {
367     Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
368            asan_ctxt, pthread_self());
369     PRINT_CURRENT_STACK();
370   }
371   REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
372                                asan_dispatch_call_block_and_release);
373 }
374
375 #if !defined(MISSING_BLOCKS_SUPPORT)
376 extern "C" {
377 void dispatch_async(dispatch_queue_t dq, void(^work)(void));
378 void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
379                           void(^work)(void));
380 void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
381                     void(^work)(void));
382 void dispatch_source_set_cancel_handler(dispatch_source_t ds,
383                                         void(^work)(void));
384 void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
385 }
386
387 #define GET_ASAN_BLOCK(work) \
388   void (^asan_block)(void);  \
389   int parent_tid = GetCurrentTidOrInvalid(); \
390   asan_block = ^(void) { \
391     GET_STACK_TRACE_THREAD; \
392     asan_register_worker_thread(parent_tid, &stack); \
393     work(); \
394   }
395
396 INTERCEPTOR(void, dispatch_async,
397             dispatch_queue_t dq, void(^work)(void)) {
398   ENABLE_FRAME_POINTER;
399   GET_ASAN_BLOCK(work);
400   REAL(dispatch_async)(dq, asan_block);
401 }
402
403 INTERCEPTOR(void, dispatch_group_async,
404             dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) {
405   ENABLE_FRAME_POINTER;
406   GET_ASAN_BLOCK(work);
407   REAL(dispatch_group_async)(dg, dq, asan_block);
408 }
409
410 INTERCEPTOR(void, dispatch_after,
411             dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) {
412   ENABLE_FRAME_POINTER;
413   GET_ASAN_BLOCK(work);
414   REAL(dispatch_after)(when, queue, asan_block);
415 }
416
417 INTERCEPTOR(void, dispatch_source_set_cancel_handler,
418             dispatch_source_t ds, void(^work)(void)) {
419   if (!work) {
420     REAL(dispatch_source_set_cancel_handler)(ds, work);
421     return;
422   }
423   ENABLE_FRAME_POINTER;
424   GET_ASAN_BLOCK(work);
425   REAL(dispatch_source_set_cancel_handler)(ds, asan_block);
426 }
427
428 INTERCEPTOR(void, dispatch_source_set_event_handler,
429             dispatch_source_t ds, void(^work)(void)) {
430   ENABLE_FRAME_POINTER;
431   GET_ASAN_BLOCK(work);
432   REAL(dispatch_source_set_event_handler)(ds, asan_block);
433 }
434 #endif
435
436 #endif  // SANITIZER_MAC