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