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