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