1 //===-- sanitizer_linux.cc ------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file is shared between AddressSanitizer and ThreadSanitizer
10 // run-time libraries and implements linux-specific functions from
12 //===----------------------------------------------------------------------===//
14 #include "sanitizer_platform.h"
16 #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD || \
17 SANITIZER_OPENBSD || SANITIZER_SOLARIS
19 #include "sanitizer_common.h"
20 #include "sanitizer_flags.h"
21 #include "sanitizer_getauxval.h"
22 #include "sanitizer_internal_defs.h"
23 #include "sanitizer_libc.h"
24 #include "sanitizer_linux.h"
25 #include "sanitizer_mutex.h"
26 #include "sanitizer_placement_new.h"
27 #include "sanitizer_procmaps.h"
30 #include <asm/param.h>
33 // For mips64, syscall(__NR_stat) fills the buffer in the 'struct kernel_stat'
34 // format. Struct kernel_stat is defined as 'struct stat' in asm/stat.h. To
35 // access stat from asm/stat.h, without conflicting with definition in
36 // sys/stat.h, we use this trick.
38 #include <asm/unistd.h>
39 #include <sys/types.h>
40 #define stat kernel_stat
53 #include <sys/param.h>
54 #if !SANITIZER_SOLARIS
55 #include <sys/ptrace.h>
57 #include <sys/resource.h>
59 #include <sys/syscall.h>
61 #include <sys/types.h>
62 #if !SANITIZER_OPENBSD
66 #include <sys/futex.h>
67 #include <sys/sysctl.h>
72 #include <sys/utsname.h>
75 #if SANITIZER_LINUX && !SANITIZER_ANDROID
76 #include <sys/personality.h>
81 #include <sys/sysctl.h>
82 #include <machine/atomic.h>
84 // <sys/umtx.h> must be included after <errno.h> and <sys/types.h> on
85 // FreeBSD 9.2 and 10.0.
89 #endif // SANITIZER_FREEBSD
92 #include <limits.h> // For NAME_MAX
93 #include <sys/sysctl.h>
95 extern struct ps_strings *__ps_strings;
96 #endif // SANITIZER_NETBSD
101 #define environ _environ
104 extern char **environ;
108 struct kernel_timeval {
113 // <linux/futex.h> is broken on some linux distributions.
114 const int FUTEX_WAIT = 0;
115 const int FUTEX_WAKE = 1;
116 const int FUTEX_PRIVATE_FLAG = 128;
117 const int FUTEX_WAIT_PRIVATE = FUTEX_WAIT | FUTEX_PRIVATE_FLAG;
118 const int FUTEX_WAKE_PRIVATE = FUTEX_WAKE | FUTEX_PRIVATE_FLAG;
119 #endif // SANITIZER_LINUX
121 // Are we using 32-bit or 64-bit Linux syscalls?
122 // x32 (which defines __x86_64__) has SANITIZER_WORDSIZE == 32
123 // but it still needs to use 64-bit syscalls.
124 #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__powerpc64__) || \
125 SANITIZER_WORDSIZE == 64)
126 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 1
128 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 0
131 // Note : FreeBSD had implemented both
132 // Linux and OpenBSD apis, available from
133 // future 12.x version most likely
134 #if SANITIZER_LINUX && defined(__NR_getrandom)
135 # if !defined(GRND_NONBLOCK)
136 # define GRND_NONBLOCK 1
138 # define SANITIZER_USE_GETRANDOM 1
140 # define SANITIZER_USE_GETRANDOM 0
141 #endif // SANITIZER_LINUX && defined(__NR_getrandom)
143 #if SANITIZER_OPENBSD
144 # define SANITIZER_USE_GETENTROPY 1
146 # if SANITIZER_FREEBSD && __FreeBSD_version >= 1200000
147 # define SANITIZER_USE_GETENTROPY 1
149 # define SANITIZER_USE_GETENTROPY 0
151 #endif // SANITIZER_USE_GETENTROPY
153 namespace __sanitizer {
155 #if SANITIZER_LINUX && defined(__x86_64__)
156 #include "sanitizer_syscall_linux_x86_64.inc"
157 #elif SANITIZER_LINUX && defined(__aarch64__)
158 #include "sanitizer_syscall_linux_aarch64.inc"
159 #elif SANITIZER_LINUX && defined(__arm__)
160 #include "sanitizer_syscall_linux_arm.inc"
162 #include "sanitizer_syscall_generic.inc"
165 // --------------- sanitizer_libc.h
166 #if !SANITIZER_SOLARIS && !SANITIZER_NETBSD
167 #if !SANITIZER_S390 && !SANITIZER_OPENBSD
168 uptr internal_mmap(void *addr, uptr length, int prot, int flags, int fd,
170 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
171 return internal_syscall(SYSCALL(mmap), (uptr)addr, length, prot, flags, fd,
174 // mmap2 specifies file offset in 4096-byte units.
175 CHECK(IsAligned(offset, 4096));
176 return internal_syscall(SYSCALL(mmap2), addr, length, prot, flags, fd,
180 #endif // !SANITIZER_S390 && !SANITIZER_OPENBSD
182 #if !SANITIZER_OPENBSD
183 uptr internal_munmap(void *addr, uptr length) {
184 return internal_syscall(SYSCALL(munmap), (uptr)addr, length);
187 int internal_mprotect(void *addr, uptr length, int prot) {
188 return internal_syscall(SYSCALL(mprotect), (uptr)addr, length, prot);
192 uptr internal_close(fd_t fd) {
193 return internal_syscall(SYSCALL(close), fd);
196 uptr internal_open(const char *filename, int flags) {
197 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
198 return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags);
200 return internal_syscall(SYSCALL(open), (uptr)filename, flags);
204 uptr internal_open(const char *filename, int flags, u32 mode) {
205 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
206 return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags,
209 return internal_syscall(SYSCALL(open), (uptr)filename, flags, mode);
213 uptr internal_read(fd_t fd, void *buf, uptr count) {
216 (sptr)internal_syscall(SYSCALL(read), fd, (uptr)buf, count));
220 uptr internal_write(fd_t fd, const void *buf, uptr count) {
223 (sptr)internal_syscall(SYSCALL(write), fd, (uptr)buf, count));
227 uptr internal_ftruncate(fd_t fd, uptr size) {
229 HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(ftruncate), fd,
234 #if !SANITIZER_LINUX_USES_64BIT_SYSCALLS && SANITIZER_LINUX
235 static void stat64_to_stat(struct stat64 *in, struct stat *out) {
236 internal_memset(out, 0, sizeof(*out));
237 out->st_dev = in->st_dev;
238 out->st_ino = in->st_ino;
239 out->st_mode = in->st_mode;
240 out->st_nlink = in->st_nlink;
241 out->st_uid = in->st_uid;
242 out->st_gid = in->st_gid;
243 out->st_rdev = in->st_rdev;
244 out->st_size = in->st_size;
245 out->st_blksize = in->st_blksize;
246 out->st_blocks = in->st_blocks;
247 out->st_atime = in->st_atime;
248 out->st_mtime = in->st_mtime;
249 out->st_ctime = in->st_ctime;
253 #if defined(__mips64)
254 // Undefine compatibility macros from <sys/stat.h>
255 // so that they would not clash with the kernel_stat
256 // st_[a|m|c]time fields
260 #if defined(SANITIZER_ANDROID)
261 // Bionic sys/stat.h defines additional macros
262 // for compatibility with the old NDKs and
263 // they clash with the kernel_stat structure
264 // st_[a|m|c]time_nsec fields.
269 static void kernel_stat_to_stat(struct kernel_stat *in, struct stat *out) {
270 internal_memset(out, 0, sizeof(*out));
271 out->st_dev = in->st_dev;
272 out->st_ino = in->st_ino;
273 out->st_mode = in->st_mode;
274 out->st_nlink = in->st_nlink;
275 out->st_uid = in->st_uid;
276 out->st_gid = in->st_gid;
277 out->st_rdev = in->st_rdev;
278 out->st_size = in->st_size;
279 out->st_blksize = in->st_blksize;
280 out->st_blocks = in->st_blocks;
281 #if defined(__USE_MISC) || \
282 defined(__USE_XOPEN2K8) || \
283 defined(SANITIZER_ANDROID)
284 out->st_atim.tv_sec = in->st_atime;
285 out->st_atim.tv_nsec = in->st_atime_nsec;
286 out->st_mtim.tv_sec = in->st_mtime;
287 out->st_mtim.tv_nsec = in->st_mtime_nsec;
288 out->st_ctim.tv_sec = in->st_ctime;
289 out->st_ctim.tv_nsec = in->st_ctime_nsec;
291 out->st_atime = in->st_atime;
292 out->st_atimensec = in->st_atime_nsec;
293 out->st_mtime = in->st_mtime;
294 out->st_mtimensec = in->st_mtime_nsec;
295 out->st_ctime = in->st_ctime;
296 out->st_atimensec = in->st_ctime_nsec;
301 uptr internal_stat(const char *path, void *buf) {
302 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD
303 return internal_syscall(SYSCALL(fstatat), AT_FDCWD, (uptr)path, (uptr)buf, 0);
304 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
305 return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path, (uptr)buf,
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) {
326 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD
327 return internal_syscall(SYSCALL(fstatat), AT_FDCWD, (uptr)path, (uptr)buf,
328 AT_SYMLINK_NOFOLLOW);
329 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
330 return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path, (uptr)buf,
331 AT_SYMLINK_NOFOLLOW);
332 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
333 # if SANITIZER_MIPS64
334 // For mips64, lstat syscall fills buffer in the format of kernel_stat
335 struct kernel_stat kbuf;
336 int res = internal_syscall(SYSCALL(lstat), path, &kbuf);
337 kernel_stat_to_stat(&kbuf, (struct stat *)buf);
340 return internal_syscall(SYSCALL(lstat), (uptr)path, (uptr)buf);
344 int res = internal_syscall(SYSCALL(lstat64), path, &buf64);
345 stat64_to_stat(&buf64, (struct stat *)buf);
350 uptr internal_fstat(fd_t fd, void *buf) {
351 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD || \
352 SANITIZER_LINUX_USES_64BIT_SYSCALLS
353 #if SANITIZER_MIPS64 && !SANITIZER_OPENBSD
354 // For mips64, fstat syscall fills buffer in the format of kernel_stat
355 struct kernel_stat kbuf;
356 int res = internal_syscall(SYSCALL(fstat), fd, &kbuf);
357 kernel_stat_to_stat(&kbuf, (struct stat *)buf);
360 return internal_syscall(SYSCALL(fstat), fd, (uptr)buf);
364 int res = internal_syscall(SYSCALL(fstat64), fd, &buf64);
365 stat64_to_stat(&buf64, (struct stat *)buf);
370 uptr internal_filesize(fd_t fd) {
372 if (internal_fstat(fd, &st))
374 return (uptr)st.st_size;
377 uptr internal_dup(int oldfd) {
378 return internal_syscall(SYSCALL(dup), oldfd);
381 uptr internal_dup2(int oldfd, int newfd) {
382 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
383 return internal_syscall(SYSCALL(dup3), oldfd, newfd, 0);
385 return internal_syscall(SYSCALL(dup2), oldfd, newfd);
389 uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
390 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
391 return internal_syscall(SYSCALL(readlinkat), AT_FDCWD, (uptr)path, (uptr)buf,
393 #elif SANITIZER_OPENBSD
394 return internal_syscall(SYSCALL(readlinkat), AT_FDCWD, (uptr)path, (uptr)buf,
397 return internal_syscall(SYSCALL(readlink), (uptr)path, (uptr)buf, bufsize);
401 uptr internal_unlink(const char *path) {
402 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS || SANITIZER_OPENBSD
403 return internal_syscall(SYSCALL(unlinkat), AT_FDCWD, (uptr)path, 0);
405 return internal_syscall(SYSCALL(unlink), (uptr)path);
409 uptr internal_rename(const char *oldpath, const char *newpath) {
410 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS || SANITIZER_OPENBSD
411 return internal_syscall(SYSCALL(renameat), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
414 return internal_syscall(SYSCALL(rename), (uptr)oldpath, (uptr)newpath);
418 uptr internal_sched_yield() {
419 return internal_syscall(SYSCALL(sched_yield));
422 void internal__exit(int exitcode) {
423 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD
424 internal_syscall(SYSCALL(exit), exitcode);
426 internal_syscall(SYSCALL(exit_group), exitcode);
428 Die(); // Unreachable.
431 unsigned int internal_sleep(unsigned int seconds) {
435 int res = internal_syscall(SYSCALL(nanosleep), &ts, &ts);
436 if (res) return ts.tv_sec;
440 uptr internal_execve(const char *filename, char *const argv[],
441 char *const envp[]) {
442 return internal_syscall(SYSCALL(execve), (uptr)filename, (uptr)argv,
445 #endif // !SANITIZER_SOLARIS && !SANITIZER_NETBSD
447 // ----------------- sanitizer_common.h
448 bool FileExists(const char *filename) {
449 if (ShouldMockFailureToOpen(filename))
452 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
453 if (internal_syscall(SYSCALL(newfstatat), AT_FDCWD, filename, &st, 0))
455 if (internal_stat(filename, &st))
458 // Sanity check: filename is a regular file.
459 return S_ISREG(st.st_mode);
462 #if !SANITIZER_NETBSD
464 #if SANITIZER_FREEBSD
468 #elif SANITIZER_OPENBSD
469 return internal_syscall(SYSCALL(getthrid));
470 #elif SANITIZER_SOLARIS
473 return internal_syscall(SYSCALL(gettid));
477 int TgKill(pid_t pid, tid_t tid, int sig) {
479 return internal_syscall(SYSCALL(tgkill), pid, tid, sig);
480 #elif SANITIZER_FREEBSD
481 return internal_syscall(SYSCALL(thr_kill2), pid, tid, sig);
482 #elif SANITIZER_OPENBSD
484 return internal_syscall(SYSCALL(thrkill), tid, sig, nullptr);
485 #elif SANITIZER_SOLARIS
487 return thr_kill(tid, sig);
492 #if !SANITIZER_SOLARIS && !SANITIZER_NETBSD
494 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD
499 internal_memset(&tv, 0, sizeof(tv));
500 internal_syscall(SYSCALL(gettimeofday), &tv, 0);
501 return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
504 uptr internal_clock_gettime(__sanitizer_clockid_t clk_id, void *tp) {
505 return internal_syscall(SYSCALL(clock_gettime), clk_id, tp);
507 #endif // !SANITIZER_SOLARIS && !SANITIZER_NETBSD
509 // Like getenv, but reads env directly from /proc (on Linux) or parses the
510 // 'environ' array (on some others) and does not use libc. This function
511 // should be called first inside __asan_init.
512 const char *GetEnv(const char *name) {
513 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD || \
515 if (::environ != 0) {
516 uptr NameLen = internal_strlen(name);
517 for (char **Env = ::environ; *Env != 0; Env++) {
518 if (internal_strncmp(*Env, name, NameLen) == 0 && (*Env)[NameLen] == '=')
519 return (*Env) + NameLen + 1;
522 return 0; // Not found.
523 #elif SANITIZER_LINUX
524 static char *environ;
530 if (!ReadFileToBuffer("/proc/self/environ", &environ, &environ_size, &len))
533 if (!environ || len == 0) return nullptr;
534 uptr namelen = internal_strlen(name);
535 const char *p = environ;
536 while (*p != '\0') { // will happen at the \0\0 that terminates the buffer
537 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
539 (char*)internal_memchr(p, '\0', len - (p - environ));
540 if (!endp) // this entry isn't NUL terminated
542 else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') // Match.
543 return p + namelen + 1; // point after =
546 return nullptr; // Not found.
548 #error "Unsupported platform"
552 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD && !SANITIZER_OPENBSD
554 SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
558 #if !SANITIZER_GO && !SANITIZER_FREEBSD && !SANITIZER_NETBSD && \
560 static void ReadNullSepFileToArray(const char *path, char ***arr,
565 *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
566 if (!ReadFileToBuffer(path, &buff, &buff_size, &buff_len, 1024 * 1024)) {
572 for (count = 1, i = 1; ; i++) {
574 if (buff[i+1] == 0) break;
575 (*arr)[count] = &buff[i+1];
576 CHECK_LE(count, arr_size - 1); // FIXME: make this more flexible.
580 (*arr)[count] = nullptr;
584 #if !SANITIZER_OPENBSD
585 static void GetArgsAndEnv(char ***argv, char ***envp) {
586 #if SANITIZER_FREEBSD
587 // On FreeBSD, retrieving the argument and environment arrays is done via the
588 // kern.ps_strings sysctl, which returns a pointer to a structure containing
589 // this information. See also <sys/exec.h>.
591 uptr sz = sizeof(pss);
592 if (internal_sysctlbyname("kern.ps_strings", &pss, &sz, NULL, 0) == -1) {
593 Printf("sysctl kern.ps_strings failed\n");
596 *argv = pss->ps_argvstr;
597 *envp = pss->ps_envstr;
598 #elif SANITIZER_NETBSD
599 *argv = __ps_strings->ps_argvstr;
600 *envp = __ps_strings->ps_envstr;
601 #else // SANITIZER_FREEBSD
603 if (&__libc_stack_end) {
604 #endif // !SANITIZER_GO
605 uptr* stack_end = (uptr*)__libc_stack_end;
606 int argc = *stack_end;
607 *argv = (char**)(stack_end + 1);
608 *envp = (char**)(stack_end + argc + 2);
611 static const int kMaxArgv = 2000, kMaxEnvp = 2000;
612 ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
613 ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
615 #endif // !SANITIZER_GO
616 #endif // SANITIZER_FREEBSD
621 GetArgsAndEnv(&argv, &envp);
625 char **GetEnviron() {
627 GetArgsAndEnv(&argv, &envp);
631 #endif // !SANITIZER_OPENBSD
633 #if !SANITIZER_SOLARIS
640 BlockingMutex::BlockingMutex() {
641 internal_memset(this, 0, sizeof(*this));
644 void BlockingMutex::Lock() {
646 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
647 if (atomic_exchange(m, MtxLocked, memory_order_acquire) == MtxUnlocked)
649 while (atomic_exchange(m, MtxSleeping, memory_order_acquire) != MtxUnlocked) {
650 #if SANITIZER_FREEBSD
651 _umtx_op(m, UMTX_OP_WAIT_UINT, MtxSleeping, 0, 0);
652 #elif SANITIZER_NETBSD
653 sched_yield(); /* No userspace futex-like synchronization */
655 internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAIT_PRIVATE, MtxSleeping,
661 void BlockingMutex::Unlock() {
662 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
663 u32 v = atomic_exchange(m, MtxUnlocked, memory_order_release);
664 CHECK_NE(v, MtxUnlocked);
665 if (v == MtxSleeping) {
666 #if SANITIZER_FREEBSD
667 _umtx_op(m, UMTX_OP_WAKE, 1, 0, 0);
668 #elif SANITIZER_NETBSD
669 /* No userspace futex-like synchronization */
671 internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAKE_PRIVATE, 1, 0, 0, 0);
676 void BlockingMutex::CheckLocked() {
677 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
678 CHECK_NE(MtxUnlocked, atomic_load(m, memory_order_relaxed));
680 #endif // !SANITIZER_SOLARIS
682 // ----------------- sanitizer_linux.h
683 // The actual size of this structure is specified by d_reclen.
684 // Note that getdents64 uses a different structure format. We only provide the
685 // 32-bit syscall here.
688 #elif SANITIZER_OPENBSD
689 // struct dirent is different for Linux and us. At this moment, we use only
690 // d_fileno (Linux call this d_ino), d_reclen, and d_name.
691 struct linux_dirent {
692 u64 d_ino; // d_fileno
694 u16 d_namlen; // not used
695 u8 d_type; // not used
696 char d_name[NAME_MAX + 1];
699 struct linux_dirent {
700 #if SANITIZER_X32 || defined(__aarch64__)
707 unsigned short d_reclen;
709 unsigned char d_type;
715 #if !SANITIZER_SOLARIS && !SANITIZER_NETBSD
717 uptr internal_ptrace(int request, int pid, void *addr, void *data) {
718 return internal_syscall(SYSCALL(ptrace), request, pid, (uptr)addr,
722 uptr internal_waitpid(int pid, int *status, int options) {
723 return internal_syscall(SYSCALL(wait4), pid, (uptr)status, options,
727 uptr internal_getpid() {
728 return internal_syscall(SYSCALL(getpid));
731 uptr internal_getppid() {
732 return internal_syscall(SYSCALL(getppid));
735 uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) {
736 #if SANITIZER_FREEBSD
737 return internal_syscall(SYSCALL(getdirentries), fd, (uptr)dirp, count, NULL);
738 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
739 return internal_syscall(SYSCALL(getdents64), fd, (uptr)dirp, count);
741 return internal_syscall(SYSCALL(getdents), fd, (uptr)dirp, count);
745 uptr internal_lseek(fd_t fd, OFF_T offset, int whence) {
746 return internal_syscall(SYSCALL(lseek), fd, offset, whence);
750 uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
751 return internal_syscall(SYSCALL(prctl), option, arg2, arg3, arg4, arg5);
755 uptr internal_sigaltstack(const void *ss, void *oss) {
756 return internal_syscall(SYSCALL(sigaltstack), (uptr)ss, (uptr)oss);
759 int internal_fork() {
760 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
761 return internal_syscall(SYSCALL(clone), SIGCHLD, 0);
763 return internal_syscall(SYSCALL(fork));
767 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD
768 int internal_sysctl(const int *name, unsigned int namelen, void *oldp,
769 uptr *oldlenp, const void *newp, uptr newlen) {
770 #if SANITIZER_OPENBSD
771 return sysctl(name, namelen, oldp, (size_t *)oldlenp, (void *)newp,
774 return internal_syscall(SYSCALL(__sysctl), name, namelen, oldp,
775 (size_t *)oldlenp, newp, (size_t)newlen);
779 #if SANITIZER_FREEBSD
780 int internal_sysctlbyname(const char *sname, void *oldp, uptr *oldlenp,
781 const void *newp, uptr newlen) {
782 return sysctlbyname(sname, oldp, (size_t *)oldlenp, newp, (size_t)newlen);
788 #define SA_RESTORER 0x04000000
789 // Doesn't set sa_restorer if the caller did not set it, so use with caution
791 int internal_sigaction_norestorer(int signum, const void *act, void *oldact) {
792 __sanitizer_kernel_sigaction_t k_act, k_oldact;
793 internal_memset(&k_act, 0, sizeof(__sanitizer_kernel_sigaction_t));
794 internal_memset(&k_oldact, 0, sizeof(__sanitizer_kernel_sigaction_t));
795 const __sanitizer_sigaction *u_act = (const __sanitizer_sigaction *)act;
796 __sanitizer_sigaction *u_oldact = (__sanitizer_sigaction *)oldact;
798 k_act.handler = u_act->handler;
799 k_act.sigaction = u_act->sigaction;
800 internal_memcpy(&k_act.sa_mask, &u_act->sa_mask,
801 sizeof(__sanitizer_kernel_sigset_t));
802 // Without SA_RESTORER kernel ignores the calls (probably returns EINVAL).
803 k_act.sa_flags = u_act->sa_flags | SA_RESTORER;
804 // FIXME: most often sa_restorer is unset, however the kernel requires it
805 // to point to a valid signal restorer that calls the rt_sigreturn syscall.
806 // If sa_restorer passed to the kernel is NULL, the program may crash upon
807 // signal delivery or fail to unwind the stack in the signal handler.
808 // libc implementation of sigaction() passes its own restorer to
809 // rt_sigaction, so we need to do the same (we'll need to reimplement the
810 // restorers; for x86_64 the restorer address can be obtained from
811 // oldact->sa_restorer upon a call to sigaction(xxx, NULL, oldact).
812 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
813 k_act.sa_restorer = u_act->sa_restorer;
817 uptr result = internal_syscall(SYSCALL(rt_sigaction), (uptr)signum,
818 (uptr)(u_act ? &k_act : nullptr),
819 (uptr)(u_oldact ? &k_oldact : nullptr),
820 (uptr)sizeof(__sanitizer_kernel_sigset_t));
822 if ((result == 0) && u_oldact) {
823 u_oldact->handler = k_oldact.handler;
824 u_oldact->sigaction = k_oldact.sigaction;
825 internal_memcpy(&u_oldact->sa_mask, &k_oldact.sa_mask,
826 sizeof(__sanitizer_kernel_sigset_t));
827 u_oldact->sa_flags = k_oldact.sa_flags;
828 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
829 u_oldact->sa_restorer = k_oldact.sa_restorer;
834 #endif // SANITIZER_LINUX
836 uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
837 __sanitizer_sigset_t *oldset) {
838 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD
839 return internal_syscall(SYSCALL(sigprocmask), how, set, oldset);
841 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
842 __sanitizer_kernel_sigset_t *k_oldset = (__sanitizer_kernel_sigset_t *)oldset;
843 return internal_syscall(SYSCALL(rt_sigprocmask), (uptr)how,
844 (uptr)&k_set->sig[0], (uptr)&k_oldset->sig[0],
845 sizeof(__sanitizer_kernel_sigset_t));
849 void internal_sigfillset(__sanitizer_sigset_t *set) {
850 internal_memset(set, 0xff, sizeof(*set));
853 void internal_sigemptyset(__sanitizer_sigset_t *set) {
854 internal_memset(set, 0, sizeof(*set));
858 void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
861 CHECK_LT(signum, sizeof(*set) * 8);
862 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
863 const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
864 const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
865 k_set->sig[idx] &= ~(1 << bit);
868 bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
871 CHECK_LT(signum, sizeof(*set) * 8);
872 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
873 const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
874 const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
875 return k_set->sig[idx] & (1 << bit);
877 #elif SANITIZER_FREEBSD
878 void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
879 sigset_t *rset = reinterpret_cast<sigset_t *>(set);
880 sigdelset(rset, signum);
883 bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
884 sigset_t *rset = reinterpret_cast<sigset_t *>(set);
885 return sigismember(rset, signum);
888 #endif // !SANITIZER_SOLARIS
890 #if !SANITIZER_NETBSD
891 // ThreadLister implementation.
892 ThreadLister::ThreadLister(pid_t pid) : pid_(pid), buffer_(4096) {
893 char task_directory_path[80];
894 internal_snprintf(task_directory_path, sizeof(task_directory_path),
895 "/proc/%d/task/", pid);
896 descriptor_ = internal_open(task_directory_path, O_RDONLY | O_DIRECTORY);
897 if (internal_iserror(descriptor_)) {
898 Report("Can't open /proc/%d/task for reading.\n", pid);
902 ThreadLister::Result ThreadLister::ListThreads(
903 InternalMmapVector<tid_t> *threads) {
904 if (internal_iserror(descriptor_))
906 internal_lseek(descriptor_, 0, SEEK_SET);
910 for (bool first_read = true;; first_read = false) {
911 // Resize to max capacity if it was downsized by IsAlive.
912 buffer_.resize(buffer_.capacity());
913 CHECK_GE(buffer_.size(), 4096);
914 uptr read = internal_getdents(
915 descriptor_, (struct linux_dirent *)buffer_.data(), buffer_.size());
918 if (internal_iserror(read)) {
919 Report("Can't read directory entries from /proc/%d/task.\n", pid_);
923 for (uptr begin = (uptr)buffer_.data(), end = begin + read; begin < end;) {
924 struct linux_dirent *entry = (struct linux_dirent *)begin;
925 begin += entry->d_reclen;
926 if (entry->d_ino == 1) {
927 // Inode 1 is for bad blocks and also can be a reason for early return.
928 // Should be emitted if kernel tried to output terminating thread.
929 // See proc_task_readdir implementation in Linux.
932 if (entry->d_ino && *entry->d_name >= '0' && *entry->d_name <= '9')
933 threads->push_back(internal_atoll(entry->d_name));
936 // Now we are going to detect short-read or early EOF. In such cases Linux
937 // can return inconsistent list with missing alive threads.
938 // Code will just remember that the list can be incomplete but it will
939 // continue reads to return as much as possible.
941 // The first one was a short-read by definition.
943 } else if (read > buffer_.size() - 1024) {
944 // Read was close to the buffer size. So double the size and assume the
946 buffer_.resize(buffer_.size() * 2);
948 } else if (!threads->empty() && !IsAlive(threads->back())) {
949 // Maybe Linux early returned from read on terminated thread (!pid_alive)
950 // and failed to restore read position.
951 // See next_tid and proc_task_instantiate in Linux.
957 bool ThreadLister::IsAlive(int tid) {
958 // /proc/%d/task/%d/status uses same call to detect alive threads as
959 // proc_task_readdir. See task_state implementation in Linux.
961 internal_snprintf(path, sizeof(path), "/proc/%d/task/%d/status", pid_, tid);
962 if (!ReadFileToVector(path, &buffer_) || buffer_.empty())
964 buffer_.push_back(0);
965 static const char kPrefix[] = "\nPPid:";
966 const char *field = internal_strstr(buffer_.data(), kPrefix);
969 field += internal_strlen(kPrefix);
970 return (int)internal_atoll(field) != 0;
973 ThreadLister::~ThreadLister() {
974 if (!internal_iserror(descriptor_))
975 internal_close(descriptor_);
979 #if SANITIZER_WORDSIZE == 32
980 // Take care of unusable kernel area in top gigabyte.
981 static uptr GetKernelAreaSize() {
982 #if SANITIZER_LINUX && !SANITIZER_X32
983 const uptr gbyte = 1UL << 30;
985 // Firstly check if there are writable segments
986 // mapped to top gigabyte (e.g. stack).
987 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
988 if (proc_maps.Error())
990 MemoryMappedSegment segment;
991 while (proc_maps.Next(&segment)) {
992 if ((segment.end >= 3 * gbyte) && segment.IsWritable()) return 0;
995 #if !SANITIZER_ANDROID
996 // Even if nothing is mapped, top Gb may still be accessible
997 // if we are running on 64-bit kernel.
998 // Uname may report misleading results if personality type
999 // is modified (e.g. under schroot) so check this as well.
1000 struct utsname uname_info;
1001 int pers = personality(0xffffffffUL);
1002 if (!(pers & PER_MASK)
1003 && uname(&uname_info) == 0
1004 && internal_strstr(uname_info.machine, "64"))
1006 #endif // SANITIZER_ANDROID
1008 // Top gigabyte is reserved for kernel.
1012 #endif // SANITIZER_LINUX && !SANITIZER_X32
1014 #endif // SANITIZER_WORDSIZE == 32
1016 uptr GetMaxVirtualAddress() {
1017 #if (SANITIZER_NETBSD || SANITIZER_OPENBSD) && defined(__x86_64__)
1018 return 0x7f7ffffff000ULL; // (0x00007f8000000000 - PAGE_SIZE)
1019 #elif SANITIZER_WORDSIZE == 64
1020 # if defined(__powerpc64__) || defined(__aarch64__)
1021 // On PowerPC64 we have two different address space layouts: 44- and 46-bit.
1022 // We somehow need to figure out which one we are using now and choose
1023 // one of 0x00000fffffffffffUL and 0x00003fffffffffffUL.
1024 // Note that with 'ulimit -s unlimited' the stack is moved away from the top
1025 // of the address space, so simply checking the stack address is not enough.
1026 // This should (does) work for both PowerPC64 Endian modes.
1027 // Similarly, aarch64 has multiple address space layouts: 39, 42 and 47-bit.
1028 return (1ULL << (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1)) - 1;
1029 # elif defined(__mips64)
1030 return (1ULL << 40) - 1; // 0x000000ffffffffffUL;
1031 # elif defined(__s390x__)
1032 return (1ULL << 53) - 1; // 0x001fffffffffffffUL;
1033 #elif defined(__sparc__)
1036 return (1ULL << 47) - 1; // 0x00007fffffffffffUL;
1038 #else // SANITIZER_WORDSIZE == 32
1039 # if defined(__s390__)
1040 return (1ULL << 31) - 1; // 0x7fffffff;
1042 return (1ULL << 32) - 1; // 0xffffffff;
1044 #endif // SANITIZER_WORDSIZE
1047 uptr GetMaxUserVirtualAddress() {
1048 uptr addr = GetMaxVirtualAddress();
1049 #if SANITIZER_WORDSIZE == 32 && !defined(__s390__)
1050 if (!common_flags()->full_address_space)
1051 addr -= GetKernelAreaSize();
1052 CHECK_LT(reinterpret_cast<uptr>(&addr), addr);
1057 #if !SANITIZER_ANDROID
1058 uptr GetPageSize() {
1059 #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__))
1060 return EXEC_PAGESIZE;
1061 #elif SANITIZER_USE_GETAUXVAL
1062 return getauxval(AT_PAGESZ);
1063 #elif SANITIZER_FREEBSD || SANITIZER_NETBSD
1064 // Use sysctl as sysconf can trigger interceptors internally.
1066 uptr pzl = sizeof(pz);
1067 int mib[2] = {CTL_HW, HW_PAGESIZE};
1068 int rv = internal_sysctl(mib, 2, &pz, &pzl, nullptr, 0);
1072 return sysconf(_SC_PAGESIZE); // EXEC_PAGESIZE may not be trustworthy.
1075 #endif // !SANITIZER_ANDROID
1077 #if !SANITIZER_OPENBSD
1078 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
1079 #if SANITIZER_SOLARIS
1080 const char *default_module_name = getexecname();
1081 CHECK_NE(default_module_name, NULL);
1082 return internal_snprintf(buf, buf_len, "%s", default_module_name);
1084 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
1085 #if SANITIZER_FREEBSD
1086 const int Mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
1088 const int Mib[4] = {CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME};
1090 const char *default_module_name = "kern.proc.pathname";
1091 uptr Size = buf_len;
1093 (internal_sysctl(Mib, ARRAY_SIZE(Mib), buf, &Size, NULL, 0) != 0);
1094 int readlink_error = IsErr ? errno : 0;
1095 uptr module_name_len = Size;
1097 const char *default_module_name = "/proc/self/exe";
1098 uptr module_name_len = internal_readlink(
1099 default_module_name, buf, buf_len);
1101 bool IsErr = internal_iserror(module_name_len, &readlink_error);
1102 #endif // SANITIZER_SOLARIS
1104 // We can't read binary name for some reason, assume it's unknown.
1105 Report("WARNING: reading executable name failed with errno %d, "
1106 "some stack frames may not be symbolized\n", readlink_error);
1107 module_name_len = internal_snprintf(buf, buf_len, "%s",
1108 default_module_name);
1109 CHECK_LT(module_name_len, buf_len);
1111 return module_name_len;
1114 #endif // !SANITIZER_OPENBSD
1116 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len) {
1121 if (ReadFileToBuffer("/proc/self/cmdline", &tmpbuf, &tmpsize, &tmplen,
1123 internal_strncpy(buf, tmpbuf, buf_len);
1124 UnmapOrDie(tmpbuf, tmpsize);
1125 return internal_strlen(buf);
1128 return ReadBinaryName(buf, buf_len);
1131 // Match full names of the form /path/to/base_name{-,.}*
1132 bool LibraryNameIs(const char *full_name, const char *base_name) {
1133 const char *name = full_name;
1135 while (*name != '\0') name++;
1136 while (name > full_name && *name != '/') name--;
1137 if (*name == '/') name++;
1138 uptr base_name_length = internal_strlen(base_name);
1139 if (internal_strncmp(name, base_name, base_name_length)) return false;
1140 return (name[base_name_length] == '-' || name[base_name_length] == '.');
1143 #if !SANITIZER_ANDROID
1144 // Call cb for each region mapped by map.
1145 void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr)) {
1146 CHECK_NE(map, nullptr);
1147 #if !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
1148 typedef ElfW(Phdr) Elf_Phdr;
1149 typedef ElfW(Ehdr) Elf_Ehdr;
1150 #endif // !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
1151 char *base = (char *)map->l_addr;
1152 Elf_Ehdr *ehdr = (Elf_Ehdr *)base;
1153 char *phdrs = base + ehdr->e_phoff;
1154 char *phdrs_end = phdrs + ehdr->e_phnum * ehdr->e_phentsize;
1156 // Find the segment with the minimum base so we can "relocate" the p_vaddr
1157 // fields. Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
1158 // objects have a non-zero base.
1159 uptr preferred_base = (uptr)-1;
1160 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
1161 Elf_Phdr *phdr = (Elf_Phdr *)iter;
1162 if (phdr->p_type == PT_LOAD && preferred_base > (uptr)phdr->p_vaddr)
1163 preferred_base = (uptr)phdr->p_vaddr;
1166 // Compute the delta from the real base to get a relocation delta.
1167 sptr delta = (uptr)base - preferred_base;
1168 // Now we can figure out what the loader really mapped.
1169 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
1170 Elf_Phdr *phdr = (Elf_Phdr *)iter;
1171 if (phdr->p_type == PT_LOAD) {
1172 uptr seg_start = phdr->p_vaddr + delta;
1173 uptr seg_end = seg_start + phdr->p_memsz;
1174 // None of these values are aligned. We consider the ragged edges of the
1175 // load command as defined, since they are mapped from the file.
1176 seg_start = RoundDownTo(seg_start, GetPageSizeCached());
1177 seg_end = RoundUpTo(seg_end, GetPageSizeCached());
1178 cb((void *)seg_start, seg_end - seg_start);
1184 #if defined(__x86_64__) && SANITIZER_LINUX
1185 // We cannot use glibc's clone wrapper, because it messes with the child
1186 // task's TLS. It writes the PID and TID of the child task to its thread
1187 // descriptor, but in our case the child task shares the thread descriptor with
1188 // the parent (because we don't know how to allocate a new thread
1189 // descriptor to keep glibc happy). So the stock version of clone(), when
1190 // used with CLONE_VM, would end up corrupting the parent's thread descriptor.
1191 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1192 int *parent_tidptr, void *newtls, int *child_tidptr) {
1194 if (!fn || !child_stack)
1196 CHECK_EQ(0, (uptr)child_stack % 16);
1197 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1198 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1199 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1200 register void *r8 __asm__("r8") = newtls;
1201 register int *r10 __asm__("r10") = child_tidptr;
1202 __asm__ __volatile__(
1203 /* %rax = syscall(%rax = SYSCALL(clone),
1205 * %rsi = child_stack,
1206 * %rdx = parent_tidptr,
1208 * %r10 = child_tidptr)
1215 "testq %%rax,%%rax\n"
1218 /* In the child. Terminate unwind chain. */
1219 // XXX: We should also terminate the CFI unwind chain
1220 // here. Unfortunately clang 3.2 doesn't support the
1221 // necessary CFI directives, so we skip that part.
1222 "xorq %%rbp,%%rbp\n"
1224 /* Call "fn(arg)". */
1229 /* Call _exit(%rax). */
1230 "movq %%rax,%%rdi\n"
1234 /* Return to parent. */
1237 : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
1243 : "memory", "r11", "rcx");
1246 #elif defined(__mips__)
1247 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1248 int *parent_tidptr, void *newtls, int *child_tidptr) {
1250 if (!fn || !child_stack)
1252 CHECK_EQ(0, (uptr)child_stack % 16);
1253 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1254 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1255 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1256 register void *a3 __asm__("$7") = newtls;
1257 register int *a4 __asm__("$8") = child_tidptr;
1258 // We don't have proper CFI directives here because it requires alot of code
1259 // for very marginal benefits.
1260 __asm__ __volatile__(
1261 /* $v0 = syscall($v0 = __NR_clone,
1263 * $a1 = child_stack,
1264 * $a2 = parent_tidptr,
1266 * $a4 = child_tidptr)
1273 /* Store the fifth argument on stack
1274 * if we are using 32-bit abi.
1276 #if SANITIZER_WORDSIZE == 32
1289 /* Call "fn(arg)". */
1290 #if SANITIZER_WORDSIZE == 32
1291 #ifdef __BIG_ENDIAN__
1304 /* Call _exit($v0). */
1309 /* Return to parent. */
1319 : "memory", "$29" );
1322 #elif defined(__aarch64__)
1323 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1324 int *parent_tidptr, void *newtls, int *child_tidptr) {
1326 if (!fn || !child_stack)
1328 CHECK_EQ(0, (uptr)child_stack % 16);
1329 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1330 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1331 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1333 register int (*__fn)(void *) __asm__("x0") = fn;
1334 register void *__stack __asm__("x1") = child_stack;
1335 register int __flags __asm__("x2") = flags;
1336 register void *__arg __asm__("x3") = arg;
1337 register int *__ptid __asm__("x4") = parent_tidptr;
1338 register void *__tls __asm__("x5") = newtls;
1339 register int *__ctid __asm__("x6") = child_tidptr;
1341 __asm__ __volatile__(
1342 "mov x0,x2\n" /* flags */
1343 "mov x2,x4\n" /* ptid */
1344 "mov x3,x5\n" /* tls */
1345 "mov x4,x6\n" /* ctid */
1346 "mov x8,%9\n" /* clone */
1356 /* In the child, now. Call "fn(arg)". */
1357 "ldp x1, x0, [sp], #16\n"
1360 /* Call _exit(%r0). */
1367 "r"(__fn), "r"(__stack), "r"(__flags), "r"(__arg),
1368 "r"(__ptid), "r"(__tls), "r"(__ctid),
1369 "i"(__NR_clone), "i"(__NR_exit)
1373 #elif defined(__powerpc64__)
1374 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1375 int *parent_tidptr, void *newtls, int *child_tidptr) {
1377 // Stack frame structure.
1378 #if SANITIZER_PPC64V1
1379 // Back chain == 0 (SP + 112)
1380 // Frame (112 bytes):
1381 // Parameter save area (SP + 48), 8 doublewords
1382 // TOC save area (SP + 40)
1383 // Link editor doubleword (SP + 32)
1384 // Compiler doubleword (SP + 24)
1385 // LR save area (SP + 16)
1386 // CR save area (SP + 8)
1387 // Back chain (SP + 0)
1388 # define FRAME_SIZE 112
1389 # define FRAME_TOC_SAVE_OFFSET 40
1390 #elif SANITIZER_PPC64V2
1391 // Back chain == 0 (SP + 32)
1392 // Frame (32 bytes):
1393 // TOC save area (SP + 24)
1394 // LR save area (SP + 16)
1395 // CR save area (SP + 8)
1396 // Back chain (SP + 0)
1397 # define FRAME_SIZE 32
1398 # define FRAME_TOC_SAVE_OFFSET 24
1400 # error "Unsupported PPC64 ABI"
1402 if (!fn || !child_stack)
1404 CHECK_EQ(0, (uptr)child_stack % 16);
1406 register int (*__fn)(void *) __asm__("r3") = fn;
1407 register void *__cstack __asm__("r4") = child_stack;
1408 register int __flags __asm__("r5") = flags;
1409 register void *__arg __asm__("r6") = arg;
1410 register int *__ptidptr __asm__("r7") = parent_tidptr;
1411 register void *__newtls __asm__("r8") = newtls;
1412 register int *__ctidptr __asm__("r9") = child_tidptr;
1414 __asm__ __volatile__(
1415 /* fn and arg are saved across the syscall */
1425 r7 == child_tidptr */
1433 /* Test if syscall was successful */
1434 "cmpdi cr1, 3, 0\n\t"
1435 "crandc cr1*4+eq, cr1*4+eq, cr0*4+so\n\t"
1438 /* Set up stack frame */
1440 "stdu 29, -8(1)\n\t"
1441 "stdu 1, -%12(1)\n\t"
1442 /* Do the function call */
1444 #if SANITIZER_PPC64V1
1448 #elif SANITIZER_PPC64V2
1452 # error "Unsupported PPC64 ABI"
1458 /* Call _exit(r3) */
1462 /* Return to parent */
1478 "i" (FRAME_TOC_SAVE_OFFSET)
1479 : "cr0", "cr1", "memory", "ctr", "r0", "r27", "r28", "r29");
1482 #elif defined(__i386__) && SANITIZER_LINUX
1483 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1484 int *parent_tidptr, void *newtls, int *child_tidptr) {
1486 if (!fn || !child_stack)
1488 CHECK_EQ(0, (uptr)child_stack % 16);
1489 child_stack = (char *)child_stack - 7 * sizeof(unsigned int);
1490 ((unsigned int *)child_stack)[0] = (uptr)flags;
1491 ((unsigned int *)child_stack)[1] = (uptr)0;
1492 ((unsigned int *)child_stack)[2] = (uptr)fn;
1493 ((unsigned int *)child_stack)[3] = (uptr)arg;
1494 __asm__ __volatile__(
1495 /* %eax = syscall(%eax = SYSCALL(clone),
1497 * %ecx = child_stack,
1498 * %edx = parent_tidptr,
1500 * %edi = child_tidptr)
1504 "movl (%%ecx), %%ebx\n"
1505 /* Do the system call */
1509 /* Remember the flag value. */
1510 "movl %%ebx, (%%ecx)\n"
1520 "test %%eax,%%eax\n"
1523 /* terminate the stack frame */
1524 "xorl %%ebp,%%ebp\n"
1531 "addl $_GLOBAL_OFFSET_TABLE_+[.-here], %%ebx\n"
1534 "movl %%eax, %%ebx\n"
1539 : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
1547 #elif defined(__arm__) && SANITIZER_LINUX
1548 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1549 int *parent_tidptr, void *newtls, int *child_tidptr) {
1551 if (!fn || !child_stack)
1553 child_stack = (char *)child_stack - 2 * sizeof(unsigned int);
1554 ((unsigned int *)child_stack)[0] = (uptr)fn;
1555 ((unsigned int *)child_stack)[1] = (uptr)arg;
1556 register int r0 __asm__("r0") = flags;
1557 register void *r1 __asm__("r1") = child_stack;
1558 register int *r2 __asm__("r2") = parent_tidptr;
1559 register void *r3 __asm__("r3") = newtls;
1560 register int *r4 __asm__("r4") = child_tidptr;
1561 register int r7 __asm__("r7") = __NR_clone;
1563 #if __ARM_ARCH > 4 || defined (__ARM_ARCH_4T__)
1564 # define ARCH_HAS_BX
1567 # define ARCH_HAS_BLX
1571 # ifdef ARCH_HAS_BLX
1572 # define BLX(R) "blx " #R "\n"
1574 # define BLX(R) "mov lr, pc; bx " #R "\n"
1577 # define BLX(R) "mov lr, pc; mov pc," #R "\n"
1580 __asm__ __volatile__(
1581 /* %r0 = syscall(%r7 = SYSCALL(clone),
1583 * %r1 = child_stack,
1584 * %r2 = parent_tidptr,
1586 * %r4 = child_tidptr)
1589 /* Do the system call */
1598 /* In the child, now. Call "fn(arg)". */
1599 "ldr r0, [sp, #4]\n"
1600 "ldr ip, [sp], #8\n"
1602 /* Call _exit(%r0). */
1608 : "r"(r0), "r"(r1), "r"(r2), "r"(r3), "r"(r4), "r"(r7),
1613 #endif // defined(__x86_64__) && SANITIZER_LINUX
1615 #if SANITIZER_ANDROID
1616 #if __ANDROID_API__ < 21
1617 extern "C" __attribute__((weak)) int dl_iterate_phdr(
1618 int (*)(struct dl_phdr_info *, size_t, void *), void *);
1621 static int dl_iterate_phdr_test_cb(struct dl_phdr_info *info, size_t size,
1623 // Any name starting with "lib" indicates a bug in L where library base names
1624 // are returned instead of paths.
1625 if (info->dlpi_name && info->dlpi_name[0] == 'l' &&
1626 info->dlpi_name[1] == 'i' && info->dlpi_name[2] == 'b') {
1627 *(bool *)data = true;
1633 static atomic_uint32_t android_api_level;
1635 static AndroidApiLevel AndroidDetectApiLevelStatic() {
1636 #if __ANDROID_API__ <= 19
1637 return ANDROID_KITKAT;
1638 #elif __ANDROID_API__ <= 22
1639 return ANDROID_LOLLIPOP_MR1;
1641 return ANDROID_POST_LOLLIPOP;
1645 static AndroidApiLevel AndroidDetectApiLevel() {
1646 if (!&dl_iterate_phdr)
1647 return ANDROID_KITKAT; // K or lower
1648 bool base_name_seen = false;
1649 dl_iterate_phdr(dl_iterate_phdr_test_cb, &base_name_seen);
1651 return ANDROID_LOLLIPOP_MR1; // L MR1
1652 return ANDROID_POST_LOLLIPOP; // post-L
1653 // Plain L (API level 21) is completely broken wrt ASan and not very
1654 // interesting to detect.
1657 extern "C" __attribute__((weak)) void* _DYNAMIC;
1659 AndroidApiLevel AndroidGetApiLevel() {
1660 AndroidApiLevel level =
1661 (AndroidApiLevel)atomic_load(&android_api_level, memory_order_relaxed);
1662 if (level) return level;
1663 level = &_DYNAMIC == nullptr ? AndroidDetectApiLevelStatic()
1664 : AndroidDetectApiLevel();
1665 atomic_store(&android_api_level, level, memory_order_relaxed);
1671 static HandleSignalMode GetHandleSignalModeImpl(int signum) {
1674 return common_flags()->handle_abort;
1676 return common_flags()->handle_sigill;
1678 return common_flags()->handle_sigtrap;
1680 return common_flags()->handle_sigfpe;
1682 return common_flags()->handle_segv;
1684 return common_flags()->handle_sigbus;
1686 return kHandleSignalNo;
1689 HandleSignalMode GetHandleSignalMode(int signum) {
1690 HandleSignalMode result = GetHandleSignalModeImpl(signum);
1691 if (result == kHandleSignalYes && !common_flags()->allow_user_segv_handler)
1692 return kHandleSignalExclusive;
1697 void *internal_start_thread(void(*func)(void *arg), void *arg) {
1698 // Start the thread with signals blocked, otherwise it can steal user signals.
1699 __sanitizer_sigset_t set, old;
1700 internal_sigfillset(&set);
1701 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1702 // Glibc uses SIGSETXID signal during setuid call. If this signal is blocked
1703 // on any thread, setuid call hangs (see test/tsan/setuid.c).
1704 internal_sigdelset(&set, 33);
1706 internal_sigprocmask(SIG_SETMASK, &set, &old);
1708 real_pthread_create(&th, nullptr, (void*(*)(void *arg))func, arg);
1709 internal_sigprocmask(SIG_SETMASK, &old, nullptr);
1713 void internal_join_thread(void *th) {
1714 real_pthread_join(th, nullptr);
1717 void *internal_start_thread(void (*func)(void *), void *arg) { return 0; }
1719 void internal_join_thread(void *th) {}
1722 #if defined(__aarch64__)
1723 // Android headers in the older NDK releases miss this definition.
1724 struct __sanitizer_esr_context {
1725 struct _aarch64_ctx head;
1729 static bool Aarch64GetESR(ucontext_t *ucontext, u64 *esr) {
1730 static const u32 kEsrMagic = 0x45535201;
1731 u8 *aux = ucontext->uc_mcontext.__reserved;
1733 _aarch64_ctx *ctx = (_aarch64_ctx *)aux;
1734 if (ctx->size == 0) break;
1735 if (ctx->magic == kEsrMagic) {
1736 *esr = ((__sanitizer_esr_context *)ctx)->esr;
1745 #if SANITIZER_OPENBSD
1746 using Context = sigcontext;
1748 using Context = ucontext_t;
1751 SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
1752 Context *ucontext = (Context *)context;
1753 #if defined(__x86_64__) || defined(__i386__)
1754 static const uptr PF_WRITE = 1U << 1;
1755 #if SANITIZER_FREEBSD
1756 uptr err = ucontext->uc_mcontext.mc_err;
1757 #elif SANITIZER_NETBSD
1758 uptr err = ucontext->uc_mcontext.__gregs[_REG_ERR];
1759 #elif SANITIZER_OPENBSD
1760 uptr err = ucontext->sc_err;
1761 #elif SANITIZER_SOLARIS && defined(__i386__)
1763 uptr err = ucontext->uc_mcontext.gregs[Err];
1765 uptr err = ucontext->uc_mcontext.gregs[REG_ERR];
1766 #endif // SANITIZER_FREEBSD
1767 return err & PF_WRITE ? WRITE : READ;
1768 #elif defined(__mips__)
1769 uint32_t *exception_source;
1770 uint32_t faulty_instruction;
1773 exception_source = (uint32_t *)ucontext->uc_mcontext.pc;
1774 faulty_instruction = (uint32_t)(*exception_source);
1776 op_code = (faulty_instruction >> 26) & 0x3f;
1778 // FIXME: Add support for FPU, microMIPS, DSP, MSA memory instructions.
1784 #if __mips_isa_rev < 6
1790 return SignalContext::WRITE;
1799 #if __mips_isa_rev < 6
1805 return SignalContext::READ;
1806 #if __mips_isa_rev == 6
1808 op_code = (faulty_instruction >> 19) & 0x3;
1812 return SignalContext::READ;
1816 return SignalContext::UNKNOWN;
1817 #elif defined(__arm__)
1818 static const uptr FSR_WRITE = 1U << 11;
1819 uptr fsr = ucontext->uc_mcontext.error_code;
1820 return fsr & FSR_WRITE ? WRITE : READ;
1821 #elif defined(__aarch64__)
1822 static const u64 ESR_ELx_WNR = 1U << 6;
1824 if (!Aarch64GetESR(ucontext, &esr)) return UNKNOWN;
1825 return esr & ESR_ELx_WNR ? WRITE : READ;
1826 #elif defined(__sparc__)
1827 // Decode the instruction to determine the access type.
1828 // From OpenSolaris $SRC/uts/sun4/os/trap.c (get_accesstype).
1829 #if SANITIZER_SOLARIS
1830 uptr pc = ucontext->uc_mcontext.gregs[REG_PC];
1832 // Historical BSDism here.
1833 struct sigcontext *scontext = (struct sigcontext *)context;
1834 #if defined(__arch64__)
1835 uptr pc = scontext->sigc_regs.tpc;
1837 uptr pc = scontext->si_regs.pc;
1840 u32 instr = *(u32 *)pc;
1841 return (instr >> 21) & 1 ? WRITE: READ;
1844 return UNKNOWN; // FIXME: Implement.
1848 void SignalContext::DumpAllRegisters(void *context) {
1849 // FIXME: Implement this.
1852 static void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
1853 #if SANITIZER_NETBSD
1854 // This covers all NetBSD architectures
1855 ucontext_t *ucontext = (ucontext_t *)context;
1856 *pc = _UC_MACHINE_PC(ucontext);
1857 *bp = _UC_MACHINE_FP(ucontext);
1858 *sp = _UC_MACHINE_SP(ucontext);
1859 #elif defined(__arm__)
1860 ucontext_t *ucontext = (ucontext_t*)context;
1861 *pc = ucontext->uc_mcontext.arm_pc;
1862 *bp = ucontext->uc_mcontext.arm_fp;
1863 *sp = ucontext->uc_mcontext.arm_sp;
1864 #elif defined(__aarch64__)
1865 ucontext_t *ucontext = (ucontext_t*)context;
1866 *pc = ucontext->uc_mcontext.pc;
1867 *bp = ucontext->uc_mcontext.regs[29];
1868 *sp = ucontext->uc_mcontext.sp;
1869 #elif defined(__hppa__)
1870 ucontext_t *ucontext = (ucontext_t*)context;
1871 *pc = ucontext->uc_mcontext.sc_iaoq[0];
1872 /* GCC uses %r3 whenever a frame pointer is needed. */
1873 *bp = ucontext->uc_mcontext.sc_gr[3];
1874 *sp = ucontext->uc_mcontext.sc_gr[30];
1875 #elif defined(__x86_64__)
1876 # if SANITIZER_FREEBSD
1877 ucontext_t *ucontext = (ucontext_t*)context;
1878 *pc = ucontext->uc_mcontext.mc_rip;
1879 *bp = ucontext->uc_mcontext.mc_rbp;
1880 *sp = ucontext->uc_mcontext.mc_rsp;
1881 #elif SANITIZER_OPENBSD
1882 sigcontext *ucontext = (sigcontext *)context;
1883 *pc = ucontext->sc_rip;
1884 *bp = ucontext->sc_rbp;
1885 *sp = ucontext->sc_rsp;
1887 ucontext_t *ucontext = (ucontext_t*)context;
1888 *pc = ucontext->uc_mcontext.gregs[REG_RIP];
1889 *bp = ucontext->uc_mcontext.gregs[REG_RBP];
1890 *sp = ucontext->uc_mcontext.gregs[REG_RSP];
1892 #elif defined(__i386__)
1893 # if SANITIZER_FREEBSD
1894 ucontext_t *ucontext = (ucontext_t*)context;
1895 *pc = ucontext->uc_mcontext.mc_eip;
1896 *bp = ucontext->uc_mcontext.mc_ebp;
1897 *sp = ucontext->uc_mcontext.mc_esp;
1898 #elif SANITIZER_OPENBSD
1899 sigcontext *ucontext = (sigcontext *)context;
1900 *pc = ucontext->sc_eip;
1901 *bp = ucontext->sc_ebp;
1902 *sp = ucontext->sc_esp;
1904 ucontext_t *ucontext = (ucontext_t*)context;
1905 # if SANITIZER_SOLARIS
1906 /* Use the numeric values: the symbolic ones are undefined by llvm
1907 include/llvm/Support/Solaris.h. */
1909 # define REG_EIP 14 // REG_PC
1912 # define REG_EBP 6 // REG_FP
1915 # define REG_ESP 17 // REG_SP
1918 *pc = ucontext->uc_mcontext.gregs[REG_EIP];
1919 *bp = ucontext->uc_mcontext.gregs[REG_EBP];
1920 *sp = ucontext->uc_mcontext.gregs[REG_ESP];
1922 #elif defined(__powerpc__) || defined(__powerpc64__)
1923 ucontext_t *ucontext = (ucontext_t*)context;
1924 *pc = ucontext->uc_mcontext.regs->nip;
1925 *sp = ucontext->uc_mcontext.regs->gpr[PT_R1];
1926 // The powerpc{,64}-linux ABIs do not specify r31 as the frame
1927 // pointer, but GCC always uses r31 when we need a frame pointer.
1928 *bp = ucontext->uc_mcontext.regs->gpr[PT_R31];
1929 #elif defined(__sparc__)
1930 #if defined(__arch64__) || defined(__sparcv9)
1931 #define STACK_BIAS 2047
1933 #define STACK_BIAS 0
1935 # if SANITIZER_SOLARIS
1936 ucontext_t *ucontext = (ucontext_t *)context;
1937 *pc = ucontext->uc_mcontext.gregs[REG_PC];
1938 *sp = ucontext->uc_mcontext.gregs[REG_O6] + STACK_BIAS;
1940 // Historical BSDism here.
1941 struct sigcontext *scontext = (struct sigcontext *)context;
1942 #if defined(__arch64__)
1943 *pc = scontext->sigc_regs.tpc;
1944 *sp = scontext->sigc_regs.u_regs[14] + STACK_BIAS;
1946 *pc = scontext->si_regs.pc;
1947 *sp = scontext->si_regs.u_regs[14];
1950 *bp = (uptr)((uhwptr *)*sp)[14] + STACK_BIAS;
1951 #elif defined(__mips__)
1952 ucontext_t *ucontext = (ucontext_t*)context;
1953 *pc = ucontext->uc_mcontext.pc;
1954 *bp = ucontext->uc_mcontext.gregs[30];
1955 *sp = ucontext->uc_mcontext.gregs[29];
1956 #elif defined(__s390__)
1957 ucontext_t *ucontext = (ucontext_t*)context;
1958 # if defined(__s390x__)
1959 *pc = ucontext->uc_mcontext.psw.addr;
1961 *pc = ucontext->uc_mcontext.psw.addr & 0x7fffffff;
1963 *bp = ucontext->uc_mcontext.gregs[11];
1964 *sp = ucontext->uc_mcontext.gregs[15];
1966 # error "Unsupported arch"
1970 void SignalContext::InitPcSpBp() { GetPcSpBp(context, &pc, &sp, &bp); }
1972 void InitializePlatformEarly() {
1976 void MaybeReexec() {
1977 // No need to re-exec on Linux.
1981 #if SANITIZER_NETBSD
1984 uptr len = sizeof(paxflags);
1987 mib[1] = internal_getpid();
1988 mib[2] = PROC_PID_PAXFLAGS;
1990 if (UNLIKELY(internal_sysctl(mib, 3, &paxflags, &len, NULL, 0) == -1)) {
1991 Printf("sysctl failed\n");
1995 if (UNLIKELY(paxflags & CTL_PROC_PAXFLAGS_ASLR)) {
1996 Printf("This sanitizer is not compatible with enabled ASLR\n");
1999 #elif SANITIZER_PPC64V2
2000 // Disable ASLR for Linux PPC64LE.
2001 int old_personality = personality(0xffffffff);
2002 if (old_personality != -1 && (old_personality & ADDR_NO_RANDOMIZE) == 0) {
2003 VReport(1, "WARNING: Program is being run with address space layout "
2004 "randomization (ASLR) enabled which prevents the thread and "
2005 "memory sanitizers from working on powerpc64le.\n"
2006 "ASLR will be disabled and the program re-executed.\n");
2007 CHECK_NE(personality(old_personality | ADDR_NO_RANDOMIZE), -1);
2015 void CheckMPROTECT() {
2016 #if SANITIZER_NETBSD
2019 uptr len = sizeof(paxflags);
2022 mib[1] = internal_getpid();
2023 mib[2] = PROC_PID_PAXFLAGS;
2025 if (UNLIKELY(internal_sysctl(mib, 3, &paxflags, &len, NULL, 0) == -1)) {
2026 Printf("sysctl failed\n");
2030 if (UNLIKELY(paxflags & CTL_PROC_PAXFLAGS_MPROTECT)) {
2031 Printf("This sanitizer is not compatible with enabled MPROTECT\n");
2039 void PrintModuleMap() { }
2041 void CheckNoDeepBind(const char *filename, int flag) {
2042 #ifdef RTLD_DEEPBIND
2043 if (flag & RTLD_DEEPBIND) {
2045 "You are trying to dlopen a %s shared library with RTLD_DEEPBIND flag"
2046 " which is incompatibe with sanitizer runtime "
2047 "(see https://github.com/google/sanitizers/issues/611 for details"
2048 "). If you want to run %s library under sanitizers please remove "
2049 "RTLD_DEEPBIND from dlopen flags.\n",
2050 filename, filename);
2056 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
2057 uptr *largest_gap_found,
2058 uptr *max_occupied_addr) {
2059 UNREACHABLE("FindAvailableMemoryRange is not available");
2063 bool GetRandom(void *buffer, uptr length, bool blocking) {
2064 if (!buffer || !length || length > 256)
2066 #if SANITIZER_USE_GETENTROPY
2067 uptr rnd = getentropy(buffer, length);
2069 if (internal_iserror(rnd, &rverrno) && rverrno == EFAULT)
2073 #endif // SANITIZER_USE_GETENTROPY
2075 #if SANITIZER_USE_GETRANDOM
2076 static atomic_uint8_t skip_getrandom_syscall;
2077 if (!atomic_load_relaxed(&skip_getrandom_syscall)) {
2078 // Up to 256 bytes, getrandom will not be interrupted.
2079 uptr res = internal_syscall(SYSCALL(getrandom), buffer, length,
2080 blocking ? 0 : GRND_NONBLOCK);
2082 if (internal_iserror(res, &rverrno) && rverrno == ENOSYS)
2083 atomic_store_relaxed(&skip_getrandom_syscall, 1);
2084 else if (res == length)
2087 #endif // SANITIZER_USE_GETRANDOM
2088 // Up to 256 bytes, a read off /dev/urandom will not be interrupted.
2089 // blocking is moot here, O_NONBLOCK has no effect when opening /dev/urandom.
2090 uptr fd = internal_open("/dev/urandom", O_RDONLY);
2091 if (internal_iserror(fd))
2093 uptr res = internal_read(fd, buffer, length);
2094 if (internal_iserror(res))
2100 } // namespace __sanitizer