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>
74 namespace __sanitizer {
76 #include "sanitizer_syscall_generic.inc"
78 // ---------------------- sanitizer_libc.h
79 uptr internal_mmap(void *addr, size_t length, int prot, int flags,
81 if (fd == -1) fd = VM_MAKE_TAG(VM_MEMORY_ANALYSIS_TOOL);
82 return (uptr)mmap(addr, length, prot, flags, fd, offset);
85 uptr internal_munmap(void *addr, uptr length) {
86 return munmap(addr, length);
89 int internal_mprotect(void *addr, uptr length, int prot) {
90 return mprotect(addr, length, prot);
93 uptr internal_close(fd_t fd) {
97 uptr internal_open(const char *filename, int flags) {
98 return open(filename, flags);
101 uptr internal_open(const char *filename, int flags, u32 mode) {
102 return open(filename, flags, mode);
105 uptr internal_read(fd_t fd, void *buf, uptr count) {
106 return read(fd, buf, count);
109 uptr internal_write(fd_t fd, const void *buf, uptr count) {
110 return write(fd, buf, count);
113 uptr internal_stat(const char *path, void *buf) {
114 return stat(path, (struct stat *)buf);
117 uptr internal_lstat(const char *path, void *buf) {
118 return lstat(path, (struct stat *)buf);
121 uptr internal_fstat(fd_t fd, void *buf) {
122 return fstat(fd, (struct stat *)buf);
125 uptr internal_filesize(fd_t fd) {
127 if (internal_fstat(fd, &st))
129 return (uptr)st.st_size;
132 uptr internal_dup2(int oldfd, int newfd) {
133 return dup2(oldfd, newfd);
136 uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
137 return readlink(path, buf, bufsize);
140 uptr internal_unlink(const char *path) {
144 uptr internal_sched_yield() {
145 return sched_yield();
148 void internal__exit(int exitcode) {
152 uptr internal_getpid() {
156 int internal_sigaction(int signum, const void *act, void *oldact) {
157 return sigaction(signum,
158 (struct sigaction *)act, (struct sigaction *)oldact);
161 void internal_sigfillset(__sanitizer_sigset_t *set) { sigfillset(set); }
163 uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
164 __sanitizer_sigset_t *oldset) {
165 return sigprocmask(how, set, oldset);
168 // Doesn't call pthread_atfork() handlers.
169 extern "C" pid_t __fork(void);
171 int internal_fork() {
175 int internal_forkpty(int *amaster) {
177 if (openpty(&master, &slave, nullptr, nullptr, nullptr) == -1) return -1;
186 CHECK_EQ(login_tty(slave), 0);
194 uptr internal_rename(const char *oldpath, const char *newpath) {
195 return rename(oldpath, newpath);
198 uptr internal_ftruncate(fd_t fd, uptr size) {
199 return ftruncate(fd, size);
202 // ----------------- sanitizer_common.h
203 bool FileExists(const char *filename) {
205 if (stat(filename, &st))
207 // Sanity check: filename is a regular file.
208 return S_ISREG(st.st_mode);
212 return reinterpret_cast<uptr>(pthread_self());
215 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
216 uptr *stack_bottom) {
219 uptr stacksize = pthread_get_stacksize_np(pthread_self());
220 // pthread_get_stacksize_np() returns an incorrect stack size for the main
221 // thread on Mavericks. See
222 // https://github.com/google/sanitizers/issues/261
223 if ((GetMacosVersion() >= MACOS_VERSION_MAVERICKS) && at_initialization &&
224 stacksize == (1 << 19)) {
226 CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
227 // Most often rl.rlim_cur will be the desired 8M.
228 if (rl.rlim_cur < kMaxThreadStackSize) {
229 stacksize = rl.rlim_cur;
231 stacksize = kMaxThreadStackSize;
234 void *stackaddr = pthread_get_stackaddr_np(pthread_self());
235 *stack_top = (uptr)stackaddr;
236 *stack_bottom = *stack_top - stacksize;
239 char **GetEnviron() {
241 char ***env_ptr = _NSGetEnviron();
243 Report("_NSGetEnviron() returned NULL. Please make sure __asan_init() is "
244 "called after libSystem_initializer().\n");
247 char **environ = *env_ptr;
253 const char *GetEnv(const char *name) {
254 char **env = GetEnviron();
255 uptr name_len = internal_strlen(name);
257 uptr len = internal_strlen(*env);
258 if (len > name_len) {
259 const char *p = *env;
260 if (!internal_memcmp(p, name, name_len) &&
261 p[name_len] == '=') { // Match.
262 return *env + name_len + 1; // String starting after =.
270 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
271 CHECK_LE(kMaxPathLength, buf_len);
273 // On OS X the executable path is saved to the stack by dyld. Reading it
274 // from there is much faster than calling dladdr, especially for large
275 // binaries with symbols.
276 InternalScopedString exe_path(kMaxPathLength);
277 uint32_t size = exe_path.size();
278 if (_NSGetExecutablePath(exe_path.data(), &size) == 0 &&
279 realpath(exe_path.data(), buf) != 0) {
280 return internal_strlen(buf);
285 uptr ReadLongProcessName(/*out*/char *buf, uptr buf_len) {
286 return ReadBinaryName(buf, buf_len);
294 return sysconf(_SC_PAGESIZE);
297 BlockingMutex::BlockingMutex() {
298 internal_memset(this, 0, sizeof(*this));
301 void BlockingMutex::Lock() {
302 CHECK(sizeof(OSSpinLock) <= sizeof(opaque_storage_));
303 CHECK_EQ(OS_SPINLOCK_INIT, 0);
304 CHECK_NE(owner_, (uptr)pthread_self());
305 OSSpinLockLock((OSSpinLock*)&opaque_storage_);
307 owner_ = (uptr)pthread_self();
310 void BlockingMutex::Unlock() {
311 CHECK(owner_ == (uptr)pthread_self());
313 OSSpinLockUnlock((OSSpinLock*)&opaque_storage_);
316 void BlockingMutex::CheckLocked() {
317 CHECK_EQ((uptr)pthread_self(), owner_);
331 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
332 uptr *tls_addr, uptr *tls_size) {
334 uptr stack_top, stack_bottom;
335 GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
336 *stk_addr = stack_bottom;
337 *stk_size = stack_top - stack_bottom;
348 uptr GetListOfModules(LoadedModule *modules, uptr max_modules,
349 string_predicate_t filter) {
350 MemoryMappingLayout memory_mapping(false);
351 return memory_mapping.DumpListOfModules(modules, max_modules, filter);
354 bool IsDeadlySignal(int signum) {
355 return (signum == SIGSEGV || signum == SIGBUS) && common_flags()->handle_segv;
358 MacosVersion cached_macos_version = MACOS_VERSION_UNINITIALIZED;
360 MacosVersion GetMacosVersionInternal() {
361 int mib[2] = { CTL_KERN, KERN_OSRELEASE };
363 uptr len = 0, maxlen = sizeof(version) / sizeof(version[0]);
364 for (uptr i = 0; i < maxlen; i++) version[i] = '\0';
365 // Get the version length.
366 CHECK_NE(sysctl(mib, 2, 0, &len, 0, 0), -1);
367 CHECK_LT(len, maxlen);
368 CHECK_NE(sysctl(mib, 2, version, &len, 0, 0), -1);
369 switch (version[0]) {
370 case '9': return MACOS_VERSION_LEOPARD;
372 switch (version[1]) {
373 case '0': return MACOS_VERSION_SNOW_LEOPARD;
374 case '1': return MACOS_VERSION_LION;
375 case '2': return MACOS_VERSION_MOUNTAIN_LION;
376 case '3': return MACOS_VERSION_MAVERICKS;
377 case '4': return MACOS_VERSION_YOSEMITE;
379 if (IsDigit(version[1]))
380 return MACOS_VERSION_UNKNOWN_NEWER;
382 return MACOS_VERSION_UNKNOWN;
385 default: return MACOS_VERSION_UNKNOWN;
389 MacosVersion GetMacosVersion() {
390 atomic_uint32_t *cache =
391 reinterpret_cast<atomic_uint32_t*>(&cached_macos_version);
392 MacosVersion result =
393 static_cast<MacosVersion>(atomic_load(cache, memory_order_acquire));
394 if (result == MACOS_VERSION_UNINITIALIZED) {
395 result = GetMacosVersionInternal();
396 atomic_store(cache, result, memory_order_release);
402 struct task_basic_info info;
403 unsigned count = TASK_BASIC_INFO_COUNT;
404 kern_return_t result =
405 task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &count);
406 if (UNLIKELY(result != KERN_SUCCESS)) {
407 Report("Cannot get task info. Error: %d\n", result);
410 return info.resident_size;
413 void *internal_start_thread(void(*func)(void *arg), void *arg) {
414 // Start the thread with signals blocked, otherwise it can steal user signals.
415 __sanitizer_sigset_t set, old;
416 internal_sigfillset(&set);
417 internal_sigprocmask(SIG_SETMASK, &set, &old);
419 pthread_create(&th, 0, (void*(*)(void *arg))func, arg);
420 internal_sigprocmask(SIG_SETMASK, &old, 0);
424 void internal_join_thread(void *th) { pthread_join((pthread_t)th, 0); }
426 static BlockingMutex syslog_lock(LINKER_INITIALIZED);
428 void WriteOneLineToSyslog(const char *s) {
429 syslog_lock.CheckLocked();
430 asl_log(nullptr, nullptr, ASL_LEVEL_ERR, "%s", s);
433 void LogMessageOnPrintf(const char *str) {
434 // Log all printf output to CrashLog.
435 if (common_flags()->abort_on_error)
436 CRAppendCrashLogMessage(str);
439 void LogFullErrorReport(const char *buffer) {
440 // Log with os_trace. This will make it into the crash log.
441 #if SANITIZER_OS_TRACE
442 if (GetMacosVersion() >= MACOS_VERSION_YOSEMITE) {
443 // os_trace requires the message (format parameter) to be a string literal.
444 if (internal_strncmp(SanitizerToolName, "AddressSanitizer",
445 sizeof("AddressSanitizer") - 1) == 0)
446 os_trace("Address Sanitizer reported a failure.");
447 else if (internal_strncmp(SanitizerToolName, "UndefinedBehaviorSanitizer",
448 sizeof("UndefinedBehaviorSanitizer") - 1) == 0)
449 os_trace("Undefined Behavior Sanitizer reported a failure.");
450 else if (internal_strncmp(SanitizerToolName, "ThreadSanitizer",
451 sizeof("ThreadSanitizer") - 1) == 0)
452 os_trace("Thread Sanitizer reported a failure.");
454 os_trace("Sanitizer tool reported a failure.");
456 if (common_flags()->log_to_syslog)
457 os_trace("Consult syslog for more information.");
462 // The logging on OS X may call pthread_create so we need the threading
463 // environment to be fully initialized. Also, this should never be called when
464 // holding the thread registry lock since that may result in a deadlock. If
465 // the reporting thread holds the thread registry mutex, and asl_log waits
466 // for GCD to dispatch a new thread, the process will deadlock, because the
467 // pthread_create wrapper needs to acquire the lock as well.
468 BlockingMutexLock l(&syslog_lock);
469 if (common_flags()->log_to_syslog)
470 WriteToSyslog(buffer);
472 // The report is added to CrashLog as part of logging all of Printf output.
475 void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
476 ucontext_t *ucontext = (ucontext_t*)context;
477 # if defined(__aarch64__)
478 *pc = ucontext->uc_mcontext->__ss.__pc;
479 # if defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
480 *bp = ucontext->uc_mcontext->__ss.__fp;
482 *bp = ucontext->uc_mcontext->__ss.__lr;
484 *sp = ucontext->uc_mcontext->__ss.__sp;
485 # elif defined(__x86_64__)
486 *pc = ucontext->uc_mcontext->__ss.__rip;
487 *bp = ucontext->uc_mcontext->__ss.__rbp;
488 *sp = ucontext->uc_mcontext->__ss.__rsp;
489 # elif defined(__arm__)
490 *pc = ucontext->uc_mcontext->__ss.__pc;
491 *bp = ucontext->uc_mcontext->__ss.__r[7];
492 *sp = ucontext->uc_mcontext->__ss.__sp;
493 # elif defined(__i386__)
494 *pc = ucontext->uc_mcontext->__ss.__eip;
495 *bp = ucontext->uc_mcontext->__ss.__ebp;
496 *sp = ucontext->uc_mcontext->__ss.__esp;
498 # error "Unknown architecture"
502 static const char kDyldInsertLibraries[] = "DYLD_INSERT_LIBRARIES";
503 LowLevelAllocator allocator_for_env;
505 // Change the value of the env var |name|, leaking the original value.
506 // If |name_value| is NULL, the variable is deleted from the environment,
507 // otherwise the corresponding "NAME=value" string is replaced with
509 void LeakyResetEnv(const char *name, const char *name_value) {
510 char **env = GetEnviron();
511 uptr name_len = internal_strlen(name);
513 uptr len = internal_strlen(*env);
514 if (len > name_len) {
515 const char *p = *env;
516 if (!internal_memcmp(p, name, name_len) && p[name_len] == '=') {
519 // Replace the old value with the new one.
520 *env = const_cast<char*>(name_value);
522 // Shift the subsequent pointers back.
534 static bool reexec_disabled = false;
536 void DisableReexec() {
537 reexec_disabled = true;
540 extern "C" double dyldVersionNumber;
541 static const double kMinDyldVersionWithAutoInterposition = 360.0;
543 bool DyldNeedsEnvVariable() {
544 // If running on OS X 10.11+ or iOS 9.0+, dyld will interpose even if
545 // DYLD_INSERT_LIBRARIES is not set. However, checking OS version via
546 // GetMacosVersion() doesn't work for the simulator. Let's instead check
547 // `dyldVersionNumber`, which is exported by dyld, against a known version
548 // number from the first OS release where this appeared.
549 return dyldVersionNumber < kMinDyldVersionWithAutoInterposition;
553 if (reexec_disabled) return;
555 // Make sure the dynamic runtime library is preloaded so that the
556 // wrappers work. If it is not, set DYLD_INSERT_LIBRARIES and re-exec
559 CHECK(dladdr((void*)((uptr)&__sanitizer_report_error_summary), &info));
560 char *dyld_insert_libraries =
561 const_cast<char*>(GetEnv(kDyldInsertLibraries));
562 uptr old_env_len = dyld_insert_libraries ?
563 internal_strlen(dyld_insert_libraries) : 0;
564 uptr fname_len = internal_strlen(info.dli_fname);
565 const char *dylib_name = StripModuleName(info.dli_fname);
566 uptr dylib_name_len = internal_strlen(dylib_name);
568 bool lib_is_in_env = dyld_insert_libraries &&
569 internal_strstr(dyld_insert_libraries, dylib_name);
570 if (DyldNeedsEnvVariable() && !lib_is_in_env) {
571 // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
573 InternalScopedString program_name(1024);
574 uint32_t buf_size = program_name.size();
575 _NSGetExecutablePath(program_name.data(), &buf_size);
576 char *new_env = const_cast<char*>(info.dli_fname);
577 if (dyld_insert_libraries) {
578 // Append the runtime dylib name to the existing value of
579 // DYLD_INSERT_LIBRARIES.
580 new_env = (char*)allocator_for_env.Allocate(old_env_len + fname_len + 2);
581 internal_strncpy(new_env, dyld_insert_libraries, old_env_len);
582 new_env[old_env_len] = ':';
583 // Copy fname_len and add a trailing zero.
584 internal_strncpy(new_env + old_env_len + 1, info.dli_fname,
586 // Ok to use setenv() since the wrappers don't depend on the value of
588 setenv(kDyldInsertLibraries, new_env, /*overwrite*/1);
590 // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name.
591 setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0);
593 VReport(1, "exec()-ing the program with\n");
594 VReport(1, "%s=%s\n", kDyldInsertLibraries, new_env);
595 VReport(1, "to enable wrappers.\n");
596 execv(program_name.data(), *_NSGetArgv());
598 // We get here only if execv() failed.
599 Report("ERROR: The process is launched without DYLD_INSERT_LIBRARIES, "
600 "which is required for the sanitizer to work. We tried to set the "
601 "environment variable and re-execute itself, but execv() failed, "
602 "possibly because of sandbox restrictions. Make sure to launch the "
603 "executable with:\n%s=%s\n", kDyldInsertLibraries, new_env);
604 CHECK("execv failed" && 0);
610 // DYLD_INSERT_LIBRARIES is set and contains the runtime library. Let's remove
611 // the dylib from the environment variable, because interceptors are installed
612 // and we don't want our children to inherit the variable.
614 uptr env_name_len = internal_strlen(kDyldInsertLibraries);
615 // Allocate memory to hold the previous env var name, its value, the '='
616 // sign and the '\0' char.
617 char *new_env = (char*)allocator_for_env.Allocate(
618 old_env_len + 2 + env_name_len);
620 internal_memset(new_env, '\0', old_env_len + 2 + env_name_len);
621 internal_strncpy(new_env, kDyldInsertLibraries, env_name_len);
622 new_env[env_name_len] = '=';
623 char *new_env_pos = new_env + env_name_len + 1;
625 // Iterate over colon-separated pieces of |dyld_insert_libraries|.
626 char *piece_start = dyld_insert_libraries;
627 char *piece_end = NULL;
628 char *old_env_end = dyld_insert_libraries + old_env_len;
630 if (piece_start[0] == ':') piece_start++;
631 piece_end = internal_strchr(piece_start, ':');
632 if (!piece_end) piece_end = dyld_insert_libraries + old_env_len;
633 if ((uptr)(piece_start - dyld_insert_libraries) > old_env_len) break;
634 uptr piece_len = piece_end - piece_start;
636 char *filename_start =
637 (char *)internal_memrchr(piece_start, '/', piece_len);
638 uptr filename_len = piece_len;
639 if (filename_start) {
641 filename_len = piece_len - (filename_start - piece_start);
643 filename_start = piece_start;
646 // If the current piece isn't the runtime library name,
647 // append it to new_env.
648 if ((dylib_name_len != filename_len) ||
649 (internal_memcmp(filename_start, dylib_name, dylib_name_len) != 0)) {
650 if (new_env_pos != new_env + env_name_len + 1) {
651 new_env_pos[0] = ':';
654 internal_strncpy(new_env_pos, piece_start, piece_len);
655 new_env_pos += piece_len;
657 // Move on to the next piece.
658 piece_start = piece_end;
659 } while (piece_start < old_env_end);
661 // Can't use setenv() here, because it requires the allocator to be
663 // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in
664 // a separate function called after InitializeAllocator().
665 if (new_env_pos == new_env + env_name_len + 1) new_env = NULL;
666 LeakyResetEnv(kDyldInsertLibraries, new_env);
669 } // namespace __sanitizer
671 #endif // SANITIZER_MAC