]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/asan/asan_mac.cc
Update LLDB snapshot to upstream r225923 (git 2b588ecd)
[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 void MaybeReexec() {
105   if (!flags()->allow_reexec) return;
106   // Make sure the dynamic ASan runtime library is preloaded so that the
107   // wrappers work. If it is not, set DYLD_INSERT_LIBRARIES and re-exec
108   // ourselves.
109   Dl_info info;
110   CHECK(dladdr((void*)((uptr)__asan_init), &info));
111   char *dyld_insert_libraries =
112       const_cast<char*>(GetEnv(kDyldInsertLibraries));
113   uptr old_env_len = dyld_insert_libraries ?
114       internal_strlen(dyld_insert_libraries) : 0;
115   uptr fname_len = internal_strlen(info.dli_fname);
116   if (!dyld_insert_libraries ||
117       !REAL(strstr)(dyld_insert_libraries, StripModuleName(info.dli_fname))) {
118     // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
119     // library.
120     char program_name[1024];
121     uint32_t buf_size = sizeof(program_name);
122     _NSGetExecutablePath(program_name, &buf_size);
123     char *new_env = const_cast<char*>(info.dli_fname);
124     if (dyld_insert_libraries) {
125       // Append the runtime dylib name to the existing value of
126       // DYLD_INSERT_LIBRARIES.
127       new_env = (char*)allocator_for_env.Allocate(old_env_len + fname_len + 2);
128       internal_strncpy(new_env, dyld_insert_libraries, old_env_len);
129       new_env[old_env_len] = ':';
130       // Copy fname_len and add a trailing zero.
131       internal_strncpy(new_env + old_env_len + 1, info.dli_fname,
132                        fname_len + 1);
133       // Ok to use setenv() since the wrappers don't depend on the value of
134       // asan_inited.
135       setenv(kDyldInsertLibraries, new_env, /*overwrite*/1);
136     } else {
137       // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name.
138       setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0);
139     }
140     VReport(1, "exec()-ing the program with\n");
141     VReport(1, "%s=%s\n", kDyldInsertLibraries, new_env);
142     VReport(1, "to enable ASan wrappers.\n");
143     VReport(1, "Set ASAN_OPTIONS=allow_reexec=0 to disable this.\n");
144     execv(program_name, *_NSGetArgv());
145   } else {
146     // DYLD_INSERT_LIBRARIES is set and contains the runtime library.
147     if (old_env_len == fname_len) {
148       // It's just the runtime library name - fine to unset the variable.
149       LeakyResetEnv(kDyldInsertLibraries, NULL);
150     } else {
151       uptr env_name_len = internal_strlen(kDyldInsertLibraries);
152       // Allocate memory to hold the previous env var name, its value, the '='
153       // sign and the '\0' char.
154       char *new_env = (char*)allocator_for_env.Allocate(
155           old_env_len + 2 + env_name_len);
156       CHECK(new_env);
157       internal_memset(new_env, '\0', old_env_len + 2 + env_name_len);
158       internal_strncpy(new_env, kDyldInsertLibraries, env_name_len);
159       new_env[env_name_len] = '=';
160       char *new_env_pos = new_env + env_name_len + 1;
161
162       // Iterate over colon-separated pieces of |dyld_insert_libraries|.
163       char *piece_start = dyld_insert_libraries;
164       char *piece_end = NULL;
165       char *old_env_end = dyld_insert_libraries + old_env_len;
166       do {
167         if (piece_start[0] == ':') piece_start++;
168         piece_end =  REAL(strchr)(piece_start, ':');
169         if (!piece_end) piece_end = dyld_insert_libraries + old_env_len;
170         if ((uptr)(piece_start - dyld_insert_libraries) > old_env_len) break;
171         uptr piece_len = piece_end - piece_start;
172
173         // If the current piece isn't the runtime library name,
174         // append it to new_env.
175         if ((piece_len != fname_len) ||
176             (internal_strncmp(piece_start, info.dli_fname, fname_len) != 0)) {
177           if (new_env_pos != new_env + env_name_len + 1) {
178             new_env_pos[0] = ':';
179             new_env_pos++;
180           }
181           internal_strncpy(new_env_pos, piece_start, piece_len);
182         }
183         // Move on to the next piece.
184         new_env_pos += piece_len;
185         piece_start = piece_end;
186       } while (piece_start < old_env_end);
187
188       // Can't use setenv() here, because it requires the allocator to be
189       // initialized.
190       // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in
191       // a separate function called after InitializeAllocator().
192       LeakyResetEnv(kDyldInsertLibraries, new_env);
193     }
194   }
195 }
196
197 // No-op. Mac does not support static linkage anyway.
198 void *AsanDoesNotSupportStaticLinkage() {
199   return 0;
200 }
201
202 // No-op. Mac does not support static linkage anyway.
203 void AsanCheckDynamicRTPrereqs() {}
204
205 // No-op. Mac does not support static linkage anyway.
206 void AsanCheckIncompatibleRT() {}
207
208 bool AsanInterceptsSignal(int signum) {
209   return (signum == SIGSEGV || signum == SIGBUS) &&
210          common_flags()->handle_segv;
211 }
212
213 void AsanPlatformThreadInit() {
214 }
215
216 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
217   UNIMPLEMENTED();
218 }
219
220 // Support for the following functions from libdispatch on Mac OS:
221 //   dispatch_async_f()
222 //   dispatch_async()
223 //   dispatch_sync_f()
224 //   dispatch_sync()
225 //   dispatch_after_f()
226 //   dispatch_after()
227 //   dispatch_group_async_f()
228 //   dispatch_group_async()
229 // TODO(glider): libdispatch API contains other functions that we don't support
230 // yet.
231 //
232 // dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
233 // they can cause jobs to run on a thread different from the current one.
234 // TODO(glider): if so, we need a test for this (otherwise we should remove
235 // them).
236 //
237 // The following functions use dispatch_barrier_async_f() (which isn't a library
238 // function but is exported) and are thus supported:
239 //   dispatch_source_set_cancel_handler_f()
240 //   dispatch_source_set_cancel_handler()
241 //   dispatch_source_set_event_handler_f()
242 //   dispatch_source_set_event_handler()
243 //
244 // The reference manual for Grand Central Dispatch is available at
245 //   http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
246 // The implementation details are at
247 //   http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
248
249 typedef void* dispatch_group_t;
250 typedef void* dispatch_queue_t;
251 typedef void* dispatch_source_t;
252 typedef u64 dispatch_time_t;
253 typedef void (*dispatch_function_t)(void *block);
254 typedef void* (*worker_t)(void *block);
255
256 // A wrapper for the ObjC blocks used to support libdispatch.
257 typedef struct {
258   void *block;
259   dispatch_function_t func;
260   u32 parent_tid;
261 } asan_block_context_t;
262
263 ALWAYS_INLINE
264 void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
265   AsanThread *t = GetCurrentThread();
266   if (!t) {
267     t = AsanThread::Create(/* start_routine */ nullptr, /* arg */ nullptr,
268                            parent_tid, stack, /* detached */ true);
269     t->Init();
270     asanThreadRegistry().StartThread(t->tid(), 0, 0);
271     SetCurrentThread(t);
272   }
273 }
274
275 // For use by only those functions that allocated the context via
276 // alloc_asan_context().
277 extern "C"
278 void asan_dispatch_call_block_and_release(void *block) {
279   GET_STACK_TRACE_THREAD;
280   asan_block_context_t *context = (asan_block_context_t*)block;
281   VReport(2,
282           "asan_dispatch_call_block_and_release(): "
283           "context: %p, pthread_self: %p\n",
284           block, pthread_self());
285   asan_register_worker_thread(context->parent_tid, &stack);
286   // Call the original dispatcher for the block.
287   context->func(context->block);
288   asan_free(context, &stack, FROM_MALLOC);
289 }
290
291 }  // namespace __asan
292
293 using namespace __asan;  // NOLINT
294
295 // Wrap |ctxt| and |func| into an asan_block_context_t.
296 // The caller retains control of the allocated context.
297 extern "C"
298 asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
299                                          BufferedStackTrace *stack) {
300   asan_block_context_t *asan_ctxt =
301       (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
302   asan_ctxt->block = ctxt;
303   asan_ctxt->func = func;
304   asan_ctxt->parent_tid = GetCurrentTidOrInvalid();
305   return asan_ctxt;
306 }
307
308 // Define interceptor for dispatch_*_f function with the three most common
309 // parameters: dispatch_queue_t, context, dispatch_function_t.
310 #define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f)                                \
311   INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt,            \
312                                   dispatch_function_t func) {                 \
313     GET_STACK_TRACE_THREAD;                                                   \
314     asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
315     if (common_flags()->verbosity >= 2) {                                     \
316       Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n",             \
317              asan_ctxt, pthread_self());                                      \
318       PRINT_CURRENT_STACK();                                                  \
319     }                                                                         \
320     return REAL(dispatch_x_f)(dq, (void*)asan_ctxt,                           \
321                               asan_dispatch_call_block_and_release);          \
322   }
323
324 INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
325 INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
326 INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
327
328 INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
329                                     dispatch_queue_t dq, void *ctxt,
330                                     dispatch_function_t func) {
331   GET_STACK_TRACE_THREAD;
332   asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
333   if (common_flags()->verbosity >= 2) {
334     Report("dispatch_after_f: %p\n", asan_ctxt);
335     PRINT_CURRENT_STACK();
336   }
337   return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
338                                 asan_dispatch_call_block_and_release);
339 }
340
341 INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
342                                           dispatch_queue_t dq, void *ctxt,
343                                           dispatch_function_t func) {
344   GET_STACK_TRACE_THREAD;
345   asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
346   if (common_flags()->verbosity >= 2) {
347     Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
348            asan_ctxt, pthread_self());
349     PRINT_CURRENT_STACK();
350   }
351   REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
352                                asan_dispatch_call_block_and_release);
353 }
354
355 #if !defined(MISSING_BLOCKS_SUPPORT)
356 extern "C" {
357 void dispatch_async(dispatch_queue_t dq, void(^work)(void));
358 void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
359                           void(^work)(void));
360 void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
361                     void(^work)(void));
362 void dispatch_source_set_cancel_handler(dispatch_source_t ds,
363                                         void(^work)(void));
364 void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
365 }
366
367 #define GET_ASAN_BLOCK(work) \
368   void (^asan_block)(void);  \
369   int parent_tid = GetCurrentTidOrInvalid(); \
370   asan_block = ^(void) { \
371     GET_STACK_TRACE_THREAD; \
372     asan_register_worker_thread(parent_tid, &stack); \
373     work(); \
374   }
375
376 // Forces the compiler to generate a frame pointer in the function.
377 #define ENABLE_FRAME_POINTER                                       \
378   do {                                                             \
379     volatile uptr enable_fp;                                       \
380     enable_fp = GET_CURRENT_FRAME();                               \
381   } while (0)
382
383 INTERCEPTOR(void, dispatch_async,
384             dispatch_queue_t dq, void(^work)(void)) {
385   ENABLE_FRAME_POINTER;
386   GET_ASAN_BLOCK(work);
387   REAL(dispatch_async)(dq, asan_block);
388 }
389
390 INTERCEPTOR(void, dispatch_group_async,
391             dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) {
392   ENABLE_FRAME_POINTER;
393   GET_ASAN_BLOCK(work);
394   REAL(dispatch_group_async)(dg, dq, asan_block);
395 }
396
397 INTERCEPTOR(void, dispatch_after,
398             dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) {
399   ENABLE_FRAME_POINTER;
400   GET_ASAN_BLOCK(work);
401   REAL(dispatch_after)(when, queue, asan_block);
402 }
403
404 INTERCEPTOR(void, dispatch_source_set_cancel_handler,
405             dispatch_source_t ds, void(^work)(void)) {
406   ENABLE_FRAME_POINTER;
407   GET_ASAN_BLOCK(work);
408   REAL(dispatch_source_set_cancel_handler)(ds, asan_block);
409 }
410
411 INTERCEPTOR(void, dispatch_source_set_event_handler,
412             dispatch_source_t ds, void(^work)(void)) {
413   ENABLE_FRAME_POINTER;
414   GET_ASAN_BLOCK(work);
415   REAL(dispatch_source_set_event_handler)(ds, asan_block);
416 }
417 #endif
418
419 #endif  // SANITIZER_MAC