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