]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/sanitizer_common/sanitizer_mac.cc
Merge ^/head r317971 through r318379.
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / sanitizer_common / sanitizer_mac.cc
1 //===-- sanitizer_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 shared between various sanitizers' runtime libraries and
11 // implements OSX-specific functions.
12 //===----------------------------------------------------------------------===//
13
14 #include "sanitizer_platform.h"
15 #if SANITIZER_MAC
16 #include "sanitizer_mac.h"
17
18 // Use 64-bit inodes in file operations. ASan does not support OS X 10.5, so
19 // the clients will most certainly use 64-bit ones as well.
20 #ifndef _DARWIN_USE_64_BIT_INODE
21 #define _DARWIN_USE_64_BIT_INODE 1
22 #endif
23 #include <stdio.h>
24
25 #include "sanitizer_common.h"
26 #include "sanitizer_flags.h"
27 #include "sanitizer_internal_defs.h"
28 #include "sanitizer_libc.h"
29 #include "sanitizer_placement_new.h"
30 #include "sanitizer_platform_limits_posix.h"
31 #include "sanitizer_procmaps.h"
32
33 #if !SANITIZER_IOS
34 #include <crt_externs.h>  // for _NSGetEnviron
35 #else
36 extern char **environ;
37 #endif
38
39 #if defined(__has_include) && __has_include(<os/trace.h>)
40 #define SANITIZER_OS_TRACE 1
41 #include <os/trace.h>
42 #else
43 #define SANITIZER_OS_TRACE 0
44 #endif
45
46 #if !SANITIZER_IOS
47 #include <crt_externs.h>  // for _NSGetArgv and _NSGetEnviron
48 #else
49 extern "C" {
50   extern char ***_NSGetArgv(void);
51 }
52 #endif
53
54 #include <asl.h>
55 #include <dlfcn.h>  // for dladdr()
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <libkern/OSAtomic.h>
59 #include <mach-o/dyld.h>
60 #include <mach/mach.h>
61 #include <mach/vm_statistics.h>
62 #include <pthread.h>
63 #include <sched.h>
64 #include <signal.h>
65 #include <stdlib.h>
66 #include <sys/mman.h>
67 #include <sys/resource.h>
68 #include <sys/stat.h>
69 #include <sys/sysctl.h>
70 #include <sys/types.h>
71 #include <sys/wait.h>
72 #include <unistd.h>
73 #include <util.h>
74
75 // From <crt_externs.h>, but we don't have that file on iOS.
76 extern "C" {
77   extern char ***_NSGetArgv(void);
78   extern char ***_NSGetEnviron(void);
79 }
80
81 // From <mach/mach_vm.h>, but we don't have that file on iOS.
82 extern "C" {
83   extern kern_return_t mach_vm_region_recurse(
84     vm_map_t target_task,
85     mach_vm_address_t *address,
86     mach_vm_size_t *size,
87     natural_t *nesting_depth,
88     vm_region_recurse_info_t info,
89     mach_msg_type_number_t *infoCnt);
90 }
91
92 namespace __sanitizer {
93
94 #include "sanitizer_syscall_generic.inc"
95
96 // Direct syscalls, don't call libmalloc hooks (but not available on 10.6).
97 extern "C" void *__mmap(void *addr, size_t len, int prot, int flags, int fildes,
98                         off_t off) SANITIZER_WEAK_ATTRIBUTE;
99 extern "C" int __munmap(void *, size_t) SANITIZER_WEAK_ATTRIBUTE;
100
101 // ---------------------- sanitizer_libc.h
102 uptr internal_mmap(void *addr, size_t length, int prot, int flags,
103                    int fd, u64 offset) {
104   if (fd == -1) fd = VM_MAKE_TAG(VM_MEMORY_ANALYSIS_TOOL);
105   if (&__mmap) return (uptr)__mmap(addr, length, prot, flags, fd, offset);
106   return (uptr)mmap(addr, length, prot, flags, fd, offset);
107 }
108
109 uptr internal_munmap(void *addr, uptr length) {
110   if (&__munmap) return __munmap(addr, length);
111   return munmap(addr, length);
112 }
113
114 int internal_mprotect(void *addr, uptr length, int prot) {
115   return mprotect(addr, length, prot);
116 }
117
118 uptr internal_close(fd_t fd) {
119   return close(fd);
120 }
121
122 uptr internal_open(const char *filename, int flags) {
123   return open(filename, flags);
124 }
125
126 uptr internal_open(const char *filename, int flags, u32 mode) {
127   return open(filename, flags, mode);
128 }
129
130 uptr internal_read(fd_t fd, void *buf, uptr count) {
131   return read(fd, buf, count);
132 }
133
134 uptr internal_write(fd_t fd, const void *buf, uptr count) {
135   return write(fd, buf, count);
136 }
137
138 uptr internal_stat(const char *path, void *buf) {
139   return stat(path, (struct stat *)buf);
140 }
141
142 uptr internal_lstat(const char *path, void *buf) {
143   return lstat(path, (struct stat *)buf);
144 }
145
146 uptr internal_fstat(fd_t fd, void *buf) {
147   return fstat(fd, (struct stat *)buf);
148 }
149
150 uptr internal_filesize(fd_t fd) {
151   struct stat st;
152   if (internal_fstat(fd, &st))
153     return -1;
154   return (uptr)st.st_size;
155 }
156
157 uptr internal_dup2(int oldfd, int newfd) {
158   return dup2(oldfd, newfd);
159 }
160
161 uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
162   return readlink(path, buf, bufsize);
163 }
164
165 uptr internal_unlink(const char *path) {
166   return unlink(path);
167 }
168
169 uptr internal_sched_yield() {
170   return sched_yield();
171 }
172
173 void internal__exit(int exitcode) {
174   _exit(exitcode);
175 }
176
177 unsigned int internal_sleep(unsigned int seconds) {
178   return sleep(seconds);
179 }
180
181 uptr internal_getpid() {
182   return getpid();
183 }
184
185 int internal_sigaction(int signum, const void *act, void *oldact) {
186   return sigaction(signum,
187                    (struct sigaction *)act, (struct sigaction *)oldact);
188 }
189
190 void internal_sigfillset(__sanitizer_sigset_t *set) { sigfillset(set); }
191
192 uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
193                           __sanitizer_sigset_t *oldset) {
194   return sigprocmask(how, set, oldset);
195 }
196
197 // Doesn't call pthread_atfork() handlers (but not available on 10.6).
198 extern "C" pid_t __fork(void) SANITIZER_WEAK_ATTRIBUTE;
199
200 int internal_fork() {
201   if (&__fork)
202     return __fork();
203   return fork();
204 }
205
206 int internal_forkpty(int *amaster) {
207   int master, slave;
208   if (openpty(&master, &slave, nullptr, nullptr, nullptr) == -1) return -1;
209   int pid = internal_fork();
210   if (pid == -1) {
211     close(master);
212     close(slave);
213     return -1;
214   }
215   if (pid == 0) {
216     close(master);
217     if (login_tty(slave) != 0) {
218       // We already forked, there's not much we can do.  Let's quit.
219       Report("login_tty failed (errno %d)\n", errno);
220       internal__exit(1);
221     }
222   } else {
223     *amaster = master;
224     close(slave);
225   }
226   return pid;
227 }
228
229 uptr internal_rename(const char *oldpath, const char *newpath) {
230   return rename(oldpath, newpath);
231 }
232
233 uptr internal_ftruncate(fd_t fd, uptr size) {
234   return ftruncate(fd, size);
235 }
236
237 uptr internal_execve(const char *filename, char *const argv[],
238                      char *const envp[]) {
239   return execve(filename, argv, envp);
240 }
241
242 uptr internal_waitpid(int pid, int *status, int options) {
243   return waitpid(pid, status, options);
244 }
245
246 // ----------------- sanitizer_common.h
247 bool FileExists(const char *filename) {
248   struct stat st;
249   if (stat(filename, &st))
250     return false;
251   // Sanity check: filename is a regular file.
252   return S_ISREG(st.st_mode);
253 }
254
255 tid_t GetTid() {
256   tid_t tid;
257   pthread_threadid_np(nullptr, &tid);
258   return tid;
259 }
260
261 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
262                                 uptr *stack_bottom) {
263   CHECK(stack_top);
264   CHECK(stack_bottom);
265   uptr stacksize = pthread_get_stacksize_np(pthread_self());
266   // pthread_get_stacksize_np() returns an incorrect stack size for the main
267   // thread on Mavericks. See
268   // https://github.com/google/sanitizers/issues/261
269   if ((GetMacosVersion() >= MACOS_VERSION_MAVERICKS) && at_initialization &&
270       stacksize == (1 << 19))  {
271     struct rlimit rl;
272     CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
273     // Most often rl.rlim_cur will be the desired 8M.
274     if (rl.rlim_cur < kMaxThreadStackSize) {
275       stacksize = rl.rlim_cur;
276     } else {
277       stacksize = kMaxThreadStackSize;
278     }
279   }
280   void *stackaddr = pthread_get_stackaddr_np(pthread_self());
281   *stack_top = (uptr)stackaddr;
282   *stack_bottom = *stack_top - stacksize;
283 }
284
285 char **GetEnviron() {
286 #if !SANITIZER_IOS
287   char ***env_ptr = _NSGetEnviron();
288   if (!env_ptr) {
289     Report("_NSGetEnviron() returned NULL. Please make sure __asan_init() is "
290            "called after libSystem_initializer().\n");
291     CHECK(env_ptr);
292   }
293   char **environ = *env_ptr;
294 #endif
295   CHECK(environ);
296   return environ;
297 }
298
299 const char *GetEnv(const char *name) {
300   char **env = GetEnviron();
301   uptr name_len = internal_strlen(name);
302   while (*env != 0) {
303     uptr len = internal_strlen(*env);
304     if (len > name_len) {
305       const char *p = *env;
306       if (!internal_memcmp(p, name, name_len) &&
307           p[name_len] == '=') {  // Match.
308         return *env + name_len + 1;  // String starting after =.
309       }
310     }
311     env++;
312   }
313   return 0;
314 }
315
316 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
317   CHECK_LE(kMaxPathLength, buf_len);
318
319   // On OS X the executable path is saved to the stack by dyld. Reading it
320   // from there is much faster than calling dladdr, especially for large
321   // binaries with symbols.
322   InternalScopedString exe_path(kMaxPathLength);
323   uint32_t size = exe_path.size();
324   if (_NSGetExecutablePath(exe_path.data(), &size) == 0 &&
325       realpath(exe_path.data(), buf) != 0) {
326     return internal_strlen(buf);
327   }
328   return 0;
329 }
330
331 uptr ReadLongProcessName(/*out*/char *buf, uptr buf_len) {
332   return ReadBinaryName(buf, buf_len);
333 }
334
335 void ReExec() {
336   UNIMPLEMENTED();
337 }
338
339 uptr GetPageSize() {
340   return sysconf(_SC_PAGESIZE);
341 }
342
343 BlockingMutex::BlockingMutex() {
344   internal_memset(this, 0, sizeof(*this));
345 }
346
347 void BlockingMutex::Lock() {
348   CHECK(sizeof(OSSpinLock) <= sizeof(opaque_storage_));
349   CHECK_EQ(OS_SPINLOCK_INIT, 0);
350   CHECK_EQ(owner_, 0);
351   OSSpinLockLock((OSSpinLock*)&opaque_storage_);
352 }
353
354 void BlockingMutex::Unlock() {
355   OSSpinLockUnlock((OSSpinLock*)&opaque_storage_);
356 }
357
358 void BlockingMutex::CheckLocked() {
359   CHECK_NE(*(OSSpinLock*)&opaque_storage_, 0);
360 }
361
362 u64 NanoTime() {
363   return 0;
364 }
365
366 uptr GetTlsSize() {
367   return 0;
368 }
369
370 void InitTlsSize() {
371 }
372
373 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
374                           uptr *tls_addr, uptr *tls_size) {
375 #if !SANITIZER_GO
376   uptr stack_top, stack_bottom;
377   GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
378   *stk_addr = stack_bottom;
379   *stk_size = stack_top - stack_bottom;
380   *tls_addr = 0;
381   *tls_size = 0;
382 #else
383   *stk_addr = 0;
384   *stk_size = 0;
385   *tls_addr = 0;
386   *tls_size = 0;
387 #endif
388 }
389
390 void ListOfModules::init() {
391   clear();
392   MemoryMappingLayout memory_mapping(false);
393   memory_mapping.DumpListOfModules(&modules_);
394 }
395
396 bool IsHandledDeadlySignal(int signum) {
397   if ((SANITIZER_WATCHOS || SANITIZER_TVOS) && !(SANITIZER_IOSSIM))
398     // Handling fatal signals on watchOS and tvOS devices is disallowed.
399     return false;
400   if (common_flags()->handle_abort && signum == SIGABRT)
401     return true;
402   if (common_flags()->handle_sigill && signum == SIGILL)
403     return true;
404   if (common_flags()->handle_sigfpe && signum == SIGFPE)
405     return true;
406   if (common_flags()->handle_segv && signum == SIGSEGV)
407     return true;
408   return common_flags()->handle_sigbus && signum == SIGBUS;
409 }
410
411 MacosVersion cached_macos_version = MACOS_VERSION_UNINITIALIZED;
412
413 MacosVersion GetMacosVersionInternal() {
414   int mib[2] = { CTL_KERN, KERN_OSRELEASE };
415   char version[100];
416   uptr len = 0, maxlen = sizeof(version) / sizeof(version[0]);
417   for (uptr i = 0; i < maxlen; i++) version[i] = '\0';
418   // Get the version length.
419   CHECK_NE(sysctl(mib, 2, 0, &len, 0, 0), -1);
420   CHECK_LT(len, maxlen);
421   CHECK_NE(sysctl(mib, 2, version, &len, 0, 0), -1);
422   switch (version[0]) {
423     case '9': return MACOS_VERSION_LEOPARD;
424     case '1': {
425       switch (version[1]) {
426         case '0': return MACOS_VERSION_SNOW_LEOPARD;
427         case '1': return MACOS_VERSION_LION;
428         case '2': return MACOS_VERSION_MOUNTAIN_LION;
429         case '3': return MACOS_VERSION_MAVERICKS;
430         case '4': return MACOS_VERSION_YOSEMITE;
431         default:
432           if (IsDigit(version[1]))
433             return MACOS_VERSION_UNKNOWN_NEWER;
434           else
435             return MACOS_VERSION_UNKNOWN;
436       }
437     }
438     default: return MACOS_VERSION_UNKNOWN;
439   }
440 }
441
442 MacosVersion GetMacosVersion() {
443   atomic_uint32_t *cache =
444       reinterpret_cast<atomic_uint32_t*>(&cached_macos_version);
445   MacosVersion result =
446       static_cast<MacosVersion>(atomic_load(cache, memory_order_acquire));
447   if (result == MACOS_VERSION_UNINITIALIZED) {
448     result = GetMacosVersionInternal();
449     atomic_store(cache, result, memory_order_release);
450   }
451   return result;
452 }
453
454 bool PlatformHasDifferentMemcpyAndMemmove() {
455   // On OS X 10.7 memcpy() and memmove() are both resolved
456   // into memmove$VARIANT$sse42.
457   // See also https://github.com/google/sanitizers/issues/34.
458   // TODO(glider): need to check dynamically that memcpy() and memmove() are
459   // actually the same function.
460   return GetMacosVersion() == MACOS_VERSION_SNOW_LEOPARD;
461 }
462
463 uptr GetRSS() {
464   struct task_basic_info info;
465   unsigned count = TASK_BASIC_INFO_COUNT;
466   kern_return_t result =
467       task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &count);
468   if (UNLIKELY(result != KERN_SUCCESS)) {
469     Report("Cannot get task info. Error: %d\n", result);
470     Die();
471   }
472   return info.resident_size;
473 }
474
475 void *internal_start_thread(void(*func)(void *arg), void *arg) {
476   // Start the thread with signals blocked, otherwise it can steal user signals.
477   __sanitizer_sigset_t set, old;
478   internal_sigfillset(&set);
479   internal_sigprocmask(SIG_SETMASK, &set, &old);
480   pthread_t th;
481   pthread_create(&th, 0, (void*(*)(void *arg))func, arg);
482   internal_sigprocmask(SIG_SETMASK, &old, 0);
483   return th;
484 }
485
486 void internal_join_thread(void *th) { pthread_join((pthread_t)th, 0); }
487
488 #if !SANITIZER_GO
489 static BlockingMutex syslog_lock(LINKER_INITIALIZED);
490 #endif
491
492 void WriteOneLineToSyslog(const char *s) {
493 #if !SANITIZER_GO
494   syslog_lock.CheckLocked();
495   asl_log(nullptr, nullptr, ASL_LEVEL_ERR, "%s", s);
496 #endif
497 }
498
499 void LogMessageOnPrintf(const char *str) {
500   // Log all printf output to CrashLog.
501   if (common_flags()->abort_on_error)
502     CRAppendCrashLogMessage(str);
503 }
504
505 void LogFullErrorReport(const char *buffer) {
506 #if !SANITIZER_GO
507   // Log with os_trace. This will make it into the crash log.
508 #if SANITIZER_OS_TRACE
509   if (GetMacosVersion() >= MACOS_VERSION_YOSEMITE) {
510     // os_trace requires the message (format parameter) to be a string literal.
511     if (internal_strncmp(SanitizerToolName, "AddressSanitizer",
512                          sizeof("AddressSanitizer") - 1) == 0)
513       os_trace("Address Sanitizer reported a failure.");
514     else if (internal_strncmp(SanitizerToolName, "UndefinedBehaviorSanitizer",
515                               sizeof("UndefinedBehaviorSanitizer") - 1) == 0)
516       os_trace("Undefined Behavior Sanitizer reported a failure.");
517     else if (internal_strncmp(SanitizerToolName, "ThreadSanitizer",
518                               sizeof("ThreadSanitizer") - 1) == 0)
519       os_trace("Thread Sanitizer reported a failure.");
520     else
521       os_trace("Sanitizer tool reported a failure.");
522
523     if (common_flags()->log_to_syslog)
524       os_trace("Consult syslog for more information.");
525   }
526 #endif
527
528   // Log to syslog.
529   // The logging on OS X may call pthread_create so we need the threading
530   // environment to be fully initialized. Also, this should never be called when
531   // holding the thread registry lock since that may result in a deadlock. If
532   // the reporting thread holds the thread registry mutex, and asl_log waits
533   // for GCD to dispatch a new thread, the process will deadlock, because the
534   // pthread_create wrapper needs to acquire the lock as well.
535   BlockingMutexLock l(&syslog_lock);
536   if (common_flags()->log_to_syslog)
537     WriteToSyslog(buffer);
538
539   // The report is added to CrashLog as part of logging all of Printf output.
540 #endif
541 }
542
543 SignalContext::WriteFlag SignalContext::GetWriteFlag(void *context) {
544 #if defined(__x86_64__) || defined(__i386__)
545   ucontext_t *ucontext = static_cast<ucontext_t*>(context);
546   return ucontext->uc_mcontext->__es.__err & 2 /*T_PF_WRITE*/ ? WRITE : READ;
547 #else
548   return UNKNOWN;
549 #endif
550 }
551
552 void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
553   ucontext_t *ucontext = (ucontext_t*)context;
554 # if defined(__aarch64__)
555   *pc = ucontext->uc_mcontext->__ss.__pc;
556 #   if defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
557   *bp = ucontext->uc_mcontext->__ss.__fp;
558 #   else
559   *bp = ucontext->uc_mcontext->__ss.__lr;
560 #   endif
561   *sp = ucontext->uc_mcontext->__ss.__sp;
562 # elif defined(__x86_64__)
563   *pc = ucontext->uc_mcontext->__ss.__rip;
564   *bp = ucontext->uc_mcontext->__ss.__rbp;
565   *sp = ucontext->uc_mcontext->__ss.__rsp;
566 # elif defined(__arm__)
567   *pc = ucontext->uc_mcontext->__ss.__pc;
568   *bp = ucontext->uc_mcontext->__ss.__r[7];
569   *sp = ucontext->uc_mcontext->__ss.__sp;
570 # elif defined(__i386__)
571   *pc = ucontext->uc_mcontext->__ss.__eip;
572   *bp = ucontext->uc_mcontext->__ss.__ebp;
573   *sp = ucontext->uc_mcontext->__ss.__esp;
574 # else
575 # error "Unknown architecture"
576 # endif
577 }
578
579 #if !SANITIZER_GO
580 static const char kDyldInsertLibraries[] = "DYLD_INSERT_LIBRARIES";
581 LowLevelAllocator allocator_for_env;
582
583 // Change the value of the env var |name|, leaking the original value.
584 // If |name_value| is NULL, the variable is deleted from the environment,
585 // otherwise the corresponding "NAME=value" string is replaced with
586 // |name_value|.
587 void LeakyResetEnv(const char *name, const char *name_value) {
588   char **env = GetEnviron();
589   uptr name_len = internal_strlen(name);
590   while (*env != 0) {
591     uptr len = internal_strlen(*env);
592     if (len > name_len) {
593       const char *p = *env;
594       if (!internal_memcmp(p, name, name_len) && p[name_len] == '=') {
595         // Match.
596         if (name_value) {
597           // Replace the old value with the new one.
598           *env = const_cast<char*>(name_value);
599         } else {
600           // Shift the subsequent pointers back.
601           char **del = env;
602           do {
603             del[0] = del[1];
604           } while (*del++);
605         }
606       }
607     }
608     env++;
609   }
610 }
611
612 SANITIZER_WEAK_CXX_DEFAULT_IMPL
613 bool ReexecDisabled() {
614   return false;
615 }
616
617 extern "C" SANITIZER_WEAK_ATTRIBUTE double dyldVersionNumber;
618 static const double kMinDyldVersionWithAutoInterposition = 360.0;
619
620 bool DyldNeedsEnvVariable() {
621   // Although sanitizer support was added to LLVM on OS X 10.7+, GCC users
622   // still may want use them on older systems. On older Darwin platforms, dyld
623   // doesn't export dyldVersionNumber symbol and we simply return true.
624   if (!&dyldVersionNumber) return true;
625   // If running on OS X 10.11+ or iOS 9.0+, dyld will interpose even if
626   // DYLD_INSERT_LIBRARIES is not set. However, checking OS version via
627   // GetMacosVersion() doesn't work for the simulator. Let's instead check
628   // `dyldVersionNumber`, which is exported by dyld, against a known version
629   // number from the first OS release where this appeared.
630   return dyldVersionNumber < kMinDyldVersionWithAutoInterposition;
631 }
632
633 void MaybeReexec() {
634   if (ReexecDisabled()) return;
635
636   // Make sure the dynamic runtime library is preloaded so that the
637   // wrappers work. If it is not, set DYLD_INSERT_LIBRARIES and re-exec
638   // ourselves.
639   Dl_info info;
640   RAW_CHECK(dladdr((void*)((uptr)&__sanitizer_report_error_summary), &info));
641   char *dyld_insert_libraries =
642       const_cast<char*>(GetEnv(kDyldInsertLibraries));
643   uptr old_env_len = dyld_insert_libraries ?
644       internal_strlen(dyld_insert_libraries) : 0;
645   uptr fname_len = internal_strlen(info.dli_fname);
646   const char *dylib_name = StripModuleName(info.dli_fname);
647   uptr dylib_name_len = internal_strlen(dylib_name);
648
649   bool lib_is_in_env = dyld_insert_libraries &&
650                        internal_strstr(dyld_insert_libraries, dylib_name);
651   if (DyldNeedsEnvVariable() && !lib_is_in_env) {
652     // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
653     // library.
654     InternalScopedString program_name(1024);
655     uint32_t buf_size = program_name.size();
656     _NSGetExecutablePath(program_name.data(), &buf_size);
657     char *new_env = const_cast<char*>(info.dli_fname);
658     if (dyld_insert_libraries) {
659       // Append the runtime dylib name to the existing value of
660       // DYLD_INSERT_LIBRARIES.
661       new_env = (char*)allocator_for_env.Allocate(old_env_len + fname_len + 2);
662       internal_strncpy(new_env, dyld_insert_libraries, old_env_len);
663       new_env[old_env_len] = ':';
664       // Copy fname_len and add a trailing zero.
665       internal_strncpy(new_env + old_env_len + 1, info.dli_fname,
666                        fname_len + 1);
667       // Ok to use setenv() since the wrappers don't depend on the value of
668       // asan_inited.
669       setenv(kDyldInsertLibraries, new_env, /*overwrite*/1);
670     } else {
671       // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name.
672       setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0);
673     }
674     VReport(1, "exec()-ing the program with\n");
675     VReport(1, "%s=%s\n", kDyldInsertLibraries, new_env);
676     VReport(1, "to enable wrappers.\n");
677     execv(program_name.data(), *_NSGetArgv());
678
679     // We get here only if execv() failed.
680     Report("ERROR: The process is launched without DYLD_INSERT_LIBRARIES, "
681            "which is required for the sanitizer to work. We tried to set the "
682            "environment variable and re-execute itself, but execv() failed, "
683            "possibly because of sandbox restrictions. Make sure to launch the "
684            "executable with:\n%s=%s\n", kDyldInsertLibraries, new_env);
685     RAW_CHECK("execv failed" && 0);
686   }
687
688   // Verify that interceptors really work.  We'll use dlsym to locate
689   // "pthread_create", if interceptors are working, it should really point to
690   // "wrap_pthread_create" within our own dylib.
691   Dl_info info_pthread_create;
692   void *dlopen_addr = dlsym(RTLD_DEFAULT, "pthread_create");
693   RAW_CHECK(dladdr(dlopen_addr, &info_pthread_create));
694   if (internal_strcmp(info.dli_fname, info_pthread_create.dli_fname) != 0) {
695     Report(
696         "ERROR: Interceptors are not working. This may be because %s is "
697         "loaded too late (e.g. via dlopen). Please launch the executable "
698         "with:\n%s=%s\n",
699         SanitizerToolName, kDyldInsertLibraries, info.dli_fname);
700     RAW_CHECK("interceptors not installed" && 0);
701   }
702
703   if (!lib_is_in_env)
704     return;
705
706   // DYLD_INSERT_LIBRARIES is set and contains the runtime library. Let's remove
707   // the dylib from the environment variable, because interceptors are installed
708   // and we don't want our children to inherit the variable.
709
710   uptr env_name_len = internal_strlen(kDyldInsertLibraries);
711   // Allocate memory to hold the previous env var name, its value, the '='
712   // sign and the '\0' char.
713   char *new_env = (char*)allocator_for_env.Allocate(
714       old_env_len + 2 + env_name_len);
715   RAW_CHECK(new_env);
716   internal_memset(new_env, '\0', old_env_len + 2 + env_name_len);
717   internal_strncpy(new_env, kDyldInsertLibraries, env_name_len);
718   new_env[env_name_len] = '=';
719   char *new_env_pos = new_env + env_name_len + 1;
720
721   // Iterate over colon-separated pieces of |dyld_insert_libraries|.
722   char *piece_start = dyld_insert_libraries;
723   char *piece_end = NULL;
724   char *old_env_end = dyld_insert_libraries + old_env_len;
725   do {
726     if (piece_start[0] == ':') piece_start++;
727     piece_end = internal_strchr(piece_start, ':');
728     if (!piece_end) piece_end = dyld_insert_libraries + old_env_len;
729     if ((uptr)(piece_start - dyld_insert_libraries) > old_env_len) break;
730     uptr piece_len = piece_end - piece_start;
731
732     char *filename_start =
733         (char *)internal_memrchr(piece_start, '/', piece_len);
734     uptr filename_len = piece_len;
735     if (filename_start) {
736       filename_start += 1;
737       filename_len = piece_len - (filename_start - piece_start);
738     } else {
739       filename_start = piece_start;
740     }
741
742     // If the current piece isn't the runtime library name,
743     // append it to new_env.
744     if ((dylib_name_len != filename_len) ||
745         (internal_memcmp(filename_start, dylib_name, dylib_name_len) != 0)) {
746       if (new_env_pos != new_env + env_name_len + 1) {
747         new_env_pos[0] = ':';
748         new_env_pos++;
749       }
750       internal_strncpy(new_env_pos, piece_start, piece_len);
751       new_env_pos += piece_len;
752     }
753     // Move on to the next piece.
754     piece_start = piece_end;
755   } while (piece_start < old_env_end);
756
757   // Can't use setenv() here, because it requires the allocator to be
758   // initialized.
759   // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in
760   // a separate function called after InitializeAllocator().
761   if (new_env_pos == new_env + env_name_len + 1) new_env = NULL;
762   LeakyResetEnv(kDyldInsertLibraries, new_env);
763 }
764 #endif  // SANITIZER_GO
765
766 char **GetArgv() {
767   return *_NSGetArgv();
768 }
769
770 uptr FindAvailableMemoryRange(uptr shadow_size,
771                               uptr alignment,
772                               uptr left_padding) {
773   typedef vm_region_submap_short_info_data_64_t RegionInfo;
774   enum { kRegionInfoSize = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64 };
775   // Start searching for available memory region past PAGEZERO, which is
776   // 4KB on 32-bit and 4GB on 64-bit.
777   mach_vm_address_t start_address =
778     (SANITIZER_WORDSIZE == 32) ? 0x000000001000 : 0x000100000000;
779
780   mach_vm_address_t address = start_address;
781   mach_vm_address_t free_begin = start_address;
782   kern_return_t kr = KERN_SUCCESS;
783   while (kr == KERN_SUCCESS) {
784     mach_vm_size_t vmsize = 0;
785     natural_t depth = 0;
786     RegionInfo vminfo;
787     mach_msg_type_number_t count = kRegionInfoSize;
788     kr = mach_vm_region_recurse(mach_task_self(), &address, &vmsize, &depth,
789                                 (vm_region_info_t)&vminfo, &count);
790     if (free_begin != address) {
791       // We found a free region [free_begin..address-1].
792       uptr shadow_address = RoundUpTo((uptr)free_begin + left_padding,
793                                       alignment);
794       if (shadow_address + shadow_size < (uptr)address) {
795         return shadow_address;
796       }
797     }
798     // Move to the next region.
799     address += vmsize;
800     free_begin = address;
801   }
802
803   // We looked at all free regions and could not find one large enough.
804   return 0;
805 }
806
807 // FIXME implement on this platform.
808 void GetMemoryProfile(fill_profile_f cb, uptr *stats, uptr stats_size) { }
809
810 void SignalContext::DumpAllRegisters(void *context) {
811   Report("Register values:\n");
812
813   ucontext_t *ucontext = (ucontext_t*)context;
814 # define DUMPREG64(r) \
815     Printf("%s = 0x%016llx  ", #r, ucontext->uc_mcontext->__ss.__ ## r);
816 # define DUMPREG32(r) \
817     Printf("%s = 0x%08x  ", #r, ucontext->uc_mcontext->__ss.__ ## r);
818 # define DUMPREG_(r)   Printf(" "); DUMPREG(r);
819 # define DUMPREG__(r)  Printf("  "); DUMPREG(r);
820 # define DUMPREG___(r) Printf("   "); DUMPREG(r);
821
822 # if defined(__x86_64__)
823 #  define DUMPREG(r) DUMPREG64(r)
824   DUMPREG(rax); DUMPREG(rbx); DUMPREG(rcx); DUMPREG(rdx); Printf("\n");
825   DUMPREG(rdi); DUMPREG(rsi); DUMPREG(rbp); DUMPREG(rsp); Printf("\n");
826   DUMPREG_(r8); DUMPREG_(r9); DUMPREG(r10); DUMPREG(r11); Printf("\n");
827   DUMPREG(r12); DUMPREG(r13); DUMPREG(r14); DUMPREG(r15); Printf("\n");
828 # elif defined(__i386__)
829 #  define DUMPREG(r) DUMPREG32(r)
830   DUMPREG(eax); DUMPREG(ebx); DUMPREG(ecx); DUMPREG(edx); Printf("\n");
831   DUMPREG(edi); DUMPREG(esi); DUMPREG(ebp); DUMPREG(esp); Printf("\n");
832 # elif defined(__aarch64__)
833 #  define DUMPREG(r) DUMPREG64(r)
834   DUMPREG_(x[0]); DUMPREG_(x[1]); DUMPREG_(x[2]); DUMPREG_(x[3]); Printf("\n");
835   DUMPREG_(x[4]); DUMPREG_(x[5]); DUMPREG_(x[6]); DUMPREG_(x[7]); Printf("\n");
836   DUMPREG_(x[8]); DUMPREG_(x[9]); DUMPREG(x[10]); DUMPREG(x[11]); Printf("\n");
837   DUMPREG(x[12]); DUMPREG(x[13]); DUMPREG(x[14]); DUMPREG(x[15]); Printf("\n");
838   DUMPREG(x[16]); DUMPREG(x[17]); DUMPREG(x[18]); DUMPREG(x[19]); Printf("\n");
839   DUMPREG(x[20]); DUMPREG(x[21]); DUMPREG(x[22]); DUMPREG(x[23]); Printf("\n");
840   DUMPREG(x[24]); DUMPREG(x[25]); DUMPREG(x[26]); DUMPREG(x[27]); Printf("\n");
841   DUMPREG(x[28]); DUMPREG___(fp); DUMPREG___(lr); DUMPREG___(sp); Printf("\n");
842 # elif defined(__arm__)
843 #  define DUMPREG(r) DUMPREG32(r)
844   DUMPREG_(r[0]); DUMPREG_(r[1]); DUMPREG_(r[2]); DUMPREG_(r[3]); Printf("\n");
845   DUMPREG_(r[4]); DUMPREG_(r[5]); DUMPREG_(r[6]); DUMPREG_(r[7]); Printf("\n");
846   DUMPREG_(r[8]); DUMPREG_(r[9]); DUMPREG(r[10]); DUMPREG(r[11]); Printf("\n");
847   DUMPREG(r[12]); DUMPREG___(sp); DUMPREG___(lr); DUMPREG___(pc); Printf("\n");
848 # else
849 # error "Unknown architecture"
850 # endif
851
852 # undef DUMPREG64
853 # undef DUMPREG32
854 # undef DUMPREG_
855 # undef DUMPREG__
856 # undef DUMPREG___
857 # undef DUMPREG
858 }
859
860 static inline bool CompareBaseAddress(const LoadedModule &a,
861                                       const LoadedModule &b) {
862   return a.base_address() < b.base_address();
863 }
864
865 void FormatUUID(char *out, uptr size, const u8 *uuid) {
866   internal_snprintf(out, size,
867                     "<%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-"
868                     "%02X%02X%02X%02X%02X%02X>",
869                     uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5],
870                     uuid[6], uuid[7], uuid[8], uuid[9], uuid[10], uuid[11],
871                     uuid[12], uuid[13], uuid[14], uuid[15]);
872 }
873
874 void PrintModuleMap() {
875   Printf("Process module map:\n");
876   MemoryMappingLayout memory_mapping(false);
877   InternalMmapVector<LoadedModule> modules(/*initial_capacity*/ 128);
878   memory_mapping.DumpListOfModules(&modules);
879   InternalSort(&modules, modules.size(), CompareBaseAddress);
880   for (uptr i = 0; i < modules.size(); ++i) {
881     char uuid_str[128];
882     FormatUUID(uuid_str, sizeof(uuid_str), modules[i].uuid());
883     Printf("0x%zx-0x%zx %s (%s) %s\n", modules[i].base_address(),
884            modules[i].max_executable_address(), modules[i].full_name(),
885            ModuleArchToString(modules[i].arch()), uuid_str);
886   }
887   Printf("End of module map.\n");
888 }
889
890 void CheckNoDeepBind(const char *filename, int flag) {
891   // Do nothing.
892 }
893
894 }  // namespace __sanitizer
895
896 #endif  // SANITIZER_MAC