1 //===-- sanitizer_linux.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 AddressSanitizer and ThreadSanitizer
11 // run-time libraries and implements linux-specific functions from
13 //===----------------------------------------------------------------------===//
15 #include "sanitizer_platform.h"
17 #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD || \
20 #include "sanitizer_common.h"
21 #include "sanitizer_flags.h"
22 #include "sanitizer_getauxval.h"
23 #include "sanitizer_internal_defs.h"
24 #include "sanitizer_libc.h"
25 #include "sanitizer_linux.h"
26 #include "sanitizer_mutex.h"
27 #include "sanitizer_placement_new.h"
28 #include "sanitizer_procmaps.h"
29 #include "sanitizer_stacktrace.h"
30 #include "sanitizer_symbolizer.h"
33 #include <asm/param.h>
40 // For mips64, syscall(__NR_stat) fills the buffer in the 'struct kernel_stat'
41 // format. Struct kernel_stat is defined as 'struct stat' in asm/stat.h. To
42 // access stat from asm/stat.h, without conflicting with definition in
43 // sys/stat.h, we use this trick.
45 #include <asm/unistd.h>
46 #include <sys/types.h>
47 #define stat kernel_stat
59 #if !SANITIZER_SOLARIS
60 #include <sys/ptrace.h>
62 #include <sys/resource.h>
64 #include <sys/syscall.h>
66 #include <sys/types.h>
71 #include <sys/utsname.h>
74 #if SANITIZER_LINUX && !SANITIZER_ANDROID
75 #include <sys/personality.h>
80 #include <sys/sysctl.h>
81 #include <machine/atomic.h>
83 // <sys/umtx.h> must be included after <errno.h> and <sys/types.h> on
84 // FreeBSD 9.2 and 10.0.
87 extern char **environ; // provided by crt1
88 #endif // SANITIZER_FREEBSD
91 #include <limits.h> // For NAME_MAX
92 #include <sys/sysctl.h>
93 extern char **environ; // provided by crt1
95 extern struct ps_strings *__ps_strings;
96 #endif // SANITIZER_NETBSD
102 extern char **_environ;
103 #define environ _environ
106 #if !SANITIZER_ANDROID
107 #include <sys/signal.h>
112 struct kernel_timeval {
117 // <linux/futex.h> is broken on some linux distributions.
118 const int FUTEX_WAIT = 0;
119 const int FUTEX_WAKE = 1;
120 #endif // SANITIZER_LINUX
122 // Are we using 32-bit or 64-bit Linux syscalls?
123 // x32 (which defines __x86_64__) has SANITIZER_WORDSIZE == 32
124 // but it still needs to use 64-bit syscalls.
125 #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__powerpc64__) || \
126 SANITIZER_WORDSIZE == 64)
127 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 1
129 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 0
132 #if defined(__x86_64__) || SANITIZER_MIPS64
134 extern void internal_sigreturn();
138 #if SANITIZER_LINUX && defined(__NR_getrandom)
139 # if !defined(GRND_NONBLOCK)
140 # define GRND_NONBLOCK 1
142 # define SANITIZER_USE_GETRANDOM 1
144 # define SANITIZER_USE_GETRANDOM 0
145 #endif // SANITIZER_LINUX && defined(__NR_getrandom)
147 namespace __sanitizer {
149 #if SANITIZER_LINUX && defined(__x86_64__)
150 #include "sanitizer_syscall_linux_x86_64.inc"
151 #elif SANITIZER_LINUX && defined(__aarch64__)
152 #include "sanitizer_syscall_linux_aarch64.inc"
153 #elif SANITIZER_LINUX && defined(__arm__)
154 #include "sanitizer_syscall_linux_arm.inc"
156 #include "sanitizer_syscall_generic.inc"
159 // --------------- sanitizer_libc.h
160 #if !SANITIZER_SOLARIS
162 uptr internal_mmap(void *addr, uptr length, int prot, int flags, int fd,
165 return internal_syscall_ptr(SYSCALL(mmap), addr, length, prot, flags, fd,
167 #elif SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
168 return internal_syscall(SYSCALL(mmap), (uptr)addr, length, prot, flags, fd,
171 // mmap2 specifies file offset in 4096-byte units.
172 CHECK(IsAligned(offset, 4096));
173 return internal_syscall(SYSCALL(mmap2), addr, length, prot, flags, fd,
177 #endif // !SANITIZER_S390
179 uptr internal_munmap(void *addr, uptr length) {
180 return internal_syscall_ptr(SYSCALL(munmap), (uptr)addr, length);
183 int internal_mprotect(void *addr, uptr length, int prot) {
184 return internal_syscall_ptr(SYSCALL(mprotect), (uptr)addr, length, prot);
187 uptr internal_close(fd_t fd) {
188 return internal_syscall(SYSCALL(close), fd);
191 uptr internal_open(const char *filename, int flags) {
192 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
193 return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags);
195 return internal_syscall_ptr(SYSCALL(open), (uptr)filename, flags);
199 uptr internal_open(const char *filename, int flags, u32 mode) {
200 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
201 return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags,
204 return internal_syscall_ptr(SYSCALL(open), (uptr)filename, flags, mode);
208 uptr internal_read(fd_t fd, void *buf, uptr count) {
210 HANDLE_EINTR(res, (sptr)internal_syscall_ptr(SYSCALL(read), fd, (uptr)buf,
215 uptr internal_write(fd_t fd, const void *buf, uptr count) {
217 HANDLE_EINTR(res, (sptr)internal_syscall_ptr(SYSCALL(write), fd, (uptr)buf,
222 uptr internal_ftruncate(fd_t fd, uptr size) {
225 HANDLE_EINTR(res, internal_syscall64(SYSCALL(ftruncate), fd, 0, (s64)size));
227 HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(ftruncate), fd,
233 #if !SANITIZER_LINUX_USES_64BIT_SYSCALLS && SANITIZER_LINUX
234 static void stat64_to_stat(struct stat64 *in, struct stat *out) {
235 internal_memset(out, 0, sizeof(*out));
236 out->st_dev = in->st_dev;
237 out->st_ino = in->st_ino;
238 out->st_mode = in->st_mode;
239 out->st_nlink = in->st_nlink;
240 out->st_uid = in->st_uid;
241 out->st_gid = in->st_gid;
242 out->st_rdev = in->st_rdev;
243 out->st_size = in->st_size;
244 out->st_blksize = in->st_blksize;
245 out->st_blocks = in->st_blocks;
246 out->st_atime = in->st_atime;
247 out->st_mtime = in->st_mtime;
248 out->st_ctime = in->st_ctime;
252 #if defined(__mips64)
253 // Undefine compatibility macros from <sys/stat.h>
254 // so that they would not clash with the kernel_stat
255 // st_[a|m|c]time fields
259 #if defined(SANITIZER_ANDROID)
260 // Bionic sys/stat.h defines additional macros
261 // for compatibility with the old NDKs and
262 // they clash with the kernel_stat structure
263 // st_[a|m|c]time_nsec fields.
268 static void kernel_stat_to_stat(struct kernel_stat *in, struct stat *out) {
269 internal_memset(out, 0, sizeof(*out));
270 out->st_dev = in->st_dev;
271 out->st_ino = in->st_ino;
272 out->st_mode = in->st_mode;
273 out->st_nlink = in->st_nlink;
274 out->st_uid = in->st_uid;
275 out->st_gid = in->st_gid;
276 out->st_rdev = in->st_rdev;
277 out->st_size = in->st_size;
278 out->st_blksize = in->st_blksize;
279 out->st_blocks = in->st_blocks;
280 #if defined(__USE_MISC) || \
281 defined(__USE_XOPEN2K8) || \
282 defined(SANITIZER_ANDROID)
283 out->st_atim.tv_sec = in->st_atime;
284 out->st_atim.tv_nsec = in->st_atime_nsec;
285 out->st_mtim.tv_sec = in->st_mtime;
286 out->st_mtim.tv_nsec = in->st_mtime_nsec;
287 out->st_ctim.tv_sec = in->st_ctime;
288 out->st_ctim.tv_nsec = in->st_ctime_nsec;
290 out->st_atime = in->st_atime;
291 out->st_atimensec = in->st_atime_nsec;
292 out->st_mtime = in->st_mtime;
293 out->st_mtimensec = in->st_mtime_nsec;
294 out->st_ctime = in->st_ctime;
295 out->st_atimensec = in->st_ctime_nsec;
300 uptr internal_stat(const char *path, void *buf) {
301 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
302 return internal_syscall_ptr(SYSCALL(fstatat), AT_FDCWD, (uptr)path,
304 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
305 return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path,
307 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
308 # if defined(__mips64)
309 // For mips64, stat syscall fills buffer in the format of kernel_stat
310 struct kernel_stat kbuf;
311 int res = internal_syscall(SYSCALL(stat), path, &kbuf);
312 kernel_stat_to_stat(&kbuf, (struct stat *)buf);
315 return internal_syscall(SYSCALL(stat), (uptr)path, (uptr)buf);
319 int res = internal_syscall(SYSCALL(stat64), path, &buf64);
320 stat64_to_stat(&buf64, (struct stat *)buf);
325 uptr internal_lstat(const char *path, void *buf) {
327 return internal_syscall_ptr(SYSCALL(lstat), path, buf);
328 #elif SANITIZER_FREEBSD
329 return internal_syscall(SYSCALL(fstatat), AT_FDCWD, (uptr)path,
330 (uptr)buf, AT_SYMLINK_NOFOLLOW);
331 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
332 return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path,
333 (uptr)buf, AT_SYMLINK_NOFOLLOW);
334 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
335 # if SANITIZER_MIPS64
336 // For mips64, lstat syscall fills buffer in the format of kernel_stat
337 struct kernel_stat kbuf;
338 int res = internal_syscall(SYSCALL(lstat), path, &kbuf);
339 kernel_stat_to_stat(&kbuf, (struct stat *)buf);
342 return internal_syscall(SYSCALL(lstat), (uptr)path, (uptr)buf);
346 int res = internal_syscall(SYSCALL(lstat64), path, &buf64);
347 stat64_to_stat(&buf64, (struct stat *)buf);
352 uptr internal_fstat(fd_t fd, void *buf) {
353 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
354 # if SANITIZER_MIPS64 && !SANITIZER_NETBSD
355 // For mips64, fstat syscall fills buffer in the format of kernel_stat
356 struct kernel_stat kbuf;
357 int res = internal_syscall(SYSCALL(fstat), fd, &kbuf);
358 kernel_stat_to_stat(&kbuf, (struct stat *)buf);
361 return internal_syscall_ptr(SYSCALL(fstat), fd, (uptr)buf);
365 int res = internal_syscall(SYSCALL(fstat64), fd, &buf64);
366 stat64_to_stat(&buf64, (struct stat *)buf);
371 uptr internal_filesize(fd_t fd) {
373 if (internal_fstat(fd, &st))
375 return (uptr)st.st_size;
378 uptr internal_dup2(int oldfd, int newfd) {
379 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
380 return internal_syscall(SYSCALL(dup3), oldfd, newfd, 0);
382 return internal_syscall(SYSCALL(dup2), oldfd, newfd);
386 uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
387 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
388 return internal_syscall(SYSCALL(readlinkat), AT_FDCWD,
389 (uptr)path, (uptr)buf, bufsize);
391 return internal_syscall_ptr(SYSCALL(readlink), path, buf, bufsize);
395 uptr internal_unlink(const char *path) {
396 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
397 return internal_syscall(SYSCALL(unlinkat), AT_FDCWD, (uptr)path, 0);
399 return internal_syscall_ptr(SYSCALL(unlink), (uptr)path);
403 uptr internal_rename(const char *oldpath, const char *newpath) {
404 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
405 return internal_syscall(SYSCALL(renameat), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
408 return internal_syscall_ptr(SYSCALL(rename), (uptr)oldpath, (uptr)newpath);
412 uptr internal_sched_yield() {
413 return internal_syscall(SYSCALL(sched_yield));
416 void internal__exit(int exitcode) {
417 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
418 internal_syscall(SYSCALL(exit), exitcode);
420 internal_syscall(SYSCALL(exit_group), exitcode);
422 Die(); // Unreachable.
425 unsigned int internal_sleep(unsigned int seconds) {
429 int res = internal_syscall_ptr(SYSCALL(nanosleep), &ts, &ts);
430 if (res) return ts.tv_sec;
434 uptr internal_execve(const char *filename, char *const argv[],
435 char *const envp[]) {
436 return internal_syscall_ptr(SYSCALL(execve), (uptr)filename, (uptr)argv,
439 #endif // !SANITIZER_SOLARIS
441 // ----------------- sanitizer_common.h
442 bool FileExists(const char *filename) {
444 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
445 if (internal_syscall(SYSCALL(newfstatat), AT_FDCWD, filename, &st, 0))
447 if (internal_stat(filename, &st))
450 // Sanity check: filename is a regular file.
451 return S_ISREG(st.st_mode);
455 #if SANITIZER_FREEBSD
456 return (uptr)pthread_self();
457 #elif SANITIZER_NETBSD
459 #elif SANITIZER_SOLARIS
460 return (uptr)thr_self();
462 return internal_syscall(SYSCALL(gettid));
466 #if !SANITIZER_SOLARIS
468 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
473 internal_memset(&tv, 0, sizeof(tv));
474 internal_syscall_ptr(SYSCALL(gettimeofday), &tv, 0);
475 return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
478 uptr internal_clock_gettime(__sanitizer_clockid_t clk_id, void *tp) {
479 return internal_syscall_ptr(SYSCALL(clock_gettime), clk_id, tp);
481 #endif // !SANITIZER_SOLARIS
483 // Like getenv, but reads env directly from /proc (on Linux) or parses the
484 // 'environ' array (on some others) and does not use libc. This function
485 // should be called first inside __asan_init.
486 const char *GetEnv(const char *name) {
487 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_SOLARIS
488 if (::environ != 0) {
489 uptr NameLen = internal_strlen(name);
490 for (char **Env = ::environ; *Env != 0; Env++) {
491 if (internal_strncmp(*Env, name, NameLen) == 0 && (*Env)[NameLen] == '=')
492 return (*Env) + NameLen + 1;
495 return 0; // Not found.
496 #elif SANITIZER_LINUX
497 static char *environ;
503 if (!ReadFileToBuffer("/proc/self/environ", &environ, &environ_size, &len))
506 if (!environ || len == 0) return nullptr;
507 uptr namelen = internal_strlen(name);
508 const char *p = environ;
509 while (*p != '\0') { // will happen at the \0\0 that terminates the buffer
510 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
512 (char*)internal_memchr(p, '\0', len - (p - environ));
513 if (!endp) // this entry isn't NUL terminated
515 else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') // Match.
516 return p + namelen + 1; // point after =
519 return nullptr; // Not found.
521 #error "Unsupported platform"
525 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
527 SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
531 #if !SANITIZER_GO && !SANITIZER_FREEBSD && !SANITIZER_NETBSD
532 static void ReadNullSepFileToArray(const char *path, char ***arr,
537 *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
538 if (!ReadFileToBuffer(path, &buff, &buff_size, &buff_len, 1024 * 1024)) {
544 for (count = 1, i = 1; ; i++) {
546 if (buff[i+1] == 0) break;
547 (*arr)[count] = &buff[i+1];
548 CHECK_LE(count, arr_size - 1); // FIXME: make this more flexible.
552 (*arr)[count] = nullptr;
556 static void GetArgsAndEnv(char ***argv, char ***envp) {
557 #if SANITIZER_FREEBSD
558 // On FreeBSD, retrieving the argument and environment arrays is done via the
559 // kern.ps_strings sysctl, which returns a pointer to a structure containing
560 // this information. See also <sys/exec.h>.
562 size_t sz = sizeof(pss);
563 if (sysctlbyname("kern.ps_strings", &pss, &sz, NULL, 0) == -1) {
564 Printf("sysctl kern.ps_strings failed\n");
567 *argv = pss->ps_argvstr;
568 *envp = pss->ps_envstr;
569 #elif SANITIZER_NETBSD
570 *argv = __ps_strings->ps_argvstr;
571 *argv = __ps_strings->ps_envstr;
574 if (&__libc_stack_end) {
576 uptr* stack_end = (uptr*)__libc_stack_end;
577 int argc = *stack_end;
578 *argv = (char**)(stack_end + 1);
579 *envp = (char**)(stack_end + argc + 2);
582 static const int kMaxArgv = 2000, kMaxEnvp = 2000;
583 ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
584 ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
592 GetArgsAndEnv(&argv, &envp);
598 const char *pathname = "/proc/self/exe";
601 static const int name[] = {
602 CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME,
608 if (sysctl(name, ARRAY_SIZE(name), path, &len, NULL, 0) != -1)
610 #elif SANITIZER_SOLARIS
611 pathname = getexecname();
612 CHECK_NE(pathname, NULL);
615 GetArgsAndEnv(&argv, &envp);
616 uptr rv = internal_execve(pathname, argv, envp);
618 CHECK_EQ(internal_iserror(rv, &rverrno), true);
619 Printf("execve failed, errno %d\n", rverrno);
623 #if !SANITIZER_SOLARIS
630 BlockingMutex::BlockingMutex() {
631 internal_memset(this, 0, sizeof(*this));
634 void BlockingMutex::Lock() {
636 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
637 if (atomic_exchange(m, MtxLocked, memory_order_acquire) == MtxUnlocked)
639 while (atomic_exchange(m, MtxSleeping, memory_order_acquire) != MtxUnlocked) {
640 #if SANITIZER_FREEBSD
641 _umtx_op(m, UMTX_OP_WAIT_UINT, MtxSleeping, 0, 0);
642 #elif SANITIZER_NETBSD
643 sched_yield(); /* No userspace futex-like synchronization */
645 internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAIT, MtxSleeping, 0, 0, 0);
650 void BlockingMutex::Unlock() {
651 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
652 u32 v = atomic_exchange(m, MtxUnlocked, memory_order_release);
653 CHECK_NE(v, MtxUnlocked);
654 if (v == MtxSleeping) {
655 #if SANITIZER_FREEBSD
656 _umtx_op(m, UMTX_OP_WAKE, 1, 0, 0);
657 #elif SANITIZER_NETBSD
658 /* No userspace futex-like synchronization */
660 internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAKE, 1, 0, 0, 0);
665 void BlockingMutex::CheckLocked() {
666 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
667 CHECK_NE(MtxUnlocked, atomic_load(m, memory_order_relaxed));
669 #endif // !SANITIZER_SOLARIS
671 // ----------------- sanitizer_linux.h
672 // The actual size of this structure is specified by d_reclen.
673 // Note that getdents64 uses a different structure format. We only provide the
674 // 32-bit syscall here.
676 // struct dirent is different for Linux and us. At this moment, we use only
677 // d_fileno (Linux call this d_ino), d_reclen, and d_name.
678 struct linux_dirent {
679 u64 d_ino; // d_fileno
681 u16 d_namlen; // not used
682 u8 d_type; // not used
683 char d_name[NAME_MAX + 1];
686 struct linux_dirent {
687 #if SANITIZER_X32 || defined(__aarch64__)
694 unsigned short d_reclen;
696 unsigned char d_type;
702 #if !SANITIZER_SOLARIS
704 uptr internal_ptrace(int request, int pid, void *addr, void *data) {
706 // XXX We need additional work for ptrace:
707 // - for request, we use PT_FOO whereas Linux uses PTRACE_FOO
708 // - data is int for us, but void * for Linux
709 // - Linux sometimes uses data in the case where we use addr instead
710 // At this moment, this function is used only within
711 // "#if SANITIZER_LINUX && defined(__x86_64__)" block in
712 // sanitizer_stoptheworld_linux_libcdep.cc.
713 return internal_syscall_ptr(SYSCALL(ptrace), request, pid, (uptr)addr,
716 return internal_syscall(SYSCALL(ptrace), request, pid, (uptr)addr,
721 uptr internal_waitpid(int pid, int *status, int options) {
722 return internal_syscall_ptr(SYSCALL(wait4), pid, (uptr)status, options,
726 uptr internal_getpid() {
727 return internal_syscall(SYSCALL(getpid));
730 uptr internal_getppid() {
731 return internal_syscall(SYSCALL(getppid));
734 uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) {
735 #if SANITIZER_FREEBSD
736 return internal_syscall(SYSCALL(getdirentries), fd, (uptr)dirp, count, NULL);
737 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
738 return internal_syscall(SYSCALL(getdents64), fd, (uptr)dirp, count);
740 return internal_syscall_ptr(SYSCALL(getdents), fd, (uptr)dirp, count);
744 uptr internal_lseek(fd_t fd, OFF_T offset, int whence) {
746 return internal_syscall64(SYSCALL(lseek), fd, 0, offset, whence);
748 return internal_syscall(SYSCALL(lseek), fd, offset, whence);
753 uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
754 return internal_syscall(SYSCALL(prctl), option, arg2, arg3, arg4, arg5);
758 uptr internal_sigaltstack(const void *ss, void *oss) {
759 return internal_syscall_ptr(SYSCALL(sigaltstack), (uptr)ss, (uptr)oss);
762 int internal_fork() {
763 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
764 return internal_syscall(SYSCALL(clone), SIGCHLD, 0);
766 return internal_syscall(SYSCALL(fork));
771 #define SA_RESTORER 0x04000000
772 // Doesn't set sa_restorer if the caller did not set it, so use with caution
774 int internal_sigaction_norestorer(int signum, const void *act, void *oldact) {
775 __sanitizer_kernel_sigaction_t k_act, k_oldact;
776 internal_memset(&k_act, 0, sizeof(__sanitizer_kernel_sigaction_t));
777 internal_memset(&k_oldact, 0, sizeof(__sanitizer_kernel_sigaction_t));
778 const __sanitizer_sigaction *u_act = (const __sanitizer_sigaction *)act;
779 __sanitizer_sigaction *u_oldact = (__sanitizer_sigaction *)oldact;
781 k_act.handler = u_act->handler;
782 k_act.sigaction = u_act->sigaction;
783 internal_memcpy(&k_act.sa_mask, &u_act->sa_mask,
784 sizeof(__sanitizer_kernel_sigset_t));
785 // Without SA_RESTORER kernel ignores the calls (probably returns EINVAL).
786 k_act.sa_flags = u_act->sa_flags | SA_RESTORER;
787 // FIXME: most often sa_restorer is unset, however the kernel requires it
788 // to point to a valid signal restorer that calls the rt_sigreturn syscall.
789 // If sa_restorer passed to the kernel is NULL, the program may crash upon
790 // signal delivery or fail to unwind the stack in the signal handler.
791 // libc implementation of sigaction() passes its own restorer to
792 // rt_sigaction, so we need to do the same (we'll need to reimplement the
793 // restorers; for x86_64 the restorer address can be obtained from
794 // oldact->sa_restorer upon a call to sigaction(xxx, NULL, oldact).
795 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
796 k_act.sa_restorer = u_act->sa_restorer;
800 uptr result = internal_syscall(SYSCALL(rt_sigaction), (uptr)signum,
801 (uptr)(u_act ? &k_act : nullptr),
802 (uptr)(u_oldact ? &k_oldact : nullptr),
803 (uptr)sizeof(__sanitizer_kernel_sigset_t));
805 if ((result == 0) && u_oldact) {
806 u_oldact->handler = k_oldact.handler;
807 u_oldact->sigaction = k_oldact.sigaction;
808 internal_memcpy(&u_oldact->sa_mask, &k_oldact.sa_mask,
809 sizeof(__sanitizer_kernel_sigset_t));
810 u_oldact->sa_flags = k_oldact.sa_flags;
811 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
812 u_oldact->sa_restorer = k_oldact.sa_restorer;
818 // Invokes sigaction via a raw syscall with a restorer, but does not support
819 // all platforms yet.
820 // We disable for Go simply because we have not yet added to buildgo.sh.
821 #if (defined(__x86_64__) || SANITIZER_MIPS64) && !SANITIZER_GO
822 int internal_sigaction_syscall(int signum, const void *act, void *oldact) {
824 return internal_sigaction_norestorer(signum, act, oldact);
825 __sanitizer_sigaction u_adjust;
826 internal_memcpy(&u_adjust, act, sizeof(u_adjust));
827 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
828 if (u_adjust.sa_restorer == nullptr) {
829 u_adjust.sa_restorer = internal_sigreturn;
832 return internal_sigaction_norestorer(signum, (const void *)&u_adjust,
835 #endif // defined(__x86_64__) && !SANITIZER_GO
836 #endif // SANITIZER_LINUX
838 uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
839 __sanitizer_sigset_t *oldset) {
840 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
841 return internal_syscall_ptr(SYSCALL(sigprocmask), how, set, oldset);
843 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
844 __sanitizer_kernel_sigset_t *k_oldset = (__sanitizer_kernel_sigset_t *)oldset;
845 return internal_syscall(SYSCALL(rt_sigprocmask), (uptr)how,
846 (uptr)&k_set->sig[0], (uptr)&k_oldset->sig[0],
847 sizeof(__sanitizer_kernel_sigset_t));
851 void internal_sigfillset(__sanitizer_sigset_t *set) {
852 internal_memset(set, 0xff, sizeof(*set));
855 void internal_sigemptyset(__sanitizer_sigset_t *set) {
856 internal_memset(set, 0, sizeof(*set));
860 void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
863 CHECK_LT(signum, sizeof(*set) * 8);
864 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
865 const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
866 const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
867 k_set->sig[idx] &= ~(1 << bit);
870 bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
873 CHECK_LT(signum, sizeof(*set) * 8);
874 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
875 const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
876 const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
877 return k_set->sig[idx] & (1 << bit);
879 #endif // SANITIZER_LINUX
880 #endif // !SANITIZER_SOLARIS
882 // ThreadLister implementation.
883 ThreadLister::ThreadLister(int pid)
888 entry_((struct linux_dirent *)buffer_.data()),
890 char task_directory_path[80];
891 internal_snprintf(task_directory_path, sizeof(task_directory_path),
892 "/proc/%d/task/", pid);
893 uptr openrv = internal_open(task_directory_path, O_RDONLY | O_DIRECTORY);
894 if (internal_iserror(openrv)) {
896 Report("Can't open /proc/%d/task for reading.\n", pid);
899 descriptor_ = openrv;
903 int ThreadLister::GetNextTID() {
908 if ((char *)entry_ >= &buffer_[bytes_read_] && !GetDirectoryEntries())
910 if (entry_->d_ino != 0 && entry_->d_name[0] >= '0' &&
911 entry_->d_name[0] <= '9') {
912 // Found a valid tid.
913 tid = (int)internal_atoll(entry_->d_name);
915 entry_ = (struct linux_dirent *)(((char *)entry_) + entry_->d_reclen);
920 void ThreadLister::Reset() {
921 if (error_ || descriptor_ < 0)
923 internal_lseek(descriptor_, 0, SEEK_SET);
926 ThreadLister::~ThreadLister() {
927 if (descriptor_ >= 0)
928 internal_close(descriptor_);
931 bool ThreadLister::error() { return error_; }
933 bool ThreadLister::GetDirectoryEntries() {
934 CHECK_GE(descriptor_, 0);
935 CHECK_NE(error_, true);
936 bytes_read_ = internal_getdents(descriptor_,
937 (struct linux_dirent *)buffer_.data(),
939 if (internal_iserror(bytes_read_)) {
940 Report("Can't read directory entries from /proc/%d/task.\n", pid_);
943 } else if (bytes_read_ == 0) {
946 entry_ = (struct linux_dirent *)buffer_.data();
950 #if SANITIZER_WORDSIZE == 32
951 // Take care of unusable kernel area in top gigabyte.
952 static uptr GetKernelAreaSize() {
953 #if SANITIZER_LINUX && !SANITIZER_X32
954 const uptr gbyte = 1UL << 30;
956 // Firstly check if there are writable segments
957 // mapped to top gigabyte (e.g. stack).
958 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
959 MemoryMappedSegment segment;
960 while (proc_maps.Next(&segment)) {
961 if ((segment.end >= 3 * gbyte) && segment.IsWritable()) return 0;
964 #if !SANITIZER_ANDROID
965 // Even if nothing is mapped, top Gb may still be accessible
966 // if we are running on 64-bit kernel.
967 // Uname may report misleading results if personality type
968 // is modified (e.g. under schroot) so check this as well.
969 struct utsname uname_info;
970 int pers = personality(0xffffffffUL);
971 if (!(pers & PER_MASK)
972 && uname(&uname_info) == 0
973 && internal_strstr(uname_info.machine, "64"))
975 #endif // SANITIZER_ANDROID
977 // Top gigabyte is reserved for kernel.
981 #endif // SANITIZER_LINUX && !SANITIZER_X32
983 #endif // SANITIZER_WORDSIZE == 32
985 uptr GetMaxVirtualAddress() {
986 #if SANITIZER_NETBSD && defined(__x86_64__)
987 return 0x7f7ffffff000ULL; // (0x00007f8000000000 - PAGE_SIZE)
988 #elif SANITIZER_WORDSIZE == 64
989 # if defined(__powerpc64__) || defined(__aarch64__)
990 // On PowerPC64 we have two different address space layouts: 44- and 46-bit.
991 // We somehow need to figure out which one we are using now and choose
992 // one of 0x00000fffffffffffUL and 0x00003fffffffffffUL.
993 // Note that with 'ulimit -s unlimited' the stack is moved away from the top
994 // of the address space, so simply checking the stack address is not enough.
995 // This should (does) work for both PowerPC64 Endian modes.
996 // Similarly, aarch64 has multiple address space layouts: 39, 42 and 47-bit.
997 return (1ULL << (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1)) - 1;
998 # elif defined(__mips64)
999 return (1ULL << 40) - 1; // 0x000000ffffffffffUL;
1000 # elif defined(__s390x__)
1001 return (1ULL << 53) - 1; // 0x001fffffffffffffUL;
1003 return (1ULL << 47) - 1; // 0x00007fffffffffffUL;
1005 #else // SANITIZER_WORDSIZE == 32
1006 # if defined(__s390__)
1007 return (1ULL << 31) - 1; // 0x7fffffff;
1009 return (1ULL << 32) - 1; // 0xffffffff;
1011 #endif // SANITIZER_WORDSIZE
1014 uptr GetMaxUserVirtualAddress() {
1015 uptr addr = GetMaxVirtualAddress();
1016 #if SANITIZER_WORDSIZE == 32 && !defined(__s390__)
1017 if (!common_flags()->full_address_space)
1018 addr -= GetKernelAreaSize();
1019 CHECK_LT(reinterpret_cast<uptr>(&addr), addr);
1024 uptr GetPageSize() {
1025 // Android post-M sysconf(_SC_PAGESIZE) crashes if called from .preinit_array.
1026 #if SANITIZER_ANDROID
1028 #elif SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__))
1029 return EXEC_PAGESIZE;
1030 #elif SANITIZER_USE_GETAUXVAL
1031 return getauxval(AT_PAGESZ);
1033 return sysconf(_SC_PAGESIZE); // EXEC_PAGESIZE may not be trustworthy.
1037 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
1038 #if SANITIZER_SOLARIS
1039 const char *default_module_name = getexecname();
1040 CHECK_NE(default_module_name, NULL);
1041 return internal_snprintf(buf, buf_len, "%s", default_module_name);
1043 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
1044 #if SANITIZER_FREEBSD
1045 const int Mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
1047 const int Mib[4] = {CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME};
1049 const char *default_module_name = "kern.proc.pathname";
1050 size_t Size = buf_len;
1051 bool IsErr = (sysctl(Mib, ARRAY_SIZE(Mib), buf, &Size, NULL, 0) != 0);
1052 int readlink_error = IsErr ? errno : 0;
1053 uptr module_name_len = Size;
1055 const char *default_module_name = "/proc/self/exe";
1056 uptr module_name_len = internal_readlink(
1057 default_module_name, buf, buf_len);
1059 bool IsErr = internal_iserror(module_name_len, &readlink_error);
1060 #endif // SANITIZER_SOLARIS
1062 // We can't read binary name for some reason, assume it's unknown.
1063 Report("WARNING: reading executable name failed with errno %d, "
1064 "some stack frames may not be symbolized\n", readlink_error);
1065 module_name_len = internal_snprintf(buf, buf_len, "%s",
1066 default_module_name);
1067 CHECK_LT(module_name_len, buf_len);
1069 return module_name_len;
1073 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len) {
1078 if (ReadFileToBuffer("/proc/self/cmdline", &tmpbuf, &tmpsize, &tmplen,
1080 internal_strncpy(buf, tmpbuf, buf_len);
1081 UnmapOrDie(tmpbuf, tmpsize);
1082 return internal_strlen(buf);
1085 return ReadBinaryName(buf, buf_len);
1088 // Match full names of the form /path/to/base_name{-,.}*
1089 bool LibraryNameIs(const char *full_name, const char *base_name) {
1090 const char *name = full_name;
1092 while (*name != '\0') name++;
1093 while (name > full_name && *name != '/') name--;
1094 if (*name == '/') name++;
1095 uptr base_name_length = internal_strlen(base_name);
1096 if (internal_strncmp(name, base_name, base_name_length)) return false;
1097 return (name[base_name_length] == '-' || name[base_name_length] == '.');
1100 #if !SANITIZER_ANDROID
1101 // Call cb for each region mapped by map.
1102 void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr)) {
1103 CHECK_NE(map, nullptr);
1104 #if !SANITIZER_FREEBSD
1105 typedef ElfW(Phdr) Elf_Phdr;
1106 typedef ElfW(Ehdr) Elf_Ehdr;
1107 #endif // !SANITIZER_FREEBSD
1108 char *base = (char *)map->l_addr;
1109 Elf_Ehdr *ehdr = (Elf_Ehdr *)base;
1110 char *phdrs = base + ehdr->e_phoff;
1111 char *phdrs_end = phdrs + ehdr->e_phnum * ehdr->e_phentsize;
1113 // Find the segment with the minimum base so we can "relocate" the p_vaddr
1114 // fields. Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
1115 // objects have a non-zero base.
1116 uptr preferred_base = (uptr)-1;
1117 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
1118 Elf_Phdr *phdr = (Elf_Phdr *)iter;
1119 if (phdr->p_type == PT_LOAD && preferred_base > (uptr)phdr->p_vaddr)
1120 preferred_base = (uptr)phdr->p_vaddr;
1123 // Compute the delta from the real base to get a relocation delta.
1124 sptr delta = (uptr)base - preferred_base;
1125 // Now we can figure out what the loader really mapped.
1126 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
1127 Elf_Phdr *phdr = (Elf_Phdr *)iter;
1128 if (phdr->p_type == PT_LOAD) {
1129 uptr seg_start = phdr->p_vaddr + delta;
1130 uptr seg_end = seg_start + phdr->p_memsz;
1131 // None of these values are aligned. We consider the ragged edges of the
1132 // load command as defined, since they are mapped from the file.
1133 seg_start = RoundDownTo(seg_start, GetPageSizeCached());
1134 seg_end = RoundUpTo(seg_end, GetPageSizeCached());
1135 cb((void *)seg_start, seg_end - seg_start);
1141 #if defined(__x86_64__) && SANITIZER_LINUX
1142 // We cannot use glibc's clone wrapper, because it messes with the child
1143 // task's TLS. It writes the PID and TID of the child task to its thread
1144 // descriptor, but in our case the child task shares the thread descriptor with
1145 // the parent (because we don't know how to allocate a new thread
1146 // descriptor to keep glibc happy). So the stock version of clone(), when
1147 // used with CLONE_VM, would end up corrupting the parent's thread descriptor.
1148 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1149 int *parent_tidptr, void *newtls, int *child_tidptr) {
1151 if (!fn || !child_stack)
1153 CHECK_EQ(0, (uptr)child_stack % 16);
1154 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1155 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1156 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1157 register void *r8 __asm__("r8") = newtls;
1158 register int *r10 __asm__("r10") = child_tidptr;
1159 __asm__ __volatile__(
1160 /* %rax = syscall(%rax = SYSCALL(clone),
1162 * %rsi = child_stack,
1163 * %rdx = parent_tidptr,
1165 * %r10 = child_tidptr)
1172 "testq %%rax,%%rax\n"
1175 /* In the child. Terminate unwind chain. */
1176 // XXX: We should also terminate the CFI unwind chain
1177 // here. Unfortunately clang 3.2 doesn't support the
1178 // necessary CFI directives, so we skip that part.
1179 "xorq %%rbp,%%rbp\n"
1181 /* Call "fn(arg)". */
1186 /* Call _exit(%rax). */
1187 "movq %%rax,%%rdi\n"
1191 /* Return to parent. */
1194 : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
1200 : "rsp", "memory", "r11", "rcx");
1203 #elif defined(__mips__)
1204 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1205 int *parent_tidptr, void *newtls, int *child_tidptr) {
1207 if (!fn || !child_stack)
1209 CHECK_EQ(0, (uptr)child_stack % 16);
1210 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1211 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1212 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1213 register void *a3 __asm__("$7") = newtls;
1214 register int *a4 __asm__("$8") = child_tidptr;
1215 // We don't have proper CFI directives here because it requires alot of code
1216 // for very marginal benefits.
1217 __asm__ __volatile__(
1218 /* $v0 = syscall($v0 = __NR_clone,
1220 * $a1 = child_stack,
1221 * $a2 = parent_tidptr,
1223 * $a4 = child_tidptr)
1230 /* Store the fifth argument on stack
1231 * if we are using 32-bit abi.
1233 #if SANITIZER_WORDSIZE == 32
1246 /* Call "fn(arg)". */
1247 #if SANITIZER_WORDSIZE == 32
1248 #ifdef __BIG_ENDIAN__
1261 /* Call _exit($v0). */
1266 /* Return to parent. */
1276 : "memory", "$29" );
1279 #elif defined(__aarch64__)
1280 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1281 int *parent_tidptr, void *newtls, int *child_tidptr) {
1283 if (!fn || !child_stack)
1285 CHECK_EQ(0, (uptr)child_stack % 16);
1286 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1287 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1288 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1290 register int (*__fn)(void *) __asm__("x0") = fn;
1291 register void *__stack __asm__("x1") = child_stack;
1292 register int __flags __asm__("x2") = flags;
1293 register void *__arg __asm__("x3") = arg;
1294 register int *__ptid __asm__("x4") = parent_tidptr;
1295 register void *__tls __asm__("x5") = newtls;
1296 register int *__ctid __asm__("x6") = child_tidptr;
1298 __asm__ __volatile__(
1299 "mov x0,x2\n" /* flags */
1300 "mov x2,x4\n" /* ptid */
1301 "mov x3,x5\n" /* tls */
1302 "mov x4,x6\n" /* ctid */
1303 "mov x8,%9\n" /* clone */
1313 /* In the child, now. Call "fn(arg)". */
1314 "ldp x1, x0, [sp], #16\n"
1317 /* Call _exit(%r0). */
1324 "r"(__fn), "r"(__stack), "r"(__flags), "r"(__arg),
1325 "r"(__ptid), "r"(__tls), "r"(__ctid),
1326 "i"(__NR_clone), "i"(__NR_exit)
1330 #elif defined(__powerpc64__)
1331 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1332 int *parent_tidptr, void *newtls, int *child_tidptr) {
1334 // Stack frame structure.
1335 #if SANITIZER_PPC64V1
1336 // Back chain == 0 (SP + 112)
1337 // Frame (112 bytes):
1338 // Parameter save area (SP + 48), 8 doublewords
1339 // TOC save area (SP + 40)
1340 // Link editor doubleword (SP + 32)
1341 // Compiler doubleword (SP + 24)
1342 // LR save area (SP + 16)
1343 // CR save area (SP + 8)
1344 // Back chain (SP + 0)
1345 # define FRAME_SIZE 112
1346 # define FRAME_TOC_SAVE_OFFSET 40
1347 #elif SANITIZER_PPC64V2
1348 // Back chain == 0 (SP + 32)
1349 // Frame (32 bytes):
1350 // TOC save area (SP + 24)
1351 // LR save area (SP + 16)
1352 // CR save area (SP + 8)
1353 // Back chain (SP + 0)
1354 # define FRAME_SIZE 32
1355 # define FRAME_TOC_SAVE_OFFSET 24
1357 # error "Unsupported PPC64 ABI"
1359 if (!fn || !child_stack)
1361 CHECK_EQ(0, (uptr)child_stack % 16);
1363 register int (*__fn)(void *) __asm__("r3") = fn;
1364 register void *__cstack __asm__("r4") = child_stack;
1365 register int __flags __asm__("r5") = flags;
1366 register void *__arg __asm__("r6") = arg;
1367 register int *__ptidptr __asm__("r7") = parent_tidptr;
1368 register void *__newtls __asm__("r8") = newtls;
1369 register int *__ctidptr __asm__("r9") = child_tidptr;
1371 __asm__ __volatile__(
1372 /* fn and arg are saved across the syscall */
1382 r7 == child_tidptr */
1390 /* Test if syscall was successful */
1391 "cmpdi cr1, 3, 0\n\t"
1392 "crandc cr1*4+eq, cr1*4+eq, cr0*4+so\n\t"
1395 /* Set up stack frame */
1397 "stdu 29, -8(1)\n\t"
1398 "stdu 1, -%12(1)\n\t"
1399 /* Do the function call */
1401 #if SANITIZER_PPC64V1
1405 #elif SANITIZER_PPC64V2
1409 # error "Unsupported PPC64 ABI"
1415 /* Call _exit(r3) */
1419 /* Return to parent */
1435 "i" (FRAME_TOC_SAVE_OFFSET)
1436 : "cr0", "cr1", "memory", "ctr", "r0", "r27", "r28", "r29");
1439 #elif defined(__i386__) && SANITIZER_LINUX
1440 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1441 int *parent_tidptr, void *newtls, int *child_tidptr) {
1443 if (!fn || !child_stack)
1445 CHECK_EQ(0, (uptr)child_stack % 16);
1446 child_stack = (char *)child_stack - 7 * sizeof(unsigned int);
1447 ((unsigned int *)child_stack)[0] = (uptr)flags;
1448 ((unsigned int *)child_stack)[1] = (uptr)0;
1449 ((unsigned int *)child_stack)[2] = (uptr)fn;
1450 ((unsigned int *)child_stack)[3] = (uptr)arg;
1451 __asm__ __volatile__(
1452 /* %eax = syscall(%eax = SYSCALL(clone),
1454 * %ecx = child_stack,
1455 * %edx = parent_tidptr,
1457 * %edi = child_tidptr)
1461 "movl (%%ecx), %%ebx\n"
1462 /* Do the system call */
1466 /* Remember the flag value. */
1467 "movl %%ebx, (%%ecx)\n"
1477 "test %%eax,%%eax\n"
1480 /* terminate the stack frame */
1481 "xorl %%ebp,%%ebp\n"
1488 "addl $_GLOBAL_OFFSET_TABLE_+[.-here], %%ebx\n"
1491 "movl %%eax, %%ebx\n"
1496 : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
1504 #elif defined(__arm__) && SANITIZER_LINUX
1505 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1506 int *parent_tidptr, void *newtls, int *child_tidptr) {
1508 if (!fn || !child_stack)
1510 child_stack = (char *)child_stack - 2 * sizeof(unsigned int);
1511 ((unsigned int *)child_stack)[0] = (uptr)fn;
1512 ((unsigned int *)child_stack)[1] = (uptr)arg;
1513 register int r0 __asm__("r0") = flags;
1514 register void *r1 __asm__("r1") = child_stack;
1515 register int *r2 __asm__("r2") = parent_tidptr;
1516 register void *r3 __asm__("r3") = newtls;
1517 register int *r4 __asm__("r4") = child_tidptr;
1518 register int r7 __asm__("r7") = __NR_clone;
1520 #if __ARM_ARCH > 4 || defined (__ARM_ARCH_4T__)
1521 # define ARCH_HAS_BX
1524 # define ARCH_HAS_BLX
1528 # ifdef ARCH_HAS_BLX
1529 # define BLX(R) "blx " #R "\n"
1531 # define BLX(R) "mov lr, pc; bx " #R "\n"
1534 # define BLX(R) "mov lr, pc; mov pc," #R "\n"
1537 __asm__ __volatile__(
1538 /* %r0 = syscall(%r7 = SYSCALL(clone),
1540 * %r1 = child_stack,
1541 * %r2 = parent_tidptr,
1543 * %r4 = child_tidptr)
1546 /* Do the system call */
1555 /* In the child, now. Call "fn(arg)". */
1556 "ldr r0, [sp, #4]\n"
1557 "ldr ip, [sp], #8\n"
1559 /* Call _exit(%r0). */
1565 : "r"(r0), "r"(r1), "r"(r2), "r"(r3), "r"(r4), "r"(r7),
1570 #endif // defined(__x86_64__) && SANITIZER_LINUX
1572 #if SANITIZER_ANDROID
1573 #if __ANDROID_API__ < 21
1574 extern "C" __attribute__((weak)) int dl_iterate_phdr(
1575 int (*)(struct dl_phdr_info *, size_t, void *), void *);
1578 static int dl_iterate_phdr_test_cb(struct dl_phdr_info *info, size_t size,
1580 // Any name starting with "lib" indicates a bug in L where library base names
1581 // are returned instead of paths.
1582 if (info->dlpi_name && info->dlpi_name[0] == 'l' &&
1583 info->dlpi_name[1] == 'i' && info->dlpi_name[2] == 'b') {
1584 *(bool *)data = true;
1590 static atomic_uint32_t android_api_level;
1592 static AndroidApiLevel AndroidDetectApiLevel() {
1593 if (!&dl_iterate_phdr)
1594 return ANDROID_KITKAT; // K or lower
1595 bool base_name_seen = false;
1596 dl_iterate_phdr(dl_iterate_phdr_test_cb, &base_name_seen);
1598 return ANDROID_LOLLIPOP_MR1; // L MR1
1599 return ANDROID_POST_LOLLIPOP; // post-L
1600 // Plain L (API level 21) is completely broken wrt ASan and not very
1601 // interesting to detect.
1604 AndroidApiLevel AndroidGetApiLevel() {
1605 AndroidApiLevel level =
1606 (AndroidApiLevel)atomic_load(&android_api_level, memory_order_relaxed);
1607 if (level) return level;
1608 level = AndroidDetectApiLevel();
1609 atomic_store(&android_api_level, level, memory_order_relaxed);
1615 static HandleSignalMode GetHandleSignalModeImpl(int signum) {
1618 return common_flags()->handle_abort;
1620 return common_flags()->handle_sigill;
1622 return common_flags()->handle_sigfpe;
1624 return common_flags()->handle_segv;
1626 return common_flags()->handle_sigbus;
1628 return kHandleSignalNo;
1631 HandleSignalMode GetHandleSignalMode(int signum) {
1632 HandleSignalMode result = GetHandleSignalModeImpl(signum);
1633 if (result == kHandleSignalYes && !common_flags()->allow_user_segv_handler)
1634 return kHandleSignalExclusive;
1639 void *internal_start_thread(void(*func)(void *arg), void *arg) {
1640 // Start the thread with signals blocked, otherwise it can steal user signals.
1641 __sanitizer_sigset_t set, old;
1642 internal_sigfillset(&set);
1643 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1644 // Glibc uses SIGSETXID signal during setuid call. If this signal is blocked
1645 // on any thread, setuid call hangs (see test/tsan/setuid.c).
1646 internal_sigdelset(&set, 33);
1648 internal_sigprocmask(SIG_SETMASK, &set, &old);
1650 real_pthread_create(&th, nullptr, (void*(*)(void *arg))func, arg);
1651 internal_sigprocmask(SIG_SETMASK, &old, nullptr);
1655 void internal_join_thread(void *th) {
1656 real_pthread_join(th, nullptr);
1659 void *internal_start_thread(void (*func)(void *), void *arg) { return 0; }
1661 void internal_join_thread(void *th) {}
1664 #if defined(__aarch64__)
1665 // Android headers in the older NDK releases miss this definition.
1666 struct __sanitizer_esr_context {
1667 struct _aarch64_ctx head;
1671 static bool Aarch64GetESR(ucontext_t *ucontext, u64 *esr) {
1672 static const u32 kEsrMagic = 0x45535201;
1673 u8 *aux = ucontext->uc_mcontext.__reserved;
1675 _aarch64_ctx *ctx = (_aarch64_ctx *)aux;
1676 if (ctx->size == 0) break;
1677 if (ctx->magic == kEsrMagic) {
1678 *esr = ((__sanitizer_esr_context *)ctx)->esr;
1687 SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
1688 ucontext_t *ucontext = (ucontext_t *)context;
1689 #if defined(__x86_64__) || defined(__i386__)
1690 static const uptr PF_WRITE = 1U << 1;
1691 #if SANITIZER_FREEBSD
1692 uptr err = ucontext->uc_mcontext.mc_err;
1693 #elif SANITIZER_NETBSD
1694 uptr err = ucontext->uc_mcontext.__gregs[_REG_ERR];
1695 #elif SANITIZER_SOLARIS && defined(__i386__)
1697 uptr err = ucontext->uc_mcontext.gregs[ERR];
1699 uptr err = ucontext->uc_mcontext.gregs[REG_ERR];
1701 return err & PF_WRITE ? WRITE : READ;
1702 #elif defined(__arm__)
1703 static const uptr FSR_WRITE = 1U << 11;
1704 uptr fsr = ucontext->uc_mcontext.error_code;
1705 return fsr & FSR_WRITE ? WRITE : READ;
1706 #elif defined(__aarch64__)
1707 static const u64 ESR_ELx_WNR = 1U << 6;
1709 if (!Aarch64GetESR(ucontext, &esr)) return UNKNOWN;
1710 return esr & ESR_ELx_WNR ? WRITE : READ;
1711 #elif SANITIZER_SOLARIS && defined(__sparc__)
1712 // Decode the instruction to determine the access type.
1713 // From OpenSolaris $SRC/uts/sun4/os/trap.c (get_accesstype).
1714 uptr pc = ucontext->uc_mcontext.gregs[REG_PC];
1715 u32 instr = *(u32 *)pc;
1716 return (instr >> 21) & 1 ? WRITE: READ;
1719 return UNKNOWN; // FIXME: Implement.
1723 void SignalContext::DumpAllRegisters(void *context) {
1724 // FIXME: Implement this.
1727 static void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
1728 #if defined(__arm__)
1729 ucontext_t *ucontext = (ucontext_t*)context;
1730 *pc = ucontext->uc_mcontext.arm_pc;
1731 *bp = ucontext->uc_mcontext.arm_fp;
1732 *sp = ucontext->uc_mcontext.arm_sp;
1733 #elif defined(__aarch64__)
1734 ucontext_t *ucontext = (ucontext_t*)context;
1735 *pc = ucontext->uc_mcontext.pc;
1736 *bp = ucontext->uc_mcontext.regs[29];
1737 *sp = ucontext->uc_mcontext.sp;
1738 #elif defined(__hppa__)
1739 ucontext_t *ucontext = (ucontext_t*)context;
1740 *pc = ucontext->uc_mcontext.sc_iaoq[0];
1741 /* GCC uses %r3 whenever a frame pointer is needed. */
1742 *bp = ucontext->uc_mcontext.sc_gr[3];
1743 *sp = ucontext->uc_mcontext.sc_gr[30];
1744 #elif defined(__x86_64__)
1745 # if SANITIZER_FREEBSD
1746 ucontext_t *ucontext = (ucontext_t*)context;
1747 *pc = ucontext->uc_mcontext.mc_rip;
1748 *bp = ucontext->uc_mcontext.mc_rbp;
1749 *sp = ucontext->uc_mcontext.mc_rsp;
1750 #elif SANITIZER_NETBSD
1751 ucontext_t *ucontext = (ucontext_t *)context;
1752 *pc = ucontext->uc_mcontext.__gregs[_REG_RIP];
1753 *bp = ucontext->uc_mcontext.__gregs[_REG_RBP];
1754 *sp = ucontext->uc_mcontext.__gregs[_REG_RSP];
1756 ucontext_t *ucontext = (ucontext_t*)context;
1757 *pc = ucontext->uc_mcontext.gregs[REG_RIP];
1758 *bp = ucontext->uc_mcontext.gregs[REG_RBP];
1759 *sp = ucontext->uc_mcontext.gregs[REG_RSP];
1761 #elif defined(__i386__)
1762 # if SANITIZER_FREEBSD
1763 ucontext_t *ucontext = (ucontext_t*)context;
1764 *pc = ucontext->uc_mcontext.mc_eip;
1765 *bp = ucontext->uc_mcontext.mc_ebp;
1766 *sp = ucontext->uc_mcontext.mc_esp;
1767 #elif SANITIZER_NETBSD
1768 ucontext_t *ucontext = (ucontext_t *)context;
1769 *pc = ucontext->uc_mcontext.__gregs[_REG_EIP];
1770 *bp = ucontext->uc_mcontext.__gregs[_REG_EBP];
1771 *sp = ucontext->uc_mcontext.__gregs[_REG_ESP];
1773 ucontext_t *ucontext = (ucontext_t*)context;
1774 # if SANITIZER_SOLARIS
1775 /* Use the numeric values: the symbolic ones are undefined by llvm
1776 include/llvm/Support/Solaris.h. */
1778 # define REG_EIP 14 // REG_PC
1781 # define REG_EBP 6 // REG_FP
1784 # define REG_ESP 17 // REG_SP
1787 *pc = ucontext->uc_mcontext.gregs[REG_EIP];
1788 *bp = ucontext->uc_mcontext.gregs[REG_EBP];
1789 *sp = ucontext->uc_mcontext.gregs[REG_ESP];
1791 #elif defined(__powerpc__) || defined(__powerpc64__)
1792 ucontext_t *ucontext = (ucontext_t*)context;
1793 *pc = ucontext->uc_mcontext.regs->nip;
1794 *sp = ucontext->uc_mcontext.regs->gpr[PT_R1];
1795 // The powerpc{,64}-linux ABIs do not specify r31 as the frame
1796 // pointer, but GCC always uses r31 when we need a frame pointer.
1797 *bp = ucontext->uc_mcontext.regs->gpr[PT_R31];
1798 #elif defined(__sparc__)
1799 ucontext_t *ucontext = (ucontext_t*)context;
1801 # if defined (__sparcv9)
1803 # define MC_PC REG_PC
1806 # define MC_O6 REG_O6
1808 # ifdef SANITIZER_SOLARIS
1809 # define mc_gregs gregs
1811 *pc = ucontext->uc_mcontext.mc_gregs[MC_PC];
1812 *sp = ucontext->uc_mcontext.mc_gregs[MC_O6];
1813 stk_ptr = (uptr *) (*sp + 2047);
1816 *pc = ucontext->uc_mcontext.gregs[REG_PC];
1817 *sp = ucontext->uc_mcontext.gregs[REG_O6];
1818 stk_ptr = (uptr *) *sp;
1821 #elif defined(__mips__)
1822 ucontext_t *ucontext = (ucontext_t*)context;
1823 *pc = ucontext->uc_mcontext.pc;
1824 *bp = ucontext->uc_mcontext.gregs[30];
1825 *sp = ucontext->uc_mcontext.gregs[29];
1826 #elif defined(__s390__)
1827 ucontext_t *ucontext = (ucontext_t*)context;
1828 # if defined(__s390x__)
1829 *pc = ucontext->uc_mcontext.psw.addr;
1831 *pc = ucontext->uc_mcontext.psw.addr & 0x7fffffff;
1833 *bp = ucontext->uc_mcontext.gregs[11];
1834 *sp = ucontext->uc_mcontext.gregs[15];
1836 # error "Unsupported arch"
1840 void SignalContext::InitPcSpBp() { GetPcSpBp(context, &pc, &sp, &bp); }
1842 void MaybeReexec() {
1843 // No need to re-exec on Linux.
1846 void PrintModuleMap() { }
1848 void CheckNoDeepBind(const char *filename, int flag) {
1849 #ifdef RTLD_DEEPBIND
1850 if (flag & RTLD_DEEPBIND) {
1852 "You are trying to dlopen a %s shared library with RTLD_DEEPBIND flag"
1853 " which is incompatibe with sanitizer runtime "
1854 "(see https://github.com/google/sanitizers/issues/611 for details"
1855 "). If you want to run %s library under sanitizers please remove "
1856 "RTLD_DEEPBIND from dlopen flags.\n",
1857 filename, filename);
1863 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
1864 uptr *largest_gap_found) {
1865 UNREACHABLE("FindAvailableMemoryRange is not available");
1869 bool GetRandom(void *buffer, uptr length, bool blocking) {
1870 if (!buffer || !length || length > 256)
1872 #if SANITIZER_USE_GETRANDOM
1873 static atomic_uint8_t skip_getrandom_syscall;
1874 if (!atomic_load_relaxed(&skip_getrandom_syscall)) {
1875 // Up to 256 bytes, getrandom will not be interrupted.
1876 uptr res = internal_syscall(SYSCALL(getrandom), buffer, length,
1877 blocking ? 0 : GRND_NONBLOCK);
1879 if (internal_iserror(res, &rverrno) && rverrno == ENOSYS)
1880 atomic_store_relaxed(&skip_getrandom_syscall, 1);
1881 else if (res == length)
1884 #endif // SANITIZER_USE_GETRANDOM
1885 // Up to 256 bytes, a read off /dev/urandom will not be interrupted.
1886 // blocking is moot here, O_NONBLOCK has no effect when opening /dev/urandom.
1887 uptr fd = internal_open("/dev/urandom", O_RDONLY);
1888 if (internal_iserror(fd))
1890 uptr res = internal_read(fd, buffer, length);
1891 if (internal_iserror(res))
1897 } // namespace __sanitizer
1899 #endif // SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD ||
1900 // SANITIZER_SOLARIS