168d75effSDimitry Andric //===-- sanitizer_mac.cpp -------------------------------------------------===//
268d75effSDimitry Andric //
368d75effSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
468d75effSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
568d75effSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
668d75effSDimitry Andric //
768d75effSDimitry Andric //===----------------------------------------------------------------------===//
868d75effSDimitry Andric //
968d75effSDimitry Andric // This file is shared between various sanitizers' runtime libraries and
1068d75effSDimitry Andric // implements OSX-specific functions.
1168d75effSDimitry Andric //===----------------------------------------------------------------------===//
1268d75effSDimitry Andric
1368d75effSDimitry Andric #include "sanitizer_platform.h"
1481ad6265SDimitry Andric #if SANITIZER_APPLE
1568d75effSDimitry Andric # include "interception/interception.h"
1606c3fb27SDimitry Andric # include "sanitizer_mac.h"
1768d75effSDimitry Andric
1868d75effSDimitry Andric // Use 64-bit inodes in file operations. ASan does not support OS X 10.5, so
1968d75effSDimitry Andric // the clients will most certainly use 64-bit ones as well.
2068d75effSDimitry Andric # ifndef _DARWIN_USE_64_BIT_INODE
2168d75effSDimitry Andric # define _DARWIN_USE_64_BIT_INODE 1
2268d75effSDimitry Andric # endif
2368d75effSDimitry Andric # include <stdio.h>
2468d75effSDimitry Andric
2568d75effSDimitry Andric # include "sanitizer_common.h"
2668d75effSDimitry Andric # include "sanitizer_file.h"
2768d75effSDimitry Andric # include "sanitizer_flags.h"
2881ad6265SDimitry Andric # include "sanitizer_interface_internal.h"
2968d75effSDimitry Andric # include "sanitizer_internal_defs.h"
3068d75effSDimitry Andric # include "sanitizer_libc.h"
3168d75effSDimitry Andric # include "sanitizer_platform_limits_posix.h"
3268d75effSDimitry Andric # include "sanitizer_procmaps.h"
335ffd83dbSDimitry Andric # include "sanitizer_ptrauth.h"
3468d75effSDimitry Andric
3568d75effSDimitry Andric # if !SANITIZER_IOS
3668d75effSDimitry Andric # include <crt_externs.h> // for _NSGetEnviron
3768d75effSDimitry Andric # else
3868d75effSDimitry Andric extern char **environ;
3968d75effSDimitry Andric # endif
4068d75effSDimitry Andric
4168d75effSDimitry Andric # if defined(__has_include) && __has_include(<os/trace.h>)
4268d75effSDimitry Andric # define SANITIZER_OS_TRACE 1
4368d75effSDimitry Andric # include <os/trace.h>
4468d75effSDimitry Andric # else
4568d75effSDimitry Andric # define SANITIZER_OS_TRACE 0
4668d75effSDimitry Andric # endif
4768d75effSDimitry Andric
48fe6060f1SDimitry Andric // import new crash reporting api
49fe6060f1SDimitry Andric # if defined(__has_include) && __has_include(<CrashReporterClient.h>)
50fe6060f1SDimitry Andric # define HAVE_CRASHREPORTERCLIENT_H 1
51fe6060f1SDimitry Andric # include <CrashReporterClient.h>
52fe6060f1SDimitry Andric # else
53fe6060f1SDimitry Andric # define HAVE_CRASHREPORTERCLIENT_H 0
54fe6060f1SDimitry Andric # endif
55fe6060f1SDimitry Andric
5668d75effSDimitry Andric # if !SANITIZER_IOS
5768d75effSDimitry Andric # include <crt_externs.h> // for _NSGetArgv and _NSGetEnviron
5868d75effSDimitry Andric # else
5968d75effSDimitry Andric extern "C" {
6068d75effSDimitry Andric extern char ***_NSGetArgv(void);
6168d75effSDimitry Andric }
6268d75effSDimitry Andric # endif
6368d75effSDimitry Andric
6468d75effSDimitry Andric # include <asl.h>
6568d75effSDimitry Andric # include <dlfcn.h> // for dladdr()
6668d75effSDimitry Andric # include <errno.h>
6768d75effSDimitry Andric # include <fcntl.h>
6868d75effSDimitry Andric # include <libkern/OSAtomic.h>
6968d75effSDimitry Andric # include <mach-o/dyld.h>
7068d75effSDimitry Andric # include <mach/mach.h>
7168d75effSDimitry Andric # include <mach/mach_time.h>
7268d75effSDimitry Andric # include <mach/vm_statistics.h>
7368d75effSDimitry Andric # include <malloc/malloc.h>
74fe6060f1SDimitry Andric # include <os/log.h>
7568d75effSDimitry Andric # include <pthread.h>
76fcaf7f86SDimitry Andric # include <pthread/introspection.h>
7768d75effSDimitry Andric # include <sched.h>
7868d75effSDimitry Andric # include <signal.h>
7968d75effSDimitry Andric # include <spawn.h>
8068d75effSDimitry Andric # include <stdlib.h>
8168d75effSDimitry Andric # include <sys/ioctl.h>
8268d75effSDimitry Andric # include <sys/mman.h>
8368d75effSDimitry Andric # include <sys/resource.h>
8468d75effSDimitry Andric # include <sys/stat.h>
8568d75effSDimitry Andric # include <sys/sysctl.h>
8668d75effSDimitry Andric # include <sys/types.h>
8768d75effSDimitry Andric # include <sys/wait.h>
8868d75effSDimitry Andric # include <unistd.h>
8968d75effSDimitry Andric # include <util.h>
9068d75effSDimitry Andric
9168d75effSDimitry Andric // From <crt_externs.h>, but we don't have that file on iOS.
9268d75effSDimitry Andric extern "C" {
9368d75effSDimitry Andric extern char ***_NSGetArgv(void);
9468d75effSDimitry Andric extern char ***_NSGetEnviron(void);
9568d75effSDimitry Andric }
9668d75effSDimitry Andric
9768d75effSDimitry Andric // From <mach/mach_vm.h>, but we don't have that file on iOS.
9868d75effSDimitry Andric extern "C" {
9968d75effSDimitry Andric extern kern_return_t mach_vm_region_recurse(
10068d75effSDimitry Andric vm_map_t target_task,
10168d75effSDimitry Andric mach_vm_address_t *address,
10268d75effSDimitry Andric mach_vm_size_t *size,
10368d75effSDimitry Andric natural_t *nesting_depth,
10468d75effSDimitry Andric vm_region_recurse_info_t info,
10568d75effSDimitry Andric mach_msg_type_number_t *infoCnt);
10668d75effSDimitry Andric }
10768d75effSDimitry Andric
10868d75effSDimitry Andric namespace __sanitizer {
10968d75effSDimitry Andric
11068d75effSDimitry Andric #include "sanitizer_syscall_generic.inc"
11168d75effSDimitry Andric
11268d75effSDimitry Andric // Direct syscalls, don't call libmalloc hooks (but not available on 10.6).
11368d75effSDimitry Andric extern "C" void *__mmap(void *addr, size_t len, int prot, int flags, int fildes,
11468d75effSDimitry Andric off_t off) SANITIZER_WEAK_ATTRIBUTE;
11568d75effSDimitry Andric extern "C" int __munmap(void *, size_t) SANITIZER_WEAK_ATTRIBUTE;
11668d75effSDimitry Andric
11768d75effSDimitry Andric // ---------------------- sanitizer_libc.h
11868d75effSDimitry Andric
11968d75effSDimitry Andric // From <mach/vm_statistics.h>, but not on older OSs.
12068d75effSDimitry Andric #ifndef VM_MEMORY_SANITIZER
12168d75effSDimitry Andric #define VM_MEMORY_SANITIZER 99
12268d75effSDimitry Andric #endif
12368d75effSDimitry Andric
12468d75effSDimitry Andric // XNU on Darwin provides a mmap flag that optimizes allocation/deallocation of
12568d75effSDimitry Andric // giant memory regions (i.e. shadow memory regions).
12668d75effSDimitry Andric #define kXnuFastMmapFd 0x4
12768d75effSDimitry Andric static size_t kXnuFastMmapThreshold = 2 << 30; // 2 GB
12868d75effSDimitry Andric static bool use_xnu_fast_mmap = false;
12968d75effSDimitry Andric
internal_mmap(void * addr,size_t length,int prot,int flags,int fd,u64 offset)13068d75effSDimitry Andric uptr internal_mmap(void *addr, size_t length, int prot, int flags,
13168d75effSDimitry Andric int fd, u64 offset) {
13268d75effSDimitry Andric if (fd == -1) {
13368d75effSDimitry Andric fd = VM_MAKE_TAG(VM_MEMORY_SANITIZER);
13468d75effSDimitry Andric if (length >= kXnuFastMmapThreshold) {
13568d75effSDimitry Andric if (use_xnu_fast_mmap) fd |= kXnuFastMmapFd;
13668d75effSDimitry Andric }
13768d75effSDimitry Andric }
13868d75effSDimitry Andric if (&__mmap) return (uptr)__mmap(addr, length, prot, flags, fd, offset);
13968d75effSDimitry Andric return (uptr)mmap(addr, length, prot, flags, fd, offset);
14068d75effSDimitry Andric }
14168d75effSDimitry Andric
internal_munmap(void * addr,uptr length)14268d75effSDimitry Andric uptr internal_munmap(void *addr, uptr length) {
14368d75effSDimitry Andric if (&__munmap) return __munmap(addr, length);
14468d75effSDimitry Andric return munmap(addr, length);
14568d75effSDimitry Andric }
14668d75effSDimitry Andric
internal_mremap(void * old_address,uptr old_size,uptr new_size,int flags,void * new_address)147fe6060f1SDimitry Andric uptr internal_mremap(void *old_address, uptr old_size, uptr new_size, int flags,
148fe6060f1SDimitry Andric void *new_address) {
149fe6060f1SDimitry Andric CHECK(false && "internal_mremap is unimplemented on Mac");
150fe6060f1SDimitry Andric return 0;
151fe6060f1SDimitry Andric }
152fe6060f1SDimitry Andric
internal_mprotect(void * addr,uptr length,int prot)15368d75effSDimitry Andric int internal_mprotect(void *addr, uptr length, int prot) {
15468d75effSDimitry Andric return mprotect(addr, length, prot);
15568d75effSDimitry Andric }
15668d75effSDimitry Andric
internal_madvise(uptr addr,uptr length,int advice)157e8d8bef9SDimitry Andric int internal_madvise(uptr addr, uptr length, int advice) {
158e8d8bef9SDimitry Andric return madvise((void *)addr, length, advice);
159e8d8bef9SDimitry Andric }
160e8d8bef9SDimitry Andric
internal_close(fd_t fd)16168d75effSDimitry Andric uptr internal_close(fd_t fd) {
16268d75effSDimitry Andric return close(fd);
16368d75effSDimitry Andric }
16468d75effSDimitry Andric
internal_open(const char * filename,int flags)16568d75effSDimitry Andric uptr internal_open(const char *filename, int flags) {
16668d75effSDimitry Andric return open(filename, flags);
16768d75effSDimitry Andric }
16868d75effSDimitry Andric
internal_open(const char * filename,int flags,u32 mode)16968d75effSDimitry Andric uptr internal_open(const char *filename, int flags, u32 mode) {
17068d75effSDimitry Andric return open(filename, flags, mode);
17168d75effSDimitry Andric }
17268d75effSDimitry Andric
internal_read(fd_t fd,void * buf,uptr count)17368d75effSDimitry Andric uptr internal_read(fd_t fd, void *buf, uptr count) {
17468d75effSDimitry Andric return read(fd, buf, count);
17568d75effSDimitry Andric }
17668d75effSDimitry Andric
internal_write(fd_t fd,const void * buf,uptr count)17768d75effSDimitry Andric uptr internal_write(fd_t fd, const void *buf, uptr count) {
17868d75effSDimitry Andric return write(fd, buf, count);
17968d75effSDimitry Andric }
18068d75effSDimitry Andric
internal_stat(const char * path,void * buf)18168d75effSDimitry Andric uptr internal_stat(const char *path, void *buf) {
18268d75effSDimitry Andric return stat(path, (struct stat *)buf);
18368d75effSDimitry Andric }
18468d75effSDimitry Andric
internal_lstat(const char * path,void * buf)18568d75effSDimitry Andric uptr internal_lstat(const char *path, void *buf) {
18668d75effSDimitry Andric return lstat(path, (struct stat *)buf);
18768d75effSDimitry Andric }
18868d75effSDimitry Andric
internal_fstat(fd_t fd,void * buf)18968d75effSDimitry Andric uptr internal_fstat(fd_t fd, void *buf) {
19068d75effSDimitry Andric return fstat(fd, (struct stat *)buf);
19168d75effSDimitry Andric }
19268d75effSDimitry Andric
internal_filesize(fd_t fd)19368d75effSDimitry Andric uptr internal_filesize(fd_t fd) {
19468d75effSDimitry Andric struct stat st;
19568d75effSDimitry Andric if (internal_fstat(fd, &st))
19668d75effSDimitry Andric return -1;
19768d75effSDimitry Andric return (uptr)st.st_size;
19868d75effSDimitry Andric }
19968d75effSDimitry Andric
internal_dup(int oldfd)20068d75effSDimitry Andric uptr internal_dup(int oldfd) {
20168d75effSDimitry Andric return dup(oldfd);
20268d75effSDimitry Andric }
20368d75effSDimitry Andric
internal_dup2(int oldfd,int newfd)20468d75effSDimitry Andric uptr internal_dup2(int oldfd, int newfd) {
20568d75effSDimitry Andric return dup2(oldfd, newfd);
20668d75effSDimitry Andric }
20768d75effSDimitry Andric
internal_readlink(const char * path,char * buf,uptr bufsize)20868d75effSDimitry Andric uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
20968d75effSDimitry Andric return readlink(path, buf, bufsize);
21068d75effSDimitry Andric }
21168d75effSDimitry Andric
internal_unlink(const char * path)21268d75effSDimitry Andric uptr internal_unlink(const char *path) {
21368d75effSDimitry Andric return unlink(path);
21468d75effSDimitry Andric }
21568d75effSDimitry Andric
internal_sched_yield()21668d75effSDimitry Andric uptr internal_sched_yield() {
21768d75effSDimitry Andric return sched_yield();
21868d75effSDimitry Andric }
21968d75effSDimitry Andric
internal__exit(int exitcode)22068d75effSDimitry Andric void internal__exit(int exitcode) {
22168d75effSDimitry Andric _exit(exitcode);
22268d75effSDimitry Andric }
22368d75effSDimitry Andric
internal_usleep(u64 useconds)224fe6060f1SDimitry Andric void internal_usleep(u64 useconds) { usleep(useconds); }
22568d75effSDimitry Andric
internal_getpid()22668d75effSDimitry Andric uptr internal_getpid() {
22768d75effSDimitry Andric return getpid();
22868d75effSDimitry Andric }
22968d75effSDimitry Andric
internal_dlinfo(void * handle,int request,void * p)2305ffd83dbSDimitry Andric int internal_dlinfo(void *handle, int request, void *p) {
2315ffd83dbSDimitry Andric UNIMPLEMENTED();
2325ffd83dbSDimitry Andric }
2335ffd83dbSDimitry Andric
internal_sigaction(int signum,const void * act,void * oldact)23468d75effSDimitry Andric int internal_sigaction(int signum, const void *act, void *oldact) {
23568d75effSDimitry Andric return sigaction(signum,
23668d75effSDimitry Andric (const struct sigaction *)act, (struct sigaction *)oldact);
23768d75effSDimitry Andric }
23868d75effSDimitry Andric
internal_sigfillset(__sanitizer_sigset_t * set)23968d75effSDimitry Andric void internal_sigfillset(__sanitizer_sigset_t *set) { sigfillset(set); }
24068d75effSDimitry Andric
internal_sigprocmask(int how,__sanitizer_sigset_t * set,__sanitizer_sigset_t * oldset)24168d75effSDimitry Andric uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
24268d75effSDimitry Andric __sanitizer_sigset_t *oldset) {
24368d75effSDimitry Andric // Don't use sigprocmask here, because it affects all threads.
24468d75effSDimitry Andric return pthread_sigmask(how, set, oldset);
24568d75effSDimitry Andric }
24668d75effSDimitry Andric
24768d75effSDimitry Andric // Doesn't call pthread_atfork() handlers (but not available on 10.6).
24868d75effSDimitry Andric extern "C" pid_t __fork(void) SANITIZER_WEAK_ATTRIBUTE;
24968d75effSDimitry Andric
internal_fork()25068d75effSDimitry Andric int internal_fork() {
25168d75effSDimitry Andric if (&__fork)
25268d75effSDimitry Andric return __fork();
25368d75effSDimitry Andric return fork();
25468d75effSDimitry Andric }
25568d75effSDimitry Andric
internal_sysctl(const int * name,unsigned int namelen,void * oldp,uptr * oldlenp,const void * newp,uptr newlen)25668d75effSDimitry Andric int internal_sysctl(const int *name, unsigned int namelen, void *oldp,
25768d75effSDimitry Andric uptr *oldlenp, const void *newp, uptr newlen) {
25868d75effSDimitry Andric return sysctl(const_cast<int *>(name), namelen, oldp, (size_t *)oldlenp,
25968d75effSDimitry Andric const_cast<void *>(newp), (size_t)newlen);
26068d75effSDimitry Andric }
26168d75effSDimitry Andric
internal_sysctlbyname(const char * sname,void * oldp,uptr * oldlenp,const void * newp,uptr newlen)26268d75effSDimitry Andric int internal_sysctlbyname(const char *sname, void *oldp, uptr *oldlenp,
26368d75effSDimitry Andric const void *newp, uptr newlen) {
26468d75effSDimitry Andric return sysctlbyname(sname, oldp, (size_t *)oldlenp, const_cast<void *>(newp),
26568d75effSDimitry Andric (size_t)newlen);
26668d75effSDimitry Andric }
26768d75effSDimitry Andric
internal_spawn_impl(const char * argv[],const char * envp[],pid_t * pid)2685ffd83dbSDimitry Andric static fd_t internal_spawn_impl(const char *argv[], const char *envp[],
2695ffd83dbSDimitry Andric pid_t *pid) {
2704824e7fdSDimitry Andric fd_t primary_fd = kInvalidFd;
2714824e7fdSDimitry Andric fd_t secondary_fd = kInvalidFd;
27268d75effSDimitry Andric
27368d75effSDimitry Andric auto fd_closer = at_scope_exit([&] {
2744824e7fdSDimitry Andric internal_close(primary_fd);
2754824e7fdSDimitry Andric internal_close(secondary_fd);
27668d75effSDimitry Andric });
27768d75effSDimitry Andric
27868d75effSDimitry Andric // We need a new pseudoterminal to avoid buffering problems. The 'atos' tool
27968d75effSDimitry Andric // in particular detects when it's talking to a pipe and forgets to flush the
28068d75effSDimitry Andric // output stream after sending a response.
2814824e7fdSDimitry Andric primary_fd = posix_openpt(O_RDWR);
2824824e7fdSDimitry Andric if (primary_fd == kInvalidFd)
2834824e7fdSDimitry Andric return kInvalidFd;
28468d75effSDimitry Andric
2854824e7fdSDimitry Andric int res = grantpt(primary_fd) || unlockpt(primary_fd);
28668d75effSDimitry Andric if (res != 0) return kInvalidFd;
28768d75effSDimitry Andric
28868d75effSDimitry Andric // Use TIOCPTYGNAME instead of ptsname() to avoid threading problems.
2894824e7fdSDimitry Andric char secondary_pty_name[128];
2904824e7fdSDimitry Andric res = ioctl(primary_fd, TIOCPTYGNAME, secondary_pty_name);
29168d75effSDimitry Andric if (res == -1) return kInvalidFd;
29268d75effSDimitry Andric
2934824e7fdSDimitry Andric secondary_fd = internal_open(secondary_pty_name, O_RDWR);
2944824e7fdSDimitry Andric if (secondary_fd == kInvalidFd)
2954824e7fdSDimitry Andric return kInvalidFd;
29668d75effSDimitry Andric
29768d75effSDimitry Andric // File descriptor actions
29868d75effSDimitry Andric posix_spawn_file_actions_t acts;
29968d75effSDimitry Andric res = posix_spawn_file_actions_init(&acts);
30068d75effSDimitry Andric if (res != 0) return kInvalidFd;
30168d75effSDimitry Andric
30268d75effSDimitry Andric auto acts_cleanup = at_scope_exit([&] {
30368d75effSDimitry Andric posix_spawn_file_actions_destroy(&acts);
30468d75effSDimitry Andric });
30568d75effSDimitry Andric
3064824e7fdSDimitry Andric res = posix_spawn_file_actions_adddup2(&acts, secondary_fd, STDIN_FILENO) ||
3074824e7fdSDimitry Andric posix_spawn_file_actions_adddup2(&acts, secondary_fd, STDOUT_FILENO) ||
3084824e7fdSDimitry Andric posix_spawn_file_actions_addclose(&acts, secondary_fd);
30968d75effSDimitry Andric if (res != 0) return kInvalidFd;
31068d75effSDimitry Andric
31168d75effSDimitry Andric // Spawn attributes
31268d75effSDimitry Andric posix_spawnattr_t attrs;
31368d75effSDimitry Andric res = posix_spawnattr_init(&attrs);
31468d75effSDimitry Andric if (res != 0) return kInvalidFd;
31568d75effSDimitry Andric
31668d75effSDimitry Andric auto attrs_cleanup = at_scope_exit([&] {
31768d75effSDimitry Andric posix_spawnattr_destroy(&attrs);
31868d75effSDimitry Andric });
31968d75effSDimitry Andric
32068d75effSDimitry Andric // In the spawned process, close all file descriptors that are not explicitly
32168d75effSDimitry Andric // described by the file actions object. This is Darwin-specific extension.
32268d75effSDimitry Andric res = posix_spawnattr_setflags(&attrs, POSIX_SPAWN_CLOEXEC_DEFAULT);
32368d75effSDimitry Andric if (res != 0) return kInvalidFd;
32468d75effSDimitry Andric
32568d75effSDimitry Andric // posix_spawn
32668d75effSDimitry Andric char **argv_casted = const_cast<char **>(argv);
3275ffd83dbSDimitry Andric char **envp_casted = const_cast<char **>(envp);
3285ffd83dbSDimitry Andric res = posix_spawn(pid, argv[0], &acts, &attrs, argv_casted, envp_casted);
32968d75effSDimitry Andric if (res != 0) return kInvalidFd;
33068d75effSDimitry Andric
33168d75effSDimitry Andric // Disable echo in the new terminal, disable CR.
33268d75effSDimitry Andric struct termios termflags;
3334824e7fdSDimitry Andric tcgetattr(primary_fd, &termflags);
33468d75effSDimitry Andric termflags.c_oflag &= ~ONLCR;
33568d75effSDimitry Andric termflags.c_lflag &= ~ECHO;
3364824e7fdSDimitry Andric tcsetattr(primary_fd, TCSANOW, &termflags);
33768d75effSDimitry Andric
3384824e7fdSDimitry Andric // On success, do not close primary_fd on scope exit.
3394824e7fdSDimitry Andric fd_t fd = primary_fd;
3404824e7fdSDimitry Andric primary_fd = kInvalidFd;
34168d75effSDimitry Andric
34268d75effSDimitry Andric return fd;
34368d75effSDimitry Andric }
34468d75effSDimitry Andric
internal_spawn(const char * argv[],const char * envp[],pid_t * pid)3455ffd83dbSDimitry Andric fd_t internal_spawn(const char *argv[], const char *envp[], pid_t *pid) {
34668d75effSDimitry Andric // The client program may close its stdin and/or stdout and/or stderr thus
34768d75effSDimitry Andric // allowing open/posix_openpt to reuse file descriptors 0, 1 or 2. In this
34868d75effSDimitry Andric // case the communication is broken if either the parent or the child tries to
34968d75effSDimitry Andric // close or duplicate these descriptors. We temporarily reserve these
35068d75effSDimitry Andric // descriptors here to prevent this.
35168d75effSDimitry Andric fd_t low_fds[3];
35268d75effSDimitry Andric size_t count = 0;
35368d75effSDimitry Andric
35468d75effSDimitry Andric for (; count < 3; count++) {
35568d75effSDimitry Andric low_fds[count] = posix_openpt(O_RDWR);
35668d75effSDimitry Andric if (low_fds[count] >= STDERR_FILENO)
35768d75effSDimitry Andric break;
35868d75effSDimitry Andric }
35968d75effSDimitry Andric
3605ffd83dbSDimitry Andric fd_t fd = internal_spawn_impl(argv, envp, pid);
36168d75effSDimitry Andric
36268d75effSDimitry Andric for (; count > 0; count--) {
36368d75effSDimitry Andric internal_close(low_fds[count]);
36468d75effSDimitry Andric }
36568d75effSDimitry Andric
36668d75effSDimitry Andric return fd;
36768d75effSDimitry Andric }
36868d75effSDimitry Andric
internal_rename(const char * oldpath,const char * newpath)36968d75effSDimitry Andric uptr internal_rename(const char *oldpath, const char *newpath) {
37068d75effSDimitry Andric return rename(oldpath, newpath);
37168d75effSDimitry Andric }
37268d75effSDimitry Andric
internal_ftruncate(fd_t fd,uptr size)37368d75effSDimitry Andric uptr internal_ftruncate(fd_t fd, uptr size) {
37468d75effSDimitry Andric return ftruncate(fd, size);
37568d75effSDimitry Andric }
37668d75effSDimitry Andric
internal_execve(const char * filename,char * const argv[],char * const envp[])37768d75effSDimitry Andric uptr internal_execve(const char *filename, char *const argv[],
37868d75effSDimitry Andric char *const envp[]) {
37968d75effSDimitry Andric return execve(filename, argv, envp);
38068d75effSDimitry Andric }
38168d75effSDimitry Andric
internal_waitpid(int pid,int * status,int options)38268d75effSDimitry Andric uptr internal_waitpid(int pid, int *status, int options) {
38368d75effSDimitry Andric return waitpid(pid, status, options);
38468d75effSDimitry Andric }
38568d75effSDimitry Andric
38668d75effSDimitry Andric // ----------------- sanitizer_common.h
FileExists(const char * filename)38768d75effSDimitry Andric bool FileExists(const char *filename) {
38868d75effSDimitry Andric if (ShouldMockFailureToOpen(filename))
38968d75effSDimitry Andric return false;
39068d75effSDimitry Andric struct stat st;
39168d75effSDimitry Andric if (stat(filename, &st))
39268d75effSDimitry Andric return false;
39368d75effSDimitry Andric // Sanity check: filename is a regular file.
39468d75effSDimitry Andric return S_ISREG(st.st_mode);
39568d75effSDimitry Andric }
39668d75effSDimitry Andric
DirExists(const char * path)39781ad6265SDimitry Andric bool DirExists(const char *path) {
39881ad6265SDimitry Andric struct stat st;
39981ad6265SDimitry Andric if (stat(path, &st))
40081ad6265SDimitry Andric return false;
40181ad6265SDimitry Andric return S_ISDIR(st.st_mode);
40281ad6265SDimitry Andric }
40381ad6265SDimitry Andric
GetTid()40468d75effSDimitry Andric tid_t GetTid() {
40568d75effSDimitry Andric tid_t tid;
40668d75effSDimitry Andric pthread_threadid_np(nullptr, &tid);
40768d75effSDimitry Andric return tid;
40868d75effSDimitry Andric }
40968d75effSDimitry Andric
GetThreadStackTopAndBottom(bool at_initialization,uptr * stack_top,uptr * stack_bottom)41068d75effSDimitry Andric void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
41168d75effSDimitry Andric uptr *stack_bottom) {
41268d75effSDimitry Andric CHECK(stack_top);
41368d75effSDimitry Andric CHECK(stack_bottom);
41468d75effSDimitry Andric uptr stacksize = pthread_get_stacksize_np(pthread_self());
41568d75effSDimitry Andric // pthread_get_stacksize_np() returns an incorrect stack size for the main
41668d75effSDimitry Andric // thread on Mavericks. See
41768d75effSDimitry Andric // https://github.com/google/sanitizers/issues/261
4185ffd83dbSDimitry Andric if ((GetMacosAlignedVersion() >= MacosVersion(10, 9)) && at_initialization &&
41968d75effSDimitry Andric stacksize == (1 << 19)) {
42068d75effSDimitry Andric struct rlimit rl;
42168d75effSDimitry Andric CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
42268d75effSDimitry Andric // Most often rl.rlim_cur will be the desired 8M.
42368d75effSDimitry Andric if (rl.rlim_cur < kMaxThreadStackSize) {
42468d75effSDimitry Andric stacksize = rl.rlim_cur;
42568d75effSDimitry Andric } else {
42668d75effSDimitry Andric stacksize = kMaxThreadStackSize;
42768d75effSDimitry Andric }
42868d75effSDimitry Andric }
42968d75effSDimitry Andric void *stackaddr = pthread_get_stackaddr_np(pthread_self());
43068d75effSDimitry Andric *stack_top = (uptr)stackaddr;
43168d75effSDimitry Andric *stack_bottom = *stack_top - stacksize;
43268d75effSDimitry Andric }
43368d75effSDimitry Andric
GetEnviron()43468d75effSDimitry Andric char **GetEnviron() {
43568d75effSDimitry Andric #if !SANITIZER_IOS
43668d75effSDimitry Andric char ***env_ptr = _NSGetEnviron();
43768d75effSDimitry Andric if (!env_ptr) {
43868d75effSDimitry Andric Report("_NSGetEnviron() returned NULL. Please make sure __asan_init() is "
43968d75effSDimitry Andric "called after libSystem_initializer().\n");
44068d75effSDimitry Andric CHECK(env_ptr);
44168d75effSDimitry Andric }
44268d75effSDimitry Andric char **environ = *env_ptr;
44368d75effSDimitry Andric #endif
44468d75effSDimitry Andric CHECK(environ);
44568d75effSDimitry Andric return environ;
44668d75effSDimitry Andric }
44768d75effSDimitry Andric
GetEnv(const char * name)44868d75effSDimitry Andric const char *GetEnv(const char *name) {
44968d75effSDimitry Andric char **env = GetEnviron();
45068d75effSDimitry Andric uptr name_len = internal_strlen(name);
45168d75effSDimitry Andric while (*env != 0) {
45268d75effSDimitry Andric uptr len = internal_strlen(*env);
45368d75effSDimitry Andric if (len > name_len) {
45468d75effSDimitry Andric const char *p = *env;
45568d75effSDimitry Andric if (!internal_memcmp(p, name, name_len) &&
45668d75effSDimitry Andric p[name_len] == '=') { // Match.
45768d75effSDimitry Andric return *env + name_len + 1; // String starting after =.
45868d75effSDimitry Andric }
45968d75effSDimitry Andric }
46068d75effSDimitry Andric env++;
46168d75effSDimitry Andric }
46268d75effSDimitry Andric return 0;
46368d75effSDimitry Andric }
46468d75effSDimitry Andric
ReadBinaryName(char * buf,uptr buf_len)46568d75effSDimitry Andric uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
46668d75effSDimitry Andric CHECK_LE(kMaxPathLength, buf_len);
46768d75effSDimitry Andric
46868d75effSDimitry Andric // On OS X the executable path is saved to the stack by dyld. Reading it
46968d75effSDimitry Andric // from there is much faster than calling dladdr, especially for large
47068d75effSDimitry Andric // binaries with symbols.
471fe6060f1SDimitry Andric InternalMmapVector<char> exe_path(kMaxPathLength);
47268d75effSDimitry Andric uint32_t size = exe_path.size();
47368d75effSDimitry Andric if (_NSGetExecutablePath(exe_path.data(), &size) == 0 &&
47468d75effSDimitry Andric realpath(exe_path.data(), buf) != 0) {
47568d75effSDimitry Andric return internal_strlen(buf);
47668d75effSDimitry Andric }
47768d75effSDimitry Andric return 0;
47868d75effSDimitry Andric }
47968d75effSDimitry Andric
ReadLongProcessName(char * buf,uptr buf_len)48068d75effSDimitry Andric uptr ReadLongProcessName(/*out*/char *buf, uptr buf_len) {
48168d75effSDimitry Andric return ReadBinaryName(buf, buf_len);
48268d75effSDimitry Andric }
48368d75effSDimitry Andric
ReExec()48468d75effSDimitry Andric void ReExec() {
48568d75effSDimitry Andric UNIMPLEMENTED();
48668d75effSDimitry Andric }
48768d75effSDimitry Andric
CheckASLR()48868d75effSDimitry Andric void CheckASLR() {
48968d75effSDimitry Andric // Do nothing
49068d75effSDimitry Andric }
49168d75effSDimitry Andric
CheckMPROTECT()49268d75effSDimitry Andric void CheckMPROTECT() {
49368d75effSDimitry Andric // Do nothing
49468d75effSDimitry Andric }
49568d75effSDimitry Andric
GetPageSize()49668d75effSDimitry Andric uptr GetPageSize() {
49768d75effSDimitry Andric return sysconf(_SC_PAGESIZE);
49868d75effSDimitry Andric }
49968d75effSDimitry Andric
50068d75effSDimitry Andric extern "C" unsigned malloc_num_zones;
50168d75effSDimitry Andric extern "C" malloc_zone_t **malloc_zones;
50268d75effSDimitry Andric malloc_zone_t sanitizer_zone;
50368d75effSDimitry Andric
50468d75effSDimitry Andric // We need to make sure that sanitizer_zone is registered as malloc_zones[0]. If
50568d75effSDimitry Andric // libmalloc tries to set up a different zone as malloc_zones[0], it will call
50668d75effSDimitry Andric // mprotect(malloc_zones, ..., PROT_READ). This interceptor will catch that and
50768d75effSDimitry Andric // make sure we are still the first (default) zone.
MprotectMallocZones(void * addr,int prot)50868d75effSDimitry Andric void MprotectMallocZones(void *addr, int prot) {
50968d75effSDimitry Andric if (addr == malloc_zones && prot == PROT_READ) {
51068d75effSDimitry Andric if (malloc_num_zones > 1 && malloc_zones[0] != &sanitizer_zone) {
51168d75effSDimitry Andric for (unsigned i = 1; i < malloc_num_zones; i++) {
51268d75effSDimitry Andric if (malloc_zones[i] == &sanitizer_zone) {
51368d75effSDimitry Andric // Swap malloc_zones[0] and malloc_zones[i].
51468d75effSDimitry Andric malloc_zones[i] = malloc_zones[0];
51568d75effSDimitry Andric malloc_zones[0] = &sanitizer_zone;
51668d75effSDimitry Andric break;
51768d75effSDimitry Andric }
51868d75effSDimitry Andric }
51968d75effSDimitry Andric }
52068d75effSDimitry Andric }
52168d75effSDimitry Andric }
52268d75effSDimitry Andric
FutexWait(atomic_uint32_t * p,u32 cmp)523fe6060f1SDimitry Andric void FutexWait(atomic_uint32_t *p, u32 cmp) {
524fe6060f1SDimitry Andric // FIXME: implement actual blocking.
525fe6060f1SDimitry Andric sched_yield();
526fe6060f1SDimitry Andric }
527fe6060f1SDimitry Andric
FutexWake(atomic_uint32_t * p,u32 count)528fe6060f1SDimitry Andric void FutexWake(atomic_uint32_t *p, u32 count) {}
529fe6060f1SDimitry Andric
NanoTime()53068d75effSDimitry Andric u64 NanoTime() {
53168d75effSDimitry Andric timeval tv;
53268d75effSDimitry Andric internal_memset(&tv, 0, sizeof(tv));
53368d75effSDimitry Andric gettimeofday(&tv, 0);
53468d75effSDimitry Andric return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
53568d75effSDimitry Andric }
53668d75effSDimitry Andric
53768d75effSDimitry Andric // This needs to be called during initialization to avoid being racy.
MonotonicNanoTime()53868d75effSDimitry Andric u64 MonotonicNanoTime() {
53968d75effSDimitry Andric static mach_timebase_info_data_t timebase_info;
54068d75effSDimitry Andric if (timebase_info.denom == 0) mach_timebase_info(&timebase_info);
54168d75effSDimitry Andric return (mach_absolute_time() * timebase_info.numer) / timebase_info.denom;
54268d75effSDimitry Andric }
54368d75effSDimitry Andric
GetTlsSize()54468d75effSDimitry Andric uptr GetTlsSize() {
54568d75effSDimitry Andric return 0;
54668d75effSDimitry Andric }
54768d75effSDimitry Andric
InitTlsSize()54868d75effSDimitry Andric void InitTlsSize() {
54968d75effSDimitry Andric }
55068d75effSDimitry Andric
TlsBaseAddr()55168d75effSDimitry Andric uptr TlsBaseAddr() {
55268d75effSDimitry Andric uptr segbase = 0;
55368d75effSDimitry Andric #if defined(__x86_64__)
55468d75effSDimitry Andric asm("movq %%gs:0,%0" : "=r"(segbase));
55568d75effSDimitry Andric #elif defined(__i386__)
55668d75effSDimitry Andric asm("movl %%gs:0,%0" : "=r"(segbase));
557349cc55cSDimitry Andric #elif defined(__aarch64__)
558349cc55cSDimitry Andric asm("mrs %x0, tpidrro_el0" : "=r"(segbase));
559349cc55cSDimitry Andric segbase &= 0x07ul; // clearing lower bits, cpu id stored there
56068d75effSDimitry Andric #endif
56168d75effSDimitry Andric return segbase;
56268d75effSDimitry Andric }
56368d75effSDimitry Andric
56468d75effSDimitry Andric // The size of the tls on darwin does not appear to be well documented,
56568d75effSDimitry Andric // however the vm memory map suggests that it is 1024 uptrs in size,
56668d75effSDimitry Andric // with a size of 0x2000 bytes on x86_64 and 0x1000 bytes on i386.
TlsSize()56768d75effSDimitry Andric uptr TlsSize() {
56868d75effSDimitry Andric #if defined(__x86_64__) || defined(__i386__)
56968d75effSDimitry Andric return 1024 * sizeof(uptr);
57068d75effSDimitry Andric #else
57168d75effSDimitry Andric return 0;
57268d75effSDimitry Andric #endif
57368d75effSDimitry Andric }
57468d75effSDimitry Andric
GetThreadStackAndTls(bool main,uptr * stk_addr,uptr * stk_size,uptr * tls_addr,uptr * tls_size)57568d75effSDimitry Andric void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
57668d75effSDimitry Andric uptr *tls_addr, uptr *tls_size) {
57768d75effSDimitry Andric #if !SANITIZER_GO
57868d75effSDimitry Andric uptr stack_top, stack_bottom;
57968d75effSDimitry Andric GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
58068d75effSDimitry Andric *stk_addr = stack_bottom;
58168d75effSDimitry Andric *stk_size = stack_top - stack_bottom;
58268d75effSDimitry Andric *tls_addr = TlsBaseAddr();
58368d75effSDimitry Andric *tls_size = TlsSize();
58468d75effSDimitry Andric #else
58568d75effSDimitry Andric *stk_addr = 0;
58668d75effSDimitry Andric *stk_size = 0;
58768d75effSDimitry Andric *tls_addr = 0;
58868d75effSDimitry Andric *tls_size = 0;
58968d75effSDimitry Andric #endif
59068d75effSDimitry Andric }
59168d75effSDimitry Andric
init()59268d75effSDimitry Andric void ListOfModules::init() {
59368d75effSDimitry Andric clearOrInit();
59468d75effSDimitry Andric MemoryMappingLayout memory_mapping(false);
59568d75effSDimitry Andric memory_mapping.DumpListOfModules(&modules_);
59668d75effSDimitry Andric }
59768d75effSDimitry Andric
fallbackInit()59868d75effSDimitry Andric void ListOfModules::fallbackInit() { clear(); }
59968d75effSDimitry Andric
GetHandleSignalModeImpl(int signum)60068d75effSDimitry Andric static HandleSignalMode GetHandleSignalModeImpl(int signum) {
60168d75effSDimitry Andric switch (signum) {
60268d75effSDimitry Andric case SIGABRT:
60368d75effSDimitry Andric return common_flags()->handle_abort;
60468d75effSDimitry Andric case SIGILL:
60568d75effSDimitry Andric return common_flags()->handle_sigill;
60668d75effSDimitry Andric case SIGTRAP:
60768d75effSDimitry Andric return common_flags()->handle_sigtrap;
60868d75effSDimitry Andric case SIGFPE:
60968d75effSDimitry Andric return common_flags()->handle_sigfpe;
61068d75effSDimitry Andric case SIGSEGV:
61168d75effSDimitry Andric return common_flags()->handle_segv;
61268d75effSDimitry Andric case SIGBUS:
61368d75effSDimitry Andric return common_flags()->handle_sigbus;
61468d75effSDimitry Andric }
61568d75effSDimitry Andric return kHandleSignalNo;
61668d75effSDimitry Andric }
61768d75effSDimitry Andric
GetHandleSignalMode(int signum)61868d75effSDimitry Andric HandleSignalMode GetHandleSignalMode(int signum) {
61968d75effSDimitry Andric // Handling fatal signals on watchOS and tvOS devices is disallowed.
62068d75effSDimitry Andric if ((SANITIZER_WATCHOS || SANITIZER_TVOS) && !(SANITIZER_IOSSIM))
62168d75effSDimitry Andric return kHandleSignalNo;
62268d75effSDimitry Andric HandleSignalMode result = GetHandleSignalModeImpl(signum);
62368d75effSDimitry Andric if (result == kHandleSignalYes && !common_flags()->allow_user_segv_handler)
62468d75effSDimitry Andric return kHandleSignalExclusive;
62568d75effSDimitry Andric return result;
62668d75effSDimitry Andric }
62768d75effSDimitry Andric
628e8d8bef9SDimitry Andric // Offset example:
629e8d8bef9SDimitry Andric // XNU 17 -- macOS 10.13 -- iOS 11 -- tvOS 11 -- watchOS 4
GetOSMajorKernelOffset()630e8d8bef9SDimitry Andric constexpr u16 GetOSMajorKernelOffset() {
631e8d8bef9SDimitry Andric if (TARGET_OS_OSX) return 4;
632e8d8bef9SDimitry Andric if (TARGET_OS_IOS || TARGET_OS_TV) return 6;
633e8d8bef9SDimitry Andric if (TARGET_OS_WATCH) return 13;
6345ffd83dbSDimitry Andric }
635e8d8bef9SDimitry Andric
636e8d8bef9SDimitry Andric using VersStr = char[64];
637e8d8bef9SDimitry Andric
ApproximateOSVersionViaKernelVersion(VersStr vers)638e8d8bef9SDimitry Andric static uptr ApproximateOSVersionViaKernelVersion(VersStr vers) {
639e8d8bef9SDimitry Andric u16 kernel_major = GetDarwinKernelVersion().major;
640e8d8bef9SDimitry Andric u16 offset = GetOSMajorKernelOffset();
641e8d8bef9SDimitry Andric CHECK_GE(kernel_major, offset);
642e8d8bef9SDimitry Andric u16 os_major = kernel_major - offset;
643e8d8bef9SDimitry Andric
644e8d8bef9SDimitry Andric const char *format = "%d.0";
645e8d8bef9SDimitry Andric if (TARGET_OS_OSX) {
646e8d8bef9SDimitry Andric if (os_major >= 16) { // macOS 11+
647e8d8bef9SDimitry Andric os_major -= 5;
648e8d8bef9SDimitry Andric } else { // macOS 10.15 and below
649e8d8bef9SDimitry Andric format = "10.%d";
650e8d8bef9SDimitry Andric }
651e8d8bef9SDimitry Andric }
652e8d8bef9SDimitry Andric return internal_snprintf(vers, sizeof(VersStr), format, os_major);
653e8d8bef9SDimitry Andric }
654e8d8bef9SDimitry Andric
GetOSVersion(VersStr vers)655e8d8bef9SDimitry Andric static void GetOSVersion(VersStr vers) {
656e8d8bef9SDimitry Andric uptr len = sizeof(VersStr);
657e8d8bef9SDimitry Andric if (SANITIZER_IOSSIM) {
658e8d8bef9SDimitry Andric const char *vers_env = GetEnv("SIMULATOR_RUNTIME_VERSION");
659e8d8bef9SDimitry Andric if (!vers_env) {
660e8d8bef9SDimitry Andric Report("ERROR: Running in simulator but SIMULATOR_RUNTIME_VERSION env "
661e8d8bef9SDimitry Andric "var is not set.\n");
662e8d8bef9SDimitry Andric Die();
663e8d8bef9SDimitry Andric }
664e8d8bef9SDimitry Andric len = internal_strlcpy(vers, vers_env, len);
665e8d8bef9SDimitry Andric } else {
666e8d8bef9SDimitry Andric int res =
667e8d8bef9SDimitry Andric internal_sysctlbyname("kern.osproductversion", vers, &len, nullptr, 0);
668e8d8bef9SDimitry Andric
669e8d8bef9SDimitry Andric // XNU 17 (macOS 10.13) and below do not provide the sysctl
670e8d8bef9SDimitry Andric // `kern.osproductversion` entry (res != 0).
671e8d8bef9SDimitry Andric bool no_os_version = res != 0;
672e8d8bef9SDimitry Andric
673e8d8bef9SDimitry Andric // For launchd, sanitizer initialization runs before sysctl is setup
674e8d8bef9SDimitry Andric // (res == 0 && len != strlen(vers), vers is not a valid version). However,
675e8d8bef9SDimitry Andric // the kernel version `kern.osrelease` is available.
676e8d8bef9SDimitry Andric bool launchd = (res == 0 && internal_strlen(vers) < 3);
677e8d8bef9SDimitry Andric if (launchd) CHECK_EQ(internal_getpid(), 1);
678e8d8bef9SDimitry Andric
679e8d8bef9SDimitry Andric if (no_os_version || launchd) {
680e8d8bef9SDimitry Andric len = ApproximateOSVersionViaKernelVersion(vers);
681e8d8bef9SDimitry Andric }
682e8d8bef9SDimitry Andric }
683e8d8bef9SDimitry Andric CHECK_LT(len, sizeof(VersStr));
684e8d8bef9SDimitry Andric }
685e8d8bef9SDimitry Andric
ParseVersion(const char * vers,u16 * major,u16 * minor)686e8d8bef9SDimitry Andric void ParseVersion(const char *vers, u16 *major, u16 *minor) {
687e8d8bef9SDimitry Andric // Format: <major>.<minor>[.<patch>]\0
688e8d8bef9SDimitry Andric CHECK_GE(internal_strlen(vers), 3);
689e8d8bef9SDimitry Andric const char *p = vers;
690e8d8bef9SDimitry Andric *major = internal_simple_strtoll(p, &p, /*base=*/10);
691e8d8bef9SDimitry Andric CHECK_EQ(*p, '.');
692e8d8bef9SDimitry Andric p += 1;
693e8d8bef9SDimitry Andric *minor = internal_simple_strtoll(p, &p, /*base=*/10);
694e8d8bef9SDimitry Andric }
695e8d8bef9SDimitry Andric
696e8d8bef9SDimitry Andric // Aligned versions example:
697e8d8bef9SDimitry Andric // macOS 10.15 -- iOS 13 -- tvOS 13 -- watchOS 6
MapToMacos(u16 * major,u16 * minor)698e8d8bef9SDimitry Andric static void MapToMacos(u16 *major, u16 *minor) {
699e8d8bef9SDimitry Andric if (TARGET_OS_OSX)
700e8d8bef9SDimitry Andric return;
701e8d8bef9SDimitry Andric
702e8d8bef9SDimitry Andric if (TARGET_OS_IOS || TARGET_OS_TV)
703e8d8bef9SDimitry Andric *major += 2;
704e8d8bef9SDimitry Andric else if (TARGET_OS_WATCH)
705e8d8bef9SDimitry Andric *major += 9;
706e8d8bef9SDimitry Andric else
707e8d8bef9SDimitry Andric UNREACHABLE("unsupported platform");
708e8d8bef9SDimitry Andric
709e8d8bef9SDimitry Andric if (*major >= 16) { // macOS 11+
710e8d8bef9SDimitry Andric *major -= 5;
711e8d8bef9SDimitry Andric } else { // macOS 10.15 and below
712e8d8bef9SDimitry Andric *minor = *major;
713e8d8bef9SDimitry Andric *major = 10;
714e8d8bef9SDimitry Andric }
715e8d8bef9SDimitry Andric }
716e8d8bef9SDimitry Andric
GetMacosAlignedVersionInternal()717e8d8bef9SDimitry Andric static MacosVersion GetMacosAlignedVersionInternal() {
718e8d8bef9SDimitry Andric VersStr vers = {};
719e8d8bef9SDimitry Andric GetOSVersion(vers);
720e8d8bef9SDimitry Andric
721e8d8bef9SDimitry Andric u16 major, minor;
722e8d8bef9SDimitry Andric ParseVersion(vers, &major, &minor);
723e8d8bef9SDimitry Andric MapToMacos(&major, &minor);
724e8d8bef9SDimitry Andric
7255ffd83dbSDimitry Andric return MacosVersion(major, minor);
7265ffd83dbSDimitry Andric }
72768d75effSDimitry Andric
7285ffd83dbSDimitry Andric static_assert(sizeof(MacosVersion) == sizeof(atomic_uint32_t::Type),
7295ffd83dbSDimitry Andric "MacosVersion cache size");
7305ffd83dbSDimitry Andric static atomic_uint32_t cached_macos_version;
73168d75effSDimitry Andric
GetMacosAlignedVersion()7325ffd83dbSDimitry Andric MacosVersion GetMacosAlignedVersion() {
7335ffd83dbSDimitry Andric atomic_uint32_t::Type result =
7345ffd83dbSDimitry Andric atomic_load(&cached_macos_version, memory_order_acquire);
7355ffd83dbSDimitry Andric if (!result) {
7365ffd83dbSDimitry Andric MacosVersion version = GetMacosAlignedVersionInternal();
7375ffd83dbSDimitry Andric result = *reinterpret_cast<atomic_uint32_t::Type *>(&version);
7385ffd83dbSDimitry Andric atomic_store(&cached_macos_version, result, memory_order_release);
7395ffd83dbSDimitry Andric }
7405ffd83dbSDimitry Andric return *reinterpret_cast<MacosVersion *>(&result);
7415ffd83dbSDimitry Andric }
7425ffd83dbSDimitry Andric
GetDarwinKernelVersion()7435ffd83dbSDimitry Andric DarwinKernelVersion GetDarwinKernelVersion() {
744e8d8bef9SDimitry Andric VersStr vers = {};
745e8d8bef9SDimitry Andric uptr len = sizeof(VersStr);
746e8d8bef9SDimitry Andric int res = internal_sysctlbyname("kern.osrelease", vers, &len, nullptr, 0);
7475ffd83dbSDimitry Andric CHECK_EQ(res, 0);
748e8d8bef9SDimitry Andric CHECK_LT(len, sizeof(VersStr));
74968d75effSDimitry Andric
7505ffd83dbSDimitry Andric u16 major, minor;
751e8d8bef9SDimitry Andric ParseVersion(vers, &major, &minor);
7525ffd83dbSDimitry Andric
7535ffd83dbSDimitry Andric return DarwinKernelVersion(major, minor);
75468d75effSDimitry Andric }
75568d75effSDimitry Andric
GetRSS()75668d75effSDimitry Andric uptr GetRSS() {
75768d75effSDimitry Andric struct task_basic_info info;
75868d75effSDimitry Andric unsigned count = TASK_BASIC_INFO_COUNT;
75968d75effSDimitry Andric kern_return_t result =
76068d75effSDimitry Andric task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &count);
76168d75effSDimitry Andric if (UNLIKELY(result != KERN_SUCCESS)) {
76268d75effSDimitry Andric Report("Cannot get task info. Error: %d\n", result);
76368d75effSDimitry Andric Die();
76468d75effSDimitry Andric }
76568d75effSDimitry Andric return info.resident_size;
76668d75effSDimitry Andric }
76768d75effSDimitry Andric
internal_start_thread(void * (* func)(void * arg),void * arg)7685ffd83dbSDimitry Andric void *internal_start_thread(void *(*func)(void *arg), void *arg) {
76968d75effSDimitry Andric // Start the thread with signals blocked, otherwise it can steal user signals.
77068d75effSDimitry Andric __sanitizer_sigset_t set, old;
77168d75effSDimitry Andric internal_sigfillset(&set);
77268d75effSDimitry Andric internal_sigprocmask(SIG_SETMASK, &set, &old);
77368d75effSDimitry Andric pthread_t th;
7745ffd83dbSDimitry Andric pthread_create(&th, 0, func, arg);
77568d75effSDimitry Andric internal_sigprocmask(SIG_SETMASK, &old, 0);
77668d75effSDimitry Andric return th;
77768d75effSDimitry Andric }
77868d75effSDimitry Andric
internal_join_thread(void * th)77968d75effSDimitry Andric void internal_join_thread(void *th) { pthread_join((pthread_t)th, 0); }
78068d75effSDimitry Andric
78168d75effSDimitry Andric #if !SANITIZER_GO
782349cc55cSDimitry Andric static Mutex syslog_lock;
78368d75effSDimitry Andric # endif
78468d75effSDimitry Andric
WriteOneLineToSyslog(const char * s)78568d75effSDimitry Andric void WriteOneLineToSyslog(const char *s) {
78668d75effSDimitry Andric #if !SANITIZER_GO
78768d75effSDimitry Andric syslog_lock.CheckLocked();
788fe6060f1SDimitry Andric if (GetMacosAlignedVersion() >= MacosVersion(10, 12)) {
789fe6060f1SDimitry Andric os_log_error(OS_LOG_DEFAULT, "%{public}s", s);
790fe6060f1SDimitry Andric } else {
79168d75effSDimitry Andric asl_log(nullptr, nullptr, ASL_LEVEL_ERR, "%s", s);
792fe6060f1SDimitry Andric }
793fe6060f1SDimitry Andric #endif
794fe6060f1SDimitry Andric }
795fe6060f1SDimitry Andric
796fe6060f1SDimitry Andric // buffer to store crash report application information
797fe6060f1SDimitry Andric static char crashreporter_info_buff[__sanitizer::kErrorMessageBufferSize] = {};
798349cc55cSDimitry Andric static Mutex crashreporter_info_mutex;
799fe6060f1SDimitry Andric
800fe6060f1SDimitry Andric extern "C" {
801fe6060f1SDimitry Andric // Integrate with crash reporter libraries.
802fe6060f1SDimitry Andric #if HAVE_CRASHREPORTERCLIENT_H
803fe6060f1SDimitry Andric CRASH_REPORTER_CLIENT_HIDDEN
804fe6060f1SDimitry Andric struct crashreporter_annotations_t gCRAnnotations
805fe6060f1SDimitry Andric __attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION))) = {
806fe6060f1SDimitry Andric CRASHREPORTER_ANNOTATIONS_VERSION,
807fe6060f1SDimitry Andric 0,
808fe6060f1SDimitry Andric 0,
809fe6060f1SDimitry Andric 0,
810fe6060f1SDimitry Andric 0,
811fe6060f1SDimitry Andric 0,
812fe6060f1SDimitry Andric 0,
813fe6060f1SDimitry Andric #if CRASHREPORTER_ANNOTATIONS_VERSION > 4
814fe6060f1SDimitry Andric 0,
815fe6060f1SDimitry Andric #endif
816fe6060f1SDimitry Andric };
817fe6060f1SDimitry Andric
818fe6060f1SDimitry Andric #else
819fe6060f1SDimitry Andric // fall back to old crashreporter api
820fe6060f1SDimitry Andric static const char *__crashreporter_info__ __attribute__((__used__)) =
821fe6060f1SDimitry Andric &crashreporter_info_buff[0];
822fe6060f1SDimitry Andric asm(".desc ___crashreporter_info__, 0x10");
823fe6060f1SDimitry Andric #endif
824fe6060f1SDimitry Andric
825fe6060f1SDimitry Andric } // extern "C"
826fe6060f1SDimitry Andric
CRAppendCrashLogMessage(const char * msg)827fe6060f1SDimitry Andric static void CRAppendCrashLogMessage(const char *msg) {
828349cc55cSDimitry Andric Lock l(&crashreporter_info_mutex);
829fe6060f1SDimitry Andric internal_strlcat(crashreporter_info_buff, msg,
830fe6060f1SDimitry Andric sizeof(crashreporter_info_buff));
831fe6060f1SDimitry Andric #if HAVE_CRASHREPORTERCLIENT_H
832fe6060f1SDimitry Andric (void)CRSetCrashLogMessage(crashreporter_info_buff);
83368d75effSDimitry Andric #endif
83468d75effSDimitry Andric }
83568d75effSDimitry Andric
LogMessageOnPrintf(const char * str)83668d75effSDimitry Andric void LogMessageOnPrintf(const char *str) {
83768d75effSDimitry Andric // Log all printf output to CrashLog.
83868d75effSDimitry Andric if (common_flags()->abort_on_error)
83968d75effSDimitry Andric CRAppendCrashLogMessage(str);
84068d75effSDimitry Andric }
84168d75effSDimitry Andric
LogFullErrorReport(const char * buffer)84268d75effSDimitry Andric void LogFullErrorReport(const char *buffer) {
84368d75effSDimitry Andric #if !SANITIZER_GO
84468d75effSDimitry Andric // Log with os_trace. This will make it into the crash log.
84568d75effSDimitry Andric #if SANITIZER_OS_TRACE
8465ffd83dbSDimitry Andric if (GetMacosAlignedVersion() >= MacosVersion(10, 10)) {
84768d75effSDimitry Andric // os_trace requires the message (format parameter) to be a string literal.
84868d75effSDimitry Andric if (internal_strncmp(SanitizerToolName, "AddressSanitizer",
84968d75effSDimitry Andric sizeof("AddressSanitizer") - 1) == 0)
85068d75effSDimitry Andric os_trace("Address Sanitizer reported a failure.");
85168d75effSDimitry Andric else if (internal_strncmp(SanitizerToolName, "UndefinedBehaviorSanitizer",
85268d75effSDimitry Andric sizeof("UndefinedBehaviorSanitizer") - 1) == 0)
85368d75effSDimitry Andric os_trace("Undefined Behavior Sanitizer reported a failure.");
85468d75effSDimitry Andric else if (internal_strncmp(SanitizerToolName, "ThreadSanitizer",
85568d75effSDimitry Andric sizeof("ThreadSanitizer") - 1) == 0)
85668d75effSDimitry Andric os_trace("Thread Sanitizer reported a failure.");
85768d75effSDimitry Andric else
85868d75effSDimitry Andric os_trace("Sanitizer tool reported a failure.");
85968d75effSDimitry Andric
86068d75effSDimitry Andric if (common_flags()->log_to_syslog)
86168d75effSDimitry Andric os_trace("Consult syslog for more information.");
86268d75effSDimitry Andric }
86368d75effSDimitry Andric #endif
86468d75effSDimitry Andric
86568d75effSDimitry Andric // Log to syslog.
86668d75effSDimitry Andric // The logging on OS X may call pthread_create so we need the threading
86768d75effSDimitry Andric // environment to be fully initialized. Also, this should never be called when
86868d75effSDimitry Andric // holding the thread registry lock since that may result in a deadlock. If
86968d75effSDimitry Andric // the reporting thread holds the thread registry mutex, and asl_log waits
87068d75effSDimitry Andric // for GCD to dispatch a new thread, the process will deadlock, because the
87168d75effSDimitry Andric // pthread_create wrapper needs to acquire the lock as well.
872349cc55cSDimitry Andric Lock l(&syslog_lock);
87368d75effSDimitry Andric if (common_flags()->log_to_syslog)
87468d75effSDimitry Andric WriteToSyslog(buffer);
87568d75effSDimitry Andric
87668d75effSDimitry Andric // The report is added to CrashLog as part of logging all of Printf output.
87768d75effSDimitry Andric #endif
87868d75effSDimitry Andric }
87968d75effSDimitry Andric
GetWriteFlag() const88068d75effSDimitry Andric SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
88168d75effSDimitry Andric #if defined(__x86_64__) || defined(__i386__)
88268d75effSDimitry Andric ucontext_t *ucontext = static_cast<ucontext_t*>(context);
883d56accc7SDimitry Andric return ucontext->uc_mcontext->__es.__err & 2 /*T_PF_WRITE*/ ? Write : Read;
88481ad6265SDimitry Andric #elif defined(__arm64__)
88581ad6265SDimitry Andric ucontext_t *ucontext = static_cast<ucontext_t*>(context);
88681ad6265SDimitry Andric return ucontext->uc_mcontext->__es.__esr & 0x40 /*ISS_DA_WNR*/ ? Write : Read;
88768d75effSDimitry Andric #else
888d56accc7SDimitry Andric return Unknown;
88968d75effSDimitry Andric #endif
89068d75effSDimitry Andric }
89168d75effSDimitry Andric
IsTrueFaultingAddress() const89268d75effSDimitry Andric bool SignalContext::IsTrueFaultingAddress() const {
89368d75effSDimitry Andric auto si = static_cast<const siginfo_t *>(siginfo);
89468d75effSDimitry Andric // "Real" SIGSEGV codes (e.g., SEGV_MAPERR, SEGV_MAPERR) are non-zero.
89568d75effSDimitry Andric return si->si_signo == SIGSEGV && si->si_code != 0;
89668d75effSDimitry Andric }
89768d75effSDimitry Andric
8985ffd83dbSDimitry Andric #if defined(__aarch64__) && defined(arm_thread_state64_get_sp)
8995ffd83dbSDimitry Andric #define AARCH64_GET_REG(r) \
9005ffd83dbSDimitry Andric (uptr)ptrauth_strip( \
9015ffd83dbSDimitry Andric (void *)arm_thread_state64_get_##r(ucontext->uc_mcontext->__ss), 0)
9025ffd83dbSDimitry Andric #else
9030eae32dcSDimitry Andric #define AARCH64_GET_REG(r) (uptr)ucontext->uc_mcontext->__ss.__##r
9045ffd83dbSDimitry Andric #endif
9055ffd83dbSDimitry Andric
GetPcSpBp(void * context,uptr * pc,uptr * sp,uptr * bp)90668d75effSDimitry Andric static void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
90768d75effSDimitry Andric ucontext_t *ucontext = (ucontext_t*)context;
90868d75effSDimitry Andric # if defined(__aarch64__)
9095ffd83dbSDimitry Andric *pc = AARCH64_GET_REG(pc);
9105ffd83dbSDimitry Andric *bp = AARCH64_GET_REG(fp);
9115ffd83dbSDimitry Andric *sp = AARCH64_GET_REG(sp);
91268d75effSDimitry Andric # elif defined(__x86_64__)
91368d75effSDimitry Andric *pc = ucontext->uc_mcontext->__ss.__rip;
91468d75effSDimitry Andric *bp = ucontext->uc_mcontext->__ss.__rbp;
91568d75effSDimitry Andric *sp = ucontext->uc_mcontext->__ss.__rsp;
91668d75effSDimitry Andric # elif defined(__arm__)
91768d75effSDimitry Andric *pc = ucontext->uc_mcontext->__ss.__pc;
91868d75effSDimitry Andric *bp = ucontext->uc_mcontext->__ss.__r[7];
91968d75effSDimitry Andric *sp = ucontext->uc_mcontext->__ss.__sp;
92068d75effSDimitry Andric # elif defined(__i386__)
92168d75effSDimitry Andric *pc = ucontext->uc_mcontext->__ss.__eip;
92268d75effSDimitry Andric *bp = ucontext->uc_mcontext->__ss.__ebp;
92368d75effSDimitry Andric *sp = ucontext->uc_mcontext->__ss.__esp;
92468d75effSDimitry Andric # else
92568d75effSDimitry Andric # error "Unknown architecture"
92668d75effSDimitry Andric # endif
92768d75effSDimitry Andric }
92868d75effSDimitry Andric
InitPcSpBp()9295ffd83dbSDimitry Andric void SignalContext::InitPcSpBp() {
9305ffd83dbSDimitry Andric addr = (uptr)ptrauth_strip((void *)addr, 0);
9315ffd83dbSDimitry Andric GetPcSpBp(context, &pc, &sp, &bp);
9325ffd83dbSDimitry Andric }
93368d75effSDimitry Andric
934e8d8bef9SDimitry Andric // ASan/TSan use mmap in a way that creates “deallocation gaps” which triggers
935e8d8bef9SDimitry Andric // EXC_GUARD exceptions on macOS 10.15+ (XNU 19.0+).
DisableMmapExcGuardExceptions()936e8d8bef9SDimitry Andric static void DisableMmapExcGuardExceptions() {
937e8d8bef9SDimitry Andric using task_exc_guard_behavior_t = uint32_t;
938e8d8bef9SDimitry Andric using task_set_exc_guard_behavior_t =
939e8d8bef9SDimitry Andric kern_return_t(task_t task, task_exc_guard_behavior_t behavior);
940e8d8bef9SDimitry Andric auto *set_behavior = (task_set_exc_guard_behavior_t *)dlsym(
941e8d8bef9SDimitry Andric RTLD_DEFAULT, "task_set_exc_guard_behavior");
942e8d8bef9SDimitry Andric if (set_behavior == nullptr) return;
943e8d8bef9SDimitry Andric const task_exc_guard_behavior_t task_exc_guard_none = 0;
944e8d8bef9SDimitry Andric set_behavior(mach_task_self(), task_exc_guard_none);
945e8d8bef9SDimitry Andric }
946e8d8bef9SDimitry Andric
947753f127fSDimitry Andric static void VerifyInterceptorsWorking();
948753f127fSDimitry Andric static void StripEnv();
949753f127fSDimitry Andric
InitializePlatformEarly()95068d75effSDimitry Andric void InitializePlatformEarly() {
9515ffd83dbSDimitry Andric // Only use xnu_fast_mmap when on x86_64 and the kernel supports it.
95268d75effSDimitry Andric use_xnu_fast_mmap =
95368d75effSDimitry Andric #if defined(__x86_64__)
9545ffd83dbSDimitry Andric GetDarwinKernelVersion() >= DarwinKernelVersion(17, 5);
95568d75effSDimitry Andric #else
95668d75effSDimitry Andric false;
95768d75effSDimitry Andric #endif
958e8d8bef9SDimitry Andric if (GetDarwinKernelVersion() >= DarwinKernelVersion(19, 0))
959e8d8bef9SDimitry Andric DisableMmapExcGuardExceptions();
960753f127fSDimitry Andric
961753f127fSDimitry Andric # if !SANITIZER_GO
962753f127fSDimitry Andric MonotonicNanoTime(); // Call to initialize mach_timebase_info
963753f127fSDimitry Andric VerifyInterceptorsWorking();
964753f127fSDimitry Andric StripEnv();
965753f127fSDimitry Andric # endif
96668d75effSDimitry Andric }
96768d75effSDimitry Andric
96868d75effSDimitry Andric #if !SANITIZER_GO
96968d75effSDimitry Andric static const char kDyldInsertLibraries[] = "DYLD_INSERT_LIBRARIES";
97068d75effSDimitry Andric LowLevelAllocator allocator_for_env;
97168d75effSDimitry Andric
ShouldCheckInterceptors()972753f127fSDimitry Andric static bool ShouldCheckInterceptors() {
973753f127fSDimitry Andric // Restrict "interceptors working?" check to ASan and TSan.
974753f127fSDimitry Andric const char *sanitizer_names[] = {"AddressSanitizer", "ThreadSanitizer"};
975753f127fSDimitry Andric size_t count = sizeof(sanitizer_names) / sizeof(sanitizer_names[0]);
976753f127fSDimitry Andric for (size_t i = 0; i < count; i++) {
977753f127fSDimitry Andric if (internal_strcmp(sanitizer_names[i], SanitizerToolName) == 0)
978753f127fSDimitry Andric return true;
979753f127fSDimitry Andric }
980753f127fSDimitry Andric return false;
981753f127fSDimitry Andric }
982753f127fSDimitry Andric
VerifyInterceptorsWorking()983753f127fSDimitry Andric static void VerifyInterceptorsWorking() {
984753f127fSDimitry Andric if (!common_flags()->verify_interceptors || !ShouldCheckInterceptors())
985753f127fSDimitry Andric return;
986753f127fSDimitry Andric
987753f127fSDimitry Andric // Verify that interceptors really work. We'll use dlsym to locate
988753f127fSDimitry Andric // "puts", if interceptors are working, it should really point to
989753f127fSDimitry Andric // "wrap_puts" within our own dylib.
990753f127fSDimitry Andric Dl_info info_puts, info_runtime;
991753f127fSDimitry Andric RAW_CHECK(dladdr(dlsym(RTLD_DEFAULT, "puts"), &info_puts));
99206c3fb27SDimitry Andric RAW_CHECK(dladdr((void *)&VerifyInterceptorsWorking, &info_runtime));
993753f127fSDimitry Andric if (internal_strcmp(info_puts.dli_fname, info_runtime.dli_fname) != 0) {
994753f127fSDimitry Andric Report(
995753f127fSDimitry Andric "ERROR: Interceptors are not working. This may be because %s is "
996753f127fSDimitry Andric "loaded too late (e.g. via dlopen). Please launch the executable "
997753f127fSDimitry Andric "with:\n%s=%s\n",
998753f127fSDimitry Andric SanitizerToolName, kDyldInsertLibraries, info_runtime.dli_fname);
999753f127fSDimitry Andric RAW_CHECK("interceptors not installed" && 0);
1000753f127fSDimitry Andric }
1001753f127fSDimitry Andric }
1002753f127fSDimitry Andric
100368d75effSDimitry Andric // Change the value of the env var |name|, leaking the original value.
100468d75effSDimitry Andric // If |name_value| is NULL, the variable is deleted from the environment,
100568d75effSDimitry Andric // otherwise the corresponding "NAME=value" string is replaced with
100668d75effSDimitry Andric // |name_value|.
LeakyResetEnv(const char * name,const char * name_value)1007753f127fSDimitry Andric static void LeakyResetEnv(const char *name, const char *name_value) {
100868d75effSDimitry Andric char **env = GetEnviron();
100968d75effSDimitry Andric uptr name_len = internal_strlen(name);
101068d75effSDimitry Andric while (*env != 0) {
101168d75effSDimitry Andric uptr len = internal_strlen(*env);
101268d75effSDimitry Andric if (len > name_len) {
101368d75effSDimitry Andric const char *p = *env;
101468d75effSDimitry Andric if (!internal_memcmp(p, name, name_len) && p[name_len] == '=') {
101568d75effSDimitry Andric // Match.
101668d75effSDimitry Andric if (name_value) {
101768d75effSDimitry Andric // Replace the old value with the new one.
101868d75effSDimitry Andric *env = const_cast<char*>(name_value);
101968d75effSDimitry Andric } else {
102068d75effSDimitry Andric // Shift the subsequent pointers back.
102168d75effSDimitry Andric char **del = env;
102268d75effSDimitry Andric do {
102368d75effSDimitry Andric del[0] = del[1];
102468d75effSDimitry Andric } while (*del++);
102568d75effSDimitry Andric }
102668d75effSDimitry Andric }
102768d75effSDimitry Andric }
102868d75effSDimitry Andric env++;
102968d75effSDimitry Andric }
103068d75effSDimitry Andric }
103168d75effSDimitry Andric
StripEnv()1032753f127fSDimitry Andric static void StripEnv() {
1033753f127fSDimitry Andric if (!common_flags()->strip_env)
103468d75effSDimitry Andric return;
103568d75effSDimitry Andric
1036753f127fSDimitry Andric char *dyld_insert_libraries =
1037753f127fSDimitry Andric const_cast<char *>(GetEnv(kDyldInsertLibraries));
1038753f127fSDimitry Andric if (!dyld_insert_libraries)
1039753f127fSDimitry Andric return;
1040753f127fSDimitry Andric
1041753f127fSDimitry Andric Dl_info info;
104206c3fb27SDimitry Andric RAW_CHECK(dladdr((void *)&StripEnv, &info));
1043753f127fSDimitry Andric const char *dylib_name = StripModuleName(info.dli_fname);
1044753f127fSDimitry Andric bool lib_is_in_env = internal_strstr(dyld_insert_libraries, dylib_name);
1045753f127fSDimitry Andric if (!lib_is_in_env)
104668d75effSDimitry Andric return;
104768d75effSDimitry Andric
104868d75effSDimitry Andric // DYLD_INSERT_LIBRARIES is set and contains the runtime library. Let's remove
104968d75effSDimitry Andric // the dylib from the environment variable, because interceptors are installed
105068d75effSDimitry Andric // and we don't want our children to inherit the variable.
105168d75effSDimitry Andric
1052753f127fSDimitry Andric uptr old_env_len = internal_strlen(dyld_insert_libraries);
1053753f127fSDimitry Andric uptr dylib_name_len = internal_strlen(dylib_name);
105468d75effSDimitry Andric uptr env_name_len = internal_strlen(kDyldInsertLibraries);
105568d75effSDimitry Andric // Allocate memory to hold the previous env var name, its value, the '='
105668d75effSDimitry Andric // sign and the '\0' char.
105768d75effSDimitry Andric char *new_env = (char*)allocator_for_env.Allocate(
105868d75effSDimitry Andric old_env_len + 2 + env_name_len);
105968d75effSDimitry Andric RAW_CHECK(new_env);
106068d75effSDimitry Andric internal_memset(new_env, '\0', old_env_len + 2 + env_name_len);
106168d75effSDimitry Andric internal_strncpy(new_env, kDyldInsertLibraries, env_name_len);
106268d75effSDimitry Andric new_env[env_name_len] = '=';
106368d75effSDimitry Andric char *new_env_pos = new_env + env_name_len + 1;
106468d75effSDimitry Andric
106568d75effSDimitry Andric // Iterate over colon-separated pieces of |dyld_insert_libraries|.
106668d75effSDimitry Andric char *piece_start = dyld_insert_libraries;
106768d75effSDimitry Andric char *piece_end = NULL;
106868d75effSDimitry Andric char *old_env_end = dyld_insert_libraries + old_env_len;
106968d75effSDimitry Andric do {
107068d75effSDimitry Andric if (piece_start[0] == ':') piece_start++;
107168d75effSDimitry Andric piece_end = internal_strchr(piece_start, ':');
107268d75effSDimitry Andric if (!piece_end) piece_end = dyld_insert_libraries + old_env_len;
107368d75effSDimitry Andric if ((uptr)(piece_start - dyld_insert_libraries) > old_env_len) break;
107468d75effSDimitry Andric uptr piece_len = piece_end - piece_start;
107568d75effSDimitry Andric
107668d75effSDimitry Andric char *filename_start =
107768d75effSDimitry Andric (char *)internal_memrchr(piece_start, '/', piece_len);
107868d75effSDimitry Andric uptr filename_len = piece_len;
107968d75effSDimitry Andric if (filename_start) {
108068d75effSDimitry Andric filename_start += 1;
108168d75effSDimitry Andric filename_len = piece_len - (filename_start - piece_start);
108268d75effSDimitry Andric } else {
108368d75effSDimitry Andric filename_start = piece_start;
108468d75effSDimitry Andric }
108568d75effSDimitry Andric
108668d75effSDimitry Andric // If the current piece isn't the runtime library name,
108768d75effSDimitry Andric // append it to new_env.
108868d75effSDimitry Andric if ((dylib_name_len != filename_len) ||
108968d75effSDimitry Andric (internal_memcmp(filename_start, dylib_name, dylib_name_len) != 0)) {
109068d75effSDimitry Andric if (new_env_pos != new_env + env_name_len + 1) {
109168d75effSDimitry Andric new_env_pos[0] = ':';
109268d75effSDimitry Andric new_env_pos++;
109368d75effSDimitry Andric }
109468d75effSDimitry Andric internal_strncpy(new_env_pos, piece_start, piece_len);
109568d75effSDimitry Andric new_env_pos += piece_len;
109668d75effSDimitry Andric }
109768d75effSDimitry Andric // Move on to the next piece.
109868d75effSDimitry Andric piece_start = piece_end;
109968d75effSDimitry Andric } while (piece_start < old_env_end);
110068d75effSDimitry Andric
110168d75effSDimitry Andric // Can't use setenv() here, because it requires the allocator to be
110268d75effSDimitry Andric // initialized.
110368d75effSDimitry Andric // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in
110468d75effSDimitry Andric // a separate function called after InitializeAllocator().
110568d75effSDimitry Andric if (new_env_pos == new_env + env_name_len + 1) new_env = NULL;
110668d75effSDimitry Andric LeakyResetEnv(kDyldInsertLibraries, new_env);
110768d75effSDimitry Andric }
110868d75effSDimitry Andric #endif // SANITIZER_GO
110968d75effSDimitry Andric
GetArgv()111068d75effSDimitry Andric char **GetArgv() {
111168d75effSDimitry Andric return *_NSGetArgv();
111268d75effSDimitry Andric }
111368d75effSDimitry Andric
1114e8d8bef9SDimitry Andric #if SANITIZER_IOS && !SANITIZER_IOSSIM
111568d75effSDimitry Andric // The task_vm_info struct is normally provided by the macOS SDK, but we need
111668d75effSDimitry Andric // fields only available in 10.12+. Declare the struct manually to be able to
111768d75effSDimitry Andric // build against older SDKs.
111868d75effSDimitry Andric struct __sanitizer_task_vm_info {
111968d75effSDimitry Andric mach_vm_size_t virtual_size;
112068d75effSDimitry Andric integer_t region_count;
112168d75effSDimitry Andric integer_t page_size;
112268d75effSDimitry Andric mach_vm_size_t resident_size;
112368d75effSDimitry Andric mach_vm_size_t resident_size_peak;
112468d75effSDimitry Andric mach_vm_size_t device;
112568d75effSDimitry Andric mach_vm_size_t device_peak;
112668d75effSDimitry Andric mach_vm_size_t internal;
112768d75effSDimitry Andric mach_vm_size_t internal_peak;
112868d75effSDimitry Andric mach_vm_size_t external;
112968d75effSDimitry Andric mach_vm_size_t external_peak;
113068d75effSDimitry Andric mach_vm_size_t reusable;
113168d75effSDimitry Andric mach_vm_size_t reusable_peak;
113268d75effSDimitry Andric mach_vm_size_t purgeable_volatile_pmap;
113368d75effSDimitry Andric mach_vm_size_t purgeable_volatile_resident;
113468d75effSDimitry Andric mach_vm_size_t purgeable_volatile_virtual;
113568d75effSDimitry Andric mach_vm_size_t compressed;
113668d75effSDimitry Andric mach_vm_size_t compressed_peak;
113768d75effSDimitry Andric mach_vm_size_t compressed_lifetime;
113868d75effSDimitry Andric mach_vm_size_t phys_footprint;
113968d75effSDimitry Andric mach_vm_address_t min_address;
114068d75effSDimitry Andric mach_vm_address_t max_address;
114168d75effSDimitry Andric };
114268d75effSDimitry Andric #define __SANITIZER_TASK_VM_INFO_COUNT ((mach_msg_type_number_t) \
114368d75effSDimitry Andric (sizeof(__sanitizer_task_vm_info) / sizeof(natural_t)))
114468d75effSDimitry Andric
GetTaskInfoMaxAddress()114568d75effSDimitry Andric static uptr GetTaskInfoMaxAddress() {
114668d75effSDimitry Andric __sanitizer_task_vm_info vm_info = {} /* zero initialize */;
114768d75effSDimitry Andric mach_msg_type_number_t count = __SANITIZER_TASK_VM_INFO_COUNT;
114868d75effSDimitry Andric int err = task_info(mach_task_self(), TASK_VM_INFO, (int *)&vm_info, &count);
114968d75effSDimitry Andric return err ? 0 : vm_info.max_address;
115068d75effSDimitry Andric }
115168d75effSDimitry Andric
GetMaxUserVirtualAddress()115268d75effSDimitry Andric uptr GetMaxUserVirtualAddress() {
115368d75effSDimitry Andric static uptr max_vm = GetTaskInfoMaxAddress();
1154fe6060f1SDimitry Andric if (max_vm != 0) {
1155fe6060f1SDimitry Andric const uptr ret_value = max_vm - 1;
1156fe6060f1SDimitry Andric CHECK_LE(ret_value, SANITIZER_MMAP_RANGE_SIZE);
1157fe6060f1SDimitry Andric return ret_value;
1158fe6060f1SDimitry Andric }
115968d75effSDimitry Andric
116068d75effSDimitry Andric // xnu cannot provide vm address limit
116168d75effSDimitry Andric # if SANITIZER_WORDSIZE == 32
1162fe6060f1SDimitry Andric constexpr uptr fallback_max_vm = 0xffe00000 - 1;
116368d75effSDimitry Andric # else
1164fe6060f1SDimitry Andric constexpr uptr fallback_max_vm = 0x200000000 - 1;
116568d75effSDimitry Andric # endif
1166fe6060f1SDimitry Andric static_assert(fallback_max_vm <= SANITIZER_MMAP_RANGE_SIZE,
1167fe6060f1SDimitry Andric "Max virtual address must be less than mmap range size.");
1168fe6060f1SDimitry Andric return fallback_max_vm;
116968d75effSDimitry Andric }
117068d75effSDimitry Andric
117168d75effSDimitry Andric #else // !SANITIZER_IOS
117268d75effSDimitry Andric
GetMaxUserVirtualAddress()117368d75effSDimitry Andric uptr GetMaxUserVirtualAddress() {
117468d75effSDimitry Andric # if SANITIZER_WORDSIZE == 64
1175fe6060f1SDimitry Andric constexpr uptr max_vm = (1ULL << 47) - 1; // 0x00007fffffffffffUL;
117668d75effSDimitry Andric # else // SANITIZER_WORDSIZE == 32
117768d75effSDimitry Andric static_assert(SANITIZER_WORDSIZE == 32, "Wrong wordsize");
1178fe6060f1SDimitry Andric constexpr uptr max_vm = (1ULL << 32) - 1; // 0xffffffff;
117968d75effSDimitry Andric # endif
1180fe6060f1SDimitry Andric static_assert(max_vm <= SANITIZER_MMAP_RANGE_SIZE,
1181fe6060f1SDimitry Andric "Max virtual address must be less than mmap range size.");
1182fe6060f1SDimitry Andric return max_vm;
118368d75effSDimitry Andric }
118468d75effSDimitry Andric #endif
118568d75effSDimitry Andric
GetMaxVirtualAddress()118668d75effSDimitry Andric uptr GetMaxVirtualAddress() {
118768d75effSDimitry Andric return GetMaxUserVirtualAddress();
118868d75effSDimitry Andric }
118968d75effSDimitry Andric
MapDynamicShadow(uptr shadow_size_bytes,uptr shadow_scale,uptr min_shadow_base_alignment,uptr & high_mem_end,uptr granularity)1190e8d8bef9SDimitry Andric uptr MapDynamicShadow(uptr shadow_size_bytes, uptr shadow_scale,
1191*0fca6ea1SDimitry Andric uptr min_shadow_base_alignment, uptr &high_mem_end,
1192*0fca6ea1SDimitry Andric uptr granularity) {
1193e8d8bef9SDimitry Andric const uptr alignment =
1194e8d8bef9SDimitry Andric Max<uptr>(granularity << shadow_scale, 1ULL << min_shadow_base_alignment);
1195e8d8bef9SDimitry Andric const uptr left_padding =
1196e8d8bef9SDimitry Andric Max<uptr>(granularity, 1ULL << min_shadow_base_alignment);
1197e8d8bef9SDimitry Andric
1198e8d8bef9SDimitry Andric uptr space_size = shadow_size_bytes + left_padding;
1199e8d8bef9SDimitry Andric
1200e8d8bef9SDimitry Andric uptr largest_gap_found = 0;
1201e8d8bef9SDimitry Andric uptr max_occupied_addr = 0;
12020eae32dcSDimitry Andric VReport(2, "FindDynamicShadowStart, space_size = %p\n", (void *)space_size);
1203e8d8bef9SDimitry Andric uptr shadow_start =
1204e8d8bef9SDimitry Andric FindAvailableMemoryRange(space_size, alignment, granularity,
1205e8d8bef9SDimitry Andric &largest_gap_found, &max_occupied_addr);
1206e8d8bef9SDimitry Andric // If the shadow doesn't fit, restrict the address space to make it fit.
1207e8d8bef9SDimitry Andric if (shadow_start == 0) {
1208e8d8bef9SDimitry Andric VReport(
1209e8d8bef9SDimitry Andric 2,
1210e8d8bef9SDimitry Andric "Shadow doesn't fit, largest_gap_found = %p, max_occupied_addr = %p\n",
12110eae32dcSDimitry Andric (void *)largest_gap_found, (void *)max_occupied_addr);
1212e8d8bef9SDimitry Andric uptr new_max_vm = RoundDownTo(largest_gap_found << shadow_scale, alignment);
1213e8d8bef9SDimitry Andric if (new_max_vm < max_occupied_addr) {
1214e8d8bef9SDimitry Andric Report("Unable to find a memory range for dynamic shadow.\n");
1215e8d8bef9SDimitry Andric Report(
1216e8d8bef9SDimitry Andric "space_size = %p, largest_gap_found = %p, max_occupied_addr = %p, "
1217e8d8bef9SDimitry Andric "new_max_vm = %p\n",
12180eae32dcSDimitry Andric (void *)space_size, (void *)largest_gap_found,
12190eae32dcSDimitry Andric (void *)max_occupied_addr, (void *)new_max_vm);
1220e8d8bef9SDimitry Andric CHECK(0 && "cannot place shadow");
1221e8d8bef9SDimitry Andric }
1222e8d8bef9SDimitry Andric RestrictMemoryToMaxAddress(new_max_vm);
1223e8d8bef9SDimitry Andric high_mem_end = new_max_vm - 1;
1224e8d8bef9SDimitry Andric space_size = (high_mem_end >> shadow_scale) + left_padding;
12250eae32dcSDimitry Andric VReport(2, "FindDynamicShadowStart, space_size = %p\n", (void *)space_size);
1226e8d8bef9SDimitry Andric shadow_start = FindAvailableMemoryRange(space_size, alignment, granularity,
1227e8d8bef9SDimitry Andric nullptr, nullptr);
1228e8d8bef9SDimitry Andric if (shadow_start == 0) {
1229e8d8bef9SDimitry Andric Report("Unable to find a memory range after restricting VM.\n");
1230e8d8bef9SDimitry Andric CHECK(0 && "cannot place shadow after restricting vm");
1231e8d8bef9SDimitry Andric }
1232e8d8bef9SDimitry Andric }
1233e8d8bef9SDimitry Andric CHECK_NE((uptr)0, shadow_start);
1234e8d8bef9SDimitry Andric CHECK(IsAligned(shadow_start, alignment));
1235e8d8bef9SDimitry Andric return shadow_start;
1236e8d8bef9SDimitry Andric }
1237e8d8bef9SDimitry Andric
MapDynamicShadowAndAliases(uptr shadow_size,uptr alias_size,uptr num_aliases,uptr ring_buffer_size)1238fe6060f1SDimitry Andric uptr MapDynamicShadowAndAliases(uptr shadow_size, uptr alias_size,
1239fe6060f1SDimitry Andric uptr num_aliases, uptr ring_buffer_size) {
1240fe6060f1SDimitry Andric CHECK(false && "HWASan aliasing is unimplemented on Mac");
1241fe6060f1SDimitry Andric return 0;
1242fe6060f1SDimitry Andric }
1243fe6060f1SDimitry Andric
FindAvailableMemoryRange(uptr size,uptr alignment,uptr left_padding,uptr * largest_gap_found,uptr * max_occupied_addr)124468d75effSDimitry Andric uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
124568d75effSDimitry Andric uptr *largest_gap_found,
124668d75effSDimitry Andric uptr *max_occupied_addr) {
124768d75effSDimitry Andric typedef vm_region_submap_short_info_data_64_t RegionInfo;
124868d75effSDimitry Andric enum { kRegionInfoSize = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64 };
124968d75effSDimitry Andric // Start searching for available memory region past PAGEZERO, which is
125068d75effSDimitry Andric // 4KB on 32-bit and 4GB on 64-bit.
125168d75effSDimitry Andric mach_vm_address_t start_address =
125268d75effSDimitry Andric (SANITIZER_WORDSIZE == 32) ? 0x000000001000 : 0x000100000000;
125368d75effSDimitry Andric
1254bdd1243dSDimitry Andric const mach_vm_address_t max_vm_address = GetMaxVirtualAddress() + 1;
125568d75effSDimitry Andric mach_vm_address_t address = start_address;
125668d75effSDimitry Andric mach_vm_address_t free_begin = start_address;
125768d75effSDimitry Andric kern_return_t kr = KERN_SUCCESS;
125868d75effSDimitry Andric if (largest_gap_found) *largest_gap_found = 0;
125968d75effSDimitry Andric if (max_occupied_addr) *max_occupied_addr = 0;
126068d75effSDimitry Andric while (kr == KERN_SUCCESS) {
126168d75effSDimitry Andric mach_vm_size_t vmsize = 0;
126268d75effSDimitry Andric natural_t depth = 0;
126368d75effSDimitry Andric RegionInfo vminfo;
126468d75effSDimitry Andric mach_msg_type_number_t count = kRegionInfoSize;
126568d75effSDimitry Andric kr = mach_vm_region_recurse(mach_task_self(), &address, &vmsize, &depth,
126668d75effSDimitry Andric (vm_region_info_t)&vminfo, &count);
126768d75effSDimitry Andric if (kr == KERN_INVALID_ADDRESS) {
126868d75effSDimitry Andric // No more regions beyond "address", consider the gap at the end of VM.
1269bdd1243dSDimitry Andric address = max_vm_address;
127068d75effSDimitry Andric vmsize = 0;
127168d75effSDimitry Andric } else {
127268d75effSDimitry Andric if (max_occupied_addr) *max_occupied_addr = address + vmsize;
127368d75effSDimitry Andric }
127468d75effSDimitry Andric if (free_begin != address) {
127568d75effSDimitry Andric // We found a free region [free_begin..address-1].
127668d75effSDimitry Andric uptr gap_start = RoundUpTo((uptr)free_begin + left_padding, alignment);
1277bdd1243dSDimitry Andric uptr gap_end = RoundDownTo((uptr)Min(address, max_vm_address), alignment);
127868d75effSDimitry Andric uptr gap_size = gap_end > gap_start ? gap_end - gap_start : 0;
127968d75effSDimitry Andric if (size < gap_size) {
128068d75effSDimitry Andric return gap_start;
128168d75effSDimitry Andric }
128268d75effSDimitry Andric
128368d75effSDimitry Andric if (largest_gap_found && *largest_gap_found < gap_size) {
128468d75effSDimitry Andric *largest_gap_found = gap_size;
128568d75effSDimitry Andric }
128668d75effSDimitry Andric }
128768d75effSDimitry Andric // Move to the next region.
128868d75effSDimitry Andric address += vmsize;
128968d75effSDimitry Andric free_begin = address;
129068d75effSDimitry Andric }
129168d75effSDimitry Andric
129268d75effSDimitry Andric // We looked at all free regions and could not find one large enough.
129368d75effSDimitry Andric return 0;
129468d75effSDimitry Andric }
129568d75effSDimitry Andric
129668d75effSDimitry Andric // FIXME implement on this platform.
GetMemoryProfile(fill_profile_f cb,uptr * stats)1297349cc55cSDimitry Andric void GetMemoryProfile(fill_profile_f cb, uptr *stats) {}
129868d75effSDimitry Andric
DumpAllRegisters(void * context)129968d75effSDimitry Andric void SignalContext::DumpAllRegisters(void *context) {
130068d75effSDimitry Andric Report("Register values:\n");
130168d75effSDimitry Andric
130268d75effSDimitry Andric ucontext_t *ucontext = (ucontext_t*)context;
130368d75effSDimitry Andric # define DUMPREG64(r) \
130468d75effSDimitry Andric Printf("%s = 0x%016llx ", #r, ucontext->uc_mcontext->__ss.__ ## r);
13055ffd83dbSDimitry Andric # define DUMPREGA64(r) \
13060eae32dcSDimitry Andric Printf(" %s = 0x%016lx ", #r, AARCH64_GET_REG(r));
130768d75effSDimitry Andric # define DUMPREG32(r) \
130868d75effSDimitry Andric Printf("%s = 0x%08x ", #r, ucontext->uc_mcontext->__ss.__ ## r);
130968d75effSDimitry Andric # define DUMPREG_(r) Printf(" "); DUMPREG(r);
131068d75effSDimitry Andric # define DUMPREG__(r) Printf(" "); DUMPREG(r);
131168d75effSDimitry Andric # define DUMPREG___(r) Printf(" "); DUMPREG(r);
131268d75effSDimitry Andric
131368d75effSDimitry Andric # if defined(__x86_64__)
131468d75effSDimitry Andric # define DUMPREG(r) DUMPREG64(r)
131568d75effSDimitry Andric DUMPREG(rax); DUMPREG(rbx); DUMPREG(rcx); DUMPREG(rdx); Printf("\n");
131668d75effSDimitry Andric DUMPREG(rdi); DUMPREG(rsi); DUMPREG(rbp); DUMPREG(rsp); Printf("\n");
131768d75effSDimitry Andric DUMPREG_(r8); DUMPREG_(r9); DUMPREG(r10); DUMPREG(r11); Printf("\n");
131868d75effSDimitry Andric DUMPREG(r12); DUMPREG(r13); DUMPREG(r14); DUMPREG(r15); Printf("\n");
131968d75effSDimitry Andric # elif defined(__i386__)
132068d75effSDimitry Andric # define DUMPREG(r) DUMPREG32(r)
132168d75effSDimitry Andric DUMPREG(eax); DUMPREG(ebx); DUMPREG(ecx); DUMPREG(edx); Printf("\n");
132268d75effSDimitry Andric DUMPREG(edi); DUMPREG(esi); DUMPREG(ebp); DUMPREG(esp); Printf("\n");
132368d75effSDimitry Andric # elif defined(__aarch64__)
132468d75effSDimitry Andric # define DUMPREG(r) DUMPREG64(r)
132568d75effSDimitry Andric DUMPREG_(x[0]); DUMPREG_(x[1]); DUMPREG_(x[2]); DUMPREG_(x[3]); Printf("\n");
132668d75effSDimitry Andric DUMPREG_(x[4]); DUMPREG_(x[5]); DUMPREG_(x[6]); DUMPREG_(x[7]); Printf("\n");
132768d75effSDimitry Andric DUMPREG_(x[8]); DUMPREG_(x[9]); DUMPREG(x[10]); DUMPREG(x[11]); Printf("\n");
132868d75effSDimitry Andric DUMPREG(x[12]); DUMPREG(x[13]); DUMPREG(x[14]); DUMPREG(x[15]); Printf("\n");
132968d75effSDimitry Andric DUMPREG(x[16]); DUMPREG(x[17]); DUMPREG(x[18]); DUMPREG(x[19]); Printf("\n");
133068d75effSDimitry Andric DUMPREG(x[20]); DUMPREG(x[21]); DUMPREG(x[22]); DUMPREG(x[23]); Printf("\n");
133168d75effSDimitry Andric DUMPREG(x[24]); DUMPREG(x[25]); DUMPREG(x[26]); DUMPREG(x[27]); Printf("\n");
13325ffd83dbSDimitry Andric DUMPREG(x[28]); DUMPREGA64(fp); DUMPREGA64(lr); DUMPREGA64(sp); Printf("\n");
133368d75effSDimitry Andric # elif defined(__arm__)
133468d75effSDimitry Andric # define DUMPREG(r) DUMPREG32(r)
133568d75effSDimitry Andric DUMPREG_(r[0]); DUMPREG_(r[1]); DUMPREG_(r[2]); DUMPREG_(r[3]); Printf("\n");
133668d75effSDimitry Andric DUMPREG_(r[4]); DUMPREG_(r[5]); DUMPREG_(r[6]); DUMPREG_(r[7]); Printf("\n");
133768d75effSDimitry Andric DUMPREG_(r[8]); DUMPREG_(r[9]); DUMPREG(r[10]); DUMPREG(r[11]); Printf("\n");
133868d75effSDimitry Andric DUMPREG(r[12]); DUMPREG___(sp); DUMPREG___(lr); DUMPREG___(pc); Printf("\n");
133968d75effSDimitry Andric # else
134068d75effSDimitry Andric # error "Unknown architecture"
134168d75effSDimitry Andric # endif
134268d75effSDimitry Andric
134368d75effSDimitry Andric # undef DUMPREG64
134468d75effSDimitry Andric # undef DUMPREG32
134568d75effSDimitry Andric # undef DUMPREG_
134668d75effSDimitry Andric # undef DUMPREG__
134768d75effSDimitry Andric # undef DUMPREG___
134868d75effSDimitry Andric # undef DUMPREG
134968d75effSDimitry Andric }
135068d75effSDimitry Andric
CompareBaseAddress(const LoadedModule & a,const LoadedModule & b)135168d75effSDimitry Andric static inline bool CompareBaseAddress(const LoadedModule &a,
135268d75effSDimitry Andric const LoadedModule &b) {
135368d75effSDimitry Andric return a.base_address() < b.base_address();
135468d75effSDimitry Andric }
135568d75effSDimitry Andric
FormatUUID(char * out,uptr size,const u8 * uuid)135668d75effSDimitry Andric void FormatUUID(char *out, uptr size, const u8 *uuid) {
135768d75effSDimitry Andric internal_snprintf(out, size,
135868d75effSDimitry Andric "<%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-"
135968d75effSDimitry Andric "%02X%02X%02X%02X%02X%02X>",
136068d75effSDimitry Andric uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5],
136168d75effSDimitry Andric uuid[6], uuid[7], uuid[8], uuid[9], uuid[10], uuid[11],
136268d75effSDimitry Andric uuid[12], uuid[13], uuid[14], uuid[15]);
136368d75effSDimitry Andric }
136468d75effSDimitry Andric
DumpProcessMap()1365e8d8bef9SDimitry Andric void DumpProcessMap() {
136668d75effSDimitry Andric Printf("Process module map:\n");
136768d75effSDimitry Andric MemoryMappingLayout memory_mapping(false);
136868d75effSDimitry Andric InternalMmapVector<LoadedModule> modules;
136968d75effSDimitry Andric modules.reserve(128);
137068d75effSDimitry Andric memory_mapping.DumpListOfModules(&modules);
137168d75effSDimitry Andric Sort(modules.data(), modules.size(), CompareBaseAddress);
137268d75effSDimitry Andric for (uptr i = 0; i < modules.size(); ++i) {
137368d75effSDimitry Andric char uuid_str[128];
137468d75effSDimitry Andric FormatUUID(uuid_str, sizeof(uuid_str), modules[i].uuid());
1375*0fca6ea1SDimitry Andric Printf("%p-%p %s (%s) %s\n", (void *)modules[i].base_address(),
1376*0fca6ea1SDimitry Andric (void *)modules[i].max_address(), modules[i].full_name(),
137768d75effSDimitry Andric ModuleArchToString(modules[i].arch()), uuid_str);
137868d75effSDimitry Andric }
137968d75effSDimitry Andric Printf("End of module map.\n");
138068d75effSDimitry Andric }
138168d75effSDimitry Andric
CheckNoDeepBind(const char * filename,int flag)138268d75effSDimitry Andric void CheckNoDeepBind(const char *filename, int flag) {
138368d75effSDimitry Andric // Do nothing.
138468d75effSDimitry Andric }
138568d75effSDimitry Andric
GetRandom(void * buffer,uptr length,bool blocking)138668d75effSDimitry Andric bool GetRandom(void *buffer, uptr length, bool blocking) {
138768d75effSDimitry Andric if (!buffer || !length || length > 256)
138868d75effSDimitry Andric return false;
138968d75effSDimitry Andric // arc4random never fails.
139068d75effSDimitry Andric REAL(arc4random_buf)(buffer, length);
139168d75effSDimitry Andric return true;
139268d75effSDimitry Andric }
139368d75effSDimitry Andric
GetNumberOfCPUs()139468d75effSDimitry Andric u32 GetNumberOfCPUs() {
139568d75effSDimitry Andric return (u32)sysconf(_SC_NPROCESSORS_ONLN);
139668d75effSDimitry Andric }
139768d75effSDimitry Andric
InitializePlatformCommonFlags(CommonFlags * cf)1398e8d8bef9SDimitry Andric void InitializePlatformCommonFlags(CommonFlags *cf) {}
1399e8d8bef9SDimitry Andric
1400fcaf7f86SDimitry Andric // Pthread introspection hook
1401fcaf7f86SDimitry Andric //
1402fcaf7f86SDimitry Andric // * GCD worker threads are created without a call to pthread_create(), but we
1403fcaf7f86SDimitry Andric // still need to register these threads (with ThreadCreate/Start()).
1404fcaf7f86SDimitry Andric // * We use the "pthread introspection hook" below to observe the creation of
1405fcaf7f86SDimitry Andric // such threads.
1406fcaf7f86SDimitry Andric // * GCD worker threads don't have parent threads and the CREATE event is
1407fcaf7f86SDimitry Andric // delivered in the context of the thread itself. CREATE events for regular
1408fcaf7f86SDimitry Andric // threads, are delivered on the parent. We use this to tell apart which
1409fcaf7f86SDimitry Andric // threads are GCD workers with `thread == pthread_self()`.
1410fcaf7f86SDimitry Andric //
1411fcaf7f86SDimitry Andric static pthread_introspection_hook_t prev_pthread_introspection_hook;
1412fcaf7f86SDimitry Andric static ThreadEventCallbacks thread_event_callbacks;
1413fcaf7f86SDimitry Andric
sanitizer_pthread_introspection_hook(unsigned int event,pthread_t thread,void * addr,size_t size)1414fcaf7f86SDimitry Andric static void sanitizer_pthread_introspection_hook(unsigned int event,
1415fcaf7f86SDimitry Andric pthread_t thread, void *addr,
1416fcaf7f86SDimitry Andric size_t size) {
1417fcaf7f86SDimitry Andric // create -> start -> terminate -> destroy
1418fcaf7f86SDimitry Andric // * create/destroy are usually (not guaranteed) delivered on the parent and
1419fcaf7f86SDimitry Andric // track resource allocation/reclamation
1420fcaf7f86SDimitry Andric // * start/terminate are guaranteed to be delivered in the context of the
1421fcaf7f86SDimitry Andric // thread and give hooks into "just after (before) thread starts (stops)
1422fcaf7f86SDimitry Andric // executing"
1423fcaf7f86SDimitry Andric DCHECK(event >= PTHREAD_INTROSPECTION_THREAD_CREATE &&
1424fcaf7f86SDimitry Andric event <= PTHREAD_INTROSPECTION_THREAD_DESTROY);
1425fcaf7f86SDimitry Andric
1426fcaf7f86SDimitry Andric if (event == PTHREAD_INTROSPECTION_THREAD_CREATE) {
1427fcaf7f86SDimitry Andric bool gcd_worker = (thread == pthread_self());
1428fcaf7f86SDimitry Andric if (thread_event_callbacks.create)
1429fcaf7f86SDimitry Andric thread_event_callbacks.create((uptr)thread, gcd_worker);
1430fcaf7f86SDimitry Andric } else if (event == PTHREAD_INTROSPECTION_THREAD_START) {
1431fcaf7f86SDimitry Andric CHECK_EQ(thread, pthread_self());
1432fcaf7f86SDimitry Andric if (thread_event_callbacks.start)
1433fcaf7f86SDimitry Andric thread_event_callbacks.start((uptr)thread);
1434fcaf7f86SDimitry Andric }
1435fcaf7f86SDimitry Andric
1436fcaf7f86SDimitry Andric if (prev_pthread_introspection_hook)
1437fcaf7f86SDimitry Andric prev_pthread_introspection_hook(event, thread, addr, size);
1438fcaf7f86SDimitry Andric
1439fcaf7f86SDimitry Andric if (event == PTHREAD_INTROSPECTION_THREAD_TERMINATE) {
1440fcaf7f86SDimitry Andric CHECK_EQ(thread, pthread_self());
1441fcaf7f86SDimitry Andric if (thread_event_callbacks.terminate)
1442fcaf7f86SDimitry Andric thread_event_callbacks.terminate((uptr)thread);
1443fcaf7f86SDimitry Andric } else if (event == PTHREAD_INTROSPECTION_THREAD_DESTROY) {
1444fcaf7f86SDimitry Andric if (thread_event_callbacks.destroy)
1445fcaf7f86SDimitry Andric thread_event_callbacks.destroy((uptr)thread);
1446fcaf7f86SDimitry Andric }
1447fcaf7f86SDimitry Andric }
1448fcaf7f86SDimitry Andric
InstallPthreadIntrospectionHook(const ThreadEventCallbacks & callbacks)1449fcaf7f86SDimitry Andric void InstallPthreadIntrospectionHook(const ThreadEventCallbacks &callbacks) {
1450fcaf7f86SDimitry Andric thread_event_callbacks = callbacks;
1451fcaf7f86SDimitry Andric prev_pthread_introspection_hook =
1452fcaf7f86SDimitry Andric pthread_introspection_hook_install(&sanitizer_pthread_introspection_hook);
1453fcaf7f86SDimitry Andric }
1454fcaf7f86SDimitry Andric
145568d75effSDimitry Andric } // namespace __sanitizer
145668d75effSDimitry Andric
145781ad6265SDimitry Andric #endif // SANITIZER_APPLE
1458