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 || \
18 SANITIZER_OPENBSD || SANITIZER_SOLARIS
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"
31 #include <asm/param.h>
34 // For mips64, syscall(__NR_stat) fills the buffer in the 'struct kernel_stat'
35 // format. Struct kernel_stat is defined as 'struct stat' in asm/stat.h. To
36 // access stat from asm/stat.h, without conflicting with definition in
37 // sys/stat.h, we use this trick.
39 #include <asm/unistd.h>
40 #include <sys/types.h>
41 #define stat kernel_stat
54 #include <sys/param.h>
55 #if !SANITIZER_SOLARIS
56 #include <sys/ptrace.h>
58 #include <sys/resource.h>
60 #include <sys/syscall.h>
62 #include <sys/types.h>
63 #if !SANITIZER_OPENBSD
67 #include <sys/futex.h>
68 #include <sys/sysctl.h>
73 #include <sys/utsname.h>
76 #if SANITIZER_LINUX && !SANITIZER_ANDROID
77 #include <sys/personality.h>
82 #include <sys/sysctl.h>
83 #include <machine/atomic.h>
85 // <sys/umtx.h> must be included after <errno.h> and <sys/types.h> on
86 // FreeBSD 9.2 and 10.0.
90 #endif // SANITIZER_FREEBSD
93 #include <limits.h> // For NAME_MAX
94 #include <sys/sysctl.h>
96 extern struct ps_strings *__ps_strings;
97 #endif // SANITIZER_NETBSD
102 #define environ _environ
105 extern char **environ;
109 struct kernel_timeval {
114 // <linux/futex.h> is broken on some linux distributions.
115 const int FUTEX_WAIT = 0;
116 const int FUTEX_WAKE = 1;
117 const int FUTEX_PRIVATE_FLAG = 128;
118 const int FUTEX_WAIT_PRIVATE = FUTEX_WAIT | FUTEX_PRIVATE_FLAG;
119 const int FUTEX_WAKE_PRIVATE = FUTEX_WAKE | FUTEX_PRIVATE_FLAG;
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 // Note : FreeBSD had implemented both
139 // Linux and OpenBSD apis, available from
140 // future 12.x version most likely
141 #if SANITIZER_LINUX && defined(__NR_getrandom)
142 # if !defined(GRND_NONBLOCK)
143 # define GRND_NONBLOCK 1
145 # define SANITIZER_USE_GETRANDOM 1
147 # define SANITIZER_USE_GETRANDOM 0
148 #endif // SANITIZER_LINUX && defined(__NR_getrandom)
150 #if SANITIZER_OPENBSD
151 # define SANITIZER_USE_GETENTROPY 1
153 # if SANITIZER_FREEBSD && __FreeBSD_version >= 1200000
154 # define SANITIZER_USE_GETENTROPY 1
156 # define SANITIZER_USE_GETENTROPY 0
158 #endif // SANITIZER_USE_GETENTROPY
160 namespace __sanitizer {
162 #if SANITIZER_LINUX && defined(__x86_64__)
163 #include "sanitizer_syscall_linux_x86_64.inc"
164 #elif SANITIZER_LINUX && defined(__aarch64__)
165 #include "sanitizer_syscall_linux_aarch64.inc"
166 #elif SANITIZER_LINUX && defined(__arm__)
167 #include "sanitizer_syscall_linux_arm.inc"
169 #include "sanitizer_syscall_generic.inc"
172 // --------------- sanitizer_libc.h
173 #if !SANITIZER_SOLARIS && !SANITIZER_NETBSD
174 #if !SANITIZER_S390 && !SANITIZER_OPENBSD
175 uptr internal_mmap(void *addr, uptr length, int prot, int flags, int fd,
177 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
178 return internal_syscall(SYSCALL(mmap), (uptr)addr, length, prot, flags, fd,
181 // mmap2 specifies file offset in 4096-byte units.
182 CHECK(IsAligned(offset, 4096));
183 return internal_syscall(SYSCALL(mmap2), addr, length, prot, flags, fd,
187 #endif // !SANITIZER_S390 && !SANITIZER_OPENBSD
189 #if !SANITIZER_OPENBSD
190 uptr internal_munmap(void *addr, uptr length) {
191 return internal_syscall(SYSCALL(munmap), (uptr)addr, length);
194 int internal_mprotect(void *addr, uptr length, int prot) {
195 return internal_syscall(SYSCALL(mprotect), (uptr)addr, length, prot);
199 uptr internal_close(fd_t fd) {
200 return internal_syscall(SYSCALL(close), fd);
203 uptr internal_open(const char *filename, int flags) {
204 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
205 return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags);
207 return internal_syscall(SYSCALL(open), (uptr)filename, flags);
211 uptr internal_open(const char *filename, int flags, u32 mode) {
212 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
213 return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags,
216 return internal_syscall(SYSCALL(open), (uptr)filename, flags, mode);
220 uptr internal_read(fd_t fd, void *buf, uptr count) {
223 (sptr)internal_syscall(SYSCALL(read), fd, (uptr)buf, count));
227 uptr internal_write(fd_t fd, const void *buf, uptr count) {
230 (sptr)internal_syscall(SYSCALL(write), fd, (uptr)buf, count));
234 uptr internal_ftruncate(fd_t fd, uptr size) {
236 HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(ftruncate), fd,
241 #if !SANITIZER_LINUX_USES_64BIT_SYSCALLS && SANITIZER_LINUX
242 static void stat64_to_stat(struct stat64 *in, struct stat *out) {
243 internal_memset(out, 0, sizeof(*out));
244 out->st_dev = in->st_dev;
245 out->st_ino = in->st_ino;
246 out->st_mode = in->st_mode;
247 out->st_nlink = in->st_nlink;
248 out->st_uid = in->st_uid;
249 out->st_gid = in->st_gid;
250 out->st_rdev = in->st_rdev;
251 out->st_size = in->st_size;
252 out->st_blksize = in->st_blksize;
253 out->st_blocks = in->st_blocks;
254 out->st_atime = in->st_atime;
255 out->st_mtime = in->st_mtime;
256 out->st_ctime = in->st_ctime;
260 #if defined(__mips64)
261 // Undefine compatibility macros from <sys/stat.h>
262 // so that they would not clash with the kernel_stat
263 // st_[a|m|c]time fields
267 #if defined(SANITIZER_ANDROID)
268 // Bionic sys/stat.h defines additional macros
269 // for compatibility with the old NDKs and
270 // they clash with the kernel_stat structure
271 // st_[a|m|c]time_nsec fields.
276 static void kernel_stat_to_stat(struct kernel_stat *in, struct stat *out) {
277 internal_memset(out, 0, sizeof(*out));
278 out->st_dev = in->st_dev;
279 out->st_ino = in->st_ino;
280 out->st_mode = in->st_mode;
281 out->st_nlink = in->st_nlink;
282 out->st_uid = in->st_uid;
283 out->st_gid = in->st_gid;
284 out->st_rdev = in->st_rdev;
285 out->st_size = in->st_size;
286 out->st_blksize = in->st_blksize;
287 out->st_blocks = in->st_blocks;
288 #if defined(__USE_MISC) || \
289 defined(__USE_XOPEN2K8) || \
290 defined(SANITIZER_ANDROID)
291 out->st_atim.tv_sec = in->st_atime;
292 out->st_atim.tv_nsec = in->st_atime_nsec;
293 out->st_mtim.tv_sec = in->st_mtime;
294 out->st_mtim.tv_nsec = in->st_mtime_nsec;
295 out->st_ctim.tv_sec = in->st_ctime;
296 out->st_ctim.tv_nsec = in->st_ctime_nsec;
298 out->st_atime = in->st_atime;
299 out->st_atimensec = in->st_atime_nsec;
300 out->st_mtime = in->st_mtime;
301 out->st_mtimensec = in->st_mtime_nsec;
302 out->st_ctime = in->st_ctime;
303 out->st_atimensec = in->st_ctime_nsec;
308 uptr internal_stat(const char *path, void *buf) {
309 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD
310 return internal_syscall(SYSCALL(fstatat), AT_FDCWD, (uptr)path, (uptr)buf, 0);
311 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
312 return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path, (uptr)buf,
314 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
315 # if defined(__mips64)
316 // For mips64, stat syscall fills buffer in the format of kernel_stat
317 struct kernel_stat kbuf;
318 int res = internal_syscall(SYSCALL(stat), path, &kbuf);
319 kernel_stat_to_stat(&kbuf, (struct stat *)buf);
322 return internal_syscall(SYSCALL(stat), (uptr)path, (uptr)buf);
326 int res = internal_syscall(SYSCALL(stat64), path, &buf64);
327 stat64_to_stat(&buf64, (struct stat *)buf);
332 uptr internal_lstat(const char *path, void *buf) {
333 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD
334 return internal_syscall(SYSCALL(fstatat), AT_FDCWD, (uptr)path, (uptr)buf,
335 AT_SYMLINK_NOFOLLOW);
336 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
337 return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path, (uptr)buf,
338 AT_SYMLINK_NOFOLLOW);
339 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
340 # if SANITIZER_MIPS64
341 // For mips64, lstat syscall fills buffer in the format of kernel_stat
342 struct kernel_stat kbuf;
343 int res = internal_syscall(SYSCALL(lstat), path, &kbuf);
344 kernel_stat_to_stat(&kbuf, (struct stat *)buf);
347 return internal_syscall(SYSCALL(lstat), (uptr)path, (uptr)buf);
351 int res = internal_syscall(SYSCALL(lstat64), path, &buf64);
352 stat64_to_stat(&buf64, (struct stat *)buf);
357 uptr internal_fstat(fd_t fd, void *buf) {
358 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD || \
359 SANITIZER_LINUX_USES_64BIT_SYSCALLS
360 #if SANITIZER_MIPS64 && !SANITIZER_OPENBSD
361 // For mips64, fstat syscall fills buffer in the format of kernel_stat
362 struct kernel_stat kbuf;
363 int res = internal_syscall(SYSCALL(fstat), fd, &kbuf);
364 kernel_stat_to_stat(&kbuf, (struct stat *)buf);
367 return internal_syscall(SYSCALL(fstat), fd, (uptr)buf);
371 int res = internal_syscall(SYSCALL(fstat64), fd, &buf64);
372 stat64_to_stat(&buf64, (struct stat *)buf);
377 uptr internal_filesize(fd_t fd) {
379 if (internal_fstat(fd, &st))
381 return (uptr)st.st_size;
384 uptr internal_dup(int oldfd) {
385 return internal_syscall(SYSCALL(dup), oldfd);
388 uptr internal_dup2(int oldfd, int newfd) {
389 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
390 return internal_syscall(SYSCALL(dup3), oldfd, newfd, 0);
392 return internal_syscall(SYSCALL(dup2), oldfd, newfd);
396 uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
397 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
398 return internal_syscall(SYSCALL(readlinkat), AT_FDCWD, (uptr)path, (uptr)buf,
400 #elif SANITIZER_OPENBSD
401 return internal_syscall(SYSCALL(readlinkat), AT_FDCWD, (uptr)path, (uptr)buf,
404 return internal_syscall(SYSCALL(readlink), path, buf, bufsize);
408 uptr internal_unlink(const char *path) {
409 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS || SANITIZER_OPENBSD
410 return internal_syscall(SYSCALL(unlinkat), AT_FDCWD, (uptr)path, 0);
412 return internal_syscall(SYSCALL(unlink), (uptr)path);
416 uptr internal_rename(const char *oldpath, const char *newpath) {
417 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS || SANITIZER_OPENBSD
418 return internal_syscall(SYSCALL(renameat), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
421 return internal_syscall(SYSCALL(rename), (uptr)oldpath, (uptr)newpath);
425 uptr internal_sched_yield() {
426 return internal_syscall(SYSCALL(sched_yield));
429 void internal__exit(int exitcode) {
430 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD
431 internal_syscall(SYSCALL(exit), exitcode);
433 internal_syscall(SYSCALL(exit_group), exitcode);
435 Die(); // Unreachable.
438 unsigned int internal_sleep(unsigned int seconds) {
442 int res = internal_syscall(SYSCALL(nanosleep), &ts, &ts);
443 if (res) return ts.tv_sec;
447 uptr internal_execve(const char *filename, char *const argv[],
448 char *const envp[]) {
449 return internal_syscall(SYSCALL(execve), (uptr)filename, (uptr)argv,
452 #endif // !SANITIZER_SOLARIS && !SANITIZER_NETBSD
454 // ----------------- sanitizer_common.h
455 bool FileExists(const char *filename) {
456 if (ShouldMockFailureToOpen(filename))
459 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
460 if (internal_syscall(SYSCALL(newfstatat), AT_FDCWD, filename, &st, 0))
462 if (internal_stat(filename, &st))
465 // Sanity check: filename is a regular file.
466 return S_ISREG(st.st_mode);
469 #if !SANITIZER_NETBSD
471 #if SANITIZER_FREEBSD
475 #elif SANITIZER_OPENBSD
476 return internal_syscall(SYSCALL(getthrid));
477 #elif SANITIZER_SOLARIS
480 return internal_syscall(SYSCALL(gettid));
484 int TgKill(pid_t pid, tid_t tid, int sig) {
486 return internal_syscall(SYSCALL(tgkill), pid, tid, sig);
487 #elif SANITIZER_FREEBSD
488 return internal_syscall(SYSCALL(thr_kill2), pid, tid, sig);
489 #elif SANITIZER_OPENBSD
491 return internal_syscall(SYSCALL(thrkill), tid, sig, nullptr);
492 #elif SANITIZER_SOLARIS
494 return thr_kill(tid, sig);
499 #if !SANITIZER_SOLARIS && !SANITIZER_NETBSD
501 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD
506 internal_memset(&tv, 0, sizeof(tv));
507 internal_syscall(SYSCALL(gettimeofday), &tv, 0);
508 return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
511 uptr internal_clock_gettime(__sanitizer_clockid_t clk_id, void *tp) {
512 return internal_syscall(SYSCALL(clock_gettime), clk_id, tp);
514 #endif // !SANITIZER_SOLARIS && !SANITIZER_NETBSD
516 // Like getenv, but reads env directly from /proc (on Linux) or parses the
517 // 'environ' array (on some others) and does not use libc. This function
518 // should be called first inside __asan_init.
519 const char *GetEnv(const char *name) {
520 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD || \
522 if (::environ != 0) {
523 uptr NameLen = internal_strlen(name);
524 for (char **Env = ::environ; *Env != 0; Env++) {
525 if (internal_strncmp(*Env, name, NameLen) == 0 && (*Env)[NameLen] == '=')
526 return (*Env) + NameLen + 1;
529 return 0; // Not found.
530 #elif SANITIZER_LINUX
531 static char *environ;
537 if (!ReadFileToBuffer("/proc/self/environ", &environ, &environ_size, &len))
540 if (!environ || len == 0) return nullptr;
541 uptr namelen = internal_strlen(name);
542 const char *p = environ;
543 while (*p != '\0') { // will happen at the \0\0 that terminates the buffer
544 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
546 (char*)internal_memchr(p, '\0', len - (p - environ));
547 if (!endp) // this entry isn't NUL terminated
549 else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') // Match.
550 return p + namelen + 1; // point after =
553 return nullptr; // Not found.
555 #error "Unsupported platform"
559 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD && !SANITIZER_OPENBSD
561 SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
565 #if !SANITIZER_GO && !SANITIZER_FREEBSD && !SANITIZER_NETBSD && \
567 static void ReadNullSepFileToArray(const char *path, char ***arr,
572 *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
573 if (!ReadFileToBuffer(path, &buff, &buff_size, &buff_len, 1024 * 1024)) {
579 for (count = 1, i = 1; ; i++) {
581 if (buff[i+1] == 0) break;
582 (*arr)[count] = &buff[i+1];
583 CHECK_LE(count, arr_size - 1); // FIXME: make this more flexible.
587 (*arr)[count] = nullptr;
591 #if !SANITIZER_OPENBSD
592 static void GetArgsAndEnv(char ***argv, char ***envp) {
593 #if SANITIZER_FREEBSD
594 // On FreeBSD, retrieving the argument and environment arrays is done via the
595 // kern.ps_strings sysctl, which returns a pointer to a structure containing
596 // this information. See also <sys/exec.h>.
598 uptr sz = sizeof(pss);
599 if (internal_sysctlbyname("kern.ps_strings", &pss, &sz, NULL, 0) == -1) {
600 Printf("sysctl kern.ps_strings failed\n");
603 *argv = pss->ps_argvstr;
604 *envp = pss->ps_envstr;
605 #elif SANITIZER_NETBSD
606 *argv = __ps_strings->ps_argvstr;
607 *envp = __ps_strings->ps_envstr;
608 #else // SANITIZER_FREEBSD
610 if (&__libc_stack_end) {
611 #endif // !SANITIZER_GO
612 uptr* stack_end = (uptr*)__libc_stack_end;
613 int argc = *stack_end;
614 *argv = (char**)(stack_end + 1);
615 *envp = (char**)(stack_end + argc + 2);
618 static const int kMaxArgv = 2000, kMaxEnvp = 2000;
619 ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
620 ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
622 #endif // !SANITIZER_GO
623 #endif // SANITIZER_FREEBSD
628 GetArgsAndEnv(&argv, &envp);
632 char **GetEnviron() {
634 GetArgsAndEnv(&argv, &envp);
638 #endif // !SANITIZER_OPENBSD
640 #if !SANITIZER_SOLARIS
647 BlockingMutex::BlockingMutex() {
648 internal_memset(this, 0, sizeof(*this));
651 void BlockingMutex::Lock() {
653 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
654 if (atomic_exchange(m, MtxLocked, memory_order_acquire) == MtxUnlocked)
656 while (atomic_exchange(m, MtxSleeping, memory_order_acquire) != MtxUnlocked) {
657 #if SANITIZER_FREEBSD
658 _umtx_op(m, UMTX_OP_WAIT_UINT, MtxSleeping, 0, 0);
659 #elif SANITIZER_NETBSD
660 sched_yield(); /* No userspace futex-like synchronization */
662 internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAIT_PRIVATE, MtxSleeping,
668 void BlockingMutex::Unlock() {
669 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
670 u32 v = atomic_exchange(m, MtxUnlocked, memory_order_release);
671 CHECK_NE(v, MtxUnlocked);
672 if (v == MtxSleeping) {
673 #if SANITIZER_FREEBSD
674 _umtx_op(m, UMTX_OP_WAKE, 1, 0, 0);
675 #elif SANITIZER_NETBSD
676 /* No userspace futex-like synchronization */
678 internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAKE_PRIVATE, 1, 0, 0, 0);
683 void BlockingMutex::CheckLocked() {
684 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
685 CHECK_NE(MtxUnlocked, atomic_load(m, memory_order_relaxed));
687 #endif // !SANITIZER_SOLARIS
689 // ----------------- sanitizer_linux.h
690 // The actual size of this structure is specified by d_reclen.
691 // Note that getdents64 uses a different structure format. We only provide the
692 // 32-bit syscall here.
695 #elif SANITIZER_OPENBSD
696 // struct dirent is different for Linux and us. At this moment, we use only
697 // d_fileno (Linux call this d_ino), d_reclen, and d_name.
698 struct linux_dirent {
699 u64 d_ino; // d_fileno
701 u16 d_namlen; // not used
702 u8 d_type; // not used
703 char d_name[NAME_MAX + 1];
706 struct linux_dirent {
707 #if SANITIZER_X32 || defined(__aarch64__)
714 unsigned short d_reclen;
716 unsigned char d_type;
722 #if !SANITIZER_SOLARIS && !SANITIZER_NETBSD
724 uptr internal_ptrace(int request, int pid, void *addr, void *data) {
725 return internal_syscall(SYSCALL(ptrace), request, pid, (uptr)addr,
729 uptr internal_waitpid(int pid, int *status, int options) {
730 return internal_syscall(SYSCALL(wait4), pid, (uptr)status, options,
734 uptr internal_getpid() {
735 return internal_syscall(SYSCALL(getpid));
738 uptr internal_getppid() {
739 return internal_syscall(SYSCALL(getppid));
742 uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) {
743 #if SANITIZER_FREEBSD
744 return internal_syscall(SYSCALL(getdirentries), fd, (uptr)dirp, count, NULL);
745 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
746 return internal_syscall(SYSCALL(getdents64), fd, (uptr)dirp, count);
748 return internal_syscall(SYSCALL(getdents), fd, (uptr)dirp, count);
752 uptr internal_lseek(fd_t fd, OFF_T offset, int whence) {
753 return internal_syscall(SYSCALL(lseek), fd, offset, whence);
757 uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
758 return internal_syscall(SYSCALL(prctl), option, arg2, arg3, arg4, arg5);
762 uptr internal_sigaltstack(const void *ss, void *oss) {
763 return internal_syscall(SYSCALL(sigaltstack), (uptr)ss, (uptr)oss);
766 int internal_fork() {
767 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
768 return internal_syscall(SYSCALL(clone), SIGCHLD, 0);
770 return internal_syscall(SYSCALL(fork));
774 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD
775 int internal_sysctl(const int *name, unsigned int namelen, void *oldp,
776 uptr *oldlenp, const void *newp, uptr newlen) {
777 #if SANITIZER_OPENBSD
778 return sysctl(name, namelen, oldp, (size_t *)oldlenp, (void *)newp,
781 return internal_syscall(SYSCALL(__sysctl), name, namelen, oldp,
782 (size_t *)oldlenp, newp, (size_t)newlen);
786 #if SANITIZER_FREEBSD
787 int internal_sysctlbyname(const char *sname, void *oldp, uptr *oldlenp,
788 const void *newp, uptr newlen) {
789 return sysctlbyname(sname, oldp, (size_t *)oldlenp, newp, (size_t)newlen);
795 #define SA_RESTORER 0x04000000
796 // Doesn't set sa_restorer if the caller did not set it, so use with caution
798 int internal_sigaction_norestorer(int signum, const void *act, void *oldact) {
799 __sanitizer_kernel_sigaction_t k_act, k_oldact;
800 internal_memset(&k_act, 0, sizeof(__sanitizer_kernel_sigaction_t));
801 internal_memset(&k_oldact, 0, sizeof(__sanitizer_kernel_sigaction_t));
802 const __sanitizer_sigaction *u_act = (const __sanitizer_sigaction *)act;
803 __sanitizer_sigaction *u_oldact = (__sanitizer_sigaction *)oldact;
805 k_act.handler = u_act->handler;
806 k_act.sigaction = u_act->sigaction;
807 internal_memcpy(&k_act.sa_mask, &u_act->sa_mask,
808 sizeof(__sanitizer_kernel_sigset_t));
809 // Without SA_RESTORER kernel ignores the calls (probably returns EINVAL).
810 k_act.sa_flags = u_act->sa_flags | SA_RESTORER;
811 // FIXME: most often sa_restorer is unset, however the kernel requires it
812 // to point to a valid signal restorer that calls the rt_sigreturn syscall.
813 // If sa_restorer passed to the kernel is NULL, the program may crash upon
814 // signal delivery or fail to unwind the stack in the signal handler.
815 // libc implementation of sigaction() passes its own restorer to
816 // rt_sigaction, so we need to do the same (we'll need to reimplement the
817 // restorers; for x86_64 the restorer address can be obtained from
818 // oldact->sa_restorer upon a call to sigaction(xxx, NULL, oldact).
819 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
820 k_act.sa_restorer = u_act->sa_restorer;
824 uptr result = internal_syscall(SYSCALL(rt_sigaction), (uptr)signum,
825 (uptr)(u_act ? &k_act : nullptr),
826 (uptr)(u_oldact ? &k_oldact : nullptr),
827 (uptr)sizeof(__sanitizer_kernel_sigset_t));
829 if ((result == 0) && u_oldact) {
830 u_oldact->handler = k_oldact.handler;
831 u_oldact->sigaction = k_oldact.sigaction;
832 internal_memcpy(&u_oldact->sa_mask, &k_oldact.sa_mask,
833 sizeof(__sanitizer_kernel_sigset_t));
834 u_oldact->sa_flags = k_oldact.sa_flags;
835 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
836 u_oldact->sa_restorer = k_oldact.sa_restorer;
842 // Invokes sigaction via a raw syscall with a restorer, but does not support
843 // all platforms yet.
844 // We disable for Go simply because we have not yet added to buildgo.sh.
845 #if (defined(__x86_64__) || SANITIZER_MIPS64) && !SANITIZER_GO
846 int internal_sigaction_syscall(int signum, const void *act, void *oldact) {
848 return internal_sigaction_norestorer(signum, act, oldact);
849 __sanitizer_sigaction u_adjust;
850 internal_memcpy(&u_adjust, act, sizeof(u_adjust));
851 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
852 if (u_adjust.sa_restorer == nullptr) {
853 u_adjust.sa_restorer = internal_sigreturn;
856 return internal_sigaction_norestorer(signum, (const void *)&u_adjust, oldact);
858 #endif // defined(__x86_64__) && !SANITIZER_GO
859 #endif // SANITIZER_LINUX
861 uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
862 __sanitizer_sigset_t *oldset) {
863 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD
864 return internal_syscall(SYSCALL(sigprocmask), how, set, oldset);
866 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
867 __sanitizer_kernel_sigset_t *k_oldset = (__sanitizer_kernel_sigset_t *)oldset;
868 return internal_syscall(SYSCALL(rt_sigprocmask), (uptr)how,
869 (uptr)&k_set->sig[0], (uptr)&k_oldset->sig[0],
870 sizeof(__sanitizer_kernel_sigset_t));
874 void internal_sigfillset(__sanitizer_sigset_t *set) {
875 internal_memset(set, 0xff, sizeof(*set));
878 void internal_sigemptyset(__sanitizer_sigset_t *set) {
879 internal_memset(set, 0, sizeof(*set));
883 void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
886 CHECK_LT(signum, sizeof(*set) * 8);
887 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
888 const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
889 const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
890 k_set->sig[idx] &= ~(1 << bit);
893 bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
896 CHECK_LT(signum, sizeof(*set) * 8);
897 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
898 const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
899 const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
900 return k_set->sig[idx] & (1 << bit);
902 #elif SANITIZER_FREEBSD
903 void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
904 sigset_t *rset = reinterpret_cast<sigset_t *>(set);
905 sigdelset(rset, signum);
908 bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
909 sigset_t *rset = reinterpret_cast<sigset_t *>(set);
910 return sigismember(rset, signum);
913 #endif // !SANITIZER_SOLARIS
915 #if !SANITIZER_NETBSD
916 // ThreadLister implementation.
917 ThreadLister::ThreadLister(pid_t pid) : pid_(pid), buffer_(4096) {
918 char task_directory_path[80];
919 internal_snprintf(task_directory_path, sizeof(task_directory_path),
920 "/proc/%d/task/", pid);
921 descriptor_ = internal_open(task_directory_path, O_RDONLY | O_DIRECTORY);
922 if (internal_iserror(descriptor_)) {
923 Report("Can't open /proc/%d/task for reading.\n", pid);
927 ThreadLister::Result ThreadLister::ListThreads(
928 InternalMmapVector<tid_t> *threads) {
929 if (internal_iserror(descriptor_))
931 internal_lseek(descriptor_, 0, SEEK_SET);
935 for (bool first_read = true;; first_read = false) {
936 // Resize to max capacity if it was downsized by IsAlive.
937 buffer_.resize(buffer_.capacity());
938 CHECK_GE(buffer_.size(), 4096);
939 uptr read = internal_getdents(
940 descriptor_, (struct linux_dirent *)buffer_.data(), buffer_.size());
943 if (internal_iserror(read)) {
944 Report("Can't read directory entries from /proc/%d/task.\n", pid_);
948 for (uptr begin = (uptr)buffer_.data(), end = begin + read; begin < end;) {
949 struct linux_dirent *entry = (struct linux_dirent *)begin;
950 begin += entry->d_reclen;
951 if (entry->d_ino == 1) {
952 // Inode 1 is for bad blocks and also can be a reason for early return.
953 // Should be emitted if kernel tried to output terminating thread.
954 // See proc_task_readdir implementation in Linux.
957 if (entry->d_ino && *entry->d_name >= '0' && *entry->d_name <= '9')
958 threads->push_back(internal_atoll(entry->d_name));
961 // Now we are going to detect short-read or early EOF. In such cases Linux
962 // can return inconsistent list with missing alive threads.
963 // Code will just remember that the list can be incomplete but it will
964 // continue reads to return as much as possible.
966 // The first one was a short-read by definition.
968 } else if (read > buffer_.size() - 1024) {
969 // Read was close to the buffer size. So double the size and assume the
971 buffer_.resize(buffer_.size() * 2);
973 } else if (!threads->empty() && !IsAlive(threads->back())) {
974 // Maybe Linux early returned from read on terminated thread (!pid_alive)
975 // and failed to restore read position.
976 // See next_tid and proc_task_instantiate in Linux.
982 bool ThreadLister::IsAlive(int tid) {
983 // /proc/%d/task/%d/status uses same call to detect alive threads as
984 // proc_task_readdir. See task_state implementation in Linux.
986 internal_snprintf(path, sizeof(path), "/proc/%d/task/%d/status", pid_, tid);
987 if (!ReadFileToVector(path, &buffer_) || buffer_.empty())
989 buffer_.push_back(0);
990 static const char kPrefix[] = "\nPPid:";
991 const char *field = internal_strstr(buffer_.data(), kPrefix);
994 field += internal_strlen(kPrefix);
995 return (int)internal_atoll(field) != 0;
998 ThreadLister::~ThreadLister() {
999 if (!internal_iserror(descriptor_))
1000 internal_close(descriptor_);
1004 #if SANITIZER_WORDSIZE == 32
1005 // Take care of unusable kernel area in top gigabyte.
1006 static uptr GetKernelAreaSize() {
1007 #if SANITIZER_LINUX && !SANITIZER_X32
1008 const uptr gbyte = 1UL << 30;
1010 // Firstly check if there are writable segments
1011 // mapped to top gigabyte (e.g. stack).
1012 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
1013 if (proc_maps.Error())
1015 MemoryMappedSegment segment;
1016 while (proc_maps.Next(&segment)) {
1017 if ((segment.end >= 3 * gbyte) && segment.IsWritable()) return 0;
1020 #if !SANITIZER_ANDROID
1021 // Even if nothing is mapped, top Gb may still be accessible
1022 // if we are running on 64-bit kernel.
1023 // Uname may report misleading results if personality type
1024 // is modified (e.g. under schroot) so check this as well.
1025 struct utsname uname_info;
1026 int pers = personality(0xffffffffUL);
1027 if (!(pers & PER_MASK)
1028 && uname(&uname_info) == 0
1029 && internal_strstr(uname_info.machine, "64"))
1031 #endif // SANITIZER_ANDROID
1033 // Top gigabyte is reserved for kernel.
1037 #endif // SANITIZER_LINUX && !SANITIZER_X32
1039 #endif // SANITIZER_WORDSIZE == 32
1041 uptr GetMaxVirtualAddress() {
1042 #if (SANITIZER_NETBSD || SANITIZER_OPENBSD) && defined(__x86_64__)
1043 return 0x7f7ffffff000ULL; // (0x00007f8000000000 - PAGE_SIZE)
1044 #elif SANITIZER_WORDSIZE == 64
1045 # if defined(__powerpc64__) || defined(__aarch64__)
1046 // On PowerPC64 we have two different address space layouts: 44- and 46-bit.
1047 // We somehow need to figure out which one we are using now and choose
1048 // one of 0x00000fffffffffffUL and 0x00003fffffffffffUL.
1049 // Note that with 'ulimit -s unlimited' the stack is moved away from the top
1050 // of the address space, so simply checking the stack address is not enough.
1051 // This should (does) work for both PowerPC64 Endian modes.
1052 // Similarly, aarch64 has multiple address space layouts: 39, 42 and 47-bit.
1053 return (1ULL << (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1)) - 1;
1054 # elif defined(__mips64)
1055 return (1ULL << 40) - 1; // 0x000000ffffffffffUL;
1056 # elif defined(__s390x__)
1057 return (1ULL << 53) - 1; // 0x001fffffffffffffUL;
1059 return (1ULL << 47) - 1; // 0x00007fffffffffffUL;
1061 #else // SANITIZER_WORDSIZE == 32
1062 # if defined(__s390__)
1063 return (1ULL << 31) - 1; // 0x7fffffff;
1065 return (1ULL << 32) - 1; // 0xffffffff;
1067 #endif // SANITIZER_WORDSIZE
1070 uptr GetMaxUserVirtualAddress() {
1071 uptr addr = GetMaxVirtualAddress();
1072 #if SANITIZER_WORDSIZE == 32 && !defined(__s390__)
1073 if (!common_flags()->full_address_space)
1074 addr -= GetKernelAreaSize();
1075 CHECK_LT(reinterpret_cast<uptr>(&addr), addr);
1080 #if !SANITIZER_ANDROID
1081 uptr GetPageSize() {
1082 #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__))
1083 return EXEC_PAGESIZE;
1084 #elif SANITIZER_USE_GETAUXVAL
1085 return getauxval(AT_PAGESZ);
1086 #elif SANITIZER_FREEBSD || SANITIZER_NETBSD
1087 // Use sysctl as sysconf can trigger interceptors internally.
1089 uptr pzl = sizeof(pz);
1090 int mib[2] = {CTL_HW, HW_PAGESIZE};
1091 int rv = internal_sysctl(mib, 2, &pz, &pzl, nullptr, 0);
1095 return sysconf(_SC_PAGESIZE); // EXEC_PAGESIZE may not be trustworthy.
1098 #endif // !SANITIZER_ANDROID
1100 #if !SANITIZER_OPENBSD
1101 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
1102 #if SANITIZER_SOLARIS
1103 const char *default_module_name = getexecname();
1104 CHECK_NE(default_module_name, NULL);
1105 return internal_snprintf(buf, buf_len, "%s", default_module_name);
1107 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
1108 #if SANITIZER_FREEBSD
1109 const int Mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
1111 const int Mib[4] = {CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME};
1113 const char *default_module_name = "kern.proc.pathname";
1114 uptr Size = buf_len;
1116 (internal_sysctl(Mib, ARRAY_SIZE(Mib), buf, &Size, NULL, 0) != 0);
1117 int readlink_error = IsErr ? errno : 0;
1118 uptr module_name_len = Size;
1120 const char *default_module_name = "/proc/self/exe";
1121 uptr module_name_len = internal_readlink(
1122 default_module_name, buf, buf_len);
1124 bool IsErr = internal_iserror(module_name_len, &readlink_error);
1125 #endif // SANITIZER_SOLARIS
1127 // We can't read binary name for some reason, assume it's unknown.
1128 Report("WARNING: reading executable name failed with errno %d, "
1129 "some stack frames may not be symbolized\n", readlink_error);
1130 module_name_len = internal_snprintf(buf, buf_len, "%s",
1131 default_module_name);
1132 CHECK_LT(module_name_len, buf_len);
1134 return module_name_len;
1137 #endif // !SANITIZER_OPENBSD
1139 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len) {
1144 if (ReadFileToBuffer("/proc/self/cmdline", &tmpbuf, &tmpsize, &tmplen,
1146 internal_strncpy(buf, tmpbuf, buf_len);
1147 UnmapOrDie(tmpbuf, tmpsize);
1148 return internal_strlen(buf);
1151 return ReadBinaryName(buf, buf_len);
1154 // Match full names of the form /path/to/base_name{-,.}*
1155 bool LibraryNameIs(const char *full_name, const char *base_name) {
1156 const char *name = full_name;
1158 while (*name != '\0') name++;
1159 while (name > full_name && *name != '/') name--;
1160 if (*name == '/') name++;
1161 uptr base_name_length = internal_strlen(base_name);
1162 if (internal_strncmp(name, base_name, base_name_length)) return false;
1163 return (name[base_name_length] == '-' || name[base_name_length] == '.');
1166 #if !SANITIZER_ANDROID
1167 // Call cb for each region mapped by map.
1168 void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr)) {
1169 CHECK_NE(map, nullptr);
1170 #if !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
1171 typedef ElfW(Phdr) Elf_Phdr;
1172 typedef ElfW(Ehdr) Elf_Ehdr;
1173 #endif // !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
1174 char *base = (char *)map->l_addr;
1175 Elf_Ehdr *ehdr = (Elf_Ehdr *)base;
1176 char *phdrs = base + ehdr->e_phoff;
1177 char *phdrs_end = phdrs + ehdr->e_phnum * ehdr->e_phentsize;
1179 // Find the segment with the minimum base so we can "relocate" the p_vaddr
1180 // fields. Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
1181 // objects have a non-zero base.
1182 uptr preferred_base = (uptr)-1;
1183 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
1184 Elf_Phdr *phdr = (Elf_Phdr *)iter;
1185 if (phdr->p_type == PT_LOAD && preferred_base > (uptr)phdr->p_vaddr)
1186 preferred_base = (uptr)phdr->p_vaddr;
1189 // Compute the delta from the real base to get a relocation delta.
1190 sptr delta = (uptr)base - preferred_base;
1191 // Now we can figure out what the loader really mapped.
1192 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
1193 Elf_Phdr *phdr = (Elf_Phdr *)iter;
1194 if (phdr->p_type == PT_LOAD) {
1195 uptr seg_start = phdr->p_vaddr + delta;
1196 uptr seg_end = seg_start + phdr->p_memsz;
1197 // None of these values are aligned. We consider the ragged edges of the
1198 // load command as defined, since they are mapped from the file.
1199 seg_start = RoundDownTo(seg_start, GetPageSizeCached());
1200 seg_end = RoundUpTo(seg_end, GetPageSizeCached());
1201 cb((void *)seg_start, seg_end - seg_start);
1207 #if defined(__x86_64__) && SANITIZER_LINUX
1208 // We cannot use glibc's clone wrapper, because it messes with the child
1209 // task's TLS. It writes the PID and TID of the child task to its thread
1210 // descriptor, but in our case the child task shares the thread descriptor with
1211 // the parent (because we don't know how to allocate a new thread
1212 // descriptor to keep glibc happy). So the stock version of clone(), when
1213 // used with CLONE_VM, would end up corrupting the parent's thread descriptor.
1214 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1215 int *parent_tidptr, void *newtls, int *child_tidptr) {
1217 if (!fn || !child_stack)
1219 CHECK_EQ(0, (uptr)child_stack % 16);
1220 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1221 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1222 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1223 register void *r8 __asm__("r8") = newtls;
1224 register int *r10 __asm__("r10") = child_tidptr;
1225 __asm__ __volatile__(
1226 /* %rax = syscall(%rax = SYSCALL(clone),
1228 * %rsi = child_stack,
1229 * %rdx = parent_tidptr,
1231 * %r10 = child_tidptr)
1238 "testq %%rax,%%rax\n"
1241 /* In the child. Terminate unwind chain. */
1242 // XXX: We should also terminate the CFI unwind chain
1243 // here. Unfortunately clang 3.2 doesn't support the
1244 // necessary CFI directives, so we skip that part.
1245 "xorq %%rbp,%%rbp\n"
1247 /* Call "fn(arg)". */
1252 /* Call _exit(%rax). */
1253 "movq %%rax,%%rdi\n"
1257 /* Return to parent. */
1260 : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
1266 : "memory", "r11", "rcx");
1269 #elif defined(__mips__)
1270 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1271 int *parent_tidptr, void *newtls, int *child_tidptr) {
1273 if (!fn || !child_stack)
1275 CHECK_EQ(0, (uptr)child_stack % 16);
1276 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1277 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1278 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1279 register void *a3 __asm__("$7") = newtls;
1280 register int *a4 __asm__("$8") = child_tidptr;
1281 // We don't have proper CFI directives here because it requires alot of code
1282 // for very marginal benefits.
1283 __asm__ __volatile__(
1284 /* $v0 = syscall($v0 = __NR_clone,
1286 * $a1 = child_stack,
1287 * $a2 = parent_tidptr,
1289 * $a4 = child_tidptr)
1296 /* Store the fifth argument on stack
1297 * if we are using 32-bit abi.
1299 #if SANITIZER_WORDSIZE == 32
1312 /* Call "fn(arg)". */
1313 #if SANITIZER_WORDSIZE == 32
1314 #ifdef __BIG_ENDIAN__
1327 /* Call _exit($v0). */
1332 /* Return to parent. */
1342 : "memory", "$29" );
1345 #elif defined(__aarch64__)
1346 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1347 int *parent_tidptr, void *newtls, int *child_tidptr) {
1349 if (!fn || !child_stack)
1351 CHECK_EQ(0, (uptr)child_stack % 16);
1352 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1353 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1354 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1356 register int (*__fn)(void *) __asm__("x0") = fn;
1357 register void *__stack __asm__("x1") = child_stack;
1358 register int __flags __asm__("x2") = flags;
1359 register void *__arg __asm__("x3") = arg;
1360 register int *__ptid __asm__("x4") = parent_tidptr;
1361 register void *__tls __asm__("x5") = newtls;
1362 register int *__ctid __asm__("x6") = child_tidptr;
1364 __asm__ __volatile__(
1365 "mov x0,x2\n" /* flags */
1366 "mov x2,x4\n" /* ptid */
1367 "mov x3,x5\n" /* tls */
1368 "mov x4,x6\n" /* ctid */
1369 "mov x8,%9\n" /* clone */
1379 /* In the child, now. Call "fn(arg)". */
1380 "ldp x1, x0, [sp], #16\n"
1383 /* Call _exit(%r0). */
1390 "r"(__fn), "r"(__stack), "r"(__flags), "r"(__arg),
1391 "r"(__ptid), "r"(__tls), "r"(__ctid),
1392 "i"(__NR_clone), "i"(__NR_exit)
1396 #elif defined(__powerpc64__)
1397 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1398 int *parent_tidptr, void *newtls, int *child_tidptr) {
1400 // Stack frame structure.
1401 #if SANITIZER_PPC64V1
1402 // Back chain == 0 (SP + 112)
1403 // Frame (112 bytes):
1404 // Parameter save area (SP + 48), 8 doublewords
1405 // TOC save area (SP + 40)
1406 // Link editor doubleword (SP + 32)
1407 // Compiler doubleword (SP + 24)
1408 // LR save area (SP + 16)
1409 // CR save area (SP + 8)
1410 // Back chain (SP + 0)
1411 # define FRAME_SIZE 112
1412 # define FRAME_TOC_SAVE_OFFSET 40
1413 #elif SANITIZER_PPC64V2
1414 // Back chain == 0 (SP + 32)
1415 // Frame (32 bytes):
1416 // TOC save area (SP + 24)
1417 // LR save area (SP + 16)
1418 // CR save area (SP + 8)
1419 // Back chain (SP + 0)
1420 # define FRAME_SIZE 32
1421 # define FRAME_TOC_SAVE_OFFSET 24
1423 # error "Unsupported PPC64 ABI"
1425 if (!fn || !child_stack)
1427 CHECK_EQ(0, (uptr)child_stack % 16);
1429 register int (*__fn)(void *) __asm__("r3") = fn;
1430 register void *__cstack __asm__("r4") = child_stack;
1431 register int __flags __asm__("r5") = flags;
1432 register void *__arg __asm__("r6") = arg;
1433 register int *__ptidptr __asm__("r7") = parent_tidptr;
1434 register void *__newtls __asm__("r8") = newtls;
1435 register int *__ctidptr __asm__("r9") = child_tidptr;
1437 __asm__ __volatile__(
1438 /* fn and arg are saved across the syscall */
1448 r7 == child_tidptr */
1456 /* Test if syscall was successful */
1457 "cmpdi cr1, 3, 0\n\t"
1458 "crandc cr1*4+eq, cr1*4+eq, cr0*4+so\n\t"
1461 /* Set up stack frame */
1463 "stdu 29, -8(1)\n\t"
1464 "stdu 1, -%12(1)\n\t"
1465 /* Do the function call */
1467 #if SANITIZER_PPC64V1
1471 #elif SANITIZER_PPC64V2
1475 # error "Unsupported PPC64 ABI"
1481 /* Call _exit(r3) */
1485 /* Return to parent */
1501 "i" (FRAME_TOC_SAVE_OFFSET)
1502 : "cr0", "cr1", "memory", "ctr", "r0", "r27", "r28", "r29");
1505 #elif defined(__i386__) && SANITIZER_LINUX
1506 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1507 int *parent_tidptr, void *newtls, int *child_tidptr) {
1509 if (!fn || !child_stack)
1511 CHECK_EQ(0, (uptr)child_stack % 16);
1512 child_stack = (char *)child_stack - 7 * sizeof(unsigned int);
1513 ((unsigned int *)child_stack)[0] = (uptr)flags;
1514 ((unsigned int *)child_stack)[1] = (uptr)0;
1515 ((unsigned int *)child_stack)[2] = (uptr)fn;
1516 ((unsigned int *)child_stack)[3] = (uptr)arg;
1517 __asm__ __volatile__(
1518 /* %eax = syscall(%eax = SYSCALL(clone),
1520 * %ecx = child_stack,
1521 * %edx = parent_tidptr,
1523 * %edi = child_tidptr)
1527 "movl (%%ecx), %%ebx\n"
1528 /* Do the system call */
1532 /* Remember the flag value. */
1533 "movl %%ebx, (%%ecx)\n"
1543 "test %%eax,%%eax\n"
1546 /* terminate the stack frame */
1547 "xorl %%ebp,%%ebp\n"
1554 "addl $_GLOBAL_OFFSET_TABLE_+[.-here], %%ebx\n"
1557 "movl %%eax, %%ebx\n"
1562 : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
1570 #elif defined(__arm__) && SANITIZER_LINUX
1571 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1572 int *parent_tidptr, void *newtls, int *child_tidptr) {
1574 if (!fn || !child_stack)
1576 child_stack = (char *)child_stack - 2 * sizeof(unsigned int);
1577 ((unsigned int *)child_stack)[0] = (uptr)fn;
1578 ((unsigned int *)child_stack)[1] = (uptr)arg;
1579 register int r0 __asm__("r0") = flags;
1580 register void *r1 __asm__("r1") = child_stack;
1581 register int *r2 __asm__("r2") = parent_tidptr;
1582 register void *r3 __asm__("r3") = newtls;
1583 register int *r4 __asm__("r4") = child_tidptr;
1584 register int r7 __asm__("r7") = __NR_clone;
1586 #if __ARM_ARCH > 4 || defined (__ARM_ARCH_4T__)
1587 # define ARCH_HAS_BX
1590 # define ARCH_HAS_BLX
1594 # ifdef ARCH_HAS_BLX
1595 # define BLX(R) "blx " #R "\n"
1597 # define BLX(R) "mov lr, pc; bx " #R "\n"
1600 # define BLX(R) "mov lr, pc; mov pc," #R "\n"
1603 __asm__ __volatile__(
1604 /* %r0 = syscall(%r7 = SYSCALL(clone),
1606 * %r1 = child_stack,
1607 * %r2 = parent_tidptr,
1609 * %r4 = child_tidptr)
1612 /* Do the system call */
1621 /* In the child, now. Call "fn(arg)". */
1622 "ldr r0, [sp, #4]\n"
1623 "ldr ip, [sp], #8\n"
1625 /* Call _exit(%r0). */
1631 : "r"(r0), "r"(r1), "r"(r2), "r"(r3), "r"(r4), "r"(r7),
1636 #endif // defined(__x86_64__) && SANITIZER_LINUX
1638 #if SANITIZER_ANDROID
1639 #if __ANDROID_API__ < 21
1640 extern "C" __attribute__((weak)) int dl_iterate_phdr(
1641 int (*)(struct dl_phdr_info *, size_t, void *), void *);
1644 static int dl_iterate_phdr_test_cb(struct dl_phdr_info *info, size_t size,
1646 // Any name starting with "lib" indicates a bug in L where library base names
1647 // are returned instead of paths.
1648 if (info->dlpi_name && info->dlpi_name[0] == 'l' &&
1649 info->dlpi_name[1] == 'i' && info->dlpi_name[2] == 'b') {
1650 *(bool *)data = true;
1656 static atomic_uint32_t android_api_level;
1658 static AndroidApiLevel AndroidDetectApiLevelStatic() {
1659 #if __ANDROID_API__ <= 19
1660 return ANDROID_KITKAT;
1661 #elif __ANDROID_API__ <= 22
1662 return ANDROID_LOLLIPOP_MR1;
1664 return ANDROID_POST_LOLLIPOP;
1668 static AndroidApiLevel AndroidDetectApiLevel() {
1669 if (!&dl_iterate_phdr)
1670 return ANDROID_KITKAT; // K or lower
1671 bool base_name_seen = false;
1672 dl_iterate_phdr(dl_iterate_phdr_test_cb, &base_name_seen);
1674 return ANDROID_LOLLIPOP_MR1; // L MR1
1675 return ANDROID_POST_LOLLIPOP; // post-L
1676 // Plain L (API level 21) is completely broken wrt ASan and not very
1677 // interesting to detect.
1680 extern "C" __attribute__((weak)) void* _DYNAMIC;
1682 AndroidApiLevel AndroidGetApiLevel() {
1683 AndroidApiLevel level =
1684 (AndroidApiLevel)atomic_load(&android_api_level, memory_order_relaxed);
1685 if (level) return level;
1686 level = &_DYNAMIC == nullptr ? AndroidDetectApiLevelStatic()
1687 : AndroidDetectApiLevel();
1688 atomic_store(&android_api_level, level, memory_order_relaxed);
1694 static HandleSignalMode GetHandleSignalModeImpl(int signum) {
1697 return common_flags()->handle_abort;
1699 return common_flags()->handle_sigill;
1701 return common_flags()->handle_sigtrap;
1703 return common_flags()->handle_sigfpe;
1705 return common_flags()->handle_segv;
1707 return common_flags()->handle_sigbus;
1709 return kHandleSignalNo;
1712 HandleSignalMode GetHandleSignalMode(int signum) {
1713 HandleSignalMode result = GetHandleSignalModeImpl(signum);
1714 if (result == kHandleSignalYes && !common_flags()->allow_user_segv_handler)
1715 return kHandleSignalExclusive;
1720 void *internal_start_thread(void(*func)(void *arg), void *arg) {
1721 // Start the thread with signals blocked, otherwise it can steal user signals.
1722 __sanitizer_sigset_t set, old;
1723 internal_sigfillset(&set);
1724 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1725 // Glibc uses SIGSETXID signal during setuid call. If this signal is blocked
1726 // on any thread, setuid call hangs (see test/tsan/setuid.c).
1727 internal_sigdelset(&set, 33);
1729 internal_sigprocmask(SIG_SETMASK, &set, &old);
1731 real_pthread_create(&th, nullptr, (void*(*)(void *arg))func, arg);
1732 internal_sigprocmask(SIG_SETMASK, &old, nullptr);
1736 void internal_join_thread(void *th) {
1737 real_pthread_join(th, nullptr);
1740 void *internal_start_thread(void (*func)(void *), void *arg) { return 0; }
1742 void internal_join_thread(void *th) {}
1745 #if defined(__aarch64__)
1746 // Android headers in the older NDK releases miss this definition.
1747 struct __sanitizer_esr_context {
1748 struct _aarch64_ctx head;
1752 static bool Aarch64GetESR(ucontext_t *ucontext, u64 *esr) {
1753 static const u32 kEsrMagic = 0x45535201;
1754 u8 *aux = ucontext->uc_mcontext.__reserved;
1756 _aarch64_ctx *ctx = (_aarch64_ctx *)aux;
1757 if (ctx->size == 0) break;
1758 if (ctx->magic == kEsrMagic) {
1759 *esr = ((__sanitizer_esr_context *)ctx)->esr;
1768 #if SANITIZER_OPENBSD
1769 using Context = sigcontext;
1771 using Context = ucontext_t;
1774 SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
1775 Context *ucontext = (Context *)context;
1776 #if defined(__x86_64__) || defined(__i386__)
1777 static const uptr PF_WRITE = 1U << 1;
1778 #if SANITIZER_FREEBSD
1779 uptr err = ucontext->uc_mcontext.mc_err;
1780 #elif SANITIZER_NETBSD
1781 uptr err = ucontext->uc_mcontext.__gregs[_REG_ERR];
1782 #elif SANITIZER_OPENBSD
1783 uptr err = ucontext->sc_err;
1784 #elif SANITIZER_SOLARIS && defined(__i386__)
1786 uptr err = ucontext->uc_mcontext.gregs[Err];
1788 uptr err = ucontext->uc_mcontext.gregs[REG_ERR];
1789 #endif // SANITIZER_FREEBSD
1790 return err & PF_WRITE ? WRITE : READ;
1791 #elif defined(__mips__)
1792 uint32_t *exception_source;
1793 uint32_t faulty_instruction;
1796 exception_source = (uint32_t *)ucontext->uc_mcontext.pc;
1797 faulty_instruction = (uint32_t)(*exception_source);
1799 op_code = (faulty_instruction >> 26) & 0x3f;
1801 // FIXME: Add support for FPU, microMIPS, DSP, MSA memory instructions.
1807 #if __mips_isa_rev < 6
1813 return SignalContext::WRITE;
1822 #if __mips_isa_rev < 6
1828 return SignalContext::READ;
1829 #if __mips_isa_rev == 6
1831 op_code = (faulty_instruction >> 19) & 0x3;
1835 return SignalContext::READ;
1839 return SignalContext::UNKNOWN;
1840 #elif defined(__arm__)
1841 static const uptr FSR_WRITE = 1U << 11;
1842 uptr fsr = ucontext->uc_mcontext.error_code;
1843 return fsr & FSR_WRITE ? WRITE : READ;
1844 #elif defined(__aarch64__)
1845 static const u64 ESR_ELx_WNR = 1U << 6;
1847 if (!Aarch64GetESR(ucontext, &esr)) return UNKNOWN;
1848 return esr & ESR_ELx_WNR ? WRITE : READ;
1849 #elif SANITIZER_SOLARIS && defined(__sparc__)
1850 // Decode the instruction to determine the access type.
1851 // From OpenSolaris $SRC/uts/sun4/os/trap.c (get_accesstype).
1852 uptr pc = ucontext->uc_mcontext.gregs[REG_PC];
1853 u32 instr = *(u32 *)pc;
1854 return (instr >> 21) & 1 ? WRITE: READ;
1857 return UNKNOWN; // FIXME: Implement.
1861 void SignalContext::DumpAllRegisters(void *context) {
1862 // FIXME: Implement this.
1865 static void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
1866 #if SANITIZER_NETBSD
1867 // This covers all NetBSD architectures
1868 ucontext_t *ucontext = (ucontext_t *)context;
1869 *pc = _UC_MACHINE_PC(ucontext);
1870 *bp = _UC_MACHINE_FP(ucontext);
1871 *sp = _UC_MACHINE_SP(ucontext);
1872 #elif defined(__arm__)
1873 ucontext_t *ucontext = (ucontext_t*)context;
1874 *pc = ucontext->uc_mcontext.arm_pc;
1875 *bp = ucontext->uc_mcontext.arm_fp;
1876 *sp = ucontext->uc_mcontext.arm_sp;
1877 #elif defined(__aarch64__)
1878 ucontext_t *ucontext = (ucontext_t*)context;
1879 *pc = ucontext->uc_mcontext.pc;
1880 *bp = ucontext->uc_mcontext.regs[29];
1881 *sp = ucontext->uc_mcontext.sp;
1882 #elif defined(__hppa__)
1883 ucontext_t *ucontext = (ucontext_t*)context;
1884 *pc = ucontext->uc_mcontext.sc_iaoq[0];
1885 /* GCC uses %r3 whenever a frame pointer is needed. */
1886 *bp = ucontext->uc_mcontext.sc_gr[3];
1887 *sp = ucontext->uc_mcontext.sc_gr[30];
1888 #elif defined(__x86_64__)
1889 # if SANITIZER_FREEBSD
1890 ucontext_t *ucontext = (ucontext_t*)context;
1891 *pc = ucontext->uc_mcontext.mc_rip;
1892 *bp = ucontext->uc_mcontext.mc_rbp;
1893 *sp = ucontext->uc_mcontext.mc_rsp;
1894 #elif SANITIZER_OPENBSD
1895 sigcontext *ucontext = (sigcontext *)context;
1896 *pc = ucontext->sc_rip;
1897 *bp = ucontext->sc_rbp;
1898 *sp = ucontext->sc_rsp;
1900 ucontext_t *ucontext = (ucontext_t*)context;
1901 *pc = ucontext->uc_mcontext.gregs[REG_RIP];
1902 *bp = ucontext->uc_mcontext.gregs[REG_RBP];
1903 *sp = ucontext->uc_mcontext.gregs[REG_RSP];
1905 #elif defined(__i386__)
1906 # if SANITIZER_FREEBSD
1907 ucontext_t *ucontext = (ucontext_t*)context;
1908 *pc = ucontext->uc_mcontext.mc_eip;
1909 *bp = ucontext->uc_mcontext.mc_ebp;
1910 *sp = ucontext->uc_mcontext.mc_esp;
1911 #elif SANITIZER_OPENBSD
1912 sigcontext *ucontext = (sigcontext *)context;
1913 *pc = ucontext->sc_eip;
1914 *bp = ucontext->sc_ebp;
1915 *sp = ucontext->sc_esp;
1917 ucontext_t *ucontext = (ucontext_t*)context;
1918 # if SANITIZER_SOLARIS
1919 /* Use the numeric values: the symbolic ones are undefined by llvm
1920 include/llvm/Support/Solaris.h. */
1922 # define REG_EIP 14 // REG_PC
1925 # define REG_EBP 6 // REG_FP
1928 # define REG_ESP 17 // REG_SP
1931 *pc = ucontext->uc_mcontext.gregs[REG_EIP];
1932 *bp = ucontext->uc_mcontext.gregs[REG_EBP];
1933 *sp = ucontext->uc_mcontext.gregs[REG_ESP];
1935 #elif defined(__powerpc__) || defined(__powerpc64__)
1936 ucontext_t *ucontext = (ucontext_t*)context;
1937 *pc = ucontext->uc_mcontext.regs->nip;
1938 *sp = ucontext->uc_mcontext.regs->gpr[PT_R1];
1939 // The powerpc{,64}-linux ABIs do not specify r31 as the frame
1940 // pointer, but GCC always uses r31 when we need a frame pointer.
1941 *bp = ucontext->uc_mcontext.regs->gpr[PT_R31];
1942 #elif defined(__sparc__)
1943 ucontext_t *ucontext = (ucontext_t*)context;
1945 # if defined(__sparcv9) || defined (__arch64__)
1947 # define MC_PC REG_PC
1950 # define MC_O6 REG_O6
1952 # if SANITIZER_SOLARIS
1953 # define mc_gregs gregs
1955 *pc = ucontext->uc_mcontext.mc_gregs[MC_PC];
1956 *sp = ucontext->uc_mcontext.mc_gregs[MC_O6];
1957 stk_ptr = (uptr *) (*sp + 2047);
1960 *pc = ucontext->uc_mcontext.gregs[REG_PC];
1961 *sp = ucontext->uc_mcontext.gregs[REG_O6];
1962 stk_ptr = (uptr *) *sp;
1965 #elif defined(__mips__)
1966 ucontext_t *ucontext = (ucontext_t*)context;
1967 *pc = ucontext->uc_mcontext.pc;
1968 *bp = ucontext->uc_mcontext.gregs[30];
1969 *sp = ucontext->uc_mcontext.gregs[29];
1970 #elif defined(__s390__)
1971 ucontext_t *ucontext = (ucontext_t*)context;
1972 # if defined(__s390x__)
1973 *pc = ucontext->uc_mcontext.psw.addr;
1975 *pc = ucontext->uc_mcontext.psw.addr & 0x7fffffff;
1977 *bp = ucontext->uc_mcontext.gregs[11];
1978 *sp = ucontext->uc_mcontext.gregs[15];
1980 # error "Unsupported arch"
1984 void SignalContext::InitPcSpBp() { GetPcSpBp(context, &pc, &sp, &bp); }
1986 void InitializePlatformEarly() {
1990 void MaybeReexec() {
1991 // No need to re-exec on Linux.
1995 #if SANITIZER_NETBSD
1998 uptr len = sizeof(paxflags);
2001 mib[1] = internal_getpid();
2002 mib[2] = PROC_PID_PAXFLAGS;
2004 if (UNLIKELY(internal_sysctl(mib, 3, &paxflags, &len, NULL, 0) == -1)) {
2005 Printf("sysctl failed\n");
2009 if (UNLIKELY(paxflags & CTL_PROC_PAXFLAGS_ASLR)) {
2010 Printf("This sanitizer is not compatible with enabled ASLR\n");
2013 #elif SANITIZER_PPC64V2
2014 // Disable ASLR for Linux PPC64LE.
2015 int old_personality = personality(0xffffffff);
2016 if (old_personality != -1 && (old_personality & ADDR_NO_RANDOMIZE) == 0) {
2017 VReport(1, "WARNING: Program is being run with address space layout "
2018 "randomization (ASLR) enabled which prevents the thread and "
2019 "memory sanitizers from working on powerpc64le.\n"
2020 "ASLR will be disabled and the program re-executed.\n");
2021 CHECK_NE(personality(old_personality | ADDR_NO_RANDOMIZE), -1);
2029 void CheckMPROTECT() {
2030 #if SANITIZER_NETBSD
2033 uptr len = sizeof(paxflags);
2036 mib[1] = internal_getpid();
2037 mib[2] = PROC_PID_PAXFLAGS;
2039 if (UNLIKELY(internal_sysctl(mib, 3, &paxflags, &len, NULL, 0) == -1)) {
2040 Printf("sysctl failed\n");
2044 if (UNLIKELY(paxflags & CTL_PROC_PAXFLAGS_MPROTECT)) {
2045 Printf("This sanitizer is not compatible with enabled MPROTECT\n");
2053 void PrintModuleMap() { }
2055 void CheckNoDeepBind(const char *filename, int flag) {
2056 #ifdef RTLD_DEEPBIND
2057 if (flag & RTLD_DEEPBIND) {
2059 "You are trying to dlopen a %s shared library with RTLD_DEEPBIND flag"
2060 " which is incompatibe with sanitizer runtime "
2061 "(see https://github.com/google/sanitizers/issues/611 for details"
2062 "). If you want to run %s library under sanitizers please remove "
2063 "RTLD_DEEPBIND from dlopen flags.\n",
2064 filename, filename);
2070 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
2071 uptr *largest_gap_found,
2072 uptr *max_occupied_addr) {
2073 UNREACHABLE("FindAvailableMemoryRange is not available");
2077 bool GetRandom(void *buffer, uptr length, bool blocking) {
2078 if (!buffer || !length || length > 256)
2080 #if SANITIZER_USE_GETENTROPY
2081 uptr rnd = getentropy(buffer, length);
2083 if (internal_iserror(rnd, &rverrno) && rverrno == EFAULT)
2087 #endif // SANITIZER_USE_GETENTROPY
2089 #if SANITIZER_USE_GETRANDOM
2090 static atomic_uint8_t skip_getrandom_syscall;
2091 if (!atomic_load_relaxed(&skip_getrandom_syscall)) {
2092 // Up to 256 bytes, getrandom will not be interrupted.
2093 uptr res = internal_syscall(SYSCALL(getrandom), buffer, length,
2094 blocking ? 0 : GRND_NONBLOCK);
2096 if (internal_iserror(res, &rverrno) && rverrno == ENOSYS)
2097 atomic_store_relaxed(&skip_getrandom_syscall, 1);
2098 else if (res == length)
2101 #endif // SANITIZER_USE_GETRANDOM
2102 // Up to 256 bytes, a read off /dev/urandom will not be interrupted.
2103 // blocking is moot here, O_NONBLOCK has no effect when opening /dev/urandom.
2104 uptr fd = internal_open("/dev/urandom", O_RDONLY);
2105 if (internal_iserror(fd))
2107 uptr res = internal_read(fd, buffer, length);
2108 if (internal_iserror(res))
2114 } // namespace __sanitizer