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