Add support for ARMv8-R architecture
[official-gcc.git] / libsanitizer / sanitizer_common / sanitizer_mac.cc
blob2a05102e9682ccc6a3ea992637e6ec55f8689374
1 //===-- sanitizer_mac.cc --------------------------------------------------===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This file is shared between various sanitizers' runtime libraries and
9 // implements OSX-specific functions.
10 //===----------------------------------------------------------------------===//
12 #include "sanitizer_platform.h"
13 #if SANITIZER_MAC
14 #include "sanitizer_mac.h"
16 // Use 64-bit inodes in file operations. ASan does not support OS X 10.5, so
17 // the clients will most certainly use 64-bit ones as well.
18 #ifndef _DARWIN_USE_64_BIT_INODE
19 #define _DARWIN_USE_64_BIT_INODE 1
20 #endif
21 #include <stdio.h>
23 #include "sanitizer_common.h"
24 #include "sanitizer_flags.h"
25 #include "sanitizer_internal_defs.h"
26 #include "sanitizer_libc.h"
27 #include "sanitizer_placement_new.h"
28 #include "sanitizer_platform_limits_posix.h"
29 #include "sanitizer_procmaps.h"
31 #if !SANITIZER_IOS
32 #include <crt_externs.h> // for _NSGetEnviron
33 #else
34 extern char **environ;
35 #endif
37 #if defined(__has_include) && __has_include(<os/trace.h>) && defined(__BLOCKS__)
38 #define SANITIZER_OS_TRACE 1
39 #include <os/trace.h>
40 #else
41 #define SANITIZER_OS_TRACE 0
42 #endif
44 #if !SANITIZER_IOS
45 #include <crt_externs.h> // for _NSGetArgv and _NSGetEnviron
46 #else
47 extern "C" {
48 extern char ***_NSGetArgv(void);
50 #endif
52 #include <asl.h>
53 #include <dlfcn.h> // for dladdr()
54 #include <errno.h>
55 #include <fcntl.h>
56 #include <libkern/OSAtomic.h>
57 #include <mach-o/dyld.h>
58 #include <mach/mach.h>
59 #include <mach/vm_statistics.h>
60 #include <pthread.h>
61 #include <sched.h>
62 #include <signal.h>
63 #include <stdlib.h>
64 #include <sys/mman.h>
65 #include <sys/resource.h>
66 #include <sys/stat.h>
67 #include <sys/sysctl.h>
68 #include <sys/types.h>
69 #include <sys/wait.h>
70 #include <unistd.h>
71 #include <util.h>
73 // From <crt_externs.h>, but we don't have that file on iOS.
74 extern "C" {
75 extern char ***_NSGetArgv(void);
76 extern char ***_NSGetEnviron(void);
79 // From <mach/mach_vm.h>, but we don't have that file on iOS.
80 extern "C" {
81 extern kern_return_t mach_vm_region_recurse(
82 vm_map_t target_task,
83 mach_vm_address_t *address,
84 mach_vm_size_t *size,
85 natural_t *nesting_depth,
86 vm_region_recurse_info_t info,
87 mach_msg_type_number_t *infoCnt);
90 namespace __sanitizer {
92 #include "sanitizer_syscall_generic.inc"
94 // Direct syscalls, don't call libmalloc hooks (but not available on 10.6).
95 extern "C" void *__mmap(void *addr, size_t len, int prot, int flags, int fildes,
96 off_t off) SANITIZER_WEAK_ATTRIBUTE;
97 extern "C" int __munmap(void *, size_t) SANITIZER_WEAK_ATTRIBUTE;
99 // ---------------------- sanitizer_libc.h
100 uptr internal_mmap(void *addr, size_t length, int prot, int flags,
101 int fd, u64 offset) {
102 if (fd == -1) fd = VM_MAKE_TAG(VM_MEMORY_ANALYSIS_TOOL);
103 if (__mmap) return (uptr)__mmap(addr, length, prot, flags, fd, offset);
104 return (uptr)mmap(addr, length, prot, flags, fd, offset);
107 uptr internal_munmap(void *addr, uptr length) {
108 if (__munmap) return __munmap(addr, 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) {
117 return close(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) {
149 struct stat st;
150 if (internal_fstat(fd, &st))
151 return -1;
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) {
164 return unlink(path);
167 uptr internal_sched_yield() {
168 return sched_yield();
171 void internal__exit(int exitcode) {
172 _exit(exitcode);
175 unsigned int internal_sleep(unsigned int seconds) {
176 return sleep(seconds);
179 uptr internal_getpid() {
180 return 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 (but not available on 10.6).
196 extern "C" pid_t __fork(void) SANITIZER_WEAK_ATTRIBUTE;
198 int internal_fork() {
199 if (__fork)
200 return __fork();
201 return fork();
204 int internal_forkpty(int *amaster) {
205 int master, slave;
206 if (openpty(&master, &slave, nullptr, nullptr, nullptr) == -1) return -1;
207 int pid = internal_fork();
208 if (pid == -1) {
209 close(master);
210 close(slave);
211 return -1;
213 if (pid == 0) {
214 close(master);
215 if (login_tty(slave) != 0) {
216 // We already forked, there's not much we can do. Let's quit.
217 Report("login_tty failed (errno %d)\n", errno);
218 internal__exit(1);
220 } else {
221 *amaster = master;
222 close(slave);
224 return pid;
227 uptr internal_rename(const char *oldpath, const char *newpath) {
228 return rename(oldpath, newpath);
231 uptr internal_ftruncate(fd_t fd, uptr size) {
232 return ftruncate(fd, size);
235 uptr internal_execve(const char *filename, char *const argv[],
236 char *const envp[]) {
237 return execve(filename, argv, envp);
240 uptr internal_waitpid(int pid, int *status, int options) {
241 return waitpid(pid, status, options);
244 // ----------------- sanitizer_common.h
245 bool FileExists(const char *filename) {
246 struct stat st;
247 if (stat(filename, &st))
248 return false;
249 // Sanity check: filename is a regular file.
250 return S_ISREG(st.st_mode);
253 uptr GetTid() {
254 // FIXME: This can potentially get truncated on 32-bit, where uptr is 4 bytes.
255 uint64_t tid;
256 pthread_threadid_np(nullptr, &tid);
257 return tid;
260 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
261 uptr *stack_bottom) {
262 CHECK(stack_top);
263 CHECK(stack_bottom);
264 uptr stacksize = pthread_get_stacksize_np(pthread_self());
265 // pthread_get_stacksize_np() returns an incorrect stack size for the main
266 // thread on Mavericks. See
267 // https://github.com/google/sanitizers/issues/261
268 if ((GetMacosVersion() >= MACOS_VERSION_MAVERICKS) && at_initialization &&
269 stacksize == (1 << 19)) {
270 struct rlimit rl;
271 CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
272 // Most often rl.rlim_cur will be the desired 8M.
273 if (rl.rlim_cur < kMaxThreadStackSize) {
274 stacksize = rl.rlim_cur;
275 } else {
276 stacksize = kMaxThreadStackSize;
279 void *stackaddr = pthread_get_stackaddr_np(pthread_self());
280 *stack_top = (uptr)stackaddr;
281 *stack_bottom = *stack_top - stacksize;
284 char **GetEnviron() {
285 #if !SANITIZER_IOS
286 char ***env_ptr = _NSGetEnviron();
287 if (!env_ptr) {
288 Report("_NSGetEnviron() returned NULL. Please make sure __asan_init() is "
289 "called after libSystem_initializer().\n");
290 CHECK(env_ptr);
292 char **environ = *env_ptr;
293 #endif
294 CHECK(environ);
295 return environ;
298 const char *GetEnv(const char *name) {
299 char **env = GetEnviron();
300 uptr name_len = internal_strlen(name);
301 while (*env != 0) {
302 uptr len = internal_strlen(*env);
303 if (len > name_len) {
304 const char *p = *env;
305 if (!internal_memcmp(p, name, name_len) &&
306 p[name_len] == '=') { // Match.
307 return *env + name_len + 1; // String starting after =.
310 env++;
312 return 0;
315 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
316 CHECK_LE(kMaxPathLength, buf_len);
318 // On OS X the executable path is saved to the stack by dyld. Reading it
319 // from there is much faster than calling dladdr, especially for large
320 // binaries with symbols.
321 InternalScopedString exe_path(kMaxPathLength);
322 uint32_t size = exe_path.size();
323 if (_NSGetExecutablePath(exe_path.data(), &size) == 0 &&
324 realpath(exe_path.data(), buf) != 0) {
325 return internal_strlen(buf);
327 return 0;
330 uptr ReadLongProcessName(/*out*/char *buf, uptr buf_len) {
331 return ReadBinaryName(buf, buf_len);
334 void ReExec() {
335 UNIMPLEMENTED();
338 uptr GetPageSize() {
339 return sysconf(_SC_PAGESIZE);
342 BlockingMutex::BlockingMutex() {
343 internal_memset(this, 0, sizeof(*this));
346 void BlockingMutex::Lock() {
347 CHECK(sizeof(OSSpinLock) <= sizeof(opaque_storage_));
348 CHECK_EQ(OS_SPINLOCK_INIT, 0);
349 CHECK_NE(owner_, (uptr)pthread_self());
350 OSSpinLockLock((OSSpinLock*)&opaque_storage_);
351 CHECK(!owner_);
352 owner_ = (uptr)pthread_self();
355 void BlockingMutex::Unlock() {
356 CHECK(owner_ == (uptr)pthread_self());
357 owner_ = 0;
358 OSSpinLockUnlock((OSSpinLock*)&opaque_storage_);
361 void BlockingMutex::CheckLocked() {
362 CHECK_EQ((uptr)pthread_self(), owner_);
365 u64 NanoTime() {
366 return 0;
369 uptr GetTlsSize() {
370 return 0;
373 void InitTlsSize() {
376 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
377 uptr *tls_addr, uptr *tls_size) {
378 #if !SANITIZER_GO
379 uptr stack_top, stack_bottom;
380 GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
381 *stk_addr = stack_bottom;
382 *stk_size = stack_top - stack_bottom;
383 *tls_addr = 0;
384 *tls_size = 0;
385 #else
386 *stk_addr = 0;
387 *stk_size = 0;
388 *tls_addr = 0;
389 *tls_size = 0;
390 #endif
393 void ListOfModules::init() {
394 clear();
395 MemoryMappingLayout memory_mapping(false);
396 memory_mapping.DumpListOfModules(&modules_);
399 bool IsHandledDeadlySignal(int signum) {
400 if ((SANITIZER_WATCHOS || SANITIZER_TVOS) && !(SANITIZER_IOSSIM))
401 // Handling fatal signals on watchOS and tvOS devices is disallowed.
402 return false;
403 if (common_flags()->handle_abort && signum == SIGABRT)
404 return true;
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 };
412 char version[100];
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;
421 case '1': {
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;
428 default:
429 if (IsDigit(version[1]))
430 return MACOS_VERSION_UNKNOWN_NEWER;
431 else
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);
448 return result;
451 uptr GetRSS() {
452 struct task_basic_info info;
453 unsigned count = TASK_BASIC_INFO_COUNT;
454 kern_return_t result =
455 task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &count);
456 if (UNLIKELY(result != KERN_SUCCESS)) {
457 Report("Cannot get task info. Error: %d\n", result);
458 Die();
460 return info.resident_size;
463 void *internal_start_thread(void(*func)(void *arg), void *arg) {
464 // Start the thread with signals blocked, otherwise it can steal user signals.
465 __sanitizer_sigset_t set, old;
466 internal_sigfillset(&set);
467 internal_sigprocmask(SIG_SETMASK, &set, &old);
468 pthread_t th;
469 pthread_create(&th, 0, (void*(*)(void *arg))func, arg);
470 internal_sigprocmask(SIG_SETMASK, &old, 0);
471 return th;
474 void internal_join_thread(void *th) { pthread_join((pthread_t)th, 0); }
476 #if !SANITIZER_GO
477 static BlockingMutex syslog_lock(LINKER_INITIALIZED);
478 #endif
480 void WriteOneLineToSyslog(const char *s) {
481 #if !SANITIZER_GO
482 syslog_lock.CheckLocked();
483 asl_log(nullptr, nullptr, ASL_LEVEL_ERR, "%s", s);
484 #endif
487 void LogMessageOnPrintf(const char *str) {
488 // Log all printf output to CrashLog.
489 if (common_flags()->abort_on_error)
490 CRAppendCrashLogMessage(str);
493 void LogFullErrorReport(const char *buffer) {
494 #if !SANITIZER_GO
495 // Log with os_trace. This will make it into the crash log.
496 #if SANITIZER_OS_TRACE
497 if (GetMacosVersion() >= MACOS_VERSION_YOSEMITE) {
498 // os_trace requires the message (format parameter) to be a string literal.
499 if (internal_strncmp(SanitizerToolName, "AddressSanitizer",
500 sizeof("AddressSanitizer") - 1) == 0)
501 os_trace("Address Sanitizer reported a failure.");
502 else if (internal_strncmp(SanitizerToolName, "UndefinedBehaviorSanitizer",
503 sizeof("UndefinedBehaviorSanitizer") - 1) == 0)
504 os_trace("Undefined Behavior Sanitizer reported a failure.");
505 else if (internal_strncmp(SanitizerToolName, "ThreadSanitizer",
506 sizeof("ThreadSanitizer") - 1) == 0)
507 os_trace("Thread Sanitizer reported a failure.");
508 else
509 os_trace("Sanitizer tool reported a failure.");
511 if (common_flags()->log_to_syslog)
512 os_trace("Consult syslog for more information.");
514 #endif
516 // Log to syslog.
517 // The logging on OS X may call pthread_create so we need the threading
518 // environment to be fully initialized. Also, this should never be called when
519 // holding the thread registry lock since that may result in a deadlock. If
520 // the reporting thread holds the thread registry mutex, and asl_log waits
521 // for GCD to dispatch a new thread, the process will deadlock, because the
522 // pthread_create wrapper needs to acquire the lock as well.
523 BlockingMutexLock l(&syslog_lock);
524 if (common_flags()->log_to_syslog)
525 WriteToSyslog(buffer);
527 // The report is added to CrashLog as part of logging all of Printf output.
528 #endif
531 SignalContext::WriteFlag SignalContext::GetWriteFlag(void *context) {
532 #if defined(__x86_64__) || defined(__i386__)
533 ucontext_t *ucontext = static_cast<ucontext_t*>(context);
534 return ucontext->uc_mcontext->__es.__err & 2 /*T_PF_WRITE*/ ? WRITE : READ;
535 #else
536 return UNKNOWN;
537 #endif
540 void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
541 ucontext_t *ucontext = (ucontext_t*)context;
542 # if defined(__aarch64__)
543 *pc = ucontext->uc_mcontext->__ss.__pc;
544 # if defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
545 *bp = ucontext->uc_mcontext->__ss.__fp;
546 # else
547 *bp = ucontext->uc_mcontext->__ss.__lr;
548 # endif
549 *sp = ucontext->uc_mcontext->__ss.__sp;
550 # elif defined(__x86_64__)
551 *pc = ucontext->uc_mcontext->__ss.__rip;
552 *bp = ucontext->uc_mcontext->__ss.__rbp;
553 *sp = ucontext->uc_mcontext->__ss.__rsp;
554 # elif defined(__arm__)
555 *pc = ucontext->uc_mcontext->__ss.__pc;
556 *bp = ucontext->uc_mcontext->__ss.__r[7];
557 *sp = ucontext->uc_mcontext->__ss.__sp;
558 # elif defined(__i386__)
559 *pc = ucontext->uc_mcontext->__ss.__eip;
560 *bp = ucontext->uc_mcontext->__ss.__ebp;
561 *sp = ucontext->uc_mcontext->__ss.__esp;
562 # else
563 # error "Unknown architecture"
564 # endif
567 #if !SANITIZER_GO
568 static const char kDyldInsertLibraries[] = "DYLD_INSERT_LIBRARIES";
569 LowLevelAllocator allocator_for_env;
571 // Change the value of the env var |name|, leaking the original value.
572 // If |name_value| is NULL, the variable is deleted from the environment,
573 // otherwise the corresponding "NAME=value" string is replaced with
574 // |name_value|.
575 void LeakyResetEnv(const char *name, const char *name_value) {
576 char **env = GetEnviron();
577 uptr name_len = internal_strlen(name);
578 while (*env != 0) {
579 uptr len = internal_strlen(*env);
580 if (len > name_len) {
581 const char *p = *env;
582 if (!internal_memcmp(p, name, name_len) && p[name_len] == '=') {
583 // Match.
584 if (name_value) {
585 // Replace the old value with the new one.
586 *env = const_cast<char*>(name_value);
587 } else {
588 // Shift the subsequent pointers back.
589 char **del = env;
590 do {
591 del[0] = del[1];
592 } while (*del++);
596 env++;
600 SANITIZER_WEAK_CXX_DEFAULT_IMPL
601 bool ReexecDisabled() {
602 return false;
605 extern "C" SANITIZER_WEAK_ATTRIBUTE double dyldVersionNumber;
606 static const double kMinDyldVersionWithAutoInterposition = 360.0;
608 bool DyldNeedsEnvVariable() {
609 // Although sanitizer support was added to LLVM on OS X 10.7+, GCC users
610 // still may want use them on older systems. On older Darwin platforms, dyld
611 // doesn't export dyldVersionNumber symbol and we simply return true.
612 if (!&dyldVersionNumber) return true;
613 // If running on OS X 10.11+ or iOS 9.0+, dyld will interpose even if
614 // DYLD_INSERT_LIBRARIES is not set. However, checking OS version via
615 // GetMacosVersion() doesn't work for the simulator. Let's instead check
616 // `dyldVersionNumber`, which is exported by dyld, against a known version
617 // number from the first OS release where this appeared.
618 return dyldVersionNumber < kMinDyldVersionWithAutoInterposition;
621 void MaybeReexec() {
622 if (ReexecDisabled()) return;
624 // Make sure the dynamic runtime library is preloaded so that the
625 // wrappers work. If it is not, set DYLD_INSERT_LIBRARIES and re-exec
626 // ourselves.
627 Dl_info info;
628 RAW_CHECK(dladdr((void*)((uptr)&__sanitizer_report_error_summary), &info));
629 char *dyld_insert_libraries =
630 const_cast<char*>(GetEnv(kDyldInsertLibraries));
631 uptr old_env_len = dyld_insert_libraries ?
632 internal_strlen(dyld_insert_libraries) : 0;
633 uptr fname_len = internal_strlen(info.dli_fname);
634 const char *dylib_name = StripModuleName(info.dli_fname);
635 uptr dylib_name_len = internal_strlen(dylib_name);
637 bool lib_is_in_env = dyld_insert_libraries &&
638 internal_strstr(dyld_insert_libraries, dylib_name);
639 if (DyldNeedsEnvVariable() && !lib_is_in_env) {
640 // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
641 // library.
642 InternalScopedString program_name(1024);
643 uint32_t buf_size = program_name.size();
644 _NSGetExecutablePath(program_name.data(), &buf_size);
645 char *new_env = const_cast<char*>(info.dli_fname);
646 if (dyld_insert_libraries) {
647 // Append the runtime dylib name to the existing value of
648 // DYLD_INSERT_LIBRARIES.
649 new_env = (char*)allocator_for_env.Allocate(old_env_len + fname_len + 2);
650 internal_strncpy(new_env, dyld_insert_libraries, old_env_len);
651 new_env[old_env_len] = ':';
652 // Copy fname_len and add a trailing zero.
653 internal_strncpy(new_env + old_env_len + 1, info.dli_fname,
654 fname_len + 1);
655 // Ok to use setenv() since the wrappers don't depend on the value of
656 // asan_inited.
657 setenv(kDyldInsertLibraries, new_env, /*overwrite*/1);
658 } else {
659 // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name.
660 setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0);
662 VReport(1, "exec()-ing the program with\n");
663 VReport(1, "%s=%s\n", kDyldInsertLibraries, new_env);
664 VReport(1, "to enable wrappers.\n");
665 execv(program_name.data(), *_NSGetArgv());
667 // We get here only if execv() failed.
668 Report("ERROR: The process is launched without DYLD_INSERT_LIBRARIES, "
669 "which is required for the sanitizer to work. We tried to set the "
670 "environment variable and re-execute itself, but execv() failed, "
671 "possibly because of sandbox restrictions. Make sure to launch the "
672 "executable with:\n%s=%s\n", kDyldInsertLibraries, new_env);
673 RAW_CHECK("execv failed" && 0);
676 // Verify that interceptors really work. We'll use dlsym to locate
677 // "pthread_create", if interceptors are working, it should really point to
678 // "wrap_pthread_create" within our own dylib.
679 Dl_info info_pthread_create;
680 void *dlopen_addr = dlsym(RTLD_DEFAULT, "pthread_create");
681 RAW_CHECK(dladdr(dlopen_addr, &info_pthread_create));
682 if (internal_strcmp(info.dli_fname, info_pthread_create.dli_fname) != 0) {
683 Report(
684 "ERROR: Interceptors are not working. This may be because %s is "
685 "loaded too late (e.g. via dlopen). Please launch the executable "
686 "with:\n%s=%s\n",
687 SanitizerToolName, kDyldInsertLibraries, info.dli_fname);
688 RAW_CHECK("interceptors not installed" && 0);
691 if (!lib_is_in_env)
692 return;
694 // DYLD_INSERT_LIBRARIES is set and contains the runtime library. Let's remove
695 // the dylib from the environment variable, because interceptors are installed
696 // and we don't want our children to inherit the variable.
698 uptr env_name_len = internal_strlen(kDyldInsertLibraries);
699 // Allocate memory to hold the previous env var name, its value, the '='
700 // sign and the '\0' char.
701 char *new_env = (char*)allocator_for_env.Allocate(
702 old_env_len + 2 + env_name_len);
703 RAW_CHECK(new_env);
704 internal_memset(new_env, '\0', old_env_len + 2 + env_name_len);
705 internal_strncpy(new_env, kDyldInsertLibraries, env_name_len);
706 new_env[env_name_len] = '=';
707 char *new_env_pos = new_env + env_name_len + 1;
709 // Iterate over colon-separated pieces of |dyld_insert_libraries|.
710 char *piece_start = dyld_insert_libraries;
711 char *piece_end = NULL;
712 char *old_env_end = dyld_insert_libraries + old_env_len;
713 do {
714 if (piece_start[0] == ':') piece_start++;
715 piece_end = internal_strchr(piece_start, ':');
716 if (!piece_end) piece_end = dyld_insert_libraries + old_env_len;
717 if ((uptr)(piece_start - dyld_insert_libraries) > old_env_len) break;
718 uptr piece_len = piece_end - piece_start;
720 char *filename_start =
721 (char *)internal_memrchr(piece_start, '/', piece_len);
722 uptr filename_len = piece_len;
723 if (filename_start) {
724 filename_start += 1;
725 filename_len = piece_len - (filename_start - piece_start);
726 } else {
727 filename_start = piece_start;
730 // If the current piece isn't the runtime library name,
731 // append it to new_env.
732 if ((dylib_name_len != filename_len) ||
733 (internal_memcmp(filename_start, dylib_name, dylib_name_len) != 0)) {
734 if (new_env_pos != new_env + env_name_len + 1) {
735 new_env_pos[0] = ':';
736 new_env_pos++;
738 internal_strncpy(new_env_pos, piece_start, piece_len);
739 new_env_pos += piece_len;
741 // Move on to the next piece.
742 piece_start = piece_end;
743 } while (piece_start < old_env_end);
745 // Can't use setenv() here, because it requires the allocator to be
746 // initialized.
747 // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in
748 // a separate function called after InitializeAllocator().
749 if (new_env_pos == new_env + env_name_len + 1) new_env = NULL;
750 LeakyResetEnv(kDyldInsertLibraries, new_env);
752 #endif // SANITIZER_GO
754 char **GetArgv() {
755 return *_NSGetArgv();
758 uptr FindAvailableMemoryRange(uptr shadow_size,
759 uptr alignment,
760 uptr left_padding) {
761 typedef vm_region_submap_short_info_data_64_t RegionInfo;
762 enum { kRegionInfoSize = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64 };
763 // Start searching for available memory region past PAGEZERO, which is
764 // 4KB on 32-bit and 4GB on 64-bit.
765 mach_vm_address_t start_address =
766 (SANITIZER_WORDSIZE == 32) ? 0x000000001000 : 0x000100000000;
768 mach_vm_address_t address = start_address;
769 mach_vm_address_t free_begin = start_address;
770 kern_return_t kr = KERN_SUCCESS;
771 while (kr == KERN_SUCCESS) {
772 mach_vm_size_t vmsize = 0;
773 natural_t depth = 0;
774 RegionInfo vminfo;
775 mach_msg_type_number_t count = kRegionInfoSize;
776 kr = mach_vm_region_recurse(mach_task_self(), &address, &vmsize, &depth,
777 (vm_region_info_t)&vminfo, &count);
778 if (free_begin != address) {
779 // We found a free region [free_begin..address-1].
780 uptr shadow_address = RoundUpTo((uptr)free_begin + left_padding,
781 alignment);
782 if (shadow_address + shadow_size < (uptr)address) {
783 return shadow_address;
786 // Move to the next region.
787 address += vmsize;
788 free_begin = address;
791 // We looked at all free regions and could not find one large enough.
792 return 0;
795 // FIXME implement on this platform.
796 void GetMemoryProfile(fill_profile_f cb, uptr *stats, uptr stats_size) { }
798 } // namespace __sanitizer
800 #endif // SANITIZER_MAC