1 //===-- sanitizer_mac.cpp -------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file is shared between various sanitizers' runtime libraries and
10 // implements OSX-specific functions.
11 //===----------------------------------------------------------------------===//
13 #include "sanitizer_platform.h"
15 # include "interception/interception.h"
16 # include "sanitizer_mac.h"
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
25 # include "sanitizer_common.h"
26 # include "sanitizer_file.h"
27 # include "sanitizer_flags.h"
28 # include "sanitizer_interface_internal.h"
29 # include "sanitizer_internal_defs.h"
30 # include "sanitizer_libc.h"
31 # include "sanitizer_platform_limits_posix.h"
32 # include "sanitizer_procmaps.h"
33 # include "sanitizer_ptrauth.h"
36 # include <crt_externs.h> // for _NSGetEnviron
38 extern char **environ
;
41 # if defined(__has_include) && __has_include(<os/trace.h>)
42 # define SANITIZER_OS_TRACE 1
43 # include <os/trace.h>
45 # define SANITIZER_OS_TRACE 0
48 // import new crash reporting api
49 # if defined(__has_include) && __has_include(<CrashReporterClient.h>)
50 # define HAVE_CRASHREPORTERCLIENT_H 1
51 # include <CrashReporterClient.h>
53 # define HAVE_CRASHREPORTERCLIENT_H 0
57 # include <crt_externs.h> // for _NSGetArgv and _NSGetEnviron
60 extern char ***_NSGetArgv(void);
65 # include <dlfcn.h> // for dladdr()
68 # include <libkern/OSAtomic.h>
69 # include <mach-o/dyld.h>
70 # include <mach/mach.h>
71 # include <mach/mach_time.h>
72 # include <mach/vm_statistics.h>
73 # include <malloc/malloc.h>
76 # include <pthread/introspection.h>
81 # include <sys/ioctl.h>
82 # include <sys/mman.h>
83 # include <sys/resource.h>
84 # include <sys/stat.h>
85 # include <sys/sysctl.h>
86 # include <sys/types.h>
87 # include <sys/wait.h>
91 // From <crt_externs.h>, but we don't have that file on iOS.
93 extern char ***_NSGetArgv(void);
94 extern char ***_NSGetEnviron(void);
97 // From <mach/mach_vm.h>, but we don't have that file on iOS.
99 extern kern_return_t
mach_vm_region_recurse(
100 vm_map_t target_task
,
101 mach_vm_address_t
*address
,
102 mach_vm_size_t
*size
,
103 natural_t
*nesting_depth
,
104 vm_region_recurse_info_t info
,
105 mach_msg_type_number_t
*infoCnt
);
108 namespace __sanitizer
{
110 #include "sanitizer_syscall_generic.inc"
112 // Direct syscalls, don't call libmalloc hooks (but not available on 10.6).
113 extern "C" void *__mmap(void *addr
, size_t len
, int prot
, int flags
, int fildes
,
114 off_t off
) SANITIZER_WEAK_ATTRIBUTE
;
115 extern "C" int __munmap(void *, size_t) SANITIZER_WEAK_ATTRIBUTE
;
117 // ---------------------- sanitizer_libc.h
119 // From <mach/vm_statistics.h>, but not on older OSs.
120 #ifndef VM_MEMORY_SANITIZER
121 #define VM_MEMORY_SANITIZER 99
124 // XNU on Darwin provides a mmap flag that optimizes allocation/deallocation of
125 // giant memory regions (i.e. shadow memory regions).
126 #define kXnuFastMmapFd 0x4
127 static size_t kXnuFastMmapThreshold
= 2 << 30; // 2 GB
128 static bool use_xnu_fast_mmap
= false;
130 uptr
internal_mmap(void *addr
, size_t length
, int prot
, int flags
,
131 int fd
, u64 offset
) {
133 fd
= VM_MAKE_TAG(VM_MEMORY_SANITIZER
);
134 if (length
>= kXnuFastMmapThreshold
) {
135 if (use_xnu_fast_mmap
) fd
|= kXnuFastMmapFd
;
138 if (&__mmap
) return (uptr
)__mmap(addr
, length
, prot
, flags
, fd
, offset
);
139 return (uptr
)mmap(addr
, length
, prot
, flags
, fd
, offset
);
142 uptr
internal_munmap(void *addr
, uptr length
) {
143 if (&__munmap
) return __munmap(addr
, length
);
144 return munmap(addr
, length
);
147 uptr
internal_mremap(void *old_address
, uptr old_size
, uptr new_size
, int flags
,
149 CHECK(false && "internal_mremap is unimplemented on Mac");
153 int internal_mprotect(void *addr
, uptr length
, int prot
) {
154 return mprotect(addr
, length
, prot
);
157 int internal_madvise(uptr addr
, uptr length
, int advice
) {
158 return madvise((void *)addr
, length
, advice
);
161 uptr
internal_close(fd_t fd
) {
165 uptr
internal_open(const char *filename
, int flags
) {
166 return open(filename
, flags
);
169 uptr
internal_open(const char *filename
, int flags
, u32 mode
) {
170 return open(filename
, flags
, mode
);
173 uptr
internal_read(fd_t fd
, void *buf
, uptr count
) {
174 return read(fd
, buf
, count
);
177 uptr
internal_write(fd_t fd
, const void *buf
, uptr count
) {
178 return write(fd
, buf
, count
);
181 uptr
internal_stat(const char *path
, void *buf
) {
182 return stat(path
, (struct stat
*)buf
);
185 uptr
internal_lstat(const char *path
, void *buf
) {
186 return lstat(path
, (struct stat
*)buf
);
189 uptr
internal_fstat(fd_t fd
, void *buf
) {
190 return fstat(fd
, (struct stat
*)buf
);
193 uptr
internal_filesize(fd_t fd
) {
195 if (internal_fstat(fd
, &st
))
197 return (uptr
)st
.st_size
;
200 uptr
internal_dup(int oldfd
) {
204 uptr
internal_dup2(int oldfd
, int newfd
) {
205 return dup2(oldfd
, newfd
);
208 uptr
internal_readlink(const char *path
, char *buf
, uptr bufsize
) {
209 return readlink(path
, buf
, bufsize
);
212 uptr
internal_unlink(const char *path
) {
216 uptr
internal_sched_yield() {
217 return sched_yield();
220 void internal__exit(int exitcode
) {
224 void internal_usleep(u64 useconds
) { usleep(useconds
); }
226 uptr
internal_getpid() {
230 int internal_dlinfo(void *handle
, int request
, void *p
) {
234 int internal_sigaction(int signum
, const void *act
, void *oldact
) {
235 return sigaction(signum
,
236 (const struct sigaction
*)act
, (struct sigaction
*)oldact
);
239 void internal_sigfillset(__sanitizer_sigset_t
*set
) { sigfillset(set
); }
241 uptr
internal_sigprocmask(int how
, __sanitizer_sigset_t
*set
,
242 __sanitizer_sigset_t
*oldset
) {
243 // Don't use sigprocmask here, because it affects all threads.
244 return pthread_sigmask(how
, set
, oldset
);
247 // Doesn't call pthread_atfork() handlers (but not available on 10.6).
248 extern "C" pid_t
__fork(void) SANITIZER_WEAK_ATTRIBUTE
;
250 int internal_fork() {
256 int internal_sysctl(const int *name
, unsigned int namelen
, void *oldp
,
257 uptr
*oldlenp
, const void *newp
, uptr newlen
) {
258 return sysctl(const_cast<int *>(name
), namelen
, oldp
, (size_t *)oldlenp
,
259 const_cast<void *>(newp
), (size_t)newlen
);
262 int internal_sysctlbyname(const char *sname
, void *oldp
, uptr
*oldlenp
,
263 const void *newp
, uptr newlen
) {
264 return sysctlbyname(sname
, oldp
, (size_t *)oldlenp
, const_cast<void *>(newp
),
268 static fd_t
internal_spawn_impl(const char *argv
[], const char *envp
[],
270 fd_t primary_fd
= kInvalidFd
;
271 fd_t secondary_fd
= kInvalidFd
;
273 auto fd_closer
= at_scope_exit([&] {
274 internal_close(primary_fd
);
275 internal_close(secondary_fd
);
278 // We need a new pseudoterminal to avoid buffering problems. The 'atos' tool
279 // in particular detects when it's talking to a pipe and forgets to flush the
280 // output stream after sending a response.
281 primary_fd
= posix_openpt(O_RDWR
);
282 if (primary_fd
== kInvalidFd
)
285 int res
= grantpt(primary_fd
) || unlockpt(primary_fd
);
286 if (res
!= 0) return kInvalidFd
;
288 // Use TIOCPTYGNAME instead of ptsname() to avoid threading problems.
289 char secondary_pty_name
[128];
290 res
= ioctl(primary_fd
, TIOCPTYGNAME
, secondary_pty_name
);
291 if (res
== -1) return kInvalidFd
;
293 secondary_fd
= internal_open(secondary_pty_name
, O_RDWR
);
294 if (secondary_fd
== kInvalidFd
)
297 // File descriptor actions
298 posix_spawn_file_actions_t acts
;
299 res
= posix_spawn_file_actions_init(&acts
);
300 if (res
!= 0) return kInvalidFd
;
302 auto acts_cleanup
= at_scope_exit([&] {
303 posix_spawn_file_actions_destroy(&acts
);
306 res
= posix_spawn_file_actions_adddup2(&acts
, secondary_fd
, STDIN_FILENO
) ||
307 posix_spawn_file_actions_adddup2(&acts
, secondary_fd
, STDOUT_FILENO
) ||
308 posix_spawn_file_actions_addclose(&acts
, secondary_fd
);
309 if (res
!= 0) return kInvalidFd
;
312 posix_spawnattr_t attrs
;
313 res
= posix_spawnattr_init(&attrs
);
314 if (res
!= 0) return kInvalidFd
;
316 auto attrs_cleanup
= at_scope_exit([&] {
317 posix_spawnattr_destroy(&attrs
);
320 // In the spawned process, close all file descriptors that are not explicitly
321 // described by the file actions object. This is Darwin-specific extension.
322 res
= posix_spawnattr_setflags(&attrs
, POSIX_SPAWN_CLOEXEC_DEFAULT
);
323 if (res
!= 0) return kInvalidFd
;
326 char **argv_casted
= const_cast<char **>(argv
);
327 char **envp_casted
= const_cast<char **>(envp
);
328 res
= posix_spawn(pid
, argv
[0], &acts
, &attrs
, argv_casted
, envp_casted
);
329 if (res
!= 0) return kInvalidFd
;
331 // Disable echo in the new terminal, disable CR.
332 struct termios termflags
;
333 tcgetattr(primary_fd
, &termflags
);
334 termflags
.c_oflag
&= ~ONLCR
;
335 termflags
.c_lflag
&= ~ECHO
;
336 tcsetattr(primary_fd
, TCSANOW
, &termflags
);
338 // On success, do not close primary_fd on scope exit.
339 fd_t fd
= primary_fd
;
340 primary_fd
= kInvalidFd
;
345 fd_t
internal_spawn(const char *argv
[], const char *envp
[], pid_t
*pid
) {
346 // The client program may close its stdin and/or stdout and/or stderr thus
347 // allowing open/posix_openpt to reuse file descriptors 0, 1 or 2. In this
348 // case the communication is broken if either the parent or the child tries to
349 // close or duplicate these descriptors. We temporarily reserve these
350 // descriptors here to prevent this.
354 for (; count
< 3; count
++) {
355 low_fds
[count
] = posix_openpt(O_RDWR
);
356 if (low_fds
[count
] >= STDERR_FILENO
)
360 fd_t fd
= internal_spawn_impl(argv
, envp
, pid
);
362 for (; count
> 0; count
--) {
363 internal_close(low_fds
[count
]);
369 uptr
internal_rename(const char *oldpath
, const char *newpath
) {
370 return rename(oldpath
, newpath
);
373 uptr
internal_ftruncate(fd_t fd
, uptr size
) {
374 return ftruncate(fd
, size
);
377 uptr
internal_execve(const char *filename
, char *const argv
[],
378 char *const envp
[]) {
379 return execve(filename
, argv
, envp
);
382 uptr
internal_waitpid(int pid
, int *status
, int options
) {
383 return waitpid(pid
, status
, options
);
386 // ----------------- sanitizer_common.h
387 bool FileExists(const char *filename
) {
388 if (ShouldMockFailureToOpen(filename
))
391 if (stat(filename
, &st
))
393 // Sanity check: filename is a regular file.
394 return S_ISREG(st
.st_mode
);
397 bool DirExists(const char *path
) {
401 return S_ISDIR(st
.st_mode
);
406 pthread_threadid_np(nullptr, &tid
);
410 void GetThreadStackTopAndBottom(bool at_initialization
, uptr
*stack_top
,
411 uptr
*stack_bottom
) {
414 uptr stacksize
= pthread_get_stacksize_np(pthread_self());
415 // pthread_get_stacksize_np() returns an incorrect stack size for the main
416 // thread on Mavericks. See
417 // https://github.com/google/sanitizers/issues/261
418 if ((GetMacosAlignedVersion() >= MacosVersion(10, 9)) && at_initialization
&&
419 stacksize
== (1 << 19)) {
421 CHECK_EQ(getrlimit(RLIMIT_STACK
, &rl
), 0);
422 // Most often rl.rlim_cur will be the desired 8M.
423 if (rl
.rlim_cur
< kMaxThreadStackSize
) {
424 stacksize
= rl
.rlim_cur
;
426 stacksize
= kMaxThreadStackSize
;
429 void *stackaddr
= pthread_get_stackaddr_np(pthread_self());
430 *stack_top
= (uptr
)stackaddr
;
431 *stack_bottom
= *stack_top
- stacksize
;
434 char **GetEnviron() {
436 char ***env_ptr
= _NSGetEnviron();
438 Report("_NSGetEnviron() returned NULL. Please make sure __asan_init() is "
439 "called after libSystem_initializer().\n");
442 char **environ
= *env_ptr
;
448 const char *GetEnv(const char *name
) {
449 char **env
= GetEnviron();
450 uptr name_len
= internal_strlen(name
);
452 uptr len
= internal_strlen(*env
);
453 if (len
> name_len
) {
454 const char *p
= *env
;
455 if (!internal_memcmp(p
, name
, name_len
) &&
456 p
[name_len
] == '=') { // Match.
457 return *env
+ name_len
+ 1; // String starting after =.
465 uptr
ReadBinaryName(/*out*/char *buf
, uptr buf_len
) {
466 CHECK_LE(kMaxPathLength
, buf_len
);
468 // On OS X the executable path is saved to the stack by dyld. Reading it
469 // from there is much faster than calling dladdr, especially for large
470 // binaries with symbols.
471 InternalMmapVector
<char> exe_path(kMaxPathLength
);
472 uint32_t size
= exe_path
.size();
473 if (_NSGetExecutablePath(exe_path
.data(), &size
) == 0 &&
474 realpath(exe_path
.data(), buf
) != 0) {
475 return internal_strlen(buf
);
480 uptr
ReadLongProcessName(/*out*/char *buf
, uptr buf_len
) {
481 return ReadBinaryName(buf
, buf_len
);
492 void CheckMPROTECT() {
497 return sysconf(_SC_PAGESIZE
);
500 extern "C" unsigned malloc_num_zones
;
501 extern "C" malloc_zone_t
**malloc_zones
;
502 malloc_zone_t sanitizer_zone
;
504 // We need to make sure that sanitizer_zone is registered as malloc_zones[0]. If
505 // libmalloc tries to set up a different zone as malloc_zones[0], it will call
506 // mprotect(malloc_zones, ..., PROT_READ). This interceptor will catch that and
507 // make sure we are still the first (default) zone.
508 void MprotectMallocZones(void *addr
, int prot
) {
509 if (addr
== malloc_zones
&& prot
== PROT_READ
) {
510 if (malloc_num_zones
> 1 && malloc_zones
[0] != &sanitizer_zone
) {
511 for (unsigned i
= 1; i
< malloc_num_zones
; i
++) {
512 if (malloc_zones
[i
] == &sanitizer_zone
) {
513 // Swap malloc_zones[0] and malloc_zones[i].
514 malloc_zones
[i
] = malloc_zones
[0];
515 malloc_zones
[0] = &sanitizer_zone
;
523 void FutexWait(atomic_uint32_t
*p
, u32 cmp
) {
524 // FIXME: implement actual blocking.
528 void FutexWake(atomic_uint32_t
*p
, u32 count
) {}
532 internal_memset(&tv
, 0, sizeof(tv
));
533 gettimeofday(&tv
, 0);
534 return (u64
)tv
.tv_sec
* 1000*1000*1000 + tv
.tv_usec
* 1000;
537 // This needs to be called during initialization to avoid being racy.
538 u64
MonotonicNanoTime() {
539 static mach_timebase_info_data_t timebase_info
;
540 if (timebase_info
.denom
== 0) mach_timebase_info(&timebase_info
);
541 return (mach_absolute_time() * timebase_info
.numer
) / timebase_info
.denom
;
550 #if defined(__x86_64__)
551 asm("movq %%gs:0,%0" : "=r"(segbase
));
552 #elif defined(__i386__)
553 asm("movl %%gs:0,%0" : "=r"(segbase
));
554 #elif defined(__aarch64__)
555 asm("mrs %x0, tpidrro_el0" : "=r"(segbase
));
556 segbase
&= 0x07ul
; // clearing lower bits, cpu id stored there
561 // The size of the tls on darwin does not appear to be well documented,
562 // however the vm memory map suggests that it is 1024 uptrs in size,
563 // with a size of 0x2000 bytes on x86_64 and 0x1000 bytes on i386.
565 #if defined(__x86_64__) || defined(__i386__)
566 return 1024 * sizeof(uptr
);
572 void GetThreadStackAndTls(bool main
, uptr
*stk_begin
, uptr
*stk_end
,
573 uptr
*tls_begin
, uptr
*tls_end
) {
575 GetThreadStackTopAndBottom(main
, stk_end
, stk_begin
);
576 *tls_begin
= TlsBaseAddr();
577 *tls_end
= *tls_begin
+ TlsSize();
586 void ListOfModules::init() {
588 MemoryMappingLayout
memory_mapping(false);
589 memory_mapping
.DumpListOfModules(&modules_
);
592 void ListOfModules::fallbackInit() { clear(); }
594 static HandleSignalMode
GetHandleSignalModeImpl(int signum
) {
597 return common_flags()->handle_abort
;
599 return common_flags()->handle_sigill
;
601 return common_flags()->handle_sigtrap
;
603 return common_flags()->handle_sigfpe
;
605 return common_flags()->handle_segv
;
607 return common_flags()->handle_sigbus
;
609 return kHandleSignalNo
;
612 HandleSignalMode
GetHandleSignalMode(int signum
) {
613 // Handling fatal signals on watchOS and tvOS devices is disallowed.
614 if ((SANITIZER_WATCHOS
|| SANITIZER_TVOS
) && !(SANITIZER_IOSSIM
))
615 return kHandleSignalNo
;
616 HandleSignalMode result
= GetHandleSignalModeImpl(signum
);
617 if (result
== kHandleSignalYes
&& !common_flags()->allow_user_segv_handler
)
618 return kHandleSignalExclusive
;
623 // XNU 17 -- macOS 10.13 -- iOS 11 -- tvOS 11 -- watchOS 4
624 constexpr u16
GetOSMajorKernelOffset() {
625 if (TARGET_OS_OSX
) return 4;
626 if (TARGET_OS_IOS
|| TARGET_OS_TV
) return 6;
627 if (TARGET_OS_WATCH
) return 13;
630 using VersStr
= char[64];
632 static uptr
ApproximateOSVersionViaKernelVersion(VersStr vers
) {
633 u16 kernel_major
= GetDarwinKernelVersion().major
;
634 u16 offset
= GetOSMajorKernelOffset();
635 CHECK_GE(kernel_major
, offset
);
636 u16 os_major
= kernel_major
- offset
;
638 const char *format
= "%d.0";
640 if (os_major
>= 16) { // macOS 11+
642 } else { // macOS 10.15 and below
646 return internal_snprintf(vers
, sizeof(VersStr
), format
, os_major
);
649 static void GetOSVersion(VersStr vers
) {
650 uptr len
= sizeof(VersStr
);
651 if (SANITIZER_IOSSIM
) {
652 const char *vers_env
= GetEnv("SIMULATOR_RUNTIME_VERSION");
654 Report("ERROR: Running in simulator but SIMULATOR_RUNTIME_VERSION env "
655 "var is not set.\n");
658 len
= internal_strlcpy(vers
, vers_env
, len
);
661 internal_sysctlbyname("kern.osproductversion", vers
, &len
, nullptr, 0);
663 // XNU 17 (macOS 10.13) and below do not provide the sysctl
664 // `kern.osproductversion` entry (res != 0).
665 bool no_os_version
= res
!= 0;
667 // For launchd, sanitizer initialization runs before sysctl is setup
668 // (res == 0 && len != strlen(vers), vers is not a valid version). However,
669 // the kernel version `kern.osrelease` is available.
670 bool launchd
= (res
== 0 && internal_strlen(vers
) < 3);
671 if (launchd
) CHECK_EQ(internal_getpid(), 1);
673 if (no_os_version
|| launchd
) {
674 len
= ApproximateOSVersionViaKernelVersion(vers
);
677 CHECK_LT(len
, sizeof(VersStr
));
680 void ParseVersion(const char *vers
, u16
*major
, u16
*minor
) {
681 // Format: <major>.<minor>[.<patch>]\0
682 CHECK_GE(internal_strlen(vers
), 3);
683 const char *p
= vers
;
684 *major
= internal_simple_strtoll(p
, &p
, /*base=*/10);
687 *minor
= internal_simple_strtoll(p
, &p
, /*base=*/10);
690 // Aligned versions example:
691 // macOS 10.15 -- iOS 13 -- tvOS 13 -- watchOS 6
692 static void MapToMacos(u16
*major
, u16
*minor
) {
696 if (TARGET_OS_IOS
|| TARGET_OS_TV
)
698 else if (TARGET_OS_WATCH
)
701 UNREACHABLE("unsupported platform");
703 if (*major
>= 16) { // macOS 11+
705 } else { // macOS 10.15 and below
711 static MacosVersion
GetMacosAlignedVersionInternal() {
716 ParseVersion(vers
, &major
, &minor
);
717 MapToMacos(&major
, &minor
);
719 return MacosVersion(major
, minor
);
722 static_assert(sizeof(MacosVersion
) == sizeof(atomic_uint32_t::Type
),
723 "MacosVersion cache size");
724 static atomic_uint32_t cached_macos_version
;
726 MacosVersion
GetMacosAlignedVersion() {
727 atomic_uint32_t::Type result
=
728 atomic_load(&cached_macos_version
, memory_order_acquire
);
730 MacosVersion version
= GetMacosAlignedVersionInternal();
731 result
= *reinterpret_cast<atomic_uint32_t::Type
*>(&version
);
732 atomic_store(&cached_macos_version
, result
, memory_order_release
);
734 return *reinterpret_cast<MacosVersion
*>(&result
);
737 DarwinKernelVersion
GetDarwinKernelVersion() {
739 uptr len
= sizeof(VersStr
);
740 int res
= internal_sysctlbyname("kern.osrelease", vers
, &len
, nullptr, 0);
742 CHECK_LT(len
, sizeof(VersStr
));
745 ParseVersion(vers
, &major
, &minor
);
747 return DarwinKernelVersion(major
, minor
);
751 struct task_basic_info info
;
752 unsigned count
= TASK_BASIC_INFO_COUNT
;
753 kern_return_t result
=
754 task_info(mach_task_self(), TASK_BASIC_INFO
, (task_info_t
)&info
, &count
);
755 if (UNLIKELY(result
!= KERN_SUCCESS
)) {
756 Report("Cannot get task info. Error: %d\n", result
);
759 return info
.resident_size
;
762 void *internal_start_thread(void *(*func
)(void *arg
), void *arg
) {
763 // Start the thread with signals blocked, otherwise it can steal user signals.
764 __sanitizer_sigset_t set
, old
;
765 internal_sigfillset(&set
);
766 internal_sigprocmask(SIG_SETMASK
, &set
, &old
);
768 pthread_create(&th
, 0, func
, arg
);
769 internal_sigprocmask(SIG_SETMASK
, &old
, 0);
773 void internal_join_thread(void *th
) { pthread_join((pthread_t
)th
, 0); }
776 static Mutex syslog_lock
;
779 void WriteOneLineToSyslog(const char *s
) {
781 syslog_lock
.CheckLocked();
782 if (GetMacosAlignedVersion() >= MacosVersion(10, 12)) {
783 os_log_error(OS_LOG_DEFAULT
, "%{public}s", s
);
785 #pragma clang diagnostic push
786 // as_log is deprecated.
787 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
788 asl_log(nullptr, nullptr, ASL_LEVEL_ERR
, "%s", s
);
789 #pragma clang diagnostic pop
794 // buffer to store crash report application information
795 static char crashreporter_info_buff
[__sanitizer::kErrorMessageBufferSize
] = {};
796 static Mutex crashreporter_info_mutex
;
799 // Integrate with crash reporter libraries.
800 #if HAVE_CRASHREPORTERCLIENT_H
801 CRASH_REPORTER_CLIENT_HIDDEN
802 struct crashreporter_annotations_t gCRAnnotations
803 __attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION
))) = {
804 CRASHREPORTER_ANNOTATIONS_VERSION
,
811 #if CRASHREPORTER_ANNOTATIONS_VERSION > 4
817 // fall back to old crashreporter api
818 static const char *__crashreporter_info__
__attribute__((__used__
)) =
819 &crashreporter_info_buff
[0];
820 asm(".desc ___crashreporter_info__, 0x10");
825 static void CRAppendCrashLogMessage(const char *msg
) {
826 Lock
l(&crashreporter_info_mutex
);
827 internal_strlcat(crashreporter_info_buff
, msg
,
828 sizeof(crashreporter_info_buff
));
829 #if HAVE_CRASHREPORTERCLIENT_H
830 (void)CRSetCrashLogMessage(crashreporter_info_buff
);
834 void LogMessageOnPrintf(const char *str
) {
835 // Log all printf output to CrashLog.
836 if (common_flags()->abort_on_error
)
837 CRAppendCrashLogMessage(str
);
840 void LogFullErrorReport(const char *buffer
) {
842 // Log with os_trace. This will make it into the crash log.
843 #if SANITIZER_OS_TRACE
844 #pragma clang diagnostic push
845 // os_trace is deprecated.
846 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
847 if (GetMacosAlignedVersion() >= MacosVersion(10, 10)) {
848 // os_trace requires the message (format parameter) to be a string literal.
849 if (internal_strncmp(SanitizerToolName
, "AddressSanitizer",
850 sizeof("AddressSanitizer") - 1) == 0)
851 os_trace("Address Sanitizer reported a failure.");
852 else if (internal_strncmp(SanitizerToolName
, "UndefinedBehaviorSanitizer",
853 sizeof("UndefinedBehaviorSanitizer") - 1) == 0)
854 os_trace("Undefined Behavior Sanitizer reported a failure.");
855 else if (internal_strncmp(SanitizerToolName
, "ThreadSanitizer",
856 sizeof("ThreadSanitizer") - 1) == 0)
857 os_trace("Thread Sanitizer reported a failure.");
859 os_trace("Sanitizer tool reported a failure.");
861 if (common_flags()->log_to_syslog
)
862 os_trace("Consult syslog for more information.");
864 #pragma clang diagnostic pop
868 // The logging on OS X may call pthread_create so we need the threading
869 // environment to be fully initialized. Also, this should never be called when
870 // holding the thread registry lock since that may result in a deadlock. If
871 // the reporting thread holds the thread registry mutex, and asl_log waits
872 // for GCD to dispatch a new thread, the process will deadlock, because the
873 // pthread_create wrapper needs to acquire the lock as well.
874 Lock
l(&syslog_lock
);
875 if (common_flags()->log_to_syslog
)
876 WriteToSyslog(buffer
);
878 // The report is added to CrashLog as part of logging all of Printf output.
882 SignalContext::WriteFlag
SignalContext::GetWriteFlag() const {
883 #if defined(__x86_64__) || defined(__i386__)
884 ucontext_t
*ucontext
= static_cast<ucontext_t
*>(context
);
885 return ucontext
->uc_mcontext
->__es
.__err
& 2 /*T_PF_WRITE*/ ? Write
: Read
;
886 #elif defined(__arm64__)
887 ucontext_t
*ucontext
= static_cast<ucontext_t
*>(context
);
888 return ucontext
->uc_mcontext
->__es
.__esr
& 0x40 /*ISS_DA_WNR*/ ? Write
: Read
;
894 bool SignalContext::IsTrueFaultingAddress() const {
895 auto si
= static_cast<const siginfo_t
*>(siginfo
);
896 // "Real" SIGSEGV codes (e.g., SEGV_MAPERR, SEGV_MAPERR) are non-zero.
897 return si
->si_signo
== SIGSEGV
&& si
->si_code
!= 0;
900 #if defined(__aarch64__) && defined(arm_thread_state64_get_sp)
901 #define AARCH64_GET_REG(r) \
902 (uptr)ptrauth_strip( \
903 (void *)arm_thread_state64_get_##r(ucontext->uc_mcontext->__ss), 0)
905 #define AARCH64_GET_REG(r) (uptr)ucontext->uc_mcontext->__ss.__##r
908 static void GetPcSpBp(void *context
, uptr
*pc
, uptr
*sp
, uptr
*bp
) {
909 ucontext_t
*ucontext
= (ucontext_t
*)context
;
910 # if defined(__aarch64__)
911 *pc
= AARCH64_GET_REG(pc
);
912 *bp
= AARCH64_GET_REG(fp
);
913 *sp
= AARCH64_GET_REG(sp
);
914 # elif defined(__x86_64__)
915 *pc
= ucontext
->uc_mcontext
->__ss
.__rip
;
916 *bp
= ucontext
->uc_mcontext
->__ss
.__rbp
;
917 *sp
= ucontext
->uc_mcontext
->__ss
.__rsp
;
918 # elif defined(__arm__)
919 *pc
= ucontext
->uc_mcontext
->__ss
.__pc
;
920 *bp
= ucontext
->uc_mcontext
->__ss
.__r
[7];
921 *sp
= ucontext
->uc_mcontext
->__ss
.__sp
;
922 # elif defined(__i386__)
923 *pc
= ucontext
->uc_mcontext
->__ss
.__eip
;
924 *bp
= ucontext
->uc_mcontext
->__ss
.__ebp
;
925 *sp
= ucontext
->uc_mcontext
->__ss
.__esp
;
927 # error "Unknown architecture"
931 void SignalContext::InitPcSpBp() {
932 addr
= (uptr
)ptrauth_strip((void *)addr
, 0);
933 GetPcSpBp(context
, &pc
, &sp
, &bp
);
936 // ASan/TSan use mmap in a way that creates “deallocation gaps” which triggers
937 // EXC_GUARD exceptions on macOS 10.15+ (XNU 19.0+).
938 static void DisableMmapExcGuardExceptions() {
939 using task_exc_guard_behavior_t
= uint32_t;
940 using task_set_exc_guard_behavior_t
=
941 kern_return_t(task_t task
, task_exc_guard_behavior_t behavior
);
942 auto *set_behavior
= (task_set_exc_guard_behavior_t
*)dlsym(
943 RTLD_DEFAULT
, "task_set_exc_guard_behavior");
944 if (set_behavior
== nullptr) return;
945 const task_exc_guard_behavior_t task_exc_guard_none
= 0;
946 set_behavior(mach_task_self(), task_exc_guard_none
);
949 static void VerifyInterceptorsWorking();
950 static void StripEnv();
952 void InitializePlatformEarly() {
953 // Only use xnu_fast_mmap when on x86_64 and the kernel supports it.
955 #if defined(__x86_64__)
956 GetDarwinKernelVersion() >= DarwinKernelVersion(17, 5);
960 if (GetDarwinKernelVersion() >= DarwinKernelVersion(19, 0))
961 DisableMmapExcGuardExceptions();
964 MonotonicNanoTime(); // Call to initialize mach_timebase_info
965 VerifyInterceptorsWorking();
971 static const char kDyldInsertLibraries
[] = "DYLD_INSERT_LIBRARIES";
972 LowLevelAllocator allocator_for_env
;
974 static bool ShouldCheckInterceptors() {
975 // Restrict "interceptors working?" check to ASan and TSan.
976 const char *sanitizer_names
[] = {"AddressSanitizer", "ThreadSanitizer"};
977 size_t count
= sizeof(sanitizer_names
) / sizeof(sanitizer_names
[0]);
978 for (size_t i
= 0; i
< count
; i
++) {
979 if (internal_strcmp(sanitizer_names
[i
], SanitizerToolName
) == 0)
985 static void VerifyInterceptorsWorking() {
986 if (!common_flags()->verify_interceptors
|| !ShouldCheckInterceptors())
989 // Verify that interceptors really work. We'll use dlsym to locate
990 // "puts", if interceptors are working, it should really point to
991 // "wrap_puts" within our own dylib.
992 Dl_info info_puts
, info_runtime
;
993 RAW_CHECK(dladdr(dlsym(RTLD_DEFAULT
, "puts"), &info_puts
));
994 RAW_CHECK(dladdr((void *)&VerifyInterceptorsWorking
, &info_runtime
));
995 if (internal_strcmp(info_puts
.dli_fname
, info_runtime
.dli_fname
) != 0) {
997 "ERROR: Interceptors are not working. This may be because %s is "
998 "loaded too late (e.g. via dlopen). Please launch the executable "
1000 SanitizerToolName
, kDyldInsertLibraries
, info_runtime
.dli_fname
);
1001 RAW_CHECK("interceptors not installed" && 0);
1005 // Change the value of the env var |name|, leaking the original value.
1006 // If |name_value| is NULL, the variable is deleted from the environment,
1007 // otherwise the corresponding "NAME=value" string is replaced with
1009 static void LeakyResetEnv(const char *name
, const char *name_value
) {
1010 char **env
= GetEnviron();
1011 uptr name_len
= internal_strlen(name
);
1013 uptr len
= internal_strlen(*env
);
1014 if (len
> name_len
) {
1015 const char *p
= *env
;
1016 if (!internal_memcmp(p
, name
, name_len
) && p
[name_len
] == '=') {
1019 // Replace the old value with the new one.
1020 *env
= const_cast<char*>(name_value
);
1022 // Shift the subsequent pointers back.
1034 static void StripEnv() {
1035 if (!common_flags()->strip_env
)
1038 char *dyld_insert_libraries
=
1039 const_cast<char *>(GetEnv(kDyldInsertLibraries
));
1040 if (!dyld_insert_libraries
)
1044 RAW_CHECK(dladdr((void *)&StripEnv
, &info
));
1045 const char *dylib_name
= StripModuleName(info
.dli_fname
);
1046 bool lib_is_in_env
= internal_strstr(dyld_insert_libraries
, dylib_name
);
1050 // DYLD_INSERT_LIBRARIES is set and contains the runtime library. Let's remove
1051 // the dylib from the environment variable, because interceptors are installed
1052 // and we don't want our children to inherit the variable.
1054 uptr old_env_len
= internal_strlen(dyld_insert_libraries
);
1055 uptr dylib_name_len
= internal_strlen(dylib_name
);
1056 uptr env_name_len
= internal_strlen(kDyldInsertLibraries
);
1057 // Allocate memory to hold the previous env var name, its value, the '='
1058 // sign and the '\0' char.
1059 char *new_env
= (char*)allocator_for_env
.Allocate(
1060 old_env_len
+ 2 + env_name_len
);
1062 internal_memset(new_env
, '\0', old_env_len
+ 2 + env_name_len
);
1063 internal_strncpy(new_env
, kDyldInsertLibraries
, env_name_len
);
1064 new_env
[env_name_len
] = '=';
1065 char *new_env_pos
= new_env
+ env_name_len
+ 1;
1067 // Iterate over colon-separated pieces of |dyld_insert_libraries|.
1068 char *piece_start
= dyld_insert_libraries
;
1069 char *piece_end
= NULL
;
1070 char *old_env_end
= dyld_insert_libraries
+ old_env_len
;
1072 if (piece_start
[0] == ':') piece_start
++;
1073 piece_end
= internal_strchr(piece_start
, ':');
1074 if (!piece_end
) piece_end
= dyld_insert_libraries
+ old_env_len
;
1075 if ((uptr
)(piece_start
- dyld_insert_libraries
) > old_env_len
) break;
1076 uptr piece_len
= piece_end
- piece_start
;
1078 char *filename_start
=
1079 (char *)internal_memrchr(piece_start
, '/', piece_len
);
1080 uptr filename_len
= piece_len
;
1081 if (filename_start
) {
1082 filename_start
+= 1;
1083 filename_len
= piece_len
- (filename_start
- piece_start
);
1085 filename_start
= piece_start
;
1088 // If the current piece isn't the runtime library name,
1089 // append it to new_env.
1090 if ((dylib_name_len
!= filename_len
) ||
1091 (internal_memcmp(filename_start
, dylib_name
, dylib_name_len
) != 0)) {
1092 if (new_env_pos
!= new_env
+ env_name_len
+ 1) {
1093 new_env_pos
[0] = ':';
1096 internal_strncpy(new_env_pos
, piece_start
, piece_len
);
1097 new_env_pos
+= piece_len
;
1099 // Move on to the next piece.
1100 piece_start
= piece_end
;
1101 } while (piece_start
< old_env_end
);
1103 // Can't use setenv() here, because it requires the allocator to be
1105 // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in
1106 // a separate function called after InitializeAllocator().
1107 if (new_env_pos
== new_env
+ env_name_len
+ 1) new_env
= NULL
;
1108 LeakyResetEnv(kDyldInsertLibraries
, new_env
);
1110 #endif // SANITIZER_GO
1113 return *_NSGetArgv();
1116 #if SANITIZER_IOS && !SANITIZER_IOSSIM
1117 // The task_vm_info struct is normally provided by the macOS SDK, but we need
1118 // fields only available in 10.12+. Declare the struct manually to be able to
1119 // build against older SDKs.
1120 struct __sanitizer_task_vm_info
{
1121 mach_vm_size_t virtual_size
;
1122 integer_t region_count
;
1123 integer_t page_size
;
1124 mach_vm_size_t resident_size
;
1125 mach_vm_size_t resident_size_peak
;
1126 mach_vm_size_t device
;
1127 mach_vm_size_t device_peak
;
1128 mach_vm_size_t internal
;
1129 mach_vm_size_t internal_peak
;
1130 mach_vm_size_t external
;
1131 mach_vm_size_t external_peak
;
1132 mach_vm_size_t reusable
;
1133 mach_vm_size_t reusable_peak
;
1134 mach_vm_size_t purgeable_volatile_pmap
;
1135 mach_vm_size_t purgeable_volatile_resident
;
1136 mach_vm_size_t purgeable_volatile_virtual
;
1137 mach_vm_size_t compressed
;
1138 mach_vm_size_t compressed_peak
;
1139 mach_vm_size_t compressed_lifetime
;
1140 mach_vm_size_t phys_footprint
;
1141 mach_vm_address_t min_address
;
1142 mach_vm_address_t max_address
;
1144 #define __SANITIZER_TASK_VM_INFO_COUNT ((mach_msg_type_number_t) \
1145 (sizeof(__sanitizer_task_vm_info) / sizeof(natural_t)))
1147 static uptr
GetTaskInfoMaxAddress() {
1148 __sanitizer_task_vm_info vm_info
= {} /* zero initialize */;
1149 mach_msg_type_number_t count
= __SANITIZER_TASK_VM_INFO_COUNT
;
1150 int err
= task_info(mach_task_self(), TASK_VM_INFO
, (int *)&vm_info
, &count
);
1151 return err
? 0 : vm_info
.max_address
;
1154 uptr
GetMaxUserVirtualAddress() {
1155 static uptr max_vm
= GetTaskInfoMaxAddress();
1157 const uptr ret_value
= max_vm
- 1;
1158 CHECK_LE(ret_value
, SANITIZER_MMAP_RANGE_SIZE
);
1162 // xnu cannot provide vm address limit
1163 # if SANITIZER_WORDSIZE == 32
1164 constexpr uptr fallback_max_vm
= 0xffe00000 - 1;
1166 constexpr uptr fallback_max_vm
= 0x200000000 - 1;
1168 static_assert(fallback_max_vm
<= SANITIZER_MMAP_RANGE_SIZE
,
1169 "Max virtual address must be less than mmap range size.");
1170 return fallback_max_vm
;
1173 #else // !SANITIZER_IOS
1175 uptr
GetMaxUserVirtualAddress() {
1176 # if SANITIZER_WORDSIZE == 64
1177 constexpr uptr max_vm
= (1ULL << 47) - 1; // 0x00007fffffffffffUL;
1178 # else // SANITIZER_WORDSIZE == 32
1179 static_assert(SANITIZER_WORDSIZE
== 32, "Wrong wordsize");
1180 constexpr uptr max_vm
= (1ULL << 32) - 1; // 0xffffffff;
1182 static_assert(max_vm
<= SANITIZER_MMAP_RANGE_SIZE
,
1183 "Max virtual address must be less than mmap range size.");
1188 uptr
GetMaxVirtualAddress() {
1189 return GetMaxUserVirtualAddress();
1192 uptr
MapDynamicShadow(uptr shadow_size_bytes
, uptr shadow_scale
,
1193 uptr min_shadow_base_alignment
, uptr
&high_mem_end
,
1195 const uptr alignment
=
1196 Max
<uptr
>(granularity
<< shadow_scale
, 1ULL << min_shadow_base_alignment
);
1197 const uptr left_padding
=
1198 Max
<uptr
>(granularity
, 1ULL << min_shadow_base_alignment
);
1200 uptr space_size
= shadow_size_bytes
+ left_padding
;
1202 uptr largest_gap_found
= 0;
1203 uptr max_occupied_addr
= 0;
1204 VReport(2, "FindDynamicShadowStart, space_size = %p\n", (void *)space_size
);
1206 FindAvailableMemoryRange(space_size
, alignment
, granularity
,
1207 &largest_gap_found
, &max_occupied_addr
);
1208 // If the shadow doesn't fit, restrict the address space to make it fit.
1209 if (shadow_start
== 0) {
1212 "Shadow doesn't fit, largest_gap_found = %p, max_occupied_addr = %p\n",
1213 (void *)largest_gap_found
, (void *)max_occupied_addr
);
1214 uptr new_max_vm
= RoundDownTo(largest_gap_found
<< shadow_scale
, alignment
);
1215 if (new_max_vm
< max_occupied_addr
) {
1216 Report("Unable to find a memory range for dynamic shadow.\n");
1218 "space_size = %p, largest_gap_found = %p, max_occupied_addr = %p, "
1219 "new_max_vm = %p\n",
1220 (void *)space_size
, (void *)largest_gap_found
,
1221 (void *)max_occupied_addr
, (void *)new_max_vm
);
1222 CHECK(0 && "cannot place shadow");
1224 RestrictMemoryToMaxAddress(new_max_vm
);
1225 high_mem_end
= new_max_vm
- 1;
1226 space_size
= (high_mem_end
>> shadow_scale
) + left_padding
;
1227 VReport(2, "FindDynamicShadowStart, space_size = %p\n", (void *)space_size
);
1228 shadow_start
= FindAvailableMemoryRange(space_size
, alignment
, granularity
,
1230 if (shadow_start
== 0) {
1231 Report("Unable to find a memory range after restricting VM.\n");
1232 CHECK(0 && "cannot place shadow after restricting vm");
1235 CHECK_NE((uptr
)0, shadow_start
);
1236 CHECK(IsAligned(shadow_start
, alignment
));
1237 return shadow_start
;
1240 uptr
MapDynamicShadowAndAliases(uptr shadow_size
, uptr alias_size
,
1241 uptr num_aliases
, uptr ring_buffer_size
) {
1242 CHECK(false && "HWASan aliasing is unimplemented on Mac");
1246 uptr
FindAvailableMemoryRange(uptr size
, uptr alignment
, uptr left_padding
,
1247 uptr
*largest_gap_found
,
1248 uptr
*max_occupied_addr
) {
1249 typedef vm_region_submap_short_info_data_64_t RegionInfo
;
1250 enum { kRegionInfoSize
= VM_REGION_SUBMAP_SHORT_INFO_COUNT_64
};
1251 // Start searching for available memory region past PAGEZERO, which is
1252 // 4KB on 32-bit and 4GB on 64-bit.
1253 mach_vm_address_t start_address
=
1254 (SANITIZER_WORDSIZE
== 32) ? 0x000000001000 : 0x000100000000;
1256 const mach_vm_address_t max_vm_address
= GetMaxVirtualAddress() + 1;
1257 mach_vm_address_t address
= start_address
;
1258 mach_vm_address_t free_begin
= start_address
;
1259 kern_return_t kr
= KERN_SUCCESS
;
1260 if (largest_gap_found
) *largest_gap_found
= 0;
1261 if (max_occupied_addr
) *max_occupied_addr
= 0;
1262 while (kr
== KERN_SUCCESS
) {
1263 mach_vm_size_t vmsize
= 0;
1264 natural_t depth
= 0;
1266 mach_msg_type_number_t count
= kRegionInfoSize
;
1267 kr
= mach_vm_region_recurse(mach_task_self(), &address
, &vmsize
, &depth
,
1268 (vm_region_info_t
)&vminfo
, &count
);
1269 if (kr
== KERN_INVALID_ADDRESS
) {
1270 // No more regions beyond "address", consider the gap at the end of VM.
1271 address
= max_vm_address
;
1274 if (max_occupied_addr
) *max_occupied_addr
= address
+ vmsize
;
1276 if (free_begin
!= address
) {
1277 // We found a free region [free_begin..address-1].
1278 uptr gap_start
= RoundUpTo((uptr
)free_begin
+ left_padding
, alignment
);
1279 uptr gap_end
= RoundDownTo((uptr
)Min(address
, max_vm_address
), alignment
);
1280 uptr gap_size
= gap_end
> gap_start
? gap_end
- gap_start
: 0;
1281 if (size
< gap_size
) {
1285 if (largest_gap_found
&& *largest_gap_found
< gap_size
) {
1286 *largest_gap_found
= gap_size
;
1289 // Move to the next region.
1291 free_begin
= address
;
1294 // We looked at all free regions and could not find one large enough.
1298 // FIXME implement on this platform.
1299 void GetMemoryProfile(fill_profile_f cb
, uptr
*stats
) {}
1301 void SignalContext::DumpAllRegisters(void *context
) {
1302 Report("Register values:\n");
1304 ucontext_t
*ucontext
= (ucontext_t
*)context
;
1305 # define DUMPREG64(r) \
1306 Printf("%s = 0x%016llx ", #r, ucontext->uc_mcontext->__ss.__ ## r);
1307 # define DUMPREGA64(r) \
1308 Printf(" %s = 0x%016lx ", #r, AARCH64_GET_REG(r));
1309 # define DUMPREG32(r) \
1310 Printf("%s = 0x%08x ", #r, ucontext->uc_mcontext->__ss.__ ## r);
1311 # define DUMPREG_(r) Printf(" "); DUMPREG(r);
1312 # define DUMPREG__(r) Printf(" "); DUMPREG(r);
1313 # define DUMPREG___(r) Printf(" "); DUMPREG(r);
1315 # if defined(__x86_64__)
1316 # define DUMPREG(r) DUMPREG64(r)
1317 DUMPREG(rax
); DUMPREG(rbx
); DUMPREG(rcx
); DUMPREG(rdx
); Printf("\n");
1318 DUMPREG(rdi
); DUMPREG(rsi
); DUMPREG(rbp
); DUMPREG(rsp
); Printf("\n");
1319 DUMPREG_(r8
); DUMPREG_(r9
); DUMPREG(r10
); DUMPREG(r11
); Printf("\n");
1320 DUMPREG(r12
); DUMPREG(r13
); DUMPREG(r14
); DUMPREG(r15
); Printf("\n");
1321 # elif defined(__i386__)
1322 # define DUMPREG(r) DUMPREG32(r)
1323 DUMPREG(eax
); DUMPREG(ebx
); DUMPREG(ecx
); DUMPREG(edx
); Printf("\n");
1324 DUMPREG(edi
); DUMPREG(esi
); DUMPREG(ebp
); DUMPREG(esp
); Printf("\n");
1325 # elif defined(__aarch64__)
1326 # define DUMPREG(r) DUMPREG64(r)
1327 DUMPREG_(x
[0]); DUMPREG_(x
[1]); DUMPREG_(x
[2]); DUMPREG_(x
[3]); Printf("\n");
1328 DUMPREG_(x
[4]); DUMPREG_(x
[5]); DUMPREG_(x
[6]); DUMPREG_(x
[7]); Printf("\n");
1329 DUMPREG_(x
[8]); DUMPREG_(x
[9]); DUMPREG(x
[10]); DUMPREG(x
[11]); Printf("\n");
1330 DUMPREG(x
[12]); DUMPREG(x
[13]); DUMPREG(x
[14]); DUMPREG(x
[15]); Printf("\n");
1331 DUMPREG(x
[16]); DUMPREG(x
[17]); DUMPREG(x
[18]); DUMPREG(x
[19]); Printf("\n");
1332 DUMPREG(x
[20]); DUMPREG(x
[21]); DUMPREG(x
[22]); DUMPREG(x
[23]); Printf("\n");
1333 DUMPREG(x
[24]); DUMPREG(x
[25]); DUMPREG(x
[26]); DUMPREG(x
[27]); Printf("\n");
1334 DUMPREG(x
[28]); DUMPREGA64(fp
); DUMPREGA64(lr
); DUMPREGA64(sp
); Printf("\n");
1335 # elif defined(__arm__)
1336 # define DUMPREG(r) DUMPREG32(r)
1337 DUMPREG_(r
[0]); DUMPREG_(r
[1]); DUMPREG_(r
[2]); DUMPREG_(r
[3]); Printf("\n");
1338 DUMPREG_(r
[4]); DUMPREG_(r
[5]); DUMPREG_(r
[6]); DUMPREG_(r
[7]); Printf("\n");
1339 DUMPREG_(r
[8]); DUMPREG_(r
[9]); DUMPREG(r
[10]); DUMPREG(r
[11]); Printf("\n");
1340 DUMPREG(r
[12]); DUMPREG___(sp
); DUMPREG___(lr
); DUMPREG___(pc
); Printf("\n");
1342 # error "Unknown architecture"
1353 static inline bool CompareBaseAddress(const LoadedModule
&a
,
1354 const LoadedModule
&b
) {
1355 return a
.base_address() < b
.base_address();
1358 void FormatUUID(char *out
, uptr size
, const u8
*uuid
) {
1359 internal_snprintf(out
, size
,
1360 "<%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-"
1361 "%02X%02X%02X%02X%02X%02X>",
1362 uuid
[0], uuid
[1], uuid
[2], uuid
[3], uuid
[4], uuid
[5],
1363 uuid
[6], uuid
[7], uuid
[8], uuid
[9], uuid
[10], uuid
[11],
1364 uuid
[12], uuid
[13], uuid
[14], uuid
[15]);
1367 void DumpProcessMap() {
1368 Printf("Process module map:\n");
1369 MemoryMappingLayout
memory_mapping(false);
1370 InternalMmapVector
<LoadedModule
> modules
;
1371 modules
.reserve(128);
1372 memory_mapping
.DumpListOfModules(&modules
);
1373 Sort(modules
.data(), modules
.size(), CompareBaseAddress
);
1374 for (uptr i
= 0; i
< modules
.size(); ++i
) {
1376 FormatUUID(uuid_str
, sizeof(uuid_str
), modules
[i
].uuid());
1377 Printf("%p-%p %s (%s) %s\n", (void *)modules
[i
].base_address(),
1378 (void *)modules
[i
].max_address(), modules
[i
].full_name(),
1379 ModuleArchToString(modules
[i
].arch()), uuid_str
);
1381 Printf("End of module map.\n");
1384 void CheckNoDeepBind(const char *filename
, int flag
) {
1388 bool GetRandom(void *buffer
, uptr length
, bool blocking
) {
1389 if (!buffer
|| !length
|| length
> 256)
1391 // arc4random never fails.
1392 REAL(arc4random_buf
)(buffer
, length
);
1396 u32
GetNumberOfCPUs() {
1397 return (u32
)sysconf(_SC_NPROCESSORS_ONLN
);
1400 void InitializePlatformCommonFlags(CommonFlags
*cf
) {}
1402 // Pthread introspection hook
1404 // * GCD worker threads are created without a call to pthread_create(), but we
1405 // still need to register these threads (with ThreadCreate/Start()).
1406 // * We use the "pthread introspection hook" below to observe the creation of
1408 // * GCD worker threads don't have parent threads and the CREATE event is
1409 // delivered in the context of the thread itself. CREATE events for regular
1410 // threads, are delivered on the parent. We use this to tell apart which
1411 // threads are GCD workers with `thread == pthread_self()`.
1413 static pthread_introspection_hook_t prev_pthread_introspection_hook
;
1414 static ThreadEventCallbacks thread_event_callbacks
;
1416 static void sanitizer_pthread_introspection_hook(unsigned int event
,
1417 pthread_t thread
, void *addr
,
1419 // create -> start -> terminate -> destroy
1420 // * create/destroy are usually (not guaranteed) delivered on the parent and
1421 // track resource allocation/reclamation
1422 // * start/terminate are guaranteed to be delivered in the context of the
1423 // thread and give hooks into "just after (before) thread starts (stops)
1425 DCHECK(event
>= PTHREAD_INTROSPECTION_THREAD_CREATE
&&
1426 event
<= PTHREAD_INTROSPECTION_THREAD_DESTROY
);
1428 if (event
== PTHREAD_INTROSPECTION_THREAD_CREATE
) {
1429 bool gcd_worker
= (thread
== pthread_self());
1430 if (thread_event_callbacks
.create
)
1431 thread_event_callbacks
.create((uptr
)thread
, gcd_worker
);
1432 } else if (event
== PTHREAD_INTROSPECTION_THREAD_START
) {
1433 CHECK_EQ(thread
, pthread_self());
1434 if (thread_event_callbacks
.start
)
1435 thread_event_callbacks
.start((uptr
)thread
);
1438 if (prev_pthread_introspection_hook
)
1439 prev_pthread_introspection_hook(event
, thread
, addr
, size
);
1441 if (event
== PTHREAD_INTROSPECTION_THREAD_TERMINATE
) {
1442 CHECK_EQ(thread
, pthread_self());
1443 if (thread_event_callbacks
.terminate
)
1444 thread_event_callbacks
.terminate((uptr
)thread
);
1445 } else if (event
== PTHREAD_INTROSPECTION_THREAD_DESTROY
) {
1446 if (thread_event_callbacks
.destroy
)
1447 thread_event_callbacks
.destroy((uptr
)thread
);
1451 void InstallPthreadIntrospectionHook(const ThreadEventCallbacks
&callbacks
) {
1452 thread_event_callbacks
= callbacks
;
1453 prev_pthread_introspection_hook
=
1454 pthread_introspection_hook_install(&sanitizer_pthread_introspection_hook
);
1457 } // namespace __sanitizer
1459 #endif // SANITIZER_APPLE