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