1 //===-- sanitizer_mac.cc --------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is shared between various sanitizers' runtime libraries and
11 // implements OSX-specific functions.
12 //===----------------------------------------------------------------------===//
14 #include "sanitizer_platform.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_flags.h"
27 #include "sanitizer_internal_defs.h"
28 #include "sanitizer_libc.h"
29 #include "sanitizer_placement_new.h"
30 #include "sanitizer_platform_limits_posix.h"
31 #include "sanitizer_procmaps.h"
34 #include <crt_externs.h> // for _NSGetEnviron
36 extern char **environ
;
39 #if defined(__has_include) && __has_include(<os/trace.h>)
40 #define SANITIZER_OS_TRACE 1
43 #define SANITIZER_OS_TRACE 0
47 #include <crt_externs.h> // for _NSGetArgv and _NSGetEnviron
50 extern char ***_NSGetArgv(void);
55 #include <dlfcn.h> // for dladdr()
58 #include <libkern/OSAtomic.h>
59 #include <mach-o/dyld.h>
60 #include <mach/mach.h>
61 #include <mach/vm_statistics.h>
67 #include <sys/resource.h>
69 #include <sys/sysctl.h>
70 #include <sys/types.h>
75 // From <crt_externs.h>, but we don't have that file on iOS.
77 extern char ***_NSGetArgv(void);
78 extern char ***_NSGetEnviron(void);
81 // From <mach/mach_vm.h>, but we don't have that file on iOS.
83 extern kern_return_t
mach_vm_region_recurse(
85 mach_vm_address_t
*address
,
87 natural_t
*nesting_depth
,
88 vm_region_recurse_info_t info
,
89 mach_msg_type_number_t
*infoCnt
);
92 namespace __sanitizer
{
94 #include "sanitizer_syscall_generic.inc"
96 // Direct syscalls, don't call libmalloc hooks.
97 extern "C" void *__mmap(void *addr
, size_t len
, int prot
, int flags
, int fildes
,
99 extern "C" int __munmap(void *, size_t);
101 // ---------------------- sanitizer_libc.h
102 uptr
internal_mmap(void *addr
, size_t length
, int prot
, int flags
,
103 int fd
, u64 offset
) {
104 if (fd
== -1) fd
= VM_MAKE_TAG(VM_MEMORY_ANALYSIS_TOOL
);
105 return (uptr
)__mmap(addr
, length
, prot
, flags
, fd
, offset
);
108 uptr
internal_munmap(void *addr
, uptr length
) {
109 return __munmap(addr
, length
);
112 int internal_mprotect(void *addr
, uptr length
, int prot
) {
113 return mprotect(addr
, length
, prot
);
116 uptr
internal_close(fd_t fd
) {
120 uptr
internal_open(const char *filename
, int flags
) {
121 return open(filename
, flags
);
124 uptr
internal_open(const char *filename
, int flags
, u32 mode
) {
125 return open(filename
, flags
, mode
);
128 uptr
internal_read(fd_t fd
, void *buf
, uptr count
) {
129 return read(fd
, buf
, count
);
132 uptr
internal_write(fd_t fd
, const void *buf
, uptr count
) {
133 return write(fd
, buf
, count
);
136 uptr
internal_stat(const char *path
, void *buf
) {
137 return stat(path
, (struct stat
*)buf
);
140 uptr
internal_lstat(const char *path
, void *buf
) {
141 return lstat(path
, (struct stat
*)buf
);
144 uptr
internal_fstat(fd_t fd
, void *buf
) {
145 return fstat(fd
, (struct stat
*)buf
);
148 uptr
internal_filesize(fd_t fd
) {
150 if (internal_fstat(fd
, &st
))
152 return (uptr
)st
.st_size
;
155 uptr
internal_dup2(int oldfd
, int newfd
) {
156 return dup2(oldfd
, newfd
);
159 uptr
internal_readlink(const char *path
, char *buf
, uptr bufsize
) {
160 return readlink(path
, buf
, bufsize
);
163 uptr
internal_unlink(const char *path
) {
167 uptr
internal_sched_yield() {
168 return sched_yield();
171 void internal__exit(int exitcode
) {
175 unsigned int internal_sleep(unsigned int seconds
) {
176 return sleep(seconds
);
179 uptr
internal_getpid() {
183 int internal_sigaction(int signum
, const void *act
, void *oldact
) {
184 return sigaction(signum
,
185 (struct sigaction
*)act
, (struct sigaction
*)oldact
);
188 void internal_sigfillset(__sanitizer_sigset_t
*set
) { sigfillset(set
); }
190 uptr
internal_sigprocmask(int how
, __sanitizer_sigset_t
*set
,
191 __sanitizer_sigset_t
*oldset
) {
192 return sigprocmask(how
, set
, oldset
);
195 // Doesn't call pthread_atfork() handlers.
196 extern "C" pid_t
__fork(void);
198 int internal_fork() {
202 int internal_forkpty(int *amaster
) {
204 if (openpty(&master
, &slave
, nullptr, nullptr, nullptr) == -1) return -1;
213 if (login_tty(slave
) != 0) {
214 // We already forked, there's not much we can do. Let's quit.
215 Report("login_tty failed (errno %d)\n", errno
);
225 uptr
internal_rename(const char *oldpath
, const char *newpath
) {
226 return rename(oldpath
, newpath
);
229 uptr
internal_ftruncate(fd_t fd
, uptr size
) {
230 return ftruncate(fd
, size
);
233 uptr
internal_execve(const char *filename
, char *const argv
[],
234 char *const envp
[]) {
235 return execve(filename
, argv
, envp
);
238 uptr
internal_waitpid(int pid
, int *status
, int options
) {
239 return waitpid(pid
, status
, options
);
242 // ----------------- sanitizer_common.h
243 bool FileExists(const char *filename
) {
245 if (stat(filename
, &st
))
247 // Sanity check: filename is a regular file.
248 return S_ISREG(st
.st_mode
);
252 // FIXME: This can potentially get truncated on 32-bit, where uptr is 4 bytes.
254 pthread_threadid_np(nullptr, &tid
);
258 void GetThreadStackTopAndBottom(bool at_initialization
, uptr
*stack_top
,
259 uptr
*stack_bottom
) {
262 uptr stacksize
= pthread_get_stacksize_np(pthread_self());
263 // pthread_get_stacksize_np() returns an incorrect stack size for the main
264 // thread on Mavericks. See
265 // https://github.com/google/sanitizers/issues/261
266 if ((GetMacosVersion() >= MACOS_VERSION_MAVERICKS
) && at_initialization
&&
267 stacksize
== (1 << 19)) {
269 CHECK_EQ(getrlimit(RLIMIT_STACK
, &rl
), 0);
270 // Most often rl.rlim_cur will be the desired 8M.
271 if (rl
.rlim_cur
< kMaxThreadStackSize
) {
272 stacksize
= rl
.rlim_cur
;
274 stacksize
= kMaxThreadStackSize
;
277 void *stackaddr
= pthread_get_stackaddr_np(pthread_self());
278 *stack_top
= (uptr
)stackaddr
;
279 *stack_bottom
= *stack_top
- stacksize
;
282 char **GetEnviron() {
284 char ***env_ptr
= _NSGetEnviron();
286 Report("_NSGetEnviron() returned NULL. Please make sure __asan_init() is "
287 "called after libSystem_initializer().\n");
290 char **environ
= *env_ptr
;
296 const char *GetEnv(const char *name
) {
297 char **env
= GetEnviron();
298 uptr name_len
= internal_strlen(name
);
300 uptr len
= internal_strlen(*env
);
301 if (len
> name_len
) {
302 const char *p
= *env
;
303 if (!internal_memcmp(p
, name
, name_len
) &&
304 p
[name_len
] == '=') { // Match.
305 return *env
+ name_len
+ 1; // String starting after =.
313 uptr
ReadBinaryName(/*out*/char *buf
, uptr buf_len
) {
314 CHECK_LE(kMaxPathLength
, buf_len
);
316 // On OS X the executable path is saved to the stack by dyld. Reading it
317 // from there is much faster than calling dladdr, especially for large
318 // binaries with symbols.
319 InternalScopedString
exe_path(kMaxPathLength
);
320 uint32_t size
= exe_path
.size();
321 if (_NSGetExecutablePath(exe_path
.data(), &size
) == 0 &&
322 realpath(exe_path
.data(), buf
) != 0) {
323 return internal_strlen(buf
);
328 uptr
ReadLongProcessName(/*out*/char *buf
, uptr buf_len
) {
329 return ReadBinaryName(buf
, buf_len
);
337 return sysconf(_SC_PAGESIZE
);
340 BlockingMutex::BlockingMutex() {
341 internal_memset(this, 0, sizeof(*this));
344 void BlockingMutex::Lock() {
345 CHECK(sizeof(OSSpinLock
) <= sizeof(opaque_storage_
));
346 CHECK_EQ(OS_SPINLOCK_INIT
, 0);
347 CHECK_NE(owner_
, (uptr
)pthread_self());
348 OSSpinLockLock((OSSpinLock
*)&opaque_storage_
);
350 owner_
= (uptr
)pthread_self();
353 void BlockingMutex::Unlock() {
354 CHECK(owner_
== (uptr
)pthread_self());
356 OSSpinLockUnlock((OSSpinLock
*)&opaque_storage_
);
359 void BlockingMutex::CheckLocked() {
360 CHECK_EQ((uptr
)pthread_self(), owner_
);
374 void GetThreadStackAndTls(bool main
, uptr
*stk_addr
, uptr
*stk_size
,
375 uptr
*tls_addr
, uptr
*tls_size
) {
377 uptr stack_top
, stack_bottom
;
378 GetThreadStackTopAndBottom(main
, &stack_top
, &stack_bottom
);
379 *stk_addr
= stack_bottom
;
380 *stk_size
= stack_top
- stack_bottom
;
391 void ListOfModules::init() {
393 MemoryMappingLayout
memory_mapping(false);
394 memory_mapping
.DumpListOfModules(&modules_
);
397 bool IsHandledDeadlySignal(int signum
) {
398 if ((SANITIZER_WATCHOS
|| SANITIZER_TVOS
) && !(SANITIZER_IOSSIM
))
399 // Handling fatal signals on watchOS and tvOS devices is disallowed.
401 if (common_flags()->handle_abort
&& signum
== SIGABRT
)
403 if (common_flags()->handle_sigill
&& signum
== SIGILL
)
405 return (signum
== SIGSEGV
|| signum
== SIGBUS
) && common_flags()->handle_segv
;
408 MacosVersion cached_macos_version
= MACOS_VERSION_UNINITIALIZED
;
410 MacosVersion
GetMacosVersionInternal() {
411 int mib
[2] = { CTL_KERN
, KERN_OSRELEASE
};
413 uptr len
= 0, maxlen
= sizeof(version
) / sizeof(version
[0]);
414 for (uptr i
= 0; i
< maxlen
; i
++) version
[i
] = '\0';
415 // Get the version length.
416 CHECK_NE(sysctl(mib
, 2, 0, &len
, 0, 0), -1);
417 CHECK_LT(len
, maxlen
);
418 CHECK_NE(sysctl(mib
, 2, version
, &len
, 0, 0), -1);
419 switch (version
[0]) {
420 case '9': return MACOS_VERSION_LEOPARD
;
422 switch (version
[1]) {
423 case '0': return MACOS_VERSION_SNOW_LEOPARD
;
424 case '1': return MACOS_VERSION_LION
;
425 case '2': return MACOS_VERSION_MOUNTAIN_LION
;
426 case '3': return MACOS_VERSION_MAVERICKS
;
427 case '4': return MACOS_VERSION_YOSEMITE
;
429 if (IsDigit(version
[1]))
430 return MACOS_VERSION_UNKNOWN_NEWER
;
432 return MACOS_VERSION_UNKNOWN
;
435 default: return MACOS_VERSION_UNKNOWN
;
439 MacosVersion
GetMacosVersion() {
440 atomic_uint32_t
*cache
=
441 reinterpret_cast<atomic_uint32_t
*>(&cached_macos_version
);
442 MacosVersion result
=
443 static_cast<MacosVersion
>(atomic_load(cache
, memory_order_acquire
));
444 if (result
== MACOS_VERSION_UNINITIALIZED
) {
445 result
= GetMacosVersionInternal();
446 atomic_store(cache
, result
, memory_order_release
);
451 bool PlatformHasDifferentMemcpyAndMemmove() {
452 // On OS X 10.7 memcpy() and memmove() are both resolved
453 // into memmove$VARIANT$sse42.
454 // See also https://github.com/google/sanitizers/issues/34.
455 // TODO(glider): need to check dynamically that memcpy() and memmove() are
456 // actually the same function.
457 return GetMacosVersion() == MACOS_VERSION_SNOW_LEOPARD
;
461 struct task_basic_info info
;
462 unsigned count
= TASK_BASIC_INFO_COUNT
;
463 kern_return_t result
=
464 task_info(mach_task_self(), TASK_BASIC_INFO
, (task_info_t
)&info
, &count
);
465 if (UNLIKELY(result
!= KERN_SUCCESS
)) {
466 Report("Cannot get task info. Error: %d\n", result
);
469 return info
.resident_size
;
472 void *internal_start_thread(void(*func
)(void *arg
), void *arg
) {
473 // Start the thread with signals blocked, otherwise it can steal user signals.
474 __sanitizer_sigset_t set
, old
;
475 internal_sigfillset(&set
);
476 internal_sigprocmask(SIG_SETMASK
, &set
, &old
);
478 pthread_create(&th
, 0, (void*(*)(void *arg
))func
, arg
);
479 internal_sigprocmask(SIG_SETMASK
, &old
, 0);
483 void internal_join_thread(void *th
) { pthread_join((pthread_t
)th
, 0); }
486 static BlockingMutex
syslog_lock(LINKER_INITIALIZED
);
489 void WriteOneLineToSyslog(const char *s
) {
491 syslog_lock
.CheckLocked();
492 asl_log(nullptr, nullptr, ASL_LEVEL_ERR
, "%s", s
);
496 void LogMessageOnPrintf(const char *str
) {
497 // Log all printf output to CrashLog.
498 if (common_flags()->abort_on_error
)
499 CRAppendCrashLogMessage(str
);
502 void LogFullErrorReport(const char *buffer
) {
504 // Log with os_trace. This will make it into the crash log.
505 #if SANITIZER_OS_TRACE
506 if (GetMacosVersion() >= MACOS_VERSION_YOSEMITE
) {
507 // os_trace requires the message (format parameter) to be a string literal.
508 if (internal_strncmp(SanitizerToolName
, "AddressSanitizer",
509 sizeof("AddressSanitizer") - 1) == 0)
510 os_trace("Address Sanitizer reported a failure.");
511 else if (internal_strncmp(SanitizerToolName
, "UndefinedBehaviorSanitizer",
512 sizeof("UndefinedBehaviorSanitizer") - 1) == 0)
513 os_trace("Undefined Behavior Sanitizer reported a failure.");
514 else if (internal_strncmp(SanitizerToolName
, "ThreadSanitizer",
515 sizeof("ThreadSanitizer") - 1) == 0)
516 os_trace("Thread Sanitizer reported a failure.");
518 os_trace("Sanitizer tool reported a failure.");
520 if (common_flags()->log_to_syslog
)
521 os_trace("Consult syslog for more information.");
526 // The logging on OS X may call pthread_create so we need the threading
527 // environment to be fully initialized. Also, this should never be called when
528 // holding the thread registry lock since that may result in a deadlock. If
529 // the reporting thread holds the thread registry mutex, and asl_log waits
530 // for GCD to dispatch a new thread, the process will deadlock, because the
531 // pthread_create wrapper needs to acquire the lock as well.
532 BlockingMutexLock
l(&syslog_lock
);
533 if (common_flags()->log_to_syslog
)
534 WriteToSyslog(buffer
);
536 // The report is added to CrashLog as part of logging all of Printf output.
540 SignalContext::WriteFlag
SignalContext::GetWriteFlag(void *context
) {
541 #if defined(__x86_64__) || defined(__i386__)
542 ucontext_t
*ucontext
= static_cast<ucontext_t
*>(context
);
543 return ucontext
->uc_mcontext
->__es
.__err
& 2 /*T_PF_WRITE*/ ? WRITE
: READ
;
549 void GetPcSpBp(void *context
, uptr
*pc
, uptr
*sp
, uptr
*bp
) {
550 ucontext_t
*ucontext
= (ucontext_t
*)context
;
551 # if defined(__aarch64__)
552 *pc
= ucontext
->uc_mcontext
->__ss
.__pc
;
553 # if defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
554 *bp
= ucontext
->uc_mcontext
->__ss
.__fp
;
556 *bp
= ucontext
->uc_mcontext
->__ss
.__lr
;
558 *sp
= ucontext
->uc_mcontext
->__ss
.__sp
;
559 # elif defined(__x86_64__)
560 *pc
= ucontext
->uc_mcontext
->__ss
.__rip
;
561 *bp
= ucontext
->uc_mcontext
->__ss
.__rbp
;
562 *sp
= ucontext
->uc_mcontext
->__ss
.__rsp
;
563 # elif defined(__arm__)
564 *pc
= ucontext
->uc_mcontext
->__ss
.__pc
;
565 *bp
= ucontext
->uc_mcontext
->__ss
.__r
[7];
566 *sp
= ucontext
->uc_mcontext
->__ss
.__sp
;
567 # elif defined(__i386__)
568 *pc
= ucontext
->uc_mcontext
->__ss
.__eip
;
569 *bp
= ucontext
->uc_mcontext
->__ss
.__ebp
;
570 *sp
= ucontext
->uc_mcontext
->__ss
.__esp
;
572 # error "Unknown architecture"
577 static const char kDyldInsertLibraries
[] = "DYLD_INSERT_LIBRARIES";
578 LowLevelAllocator allocator_for_env
;
580 // Change the value of the env var |name|, leaking the original value.
581 // If |name_value| is NULL, the variable is deleted from the environment,
582 // otherwise the corresponding "NAME=value" string is replaced with
584 void LeakyResetEnv(const char *name
, const char *name_value
) {
585 char **env
= GetEnviron();
586 uptr name_len
= internal_strlen(name
);
588 uptr len
= internal_strlen(*env
);
589 if (len
> name_len
) {
590 const char *p
= *env
;
591 if (!internal_memcmp(p
, name
, name_len
) && p
[name_len
] == '=') {
594 // Replace the old value with the new one.
595 *env
= const_cast<char*>(name_value
);
597 // Shift the subsequent pointers back.
609 SANITIZER_WEAK_CXX_DEFAULT_IMPL
610 bool ReexecDisabled() {
614 extern "C" SANITIZER_WEAK_ATTRIBUTE
double dyldVersionNumber
;
615 static const double kMinDyldVersionWithAutoInterposition
= 360.0;
617 bool DyldNeedsEnvVariable() {
618 // Although sanitizer support was added to LLVM on OS X 10.7+, GCC users
619 // still may want use them on older systems. On older Darwin platforms, dyld
620 // doesn't export dyldVersionNumber symbol and we simply return true.
621 if (!&dyldVersionNumber
) return true;
622 // If running on OS X 10.11+ or iOS 9.0+, dyld will interpose even if
623 // DYLD_INSERT_LIBRARIES is not set. However, checking OS version via
624 // GetMacosVersion() doesn't work for the simulator. Let's instead check
625 // `dyldVersionNumber`, which is exported by dyld, against a known version
626 // number from the first OS release where this appeared.
627 return dyldVersionNumber
< kMinDyldVersionWithAutoInterposition
;
631 if (ReexecDisabled()) return;
633 // Make sure the dynamic runtime library is preloaded so that the
634 // wrappers work. If it is not, set DYLD_INSERT_LIBRARIES and re-exec
637 RAW_CHECK(dladdr((void*)((uptr
)&__sanitizer_report_error_summary
), &info
));
638 char *dyld_insert_libraries
=
639 const_cast<char*>(GetEnv(kDyldInsertLibraries
));
640 uptr old_env_len
= dyld_insert_libraries
?
641 internal_strlen(dyld_insert_libraries
) : 0;
642 uptr fname_len
= internal_strlen(info
.dli_fname
);
643 const char *dylib_name
= StripModuleName(info
.dli_fname
);
644 uptr dylib_name_len
= internal_strlen(dylib_name
);
646 bool lib_is_in_env
= dyld_insert_libraries
&&
647 internal_strstr(dyld_insert_libraries
, dylib_name
);
648 if (DyldNeedsEnvVariable() && !lib_is_in_env
) {
649 // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
651 InternalScopedString
program_name(1024);
652 uint32_t buf_size
= program_name
.size();
653 _NSGetExecutablePath(program_name
.data(), &buf_size
);
654 char *new_env
= const_cast<char*>(info
.dli_fname
);
655 if (dyld_insert_libraries
) {
656 // Append the runtime dylib name to the existing value of
657 // DYLD_INSERT_LIBRARIES.
658 new_env
= (char*)allocator_for_env
.Allocate(old_env_len
+ fname_len
+ 2);
659 internal_strncpy(new_env
, dyld_insert_libraries
, old_env_len
);
660 new_env
[old_env_len
] = ':';
661 // Copy fname_len and add a trailing zero.
662 internal_strncpy(new_env
+ old_env_len
+ 1, info
.dli_fname
,
664 // Ok to use setenv() since the wrappers don't depend on the value of
666 setenv(kDyldInsertLibraries
, new_env
, /*overwrite*/1);
668 // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name.
669 setenv(kDyldInsertLibraries
, info
.dli_fname
, /*overwrite*/0);
671 VReport(1, "exec()-ing the program with\n");
672 VReport(1, "%s=%s\n", kDyldInsertLibraries
, new_env
);
673 VReport(1, "to enable wrappers.\n");
674 execv(program_name
.data(), *_NSGetArgv());
676 // We get here only if execv() failed.
677 Report("ERROR: The process is launched without DYLD_INSERT_LIBRARIES, "
678 "which is required for the sanitizer to work. We tried to set the "
679 "environment variable and re-execute itself, but execv() failed, "
680 "possibly because of sandbox restrictions. Make sure to launch the "
681 "executable with:\n%s=%s\n", kDyldInsertLibraries
, new_env
);
682 RAW_CHECK("execv failed" && 0);
685 // Verify that interceptors really work. We'll use dlsym to locate
686 // "pthread_create", if interceptors are working, it should really point to
687 // "wrap_pthread_create" within our own dylib.
688 Dl_info info_pthread_create
;
689 void *dlopen_addr
= dlsym(RTLD_DEFAULT
, "pthread_create");
690 RAW_CHECK(dladdr(dlopen_addr
, &info_pthread_create
));
691 if (internal_strcmp(info
.dli_fname
, info_pthread_create
.dli_fname
) != 0) {
693 "ERROR: Interceptors are not working. This may be because %s is "
694 "loaded too late (e.g. via dlopen). Please launch the executable "
696 SanitizerToolName
, kDyldInsertLibraries
, info
.dli_fname
);
697 RAW_CHECK("interceptors not installed" && 0);
703 // DYLD_INSERT_LIBRARIES is set and contains the runtime library. Let's remove
704 // the dylib from the environment variable, because interceptors are installed
705 // and we don't want our children to inherit the variable.
707 uptr env_name_len
= internal_strlen(kDyldInsertLibraries
);
708 // Allocate memory to hold the previous env var name, its value, the '='
709 // sign and the '\0' char.
710 char *new_env
= (char*)allocator_for_env
.Allocate(
711 old_env_len
+ 2 + env_name_len
);
713 internal_memset(new_env
, '\0', old_env_len
+ 2 + env_name_len
);
714 internal_strncpy(new_env
, kDyldInsertLibraries
, env_name_len
);
715 new_env
[env_name_len
] = '=';
716 char *new_env_pos
= new_env
+ env_name_len
+ 1;
718 // Iterate over colon-separated pieces of |dyld_insert_libraries|.
719 char *piece_start
= dyld_insert_libraries
;
720 char *piece_end
= NULL
;
721 char *old_env_end
= dyld_insert_libraries
+ old_env_len
;
723 if (piece_start
[0] == ':') piece_start
++;
724 piece_end
= internal_strchr(piece_start
, ':');
725 if (!piece_end
) piece_end
= dyld_insert_libraries
+ old_env_len
;
726 if ((uptr
)(piece_start
- dyld_insert_libraries
) > old_env_len
) break;
727 uptr piece_len
= piece_end
- piece_start
;
729 char *filename_start
=
730 (char *)internal_memrchr(piece_start
, '/', piece_len
);
731 uptr filename_len
= piece_len
;
732 if (filename_start
) {
734 filename_len
= piece_len
- (filename_start
- piece_start
);
736 filename_start
= piece_start
;
739 // If the current piece isn't the runtime library name,
740 // append it to new_env.
741 if ((dylib_name_len
!= filename_len
) ||
742 (internal_memcmp(filename_start
, dylib_name
, dylib_name_len
) != 0)) {
743 if (new_env_pos
!= new_env
+ env_name_len
+ 1) {
744 new_env_pos
[0] = ':';
747 internal_strncpy(new_env_pos
, piece_start
, piece_len
);
748 new_env_pos
+= piece_len
;
750 // Move on to the next piece.
751 piece_start
= piece_end
;
752 } while (piece_start
< old_env_end
);
754 // Can't use setenv() here, because it requires the allocator to be
756 // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in
757 // a separate function called after InitializeAllocator().
758 if (new_env_pos
== new_env
+ env_name_len
+ 1) new_env
= NULL
;
759 LeakyResetEnv(kDyldInsertLibraries
, new_env
);
761 #endif // SANITIZER_GO
764 return *_NSGetArgv();
767 uptr
FindAvailableMemoryRange(uptr shadow_size
,
770 typedef vm_region_submap_short_info_data_64_t RegionInfo
;
771 enum { kRegionInfoSize
= VM_REGION_SUBMAP_SHORT_INFO_COUNT_64
};
772 // Start searching for available memory region past PAGEZERO, which is
773 // 4KB on 32-bit and 4GB on 64-bit.
774 mach_vm_address_t start_address
=
775 (SANITIZER_WORDSIZE
== 32) ? 0x000000001000 : 0x000100000000;
777 mach_vm_address_t address
= start_address
;
778 mach_vm_address_t free_begin
= start_address
;
779 kern_return_t kr
= KERN_SUCCESS
;
780 while (kr
== KERN_SUCCESS
) {
781 mach_vm_size_t vmsize
= 0;
784 mach_msg_type_number_t count
= kRegionInfoSize
;
785 kr
= mach_vm_region_recurse(mach_task_self(), &address
, &vmsize
, &depth
,
786 (vm_region_info_t
)&vminfo
, &count
);
787 if (free_begin
!= address
) {
788 // We found a free region [free_begin..address-1].
789 uptr shadow_address
= RoundUpTo((uptr
)free_begin
+ left_padding
,
791 if (shadow_address
+ shadow_size
< (uptr
)address
) {
792 return shadow_address
;
795 // Move to the next region.
797 free_begin
= address
;
800 // We looked at all free regions and could not find one large enough.
804 // FIXME implement on this platform.
805 void GetMemoryProfile(fill_profile_f cb
, uptr
*stats
, uptr stats_size
) { }
807 void SignalContext::DumpAllRegisters(void *context
) {
808 Report("Register values:\n");
810 ucontext_t
*ucontext
= (ucontext_t
*)context
;
811 # define DUMPREG64(r) \
812 Printf("%s = 0x%016llx ", #r, ucontext->uc_mcontext->__ss.__ ## r);
813 # define DUMPREG32(r) \
814 Printf("%s = 0x%08x ", #r, ucontext->uc_mcontext->__ss.__ ## r);
815 # define DUMPREG_(r) Printf(" "); DUMPREG(r);
816 # define DUMPREG__(r) Printf(" "); DUMPREG(r);
817 # define DUMPREG___(r) Printf(" "); DUMPREG(r);
819 # if defined(__x86_64__)
820 # define DUMPREG(r) DUMPREG64(r)
821 DUMPREG(rax
); DUMPREG(rbx
); DUMPREG(rcx
); DUMPREG(rdx
); Printf("\n");
822 DUMPREG(rdi
); DUMPREG(rsi
); DUMPREG(rbp
); DUMPREG(rsp
); Printf("\n");
823 DUMPREG_(r8
); DUMPREG_(r9
); DUMPREG(r10
); DUMPREG(r11
); Printf("\n");
824 DUMPREG(r12
); DUMPREG(r13
); DUMPREG(r14
); DUMPREG(r15
); Printf("\n");
825 # elif defined(__i386__)
826 # define DUMPREG(r) DUMPREG32(r)
827 DUMPREG(eax
); DUMPREG(ebx
); DUMPREG(ecx
); DUMPREG(edx
); Printf("\n");
828 DUMPREG(edi
); DUMPREG(esi
); DUMPREG(ebp
); DUMPREG(esp
); Printf("\n");
829 # elif defined(__aarch64__)
830 # define DUMPREG(r) DUMPREG64(r)
831 DUMPREG_(x
[0]); DUMPREG_(x
[1]); DUMPREG_(x
[2]); DUMPREG_(x
[3]); Printf("\n");
832 DUMPREG_(x
[4]); DUMPREG_(x
[5]); DUMPREG_(x
[6]); DUMPREG_(x
[7]); Printf("\n");
833 DUMPREG_(x
[8]); DUMPREG_(x
[9]); DUMPREG(x
[10]); DUMPREG(x
[11]); Printf("\n");
834 DUMPREG(x
[12]); DUMPREG(x
[13]); DUMPREG(x
[14]); DUMPREG(x
[15]); Printf("\n");
835 DUMPREG(x
[16]); DUMPREG(x
[17]); DUMPREG(x
[18]); DUMPREG(x
[19]); Printf("\n");
836 DUMPREG(x
[20]); DUMPREG(x
[21]); DUMPREG(x
[22]); DUMPREG(x
[23]); Printf("\n");
837 DUMPREG(x
[24]); DUMPREG(x
[25]); DUMPREG(x
[26]); DUMPREG(x
[27]); Printf("\n");
838 DUMPREG(x
[28]); DUMPREG___(fp
); DUMPREG___(lr
); DUMPREG___(sp
); Printf("\n");
839 # elif defined(__arm__)
840 # define DUMPREG(r) DUMPREG32(r)
841 DUMPREG_(r
[0]); DUMPREG_(r
[1]); DUMPREG_(r
[2]); DUMPREG_(r
[3]); Printf("\n");
842 DUMPREG_(r
[4]); DUMPREG_(r
[5]); DUMPREG_(r
[6]); DUMPREG_(r
[7]); Printf("\n");
843 DUMPREG_(r
[8]); DUMPREG_(r
[9]); DUMPREG(r
[10]); DUMPREG(r
[11]); Printf("\n");
844 DUMPREG(r
[12]); DUMPREG___(sp
); DUMPREG___(lr
); DUMPREG___(pc
); Printf("\n");
846 # error "Unknown architecture"
857 static inline bool CompareBaseAddress(const LoadedModule
&a
,
858 const LoadedModule
&b
) {
859 return a
.base_address() < b
.base_address();
862 void FormatUUID(char *out
, uptr size
, const u8
*uuid
) {
863 internal_snprintf(out
, size
,
864 "<%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-"
865 "%02X%02X%02X%02X%02X%02X>",
866 uuid
[0], uuid
[1], uuid
[2], uuid
[3], uuid
[4], uuid
[5],
867 uuid
[6], uuid
[7], uuid
[8], uuid
[9], uuid
[10], uuid
[11],
868 uuid
[12], uuid
[13], uuid
[14], uuid
[15]);
871 void PrintModuleMap() {
872 Printf("Process module map:\n");
873 MemoryMappingLayout
memory_mapping(false);
874 InternalMmapVector
<LoadedModule
> modules(/*initial_capacity*/ 128);
875 memory_mapping
.DumpListOfModules(&modules
);
876 InternalSort(&modules
, modules
.size(), CompareBaseAddress
);
877 for (uptr i
= 0; i
< modules
.size(); ++i
) {
879 FormatUUID(uuid_str
, sizeof(uuid_str
), modules
[i
].uuid());
880 Printf("0x%zx-0x%zx %s (%s) %s\n", modules
[i
].base_address(),
881 modules
[i
].max_executable_address(), modules
[i
].full_name(),
882 ModuleArchToString(modules
[i
].arch()), uuid_str
);
884 Printf("End of module map.\n");
887 } // namespace __sanitizer
889 #endif // SANITIZER_MAC