1 //===-- sanitizer_mac.cpp -------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is shared between various sanitizers' runtime libraries and
10 // implements OSX-specific functions.
11 //===----------------------------------------------------------------------===//
12 
13 #include "sanitizer_platform.h"
14 #if SANITIZER_MAC
15 #include "sanitizer_mac.h"
16 #include "interception/interception.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_platform_limits_posix.h"
31 #include "sanitizer_procmaps.h"
32 #include "sanitizer_ptrauth.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 // import new crash reporting api
48 #if defined(__has_include) && __has_include(<CrashReporterClient.h>)
49 #define HAVE_CRASHREPORTERCLIENT_H 1
50 #include <CrashReporterClient.h>
51 #else
52 #define HAVE_CRASHREPORTERCLIENT_H 0
53 #endif
54 
55 #if !SANITIZER_IOS
56 #include <crt_externs.h>  // for _NSGetArgv and _NSGetEnviron
57 #else
58 extern "C" {
59   extern char ***_NSGetArgv(void);
60 }
61 #endif
62 
63 #include <asl.h>
64 #include <dlfcn.h>  // for dladdr()
65 #include <errno.h>
66 #include <fcntl.h>
67 #include <libkern/OSAtomic.h>
68 #include <mach-o/dyld.h>
69 #include <mach/mach.h>
70 #include <mach/mach_time.h>
71 #include <mach/vm_statistics.h>
72 #include <malloc/malloc.h>
73 #include <os/log.h>
74 #include <pthread.h>
75 #include <sched.h>
76 #include <signal.h>
77 #include <spawn.h>
78 #include <stdlib.h>
79 #include <sys/ioctl.h>
80 #include <sys/mman.h>
81 #include <sys/resource.h>
82 #include <sys/stat.h>
83 #include <sys/sysctl.h>
84 #include <sys/types.h>
85 #include <sys/wait.h>
86 #include <unistd.h>
87 #include <util.h>
88 
89 // From <crt_externs.h>, but we don't have that file on iOS.
90 extern "C" {
91   extern char ***_NSGetArgv(void);
92   extern char ***_NSGetEnviron(void);
93 }
94 
95 // From <mach/mach_vm.h>, but we don't have that file on iOS.
96 extern "C" {
97   extern kern_return_t mach_vm_region_recurse(
98     vm_map_t target_task,
99     mach_vm_address_t *address,
100     mach_vm_size_t *size,
101     natural_t *nesting_depth,
102     vm_region_recurse_info_t info,
103     mach_msg_type_number_t *infoCnt);
104 }
105 
106 namespace __sanitizer {
107 
108 #include "sanitizer_syscall_generic.inc"
109 
110 // Direct syscalls, don't call libmalloc hooks (but not available on 10.6).
111 extern "C" void *__mmap(void *addr, size_t len, int prot, int flags, int fildes,
112                         off_t off) SANITIZER_WEAK_ATTRIBUTE;
113 extern "C" int __munmap(void *, size_t) SANITIZER_WEAK_ATTRIBUTE;
114 
115 // ---------------------- sanitizer_libc.h
116 
117 // From <mach/vm_statistics.h>, but not on older OSs.
118 #ifndef VM_MEMORY_SANITIZER
119 #define VM_MEMORY_SANITIZER 99
120 #endif
121 
122 // XNU on Darwin provides a mmap flag that optimizes allocation/deallocation of
123 // giant memory regions (i.e. shadow memory regions).
124 #define kXnuFastMmapFd 0x4
125 static size_t kXnuFastMmapThreshold = 2 << 30; // 2 GB
126 static bool use_xnu_fast_mmap = false;
127 
128 uptr internal_mmap(void *addr, size_t length, int prot, int flags,
129                    int fd, u64 offset) {
130   if (fd == -1) {
131     fd = VM_MAKE_TAG(VM_MEMORY_SANITIZER);
132     if (length >= kXnuFastMmapThreshold) {
133       if (use_xnu_fast_mmap) fd |= kXnuFastMmapFd;
134     }
135   }
136   if (&__mmap) return (uptr)__mmap(addr, length, prot, flags, fd, offset);
137   return (uptr)mmap(addr, length, prot, flags, fd, offset);
138 }
139 
140 uptr internal_munmap(void *addr, uptr length) {
141   if (&__munmap) return __munmap(addr, length);
142   return munmap(addr, length);
143 }
144 
145 int internal_mprotect(void *addr, uptr length, int prot) {
146   return mprotect(addr, length, prot);
147 }
148 
149 int internal_madvise(uptr addr, uptr length, int advice) {
150   return madvise((void *)addr, length, advice);
151 }
152 
153 uptr internal_close(fd_t fd) {
154   return close(fd);
155 }
156 
157 uptr internal_open(const char *filename, int flags) {
158   return open(filename, flags);
159 }
160 
161 uptr internal_open(const char *filename, int flags, u32 mode) {
162   return open(filename, flags, mode);
163 }
164 
165 uptr internal_read(fd_t fd, void *buf, uptr count) {
166   return read(fd, buf, count);
167 }
168 
169 uptr internal_write(fd_t fd, const void *buf, uptr count) {
170   return write(fd, buf, count);
171 }
172 
173 uptr internal_stat(const char *path, void *buf) {
174   return stat(path, (struct stat *)buf);
175 }
176 
177 uptr internal_lstat(const char *path, void *buf) {
178   return lstat(path, (struct stat *)buf);
179 }
180 
181 uptr internal_fstat(fd_t fd, void *buf) {
182   return fstat(fd, (struct stat *)buf);
183 }
184 
185 uptr internal_filesize(fd_t fd) {
186   struct stat st;
187   if (internal_fstat(fd, &st))
188     return -1;
189   return (uptr)st.st_size;
190 }
191 
192 uptr internal_dup(int oldfd) {
193   return dup(oldfd);
194 }
195 
196 uptr internal_dup2(int oldfd, int newfd) {
197   return dup2(oldfd, newfd);
198 }
199 
200 uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
201   return readlink(path, buf, bufsize);
202 }
203 
204 uptr internal_unlink(const char *path) {
205   return unlink(path);
206 }
207 
208 uptr internal_sched_yield() {
209   return sched_yield();
210 }
211 
212 void internal__exit(int exitcode) {
213   _exit(exitcode);
214 }
215 
216 unsigned int internal_sleep(unsigned int seconds) {
217   return sleep(seconds);
218 }
219 
220 uptr internal_getpid() {
221   return getpid();
222 }
223 
224 int internal_dlinfo(void *handle, int request, void *p) {
225   UNIMPLEMENTED();
226 }
227 
228 int internal_sigaction(int signum, const void *act, void *oldact) {
229   return sigaction(signum,
230                    (const struct sigaction *)act, (struct sigaction *)oldact);
231 }
232 
233 void internal_sigfillset(__sanitizer_sigset_t *set) { sigfillset(set); }
234 
235 uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
236                           __sanitizer_sigset_t *oldset) {
237   // Don't use sigprocmask here, because it affects all threads.
238   return pthread_sigmask(how, set, oldset);
239 }
240 
241 // Doesn't call pthread_atfork() handlers (but not available on 10.6).
242 extern "C" pid_t __fork(void) SANITIZER_WEAK_ATTRIBUTE;
243 
244 int internal_fork() {
245   if (&__fork)
246     return __fork();
247   return fork();
248 }
249 
250 int internal_sysctl(const int *name, unsigned int namelen, void *oldp,
251                     uptr *oldlenp, const void *newp, uptr newlen) {
252   return sysctl(const_cast<int *>(name), namelen, oldp, (size_t *)oldlenp,
253                 const_cast<void *>(newp), (size_t)newlen);
254 }
255 
256 int internal_sysctlbyname(const char *sname, void *oldp, uptr *oldlenp,
257                           const void *newp, uptr newlen) {
258   return sysctlbyname(sname, oldp, (size_t *)oldlenp, const_cast<void *>(newp),
259                       (size_t)newlen);
260 }
261 
262 static fd_t internal_spawn_impl(const char *argv[], const char *envp[],
263                                 pid_t *pid) {
264   fd_t master_fd = kInvalidFd;
265   fd_t slave_fd = kInvalidFd;
266 
267   auto fd_closer = at_scope_exit([&] {
268     internal_close(master_fd);
269     internal_close(slave_fd);
270   });
271 
272   // We need a new pseudoterminal to avoid buffering problems. The 'atos' tool
273   // in particular detects when it's talking to a pipe and forgets to flush the
274   // output stream after sending a response.
275   master_fd = posix_openpt(O_RDWR);
276   if (master_fd == kInvalidFd) return kInvalidFd;
277 
278   int res = grantpt(master_fd) || unlockpt(master_fd);
279   if (res != 0) return kInvalidFd;
280 
281   // Use TIOCPTYGNAME instead of ptsname() to avoid threading problems.
282   char slave_pty_name[128];
283   res = ioctl(master_fd, TIOCPTYGNAME, slave_pty_name);
284   if (res == -1) return kInvalidFd;
285 
286   slave_fd = internal_open(slave_pty_name, O_RDWR);
287   if (slave_fd == kInvalidFd) return kInvalidFd;
288 
289   // File descriptor actions
290   posix_spawn_file_actions_t acts;
291   res = posix_spawn_file_actions_init(&acts);
292   if (res != 0) return kInvalidFd;
293 
294   auto acts_cleanup = at_scope_exit([&] {
295     posix_spawn_file_actions_destroy(&acts);
296   });
297 
298   res = posix_spawn_file_actions_adddup2(&acts, slave_fd, STDIN_FILENO) ||
299         posix_spawn_file_actions_adddup2(&acts, slave_fd, STDOUT_FILENO) ||
300         posix_spawn_file_actions_addclose(&acts, slave_fd);
301   if (res != 0) return kInvalidFd;
302 
303   // Spawn attributes
304   posix_spawnattr_t attrs;
305   res = posix_spawnattr_init(&attrs);
306   if (res != 0) return kInvalidFd;
307 
308   auto attrs_cleanup  = at_scope_exit([&] {
309     posix_spawnattr_destroy(&attrs);
310   });
311 
312   // In the spawned process, close all file descriptors that are not explicitly
313   // described by the file actions object. This is Darwin-specific extension.
314   res = posix_spawnattr_setflags(&attrs, POSIX_SPAWN_CLOEXEC_DEFAULT);
315   if (res != 0) return kInvalidFd;
316 
317   // posix_spawn
318   char **argv_casted = const_cast<char **>(argv);
319   char **envp_casted = const_cast<char **>(envp);
320   res = posix_spawn(pid, argv[0], &acts, &attrs, argv_casted, envp_casted);
321   if (res != 0) return kInvalidFd;
322 
323   // Disable echo in the new terminal, disable CR.
324   struct termios termflags;
325   tcgetattr(master_fd, &termflags);
326   termflags.c_oflag &= ~ONLCR;
327   termflags.c_lflag &= ~ECHO;
328   tcsetattr(master_fd, TCSANOW, &termflags);
329 
330   // On success, do not close master_fd on scope exit.
331   fd_t fd = master_fd;
332   master_fd = kInvalidFd;
333 
334   return fd;
335 }
336 
337 fd_t internal_spawn(const char *argv[], const char *envp[], pid_t *pid) {
338   // The client program may close its stdin and/or stdout and/or stderr thus
339   // allowing open/posix_openpt to reuse file descriptors 0, 1 or 2. In this
340   // case the communication is broken if either the parent or the child tries to
341   // close or duplicate these descriptors. We temporarily reserve these
342   // descriptors here to prevent this.
343   fd_t low_fds[3];
344   size_t count = 0;
345 
346   for (; count < 3; count++) {
347     low_fds[count] = posix_openpt(O_RDWR);
348     if (low_fds[count] >= STDERR_FILENO)
349       break;
350   }
351 
352   fd_t fd = internal_spawn_impl(argv, envp, pid);
353 
354   for (; count > 0; count--) {
355     internal_close(low_fds[count]);
356   }
357 
358   return fd;
359 }
360 
361 uptr internal_rename(const char *oldpath, const char *newpath) {
362   return rename(oldpath, newpath);
363 }
364 
365 uptr internal_ftruncate(fd_t fd, uptr size) {
366   return ftruncate(fd, size);
367 }
368 
369 uptr internal_execve(const char *filename, char *const argv[],
370                      char *const envp[]) {
371   return execve(filename, argv, envp);
372 }
373 
374 uptr internal_waitpid(int pid, int *status, int options) {
375   return waitpid(pid, status, options);
376 }
377 
378 // ----------------- sanitizer_common.h
379 bool FileExists(const char *filename) {
380   if (ShouldMockFailureToOpen(filename))
381     return false;
382   struct stat st;
383   if (stat(filename, &st))
384     return false;
385   // Sanity check: filename is a regular file.
386   return S_ISREG(st.st_mode);
387 }
388 
389 tid_t GetTid() {
390   tid_t tid;
391   pthread_threadid_np(nullptr, &tid);
392   return tid;
393 }
394 
395 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
396                                 uptr *stack_bottom) {
397   CHECK(stack_top);
398   CHECK(stack_bottom);
399   uptr stacksize = pthread_get_stacksize_np(pthread_self());
400   // pthread_get_stacksize_np() returns an incorrect stack size for the main
401   // thread on Mavericks. See
402   // https://github.com/google/sanitizers/issues/261
403   if ((GetMacosAlignedVersion() >= MacosVersion(10, 9)) && at_initialization &&
404       stacksize == (1 << 19))  {
405     struct rlimit rl;
406     CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
407     // Most often rl.rlim_cur will be the desired 8M.
408     if (rl.rlim_cur < kMaxThreadStackSize) {
409       stacksize = rl.rlim_cur;
410     } else {
411       stacksize = kMaxThreadStackSize;
412     }
413   }
414   void *stackaddr = pthread_get_stackaddr_np(pthread_self());
415   *stack_top = (uptr)stackaddr;
416   *stack_bottom = *stack_top - stacksize;
417 }
418 
419 char **GetEnviron() {
420 #if !SANITIZER_IOS
421   char ***env_ptr = _NSGetEnviron();
422   if (!env_ptr) {
423     Report("_NSGetEnviron() returned NULL. Please make sure __asan_init() is "
424            "called after libSystem_initializer().\n");
425     CHECK(env_ptr);
426   }
427   char **environ = *env_ptr;
428 #endif
429   CHECK(environ);
430   return environ;
431 }
432 
433 const char *GetEnv(const char *name) {
434   char **env = GetEnviron();
435   uptr name_len = internal_strlen(name);
436   while (*env != 0) {
437     uptr len = internal_strlen(*env);
438     if (len > name_len) {
439       const char *p = *env;
440       if (!internal_memcmp(p, name, name_len) &&
441           p[name_len] == '=') {  // Match.
442         return *env + name_len + 1;  // String starting after =.
443       }
444     }
445     env++;
446   }
447   return 0;
448 }
449 
450 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
451   CHECK_LE(kMaxPathLength, buf_len);
452 
453   // On OS X the executable path is saved to the stack by dyld. Reading it
454   // from there is much faster than calling dladdr, especially for large
455   // binaries with symbols.
456   InternalScopedString exe_path(kMaxPathLength);
457   uint32_t size = exe_path.size();
458   if (_NSGetExecutablePath(exe_path.data(), &size) == 0 &&
459       realpath(exe_path.data(), buf) != 0) {
460     return internal_strlen(buf);
461   }
462   return 0;
463 }
464 
465 uptr ReadLongProcessName(/*out*/char *buf, uptr buf_len) {
466   return ReadBinaryName(buf, buf_len);
467 }
468 
469 void ReExec() {
470   UNIMPLEMENTED();
471 }
472 
473 void CheckASLR() {
474   // Do nothing
475 }
476 
477 void CheckMPROTECT() {
478   // Do nothing
479 }
480 
481 uptr GetPageSize() {
482   return sysconf(_SC_PAGESIZE);
483 }
484 
485 extern "C" unsigned malloc_num_zones;
486 extern "C" malloc_zone_t **malloc_zones;
487 malloc_zone_t sanitizer_zone;
488 
489 // We need to make sure that sanitizer_zone is registered as malloc_zones[0]. If
490 // libmalloc tries to set up a different zone as malloc_zones[0], it will call
491 // mprotect(malloc_zones, ..., PROT_READ).  This interceptor will catch that and
492 // make sure we are still the first (default) zone.
493 void MprotectMallocZones(void *addr, int prot) {
494   if (addr == malloc_zones && prot == PROT_READ) {
495     if (malloc_num_zones > 1 && malloc_zones[0] != &sanitizer_zone) {
496       for (unsigned i = 1; i < malloc_num_zones; i++) {
497         if (malloc_zones[i] == &sanitizer_zone) {
498           // Swap malloc_zones[0] and malloc_zones[i].
499           malloc_zones[i] = malloc_zones[0];
500           malloc_zones[0] = &sanitizer_zone;
501           break;
502         }
503       }
504     }
505   }
506 }
507 
508 BlockingMutex::BlockingMutex() {
509   internal_memset(this, 0, sizeof(*this));
510 }
511 
512 void BlockingMutex::Lock() {
513   CHECK(sizeof(OSSpinLock) <= sizeof(opaque_storage_));
514   CHECK_EQ(OS_SPINLOCK_INIT, 0);
515   CHECK_EQ(owner_, 0);
516   OSSpinLockLock((OSSpinLock*)&opaque_storage_);
517 }
518 
519 void BlockingMutex::Unlock() {
520   OSSpinLockUnlock((OSSpinLock*)&opaque_storage_);
521 }
522 
523 void BlockingMutex::CheckLocked() {
524   CHECK_NE(*(OSSpinLock*)&opaque_storage_, 0);
525 }
526 
527 u64 NanoTime() {
528   timeval tv;
529   internal_memset(&tv, 0, sizeof(tv));
530   gettimeofday(&tv, 0);
531   return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
532 }
533 
534 // This needs to be called during initialization to avoid being racy.
535 u64 MonotonicNanoTime() {
536   static mach_timebase_info_data_t timebase_info;
537   if (timebase_info.denom == 0) mach_timebase_info(&timebase_info);
538   return (mach_absolute_time() * timebase_info.numer) / timebase_info.denom;
539 }
540 
541 uptr GetTlsSize() {
542   return 0;
543 }
544 
545 void InitTlsSize() {
546 }
547 
548 uptr TlsBaseAddr() {
549   uptr segbase = 0;
550 #if defined(__x86_64__)
551   asm("movq %%gs:0,%0" : "=r"(segbase));
552 #elif defined(__i386__)
553   asm("movl %%gs:0,%0" : "=r"(segbase));
554 #endif
555   return segbase;
556 }
557 
558 // The size of the tls on darwin does not appear to be well documented,
559 // however the vm memory map suggests that it is 1024 uptrs in size,
560 // with a size of 0x2000 bytes on x86_64 and 0x1000 bytes on i386.
561 uptr TlsSize() {
562 #if defined(__x86_64__) || defined(__i386__)
563   return 1024 * sizeof(uptr);
564 #else
565   return 0;
566 #endif
567 }
568 
569 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
570                           uptr *tls_addr, uptr *tls_size) {
571 #if !SANITIZER_GO
572   uptr stack_top, stack_bottom;
573   GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
574   *stk_addr = stack_bottom;
575   *stk_size = stack_top - stack_bottom;
576   *tls_addr = TlsBaseAddr();
577   *tls_size = TlsSize();
578 #else
579   *stk_addr = 0;
580   *stk_size = 0;
581   *tls_addr = 0;
582   *tls_size = 0;
583 #endif
584 }
585 
586 void ListOfModules::init() {
587   clearOrInit();
588   MemoryMappingLayout memory_mapping(false);
589   memory_mapping.DumpListOfModules(&modules_);
590 }
591 
592 void ListOfModules::fallbackInit() { clear(); }
593 
594 static HandleSignalMode GetHandleSignalModeImpl(int signum) {
595   switch (signum) {
596     case SIGABRT:
597       return common_flags()->handle_abort;
598     case SIGILL:
599       return common_flags()->handle_sigill;
600     case SIGTRAP:
601       return common_flags()->handle_sigtrap;
602     case SIGFPE:
603       return common_flags()->handle_sigfpe;
604     case SIGSEGV:
605       return common_flags()->handle_segv;
606     case SIGBUS:
607       return common_flags()->handle_sigbus;
608   }
609   return kHandleSignalNo;
610 }
611 
612 HandleSignalMode GetHandleSignalMode(int signum) {
613   // Handling fatal signals on watchOS and tvOS devices is disallowed.
614   if ((SANITIZER_WATCHOS || SANITIZER_TVOS) && !(SANITIZER_IOSSIM))
615     return kHandleSignalNo;
616   HandleSignalMode result = GetHandleSignalModeImpl(signum);
617   if (result == kHandleSignalYes && !common_flags()->allow_user_segv_handler)
618     return kHandleSignalExclusive;
619   return result;
620 }
621 
622 // Offset example:
623 // XNU 17 -- macOS 10.13 -- iOS 11 -- tvOS 11 -- watchOS 4
624 constexpr u16 GetOSMajorKernelOffset() {
625   if (TARGET_OS_OSX) return 4;
626   if (TARGET_OS_IOS || TARGET_OS_TV) return 6;
627   if (TARGET_OS_WATCH) return 13;
628 }
629 
630 using VersStr = char[64];
631 
632 static uptr ApproximateOSVersionViaKernelVersion(VersStr vers) {
633   u16 kernel_major = GetDarwinKernelVersion().major;
634   u16 offset = GetOSMajorKernelOffset();
635   CHECK_GE(kernel_major, offset);
636   u16 os_major = kernel_major - offset;
637 
638   const char *format = "%d.0";
639   if (TARGET_OS_OSX) {
640     if (os_major >= 16) {  // macOS 11+
641       os_major -= 5;
642     } else {  // macOS 10.15 and below
643       format = "10.%d";
644     }
645   }
646   return internal_snprintf(vers, sizeof(VersStr), format, os_major);
647 }
648 
649 static void GetOSVersion(VersStr vers) {
650   uptr len = sizeof(VersStr);
651   if (SANITIZER_IOSSIM) {
652     const char *vers_env = GetEnv("SIMULATOR_RUNTIME_VERSION");
653     if (!vers_env) {
654       Report("ERROR: Running in simulator but SIMULATOR_RUNTIME_VERSION env "
655           "var is not set.\n");
656       Die();
657     }
658     len = internal_strlcpy(vers, vers_env, len);
659   } else {
660     int res =
661         internal_sysctlbyname("kern.osproductversion", vers, &len, nullptr, 0);
662 
663     // XNU 17 (macOS 10.13) and below do not provide the sysctl
664     // `kern.osproductversion` entry (res != 0).
665     bool no_os_version = res != 0;
666 
667     // For launchd, sanitizer initialization runs before sysctl is setup
668     // (res == 0 && len != strlen(vers), vers is not a valid version).  However,
669     // the kernel version `kern.osrelease` is available.
670     bool launchd = (res == 0 && internal_strlen(vers) < 3);
671     if (launchd) CHECK_EQ(internal_getpid(), 1);
672 
673     if (no_os_version || launchd) {
674       len = ApproximateOSVersionViaKernelVersion(vers);
675     }
676   }
677   CHECK_LT(len, sizeof(VersStr));
678 }
679 
680 void ParseVersion(const char *vers, u16 *major, u16 *minor) {
681   // Format: <major>.<minor>[.<patch>]\0
682   CHECK_GE(internal_strlen(vers), 3);
683   const char *p = vers;
684   *major = internal_simple_strtoll(p, &p, /*base=*/10);
685   CHECK_EQ(*p, '.');
686   p += 1;
687   *minor = internal_simple_strtoll(p, &p, /*base=*/10);
688 }
689 
690 // Aligned versions example:
691 // macOS 10.15 -- iOS 13 -- tvOS 13 -- watchOS 6
692 static void MapToMacos(u16 *major, u16 *minor) {
693   if (TARGET_OS_OSX)
694     return;
695 
696   if (TARGET_OS_IOS || TARGET_OS_TV)
697     *major += 2;
698   else if (TARGET_OS_WATCH)
699     *major += 9;
700   else
701     UNREACHABLE("unsupported platform");
702 
703   if (*major >= 16) {  // macOS 11+
704     *major -= 5;
705   } else {  // macOS 10.15 and below
706     *minor = *major;
707     *major = 10;
708   }
709 }
710 
711 static MacosVersion GetMacosAlignedVersionInternal() {
712   VersStr vers = {};
713   GetOSVersion(vers);
714 
715   u16 major, minor;
716   ParseVersion(vers, &major, &minor);
717   MapToMacos(&major, &minor);
718 
719   return MacosVersion(major, minor);
720 }
721 
722 static_assert(sizeof(MacosVersion) == sizeof(atomic_uint32_t::Type),
723               "MacosVersion cache size");
724 static atomic_uint32_t cached_macos_version;
725 
726 MacosVersion GetMacosAlignedVersion() {
727   atomic_uint32_t::Type result =
728       atomic_load(&cached_macos_version, memory_order_acquire);
729   if (!result) {
730     MacosVersion version = GetMacosAlignedVersionInternal();
731     result = *reinterpret_cast<atomic_uint32_t::Type *>(&version);
732     atomic_store(&cached_macos_version, result, memory_order_release);
733   }
734   return *reinterpret_cast<MacosVersion *>(&result);
735 }
736 
737 DarwinKernelVersion GetDarwinKernelVersion() {
738   VersStr vers = {};
739   uptr len = sizeof(VersStr);
740   int res = internal_sysctlbyname("kern.osrelease", vers, &len, nullptr, 0);
741   CHECK_EQ(res, 0);
742   CHECK_LT(len, sizeof(VersStr));
743 
744   u16 major, minor;
745   ParseVersion(vers, &major, &minor);
746 
747   return DarwinKernelVersion(major, minor);
748 }
749 
750 uptr GetRSS() {
751   struct task_basic_info info;
752   unsigned count = TASK_BASIC_INFO_COUNT;
753   kern_return_t result =
754       task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &count);
755   if (UNLIKELY(result != KERN_SUCCESS)) {
756     Report("Cannot get task info. Error: %d\n", result);
757     Die();
758   }
759   return info.resident_size;
760 }
761 
762 void *internal_start_thread(void *(*func)(void *arg), void *arg) {
763   // Start the thread with signals blocked, otherwise it can steal user signals.
764   __sanitizer_sigset_t set, old;
765   internal_sigfillset(&set);
766   internal_sigprocmask(SIG_SETMASK, &set, &old);
767   pthread_t th;
768   pthread_create(&th, 0, func, arg);
769   internal_sigprocmask(SIG_SETMASK, &old, 0);
770   return th;
771 }
772 
773 void internal_join_thread(void *th) { pthread_join((pthread_t)th, 0); }
774 
775 #if !SANITIZER_GO
776 static BlockingMutex syslog_lock(LINKER_INITIALIZED);
777 #endif
778 
779 void WriteOneLineToSyslog(const char *s) {
780 #if !SANITIZER_GO
781   syslog_lock.CheckLocked();
782   if (GetMacosAlignedVersion() >= MacosVersion(10, 12)) {
783     os_log_error(OS_LOG_DEFAULT, "%{public}s", s);
784   } else {
785     asl_log(nullptr, nullptr, ASL_LEVEL_ERR, "%s", s);
786   }
787 #endif
788 }
789 
790 // buffer to store crash report application information
791 static char crashreporter_info_buff[__sanitizer::kErrorMessageBufferSize] = {};
792 static BlockingMutex crashreporter_info_mutex(LINKER_INITIALIZED);
793 
794 extern "C" {
795 // Integrate with crash reporter libraries.
796 #if HAVE_CRASHREPORTERCLIENT_H
797 CRASH_REPORTER_CLIENT_HIDDEN
798 struct crashreporter_annotations_t gCRAnnotations
799     __attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION))) = {
800         CRASHREPORTER_ANNOTATIONS_VERSION,
801         0,
802         0,
803         0,
804         0,
805         0,
806         0,
807 #if CRASHREPORTER_ANNOTATIONS_VERSION > 4
808         0,
809 #endif
810 };
811 
812 #else
813 // fall back to old crashreporter api
814 static const char *__crashreporter_info__ __attribute__((__used__)) =
815     &crashreporter_info_buff[0];
816 asm(".desc ___crashreporter_info__, 0x10");
817 #endif
818 
819 }  // extern "C"
820 
821 static void CRAppendCrashLogMessage(const char *msg) {
822   BlockingMutexLock l(&crashreporter_info_mutex);
823   internal_strlcat(crashreporter_info_buff, msg,
824                    sizeof(crashreporter_info_buff));
825 #if HAVE_CRASHREPORTERCLIENT_H
826   (void)CRSetCrashLogMessage(crashreporter_info_buff);
827 #endif
828 }
829 
830 void LogMessageOnPrintf(const char *str) {
831   // Log all printf output to CrashLog.
832   if (common_flags()->abort_on_error)
833     CRAppendCrashLogMessage(str);
834 }
835 
836 void LogFullErrorReport(const char *buffer) {
837 #if !SANITIZER_GO
838   // Log with os_trace. This will make it into the crash log.
839 #if SANITIZER_OS_TRACE
840   if (GetMacosAlignedVersion() >= MacosVersion(10, 10)) {
841     // os_trace requires the message (format parameter) to be a string literal.
842     if (internal_strncmp(SanitizerToolName, "AddressSanitizer",
843                          sizeof("AddressSanitizer") - 1) == 0)
844       os_trace("Address Sanitizer reported a failure.");
845     else if (internal_strncmp(SanitizerToolName, "UndefinedBehaviorSanitizer",
846                               sizeof("UndefinedBehaviorSanitizer") - 1) == 0)
847       os_trace("Undefined Behavior Sanitizer reported a failure.");
848     else if (internal_strncmp(SanitizerToolName, "ThreadSanitizer",
849                               sizeof("ThreadSanitizer") - 1) == 0)
850       os_trace("Thread Sanitizer reported a failure.");
851     else
852       os_trace("Sanitizer tool reported a failure.");
853 
854     if (common_flags()->log_to_syslog)
855       os_trace("Consult syslog for more information.");
856   }
857 #endif
858 
859   // Log to syslog.
860   // The logging on OS X may call pthread_create so we need the threading
861   // environment to be fully initialized. Also, this should never be called when
862   // holding the thread registry lock since that may result in a deadlock. If
863   // the reporting thread holds the thread registry mutex, and asl_log waits
864   // for GCD to dispatch a new thread, the process will deadlock, because the
865   // pthread_create wrapper needs to acquire the lock as well.
866   BlockingMutexLock l(&syslog_lock);
867   if (common_flags()->log_to_syslog)
868     WriteToSyslog(buffer);
869 
870   // The report is added to CrashLog as part of logging all of Printf output.
871 #endif
872 }
873 
874 SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
875 #if defined(__x86_64__) || defined(__i386__)
876   ucontext_t *ucontext = static_cast<ucontext_t*>(context);
877   return ucontext->uc_mcontext->__es.__err & 2 /*T_PF_WRITE*/ ? WRITE : READ;
878 #else
879   return UNKNOWN;
880 #endif
881 }
882 
883 bool SignalContext::IsTrueFaultingAddress() const {
884   auto si = static_cast<const siginfo_t *>(siginfo);
885   // "Real" SIGSEGV codes (e.g., SEGV_MAPERR, SEGV_MAPERR) are non-zero.
886   return si->si_signo == SIGSEGV && si->si_code != 0;
887 }
888 
889 #if defined(__aarch64__) && defined(arm_thread_state64_get_sp)
890   #define AARCH64_GET_REG(r) \
891     (uptr)ptrauth_strip(     \
892         (void *)arm_thread_state64_get_##r(ucontext->uc_mcontext->__ss), 0)
893 #else
894   #define AARCH64_GET_REG(r) ucontext->uc_mcontext->__ss.__##r
895 #endif
896 
897 static void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
898   ucontext_t *ucontext = (ucontext_t*)context;
899 # if defined(__aarch64__)
900   *pc = AARCH64_GET_REG(pc);
901 #   if defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
902   *bp = AARCH64_GET_REG(fp);
903 #   else
904   *bp = AARCH64_GET_REG(lr);
905 #   endif
906   *sp = AARCH64_GET_REG(sp);
907 # elif defined(__x86_64__)
908   *pc = ucontext->uc_mcontext->__ss.__rip;
909   *bp = ucontext->uc_mcontext->__ss.__rbp;
910   *sp = ucontext->uc_mcontext->__ss.__rsp;
911 # elif defined(__arm__)
912   *pc = ucontext->uc_mcontext->__ss.__pc;
913   *bp = ucontext->uc_mcontext->__ss.__r[7];
914   *sp = ucontext->uc_mcontext->__ss.__sp;
915 # elif defined(__i386__)
916   *pc = ucontext->uc_mcontext->__ss.__eip;
917   *bp = ucontext->uc_mcontext->__ss.__ebp;
918   *sp = ucontext->uc_mcontext->__ss.__esp;
919 # else
920 # error "Unknown architecture"
921 # endif
922 }
923 
924 void SignalContext::InitPcSpBp() {
925   addr = (uptr)ptrauth_strip((void *)addr, 0);
926   GetPcSpBp(context, &pc, &sp, &bp);
927 }
928 
929 // ASan/TSan use mmap in a way that creates “deallocation gaps” which triggers
930 // EXC_GUARD exceptions on macOS 10.15+ (XNU 19.0+).
931 static void DisableMmapExcGuardExceptions() {
932   using task_exc_guard_behavior_t = uint32_t;
933   using task_set_exc_guard_behavior_t =
934       kern_return_t(task_t task, task_exc_guard_behavior_t behavior);
935   auto *set_behavior = (task_set_exc_guard_behavior_t *)dlsym(
936       RTLD_DEFAULT, "task_set_exc_guard_behavior");
937   if (set_behavior == nullptr) return;
938   const task_exc_guard_behavior_t task_exc_guard_none = 0;
939   set_behavior(mach_task_self(), task_exc_guard_none);
940 }
941 
942 void InitializePlatformEarly() {
943   // Only use xnu_fast_mmap when on x86_64 and the kernel supports it.
944   use_xnu_fast_mmap =
945 #if defined(__x86_64__)
946       GetDarwinKernelVersion() >= DarwinKernelVersion(17, 5);
947 #else
948       false;
949 #endif
950   if (GetDarwinKernelVersion() >= DarwinKernelVersion(19, 0))
951     DisableMmapExcGuardExceptions();
952 }
953 
954 #if !SANITIZER_GO
955 static const char kDyldInsertLibraries[] = "DYLD_INSERT_LIBRARIES";
956 LowLevelAllocator allocator_for_env;
957 
958 // Change the value of the env var |name|, leaking the original value.
959 // If |name_value| is NULL, the variable is deleted from the environment,
960 // otherwise the corresponding "NAME=value" string is replaced with
961 // |name_value|.
962 void LeakyResetEnv(const char *name, const char *name_value) {
963   char **env = GetEnviron();
964   uptr name_len = internal_strlen(name);
965   while (*env != 0) {
966     uptr len = internal_strlen(*env);
967     if (len > name_len) {
968       const char *p = *env;
969       if (!internal_memcmp(p, name, name_len) && p[name_len] == '=') {
970         // Match.
971         if (name_value) {
972           // Replace the old value with the new one.
973           *env = const_cast<char*>(name_value);
974         } else {
975           // Shift the subsequent pointers back.
976           char **del = env;
977           do {
978             del[0] = del[1];
979           } while (*del++);
980         }
981       }
982     }
983     env++;
984   }
985 }
986 
987 SANITIZER_WEAK_CXX_DEFAULT_IMPL
988 bool ReexecDisabled() {
989   return false;
990 }
991 
992 static bool DyldNeedsEnvVariable() {
993   // If running on OS X 10.11+ or iOS 9.0+, dyld will interpose even if
994   // DYLD_INSERT_LIBRARIES is not set.
995   return GetMacosAlignedVersion() < MacosVersion(10, 11);
996 }
997 
998 void MaybeReexec() {
999   // FIXME: This should really live in some "InitializePlatform" method.
1000   MonotonicNanoTime();
1001 
1002   if (ReexecDisabled()) return;
1003 
1004   // Make sure the dynamic runtime library is preloaded so that the
1005   // wrappers work. If it is not, set DYLD_INSERT_LIBRARIES and re-exec
1006   // ourselves.
1007   Dl_info info;
1008   RAW_CHECK(dladdr((void*)((uptr)&__sanitizer_report_error_summary), &info));
1009   char *dyld_insert_libraries =
1010       const_cast<char*>(GetEnv(kDyldInsertLibraries));
1011   uptr old_env_len = dyld_insert_libraries ?
1012       internal_strlen(dyld_insert_libraries) : 0;
1013   uptr fname_len = internal_strlen(info.dli_fname);
1014   const char *dylib_name = StripModuleName(info.dli_fname);
1015   uptr dylib_name_len = internal_strlen(dylib_name);
1016 
1017   bool lib_is_in_env = dyld_insert_libraries &&
1018                        internal_strstr(dyld_insert_libraries, dylib_name);
1019   if (DyldNeedsEnvVariable() && !lib_is_in_env) {
1020     // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
1021     // library.
1022     InternalScopedString program_name(1024);
1023     uint32_t buf_size = program_name.size();
1024     _NSGetExecutablePath(program_name.data(), &buf_size);
1025     char *new_env = const_cast<char*>(info.dli_fname);
1026     if (dyld_insert_libraries) {
1027       // Append the runtime dylib name to the existing value of
1028       // DYLD_INSERT_LIBRARIES.
1029       new_env = (char*)allocator_for_env.Allocate(old_env_len + fname_len + 2);
1030       internal_strncpy(new_env, dyld_insert_libraries, old_env_len);
1031       new_env[old_env_len] = ':';
1032       // Copy fname_len and add a trailing zero.
1033       internal_strncpy(new_env + old_env_len + 1, info.dli_fname,
1034                        fname_len + 1);
1035       // Ok to use setenv() since the wrappers don't depend on the value of
1036       // asan_inited.
1037       setenv(kDyldInsertLibraries, new_env, /*overwrite*/1);
1038     } else {
1039       // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name.
1040       setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0);
1041     }
1042     VReport(1, "exec()-ing the program with\n");
1043     VReport(1, "%s=%s\n", kDyldInsertLibraries, new_env);
1044     VReport(1, "to enable wrappers.\n");
1045     execv(program_name.data(), *_NSGetArgv());
1046 
1047     // We get here only if execv() failed.
1048     Report("ERROR: The process is launched without DYLD_INSERT_LIBRARIES, "
1049            "which is required for the sanitizer to work. We tried to set the "
1050            "environment variable and re-execute itself, but execv() failed, "
1051            "possibly because of sandbox restrictions. Make sure to launch the "
1052            "executable with:\n%s=%s\n", kDyldInsertLibraries, new_env);
1053     RAW_CHECK("execv failed" && 0);
1054   }
1055 
1056   // Verify that interceptors really work.  We'll use dlsym to locate
1057   // "pthread_create", if interceptors are working, it should really point to
1058   // "wrap_pthread_create" within our own dylib.
1059   Dl_info info_pthread_create;
1060   void *dlopen_addr = dlsym(RTLD_DEFAULT, "pthread_create");
1061   RAW_CHECK(dladdr(dlopen_addr, &info_pthread_create));
1062   if (internal_strcmp(info.dli_fname, info_pthread_create.dli_fname) != 0) {
1063     Report(
1064         "ERROR: Interceptors are not working. This may be because %s is "
1065         "loaded too late (e.g. via dlopen). Please launch the executable "
1066         "with:\n%s=%s\n",
1067         SanitizerToolName, kDyldInsertLibraries, info.dli_fname);
1068     RAW_CHECK("interceptors not installed" && 0);
1069   }
1070 
1071   if (!lib_is_in_env)
1072     return;
1073 
1074   if (!common_flags()->strip_env)
1075     return;
1076 
1077   // DYLD_INSERT_LIBRARIES is set and contains the runtime library. Let's remove
1078   // the dylib from the environment variable, because interceptors are installed
1079   // and we don't want our children to inherit the variable.
1080 
1081   uptr env_name_len = internal_strlen(kDyldInsertLibraries);
1082   // Allocate memory to hold the previous env var name, its value, the '='
1083   // sign and the '\0' char.
1084   char *new_env = (char*)allocator_for_env.Allocate(
1085       old_env_len + 2 + env_name_len);
1086   RAW_CHECK(new_env);
1087   internal_memset(new_env, '\0', old_env_len + 2 + env_name_len);
1088   internal_strncpy(new_env, kDyldInsertLibraries, env_name_len);
1089   new_env[env_name_len] = '=';
1090   char *new_env_pos = new_env + env_name_len + 1;
1091 
1092   // Iterate over colon-separated pieces of |dyld_insert_libraries|.
1093   char *piece_start = dyld_insert_libraries;
1094   char *piece_end = NULL;
1095   char *old_env_end = dyld_insert_libraries + old_env_len;
1096   do {
1097     if (piece_start[0] == ':') piece_start++;
1098     piece_end = internal_strchr(piece_start, ':');
1099     if (!piece_end) piece_end = dyld_insert_libraries + old_env_len;
1100     if ((uptr)(piece_start - dyld_insert_libraries) > old_env_len) break;
1101     uptr piece_len = piece_end - piece_start;
1102 
1103     char *filename_start =
1104         (char *)internal_memrchr(piece_start, '/', piece_len);
1105     uptr filename_len = piece_len;
1106     if (filename_start) {
1107       filename_start += 1;
1108       filename_len = piece_len - (filename_start - piece_start);
1109     } else {
1110       filename_start = piece_start;
1111     }
1112 
1113     // If the current piece isn't the runtime library name,
1114     // append it to new_env.
1115     if ((dylib_name_len != filename_len) ||
1116         (internal_memcmp(filename_start, dylib_name, dylib_name_len) != 0)) {
1117       if (new_env_pos != new_env + env_name_len + 1) {
1118         new_env_pos[0] = ':';
1119         new_env_pos++;
1120       }
1121       internal_strncpy(new_env_pos, piece_start, piece_len);
1122       new_env_pos += piece_len;
1123     }
1124     // Move on to the next piece.
1125     piece_start = piece_end;
1126   } while (piece_start < old_env_end);
1127 
1128   // Can't use setenv() here, because it requires the allocator to be
1129   // initialized.
1130   // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in
1131   // a separate function called after InitializeAllocator().
1132   if (new_env_pos == new_env + env_name_len + 1) new_env = NULL;
1133   LeakyResetEnv(kDyldInsertLibraries, new_env);
1134 }
1135 #endif  // SANITIZER_GO
1136 
1137 char **GetArgv() {
1138   return *_NSGetArgv();
1139 }
1140 
1141 #if SANITIZER_IOS && !SANITIZER_IOSSIM
1142 // The task_vm_info struct is normally provided by the macOS SDK, but we need
1143 // fields only available in 10.12+. Declare the struct manually to be able to
1144 // build against older SDKs.
1145 struct __sanitizer_task_vm_info {
1146   mach_vm_size_t virtual_size;
1147   integer_t region_count;
1148   integer_t page_size;
1149   mach_vm_size_t resident_size;
1150   mach_vm_size_t resident_size_peak;
1151   mach_vm_size_t device;
1152   mach_vm_size_t device_peak;
1153   mach_vm_size_t internal;
1154   mach_vm_size_t internal_peak;
1155   mach_vm_size_t external;
1156   mach_vm_size_t external_peak;
1157   mach_vm_size_t reusable;
1158   mach_vm_size_t reusable_peak;
1159   mach_vm_size_t purgeable_volatile_pmap;
1160   mach_vm_size_t purgeable_volatile_resident;
1161   mach_vm_size_t purgeable_volatile_virtual;
1162   mach_vm_size_t compressed;
1163   mach_vm_size_t compressed_peak;
1164   mach_vm_size_t compressed_lifetime;
1165   mach_vm_size_t phys_footprint;
1166   mach_vm_address_t min_address;
1167   mach_vm_address_t max_address;
1168 };
1169 #define __SANITIZER_TASK_VM_INFO_COUNT ((mach_msg_type_number_t) \
1170     (sizeof(__sanitizer_task_vm_info) / sizeof(natural_t)))
1171 
1172 static uptr GetTaskInfoMaxAddress() {
1173   __sanitizer_task_vm_info vm_info = {} /* zero initialize */;
1174   mach_msg_type_number_t count = __SANITIZER_TASK_VM_INFO_COUNT;
1175   int err = task_info(mach_task_self(), TASK_VM_INFO, (int *)&vm_info, &count);
1176   return err ? 0 : vm_info.max_address;
1177 }
1178 
1179 uptr GetMaxUserVirtualAddress() {
1180   static uptr max_vm = GetTaskInfoMaxAddress();
1181   if (max_vm != 0)
1182     return max_vm - 1;
1183 
1184   // xnu cannot provide vm address limit
1185 # if SANITIZER_WORDSIZE == 32
1186   return 0xffe00000 - 1;
1187 # else
1188   return 0x200000000 - 1;
1189 # endif
1190 }
1191 
1192 #else // !SANITIZER_IOS
1193 
1194 uptr GetMaxUserVirtualAddress() {
1195 # if SANITIZER_WORDSIZE == 64
1196   return (1ULL << 47) - 1;  // 0x00007fffffffffffUL;
1197 # else // SANITIZER_WORDSIZE == 32
1198   static_assert(SANITIZER_WORDSIZE == 32, "Wrong wordsize");
1199   return (1ULL << 32) - 1;  // 0xffffffff;
1200 # endif
1201 }
1202 #endif
1203 
1204 uptr GetMaxVirtualAddress() {
1205   return GetMaxUserVirtualAddress();
1206 }
1207 
1208 uptr MapDynamicShadow(uptr shadow_size_bytes, uptr shadow_scale,
1209                       uptr min_shadow_base_alignment, uptr &high_mem_end) {
1210   const uptr granularity = GetMmapGranularity();
1211   const uptr alignment =
1212       Max<uptr>(granularity << shadow_scale, 1ULL << min_shadow_base_alignment);
1213   const uptr left_padding =
1214       Max<uptr>(granularity, 1ULL << min_shadow_base_alignment);
1215 
1216   uptr space_size = shadow_size_bytes + left_padding;
1217 
1218   uptr largest_gap_found = 0;
1219   uptr max_occupied_addr = 0;
1220   VReport(2, "FindDynamicShadowStart, space_size = %p\n", space_size);
1221   uptr shadow_start =
1222       FindAvailableMemoryRange(space_size, alignment, granularity,
1223                                &largest_gap_found, &max_occupied_addr);
1224   // If the shadow doesn't fit, restrict the address space to make it fit.
1225   if (shadow_start == 0) {
1226     VReport(
1227         2,
1228         "Shadow doesn't fit, largest_gap_found = %p, max_occupied_addr = %p\n",
1229         largest_gap_found, max_occupied_addr);
1230     uptr new_max_vm = RoundDownTo(largest_gap_found << shadow_scale, alignment);
1231     if (new_max_vm < max_occupied_addr) {
1232       Report("Unable to find a memory range for dynamic shadow.\n");
1233       Report(
1234           "space_size = %p, largest_gap_found = %p, max_occupied_addr = %p, "
1235           "new_max_vm = %p\n",
1236           space_size, largest_gap_found, max_occupied_addr, new_max_vm);
1237       CHECK(0 && "cannot place shadow");
1238     }
1239     RestrictMemoryToMaxAddress(new_max_vm);
1240     high_mem_end = new_max_vm - 1;
1241     space_size = (high_mem_end >> shadow_scale) + left_padding;
1242     VReport(2, "FindDynamicShadowStart, space_size = %p\n", space_size);
1243     shadow_start = FindAvailableMemoryRange(space_size, alignment, granularity,
1244                                             nullptr, nullptr);
1245     if (shadow_start == 0) {
1246       Report("Unable to find a memory range after restricting VM.\n");
1247       CHECK(0 && "cannot place shadow after restricting vm");
1248     }
1249   }
1250   CHECK_NE((uptr)0, shadow_start);
1251   CHECK(IsAligned(shadow_start, alignment));
1252   return shadow_start;
1253 }
1254 
1255 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
1256                               uptr *largest_gap_found,
1257                               uptr *max_occupied_addr) {
1258   typedef vm_region_submap_short_info_data_64_t RegionInfo;
1259   enum { kRegionInfoSize = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64 };
1260   // Start searching for available memory region past PAGEZERO, which is
1261   // 4KB on 32-bit and 4GB on 64-bit.
1262   mach_vm_address_t start_address =
1263     (SANITIZER_WORDSIZE == 32) ? 0x000000001000 : 0x000100000000;
1264 
1265   mach_vm_address_t address = start_address;
1266   mach_vm_address_t free_begin = start_address;
1267   kern_return_t kr = KERN_SUCCESS;
1268   if (largest_gap_found) *largest_gap_found = 0;
1269   if (max_occupied_addr) *max_occupied_addr = 0;
1270   while (kr == KERN_SUCCESS) {
1271     mach_vm_size_t vmsize = 0;
1272     natural_t depth = 0;
1273     RegionInfo vminfo;
1274     mach_msg_type_number_t count = kRegionInfoSize;
1275     kr = mach_vm_region_recurse(mach_task_self(), &address, &vmsize, &depth,
1276                                 (vm_region_info_t)&vminfo, &count);
1277     if (kr == KERN_INVALID_ADDRESS) {
1278       // No more regions beyond "address", consider the gap at the end of VM.
1279       address = GetMaxVirtualAddress() + 1;
1280       vmsize = 0;
1281     } else {
1282       if (max_occupied_addr) *max_occupied_addr = address + vmsize;
1283     }
1284     if (free_begin != address) {
1285       // We found a free region [free_begin..address-1].
1286       uptr gap_start = RoundUpTo((uptr)free_begin + left_padding, alignment);
1287       uptr gap_end = RoundDownTo((uptr)address, alignment);
1288       uptr gap_size = gap_end > gap_start ? gap_end - gap_start : 0;
1289       if (size < gap_size) {
1290         return gap_start;
1291       }
1292 
1293       if (largest_gap_found && *largest_gap_found < gap_size) {
1294         *largest_gap_found = gap_size;
1295       }
1296     }
1297     // Move to the next region.
1298     address += vmsize;
1299     free_begin = address;
1300   }
1301 
1302   // We looked at all free regions and could not find one large enough.
1303   return 0;
1304 }
1305 
1306 // FIXME implement on this platform.
1307 void GetMemoryProfile(fill_profile_f cb, uptr *stats, uptr stats_size) { }
1308 
1309 void SignalContext::DumpAllRegisters(void *context) {
1310   Report("Register values:\n");
1311 
1312   ucontext_t *ucontext = (ucontext_t*)context;
1313 # define DUMPREG64(r) \
1314     Printf("%s = 0x%016llx  ", #r, ucontext->uc_mcontext->__ss.__ ## r);
1315 # define DUMPREGA64(r) \
1316     Printf("   %s = 0x%016llx  ", #r, AARCH64_GET_REG(r));
1317 # define DUMPREG32(r) \
1318     Printf("%s = 0x%08x  ", #r, ucontext->uc_mcontext->__ss.__ ## r);
1319 # define DUMPREG_(r)   Printf(" "); DUMPREG(r);
1320 # define DUMPREG__(r)  Printf("  "); DUMPREG(r);
1321 # define DUMPREG___(r) Printf("   "); DUMPREG(r);
1322 
1323 # if defined(__x86_64__)
1324 #  define DUMPREG(r) DUMPREG64(r)
1325   DUMPREG(rax); DUMPREG(rbx); DUMPREG(rcx); DUMPREG(rdx); Printf("\n");
1326   DUMPREG(rdi); DUMPREG(rsi); DUMPREG(rbp); DUMPREG(rsp); Printf("\n");
1327   DUMPREG_(r8); DUMPREG_(r9); DUMPREG(r10); DUMPREG(r11); Printf("\n");
1328   DUMPREG(r12); DUMPREG(r13); DUMPREG(r14); DUMPREG(r15); Printf("\n");
1329 # elif defined(__i386__)
1330 #  define DUMPREG(r) DUMPREG32(r)
1331   DUMPREG(eax); DUMPREG(ebx); DUMPREG(ecx); DUMPREG(edx); Printf("\n");
1332   DUMPREG(edi); DUMPREG(esi); DUMPREG(ebp); DUMPREG(esp); Printf("\n");
1333 # elif defined(__aarch64__)
1334 #  define DUMPREG(r) DUMPREG64(r)
1335   DUMPREG_(x[0]); DUMPREG_(x[1]); DUMPREG_(x[2]); DUMPREG_(x[3]); Printf("\n");
1336   DUMPREG_(x[4]); DUMPREG_(x[5]); DUMPREG_(x[6]); DUMPREG_(x[7]); Printf("\n");
1337   DUMPREG_(x[8]); DUMPREG_(x[9]); DUMPREG(x[10]); DUMPREG(x[11]); Printf("\n");
1338   DUMPREG(x[12]); DUMPREG(x[13]); DUMPREG(x[14]); DUMPREG(x[15]); Printf("\n");
1339   DUMPREG(x[16]); DUMPREG(x[17]); DUMPREG(x[18]); DUMPREG(x[19]); Printf("\n");
1340   DUMPREG(x[20]); DUMPREG(x[21]); DUMPREG(x[22]); DUMPREG(x[23]); Printf("\n");
1341   DUMPREG(x[24]); DUMPREG(x[25]); DUMPREG(x[26]); DUMPREG(x[27]); Printf("\n");
1342   DUMPREG(x[28]); DUMPREGA64(fp); DUMPREGA64(lr); DUMPREGA64(sp); Printf("\n");
1343 # elif defined(__arm__)
1344 #  define DUMPREG(r) DUMPREG32(r)
1345   DUMPREG_(r[0]); DUMPREG_(r[1]); DUMPREG_(r[2]); DUMPREG_(r[3]); Printf("\n");
1346   DUMPREG_(r[4]); DUMPREG_(r[5]); DUMPREG_(r[6]); DUMPREG_(r[7]); Printf("\n");
1347   DUMPREG_(r[8]); DUMPREG_(r[9]); DUMPREG(r[10]); DUMPREG(r[11]); Printf("\n");
1348   DUMPREG(r[12]); DUMPREG___(sp); DUMPREG___(lr); DUMPREG___(pc); Printf("\n");
1349 # else
1350 # error "Unknown architecture"
1351 # endif
1352 
1353 # undef DUMPREG64
1354 # undef DUMPREG32
1355 # undef DUMPREG_
1356 # undef DUMPREG__
1357 # undef DUMPREG___
1358 # undef DUMPREG
1359 }
1360 
1361 static inline bool CompareBaseAddress(const LoadedModule &a,
1362                                       const LoadedModule &b) {
1363   return a.base_address() < b.base_address();
1364 }
1365 
1366 void FormatUUID(char *out, uptr size, const u8 *uuid) {
1367   internal_snprintf(out, size,
1368                     "<%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-"
1369                     "%02X%02X%02X%02X%02X%02X>",
1370                     uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5],
1371                     uuid[6], uuid[7], uuid[8], uuid[9], uuid[10], uuid[11],
1372                     uuid[12], uuid[13], uuid[14], uuid[15]);
1373 }
1374 
1375 void DumpProcessMap() {
1376   Printf("Process module map:\n");
1377   MemoryMappingLayout memory_mapping(false);
1378   InternalMmapVector<LoadedModule> modules;
1379   modules.reserve(128);
1380   memory_mapping.DumpListOfModules(&modules);
1381   Sort(modules.data(), modules.size(), CompareBaseAddress);
1382   for (uptr i = 0; i < modules.size(); ++i) {
1383     char uuid_str[128];
1384     FormatUUID(uuid_str, sizeof(uuid_str), modules[i].uuid());
1385     Printf("0x%zx-0x%zx %s (%s) %s\n", modules[i].base_address(),
1386            modules[i].max_executable_address(), modules[i].full_name(),
1387            ModuleArchToString(modules[i].arch()), uuid_str);
1388   }
1389   Printf("End of module map.\n");
1390 }
1391 
1392 void CheckNoDeepBind(const char *filename, int flag) {
1393   // Do nothing.
1394 }
1395 
1396 bool GetRandom(void *buffer, uptr length, bool blocking) {
1397   if (!buffer || !length || length > 256)
1398     return false;
1399   // arc4random never fails.
1400   REAL(arc4random_buf)(buffer, length);
1401   return true;
1402 }
1403 
1404 u32 GetNumberOfCPUs() {
1405   return (u32)sysconf(_SC_NPROCESSORS_ONLN);
1406 }
1407 
1408 void InitializePlatformCommonFlags(CommonFlags *cf) {}
1409 
1410 }  // namespace __sanitizer
1411 
1412 #endif  // SANITIZER_MAC
1413