1 //===-- sanitizer_linux.cpp -----------------------------------------------===//
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) {
411 return internal_syscall(SYSCALL(renameat2), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
413 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS || SANITIZER_OPENBSD
414 return internal_syscall(SYSCALL(renameat), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
417 return internal_syscall(SYSCALL(rename), (uptr)oldpath, (uptr)newpath);
421 uptr internal_sched_yield() {
422 return internal_syscall(SYSCALL(sched_yield));
425 void internal__exit(int exitcode) {
426 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD
427 internal_syscall(SYSCALL(exit), exitcode);
429 internal_syscall(SYSCALL(exit_group), exitcode);
431 Die(); // Unreachable.
434 unsigned int internal_sleep(unsigned int seconds) {
438 int res = internal_syscall(SYSCALL(nanosleep), &ts, &ts);
439 if (res) return ts.tv_sec;
443 uptr internal_execve(const char *filename, char *const argv[],
444 char *const envp[]) {
445 return internal_syscall(SYSCALL(execve), (uptr)filename, (uptr)argv,
448 #endif // !SANITIZER_SOLARIS && !SANITIZER_NETBSD
450 // ----------------- sanitizer_common.h
451 bool FileExists(const char *filename) {
452 if (ShouldMockFailureToOpen(filename))
455 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
456 if (internal_syscall(SYSCALL(newfstatat), AT_FDCWD, filename, &st, 0))
458 if (internal_stat(filename, &st))
461 // Sanity check: filename is a regular file.
462 return S_ISREG(st.st_mode);
465 #if !SANITIZER_NETBSD
467 #if SANITIZER_FREEBSD
471 #elif SANITIZER_OPENBSD
472 return internal_syscall(SYSCALL(getthrid));
473 #elif SANITIZER_SOLARIS
476 return internal_syscall(SYSCALL(gettid));
480 int TgKill(pid_t pid, tid_t tid, int sig) {
482 return internal_syscall(SYSCALL(tgkill), pid, tid, sig);
483 #elif SANITIZER_FREEBSD
484 return internal_syscall(SYSCALL(thr_kill2), pid, tid, sig);
485 #elif SANITIZER_OPENBSD
487 return internal_syscall(SYSCALL(thrkill), tid, sig, nullptr);
488 #elif SANITIZER_SOLARIS
490 return thr_kill(tid, sig);
495 #if !SANITIZER_SOLARIS && !SANITIZER_NETBSD
497 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD
502 internal_memset(&tv, 0, sizeof(tv));
503 internal_syscall(SYSCALL(gettimeofday), &tv, 0);
504 return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
507 uptr internal_clock_gettime(__sanitizer_clockid_t clk_id, void *tp) {
508 return internal_syscall(SYSCALL(clock_gettime), clk_id, tp);
510 #endif // !SANITIZER_SOLARIS && !SANITIZER_NETBSD
512 // Like getenv, but reads env directly from /proc (on Linux) or parses the
513 // 'environ' array (on some others) and does not use libc. This function
514 // should be called first inside __asan_init.
515 const char *GetEnv(const char *name) {
516 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD || \
518 if (::environ != 0) {
519 uptr NameLen = internal_strlen(name);
520 for (char **Env = ::environ; *Env != 0; Env++) {
521 if (internal_strncmp(*Env, name, NameLen) == 0 && (*Env)[NameLen] == '=')
522 return (*Env) + NameLen + 1;
525 return 0; // Not found.
526 #elif SANITIZER_LINUX
527 static char *environ;
533 if (!ReadFileToBuffer("/proc/self/environ", &environ, &environ_size, &len))
536 if (!environ || len == 0) return nullptr;
537 uptr namelen = internal_strlen(name);
538 const char *p = environ;
539 while (*p != '\0') { // will happen at the \0\0 that terminates the buffer
540 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
542 (char*)internal_memchr(p, '\0', len - (p - environ));
543 if (!endp) // this entry isn't NUL terminated
545 else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') // Match.
546 return p + namelen + 1; // point after =
549 return nullptr; // Not found.
551 #error "Unsupported platform"
555 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD && !SANITIZER_OPENBSD
557 SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
561 #if !SANITIZER_GO && !SANITIZER_FREEBSD && !SANITIZER_NETBSD && \
563 static void ReadNullSepFileToArray(const char *path, char ***arr,
568 *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
569 if (!ReadFileToBuffer(path, &buff, &buff_size, &buff_len, 1024 * 1024)) {
575 for (count = 1, i = 1; ; i++) {
577 if (buff[i+1] == 0) break;
578 (*arr)[count] = &buff[i+1];
579 CHECK_LE(count, arr_size - 1); // FIXME: make this more flexible.
583 (*arr)[count] = nullptr;
587 #if !SANITIZER_OPENBSD
588 static void GetArgsAndEnv(char ***argv, char ***envp) {
589 #if SANITIZER_FREEBSD
590 // On FreeBSD, retrieving the argument and environment arrays is done via the
591 // kern.ps_strings sysctl, which returns a pointer to a structure containing
592 // this information. See also <sys/exec.h>.
594 uptr sz = sizeof(pss);
595 if (internal_sysctlbyname("kern.ps_strings", &pss, &sz, NULL, 0) == -1) {
596 Printf("sysctl kern.ps_strings failed\n");
599 *argv = pss->ps_argvstr;
600 *envp = pss->ps_envstr;
601 #elif SANITIZER_NETBSD
602 *argv = __ps_strings->ps_argvstr;
603 *envp = __ps_strings->ps_envstr;
604 #else // SANITIZER_FREEBSD
606 if (&__libc_stack_end) {
607 #endif // !SANITIZER_GO
608 uptr* stack_end = (uptr*)__libc_stack_end;
609 int argc = *stack_end;
610 *argv = (char**)(stack_end + 1);
611 *envp = (char**)(stack_end + argc + 2);
614 static const int kMaxArgv = 2000, kMaxEnvp = 2000;
615 ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
616 ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
618 #endif // !SANITIZER_GO
619 #endif // SANITIZER_FREEBSD
624 GetArgsAndEnv(&argv, &envp);
628 char **GetEnviron() {
630 GetArgsAndEnv(&argv, &envp);
634 #endif // !SANITIZER_OPENBSD
636 #if !SANITIZER_SOLARIS
643 BlockingMutex::BlockingMutex() {
644 internal_memset(this, 0, sizeof(*this));
647 void BlockingMutex::Lock() {
649 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
650 if (atomic_exchange(m, MtxLocked, memory_order_acquire) == MtxUnlocked)
652 while (atomic_exchange(m, MtxSleeping, memory_order_acquire) != MtxUnlocked) {
653 #if SANITIZER_FREEBSD
654 _umtx_op(m, UMTX_OP_WAIT_UINT, MtxSleeping, 0, 0);
655 #elif SANITIZER_NETBSD
656 sched_yield(); /* No userspace futex-like synchronization */
658 internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAIT_PRIVATE, MtxSleeping,
664 void BlockingMutex::Unlock() {
665 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
666 u32 v = atomic_exchange(m, MtxUnlocked, memory_order_release);
667 CHECK_NE(v, MtxUnlocked);
668 if (v == MtxSleeping) {
669 #if SANITIZER_FREEBSD
670 _umtx_op(m, UMTX_OP_WAKE, 1, 0, 0);
671 #elif SANITIZER_NETBSD
672 /* No userspace futex-like synchronization */
674 internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAKE_PRIVATE, 1, 0, 0, 0);
679 void BlockingMutex::CheckLocked() {
680 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
681 CHECK_NE(MtxUnlocked, atomic_load(m, memory_order_relaxed));
683 #endif // !SANITIZER_SOLARIS
685 // ----------------- sanitizer_linux.h
686 // The actual size of this structure is specified by d_reclen.
687 // Note that getdents64 uses a different structure format. We only provide the
688 // 32-bit syscall here.
691 #elif SANITIZER_OPENBSD
692 // struct dirent is different for Linux and us. At this moment, we use only
693 // d_fileno (Linux call this d_ino), d_reclen, and d_name.
694 struct linux_dirent {
695 u64 d_ino; // d_fileno
697 u16 d_namlen; // not used
698 u8 d_type; // not used
699 char d_name[NAME_MAX + 1];
702 struct linux_dirent {
703 #if SANITIZER_X32 || defined(__aarch64__)
710 unsigned short d_reclen;
712 unsigned char d_type;
718 #if !SANITIZER_SOLARIS && !SANITIZER_NETBSD
720 uptr internal_ptrace(int request, int pid, void *addr, void *data) {
721 return internal_syscall(SYSCALL(ptrace), request, pid, (uptr)addr,
725 uptr internal_waitpid(int pid, int *status, int options) {
726 return internal_syscall(SYSCALL(wait4), pid, (uptr)status, options,
730 uptr internal_getpid() {
731 return internal_syscall(SYSCALL(getpid));
734 uptr internal_getppid() {
735 return internal_syscall(SYSCALL(getppid));
738 uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) {
739 #if SANITIZER_FREEBSD
740 return internal_syscall(SYSCALL(getdirentries), fd, (uptr)dirp, count, NULL);
741 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
742 return internal_syscall(SYSCALL(getdents64), fd, (uptr)dirp, count);
744 return internal_syscall(SYSCALL(getdents), fd, (uptr)dirp, count);
748 uptr internal_lseek(fd_t fd, OFF_T offset, int whence) {
749 return internal_syscall(SYSCALL(lseek), fd, offset, whence);
753 uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
754 return internal_syscall(SYSCALL(prctl), option, arg2, arg3, arg4, arg5);
758 uptr internal_sigaltstack(const void *ss, void *oss) {
759 return internal_syscall(SYSCALL(sigaltstack), (uptr)ss, (uptr)oss);
762 int internal_fork() {
763 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
764 return internal_syscall(SYSCALL(clone), SIGCHLD, 0);
766 return internal_syscall(SYSCALL(fork));
770 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD
771 int internal_sysctl(const int *name, unsigned int namelen, void *oldp,
772 uptr *oldlenp, const void *newp, uptr newlen) {
773 #if SANITIZER_OPENBSD
774 return sysctl(name, namelen, oldp, (size_t *)oldlenp, (void *)newp,
777 return internal_syscall(SYSCALL(__sysctl), name, namelen, oldp,
778 (size_t *)oldlenp, newp, (size_t)newlen);
782 #if SANITIZER_FREEBSD
783 int internal_sysctlbyname(const char *sname, void *oldp, uptr *oldlenp,
784 const void *newp, uptr newlen) {
785 static decltype(sysctlbyname) *real = nullptr;
787 real = (decltype(sysctlbyname) *)dlsym(RTLD_NEXT, "sysctlbyname");
789 return real(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;
841 #endif // SANITIZER_LINUX
843 uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
844 __sanitizer_sigset_t *oldset) {
845 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD
846 return internal_syscall(SYSCALL(sigprocmask), how, set, oldset);
848 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
849 __sanitizer_kernel_sigset_t *k_oldset = (__sanitizer_kernel_sigset_t *)oldset;
850 return internal_syscall(SYSCALL(rt_sigprocmask), (uptr)how,
851 (uptr)&k_set->sig[0], (uptr)&k_oldset->sig[0],
852 sizeof(__sanitizer_kernel_sigset_t));
856 void internal_sigfillset(__sanitizer_sigset_t *set) {
857 internal_memset(set, 0xff, sizeof(*set));
860 void internal_sigemptyset(__sanitizer_sigset_t *set) {
861 internal_memset(set, 0, sizeof(*set));
865 void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
868 CHECK_LT(signum, sizeof(*set) * 8);
869 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
870 const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
871 const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
872 k_set->sig[idx] &= ~(1 << bit);
875 bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
878 CHECK_LT(signum, sizeof(*set) * 8);
879 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
880 const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
881 const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
882 return k_set->sig[idx] & (1 << bit);
884 #elif SANITIZER_FREEBSD
885 void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
886 sigset_t *rset = reinterpret_cast<sigset_t *>(set);
887 sigdelset(rset, signum);
890 bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
891 sigset_t *rset = reinterpret_cast<sigset_t *>(set);
892 return sigismember(rset, signum);
895 #endif // !SANITIZER_SOLARIS
897 #if !SANITIZER_NETBSD
898 // ThreadLister implementation.
899 ThreadLister::ThreadLister(pid_t pid) : pid_(pid), buffer_(4096) {
900 char task_directory_path[80];
901 internal_snprintf(task_directory_path, sizeof(task_directory_path),
902 "/proc/%d/task/", pid);
903 descriptor_ = internal_open(task_directory_path, O_RDONLY | O_DIRECTORY);
904 if (internal_iserror(descriptor_)) {
905 Report("Can't open /proc/%d/task for reading.\n", pid);
909 ThreadLister::Result ThreadLister::ListThreads(
910 InternalMmapVector<tid_t> *threads) {
911 if (internal_iserror(descriptor_))
913 internal_lseek(descriptor_, 0, SEEK_SET);
917 for (bool first_read = true;; first_read = false) {
918 // Resize to max capacity if it was downsized by IsAlive.
919 buffer_.resize(buffer_.capacity());
920 CHECK_GE(buffer_.size(), 4096);
921 uptr read = internal_getdents(
922 descriptor_, (struct linux_dirent *)buffer_.data(), buffer_.size());
925 if (internal_iserror(read)) {
926 Report("Can't read directory entries from /proc/%d/task.\n", pid_);
930 for (uptr begin = (uptr)buffer_.data(), end = begin + read; begin < end;) {
931 struct linux_dirent *entry = (struct linux_dirent *)begin;
932 begin += entry->d_reclen;
933 if (entry->d_ino == 1) {
934 // Inode 1 is for bad blocks and also can be a reason for early return.
935 // Should be emitted if kernel tried to output terminating thread.
936 // See proc_task_readdir implementation in Linux.
939 if (entry->d_ino && *entry->d_name >= '0' && *entry->d_name <= '9')
940 threads->push_back(internal_atoll(entry->d_name));
943 // Now we are going to detect short-read or early EOF. In such cases Linux
944 // can return inconsistent list with missing alive threads.
945 // Code will just remember that the list can be incomplete but it will
946 // continue reads to return as much as possible.
948 // The first one was a short-read by definition.
950 } else if (read > buffer_.size() - 1024) {
951 // Read was close to the buffer size. So double the size and assume the
953 buffer_.resize(buffer_.size() * 2);
955 } else if (!threads->empty() && !IsAlive(threads->back())) {
956 // Maybe Linux early returned from read on terminated thread (!pid_alive)
957 // and failed to restore read position.
958 // See next_tid and proc_task_instantiate in Linux.
964 bool ThreadLister::IsAlive(int tid) {
965 // /proc/%d/task/%d/status uses same call to detect alive threads as
966 // proc_task_readdir. See task_state implementation in Linux.
968 internal_snprintf(path, sizeof(path), "/proc/%d/task/%d/status", pid_, tid);
969 if (!ReadFileToVector(path, &buffer_) || buffer_.empty())
971 buffer_.push_back(0);
972 static const char kPrefix[] = "\nPPid:";
973 const char *field = internal_strstr(buffer_.data(), kPrefix);
976 field += internal_strlen(kPrefix);
977 return (int)internal_atoll(field) != 0;
980 ThreadLister::~ThreadLister() {
981 if (!internal_iserror(descriptor_))
982 internal_close(descriptor_);
986 #if SANITIZER_WORDSIZE == 32
987 // Take care of unusable kernel area in top gigabyte.
988 static uptr GetKernelAreaSize() {
989 #if SANITIZER_LINUX && !SANITIZER_X32
990 const uptr gbyte = 1UL << 30;
992 // Firstly check if there are writable segments
993 // mapped to top gigabyte (e.g. stack).
994 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
995 if (proc_maps.Error())
997 MemoryMappedSegment segment;
998 while (proc_maps.Next(&segment)) {
999 if ((segment.end >= 3 * gbyte) && segment.IsWritable()) return 0;
1002 #if !SANITIZER_ANDROID
1003 // Even if nothing is mapped, top Gb may still be accessible
1004 // if we are running on 64-bit kernel.
1005 // Uname may report misleading results if personality type
1006 // is modified (e.g. under schroot) so check this as well.
1007 struct utsname uname_info;
1008 int pers = personality(0xffffffffUL);
1009 if (!(pers & PER_MASK)
1010 && uname(&uname_info) == 0
1011 && internal_strstr(uname_info.machine, "64"))
1013 #endif // SANITIZER_ANDROID
1015 // Top gigabyte is reserved for kernel.
1019 #endif // SANITIZER_LINUX && !SANITIZER_X32
1021 #endif // SANITIZER_WORDSIZE == 32
1023 uptr GetMaxVirtualAddress() {
1024 #if (SANITIZER_NETBSD || SANITIZER_OPENBSD) && defined(__x86_64__)
1025 return 0x7f7ffffff000ULL; // (0x00007f8000000000 - PAGE_SIZE)
1026 #elif SANITIZER_WORDSIZE == 64
1027 # if defined(__powerpc64__) || defined(__aarch64__)
1028 // On PowerPC64 we have two different address space layouts: 44- and 46-bit.
1029 // We somehow need to figure out which one we are using now and choose
1030 // one of 0x00000fffffffffffUL and 0x00003fffffffffffUL.
1031 // Note that with 'ulimit -s unlimited' the stack is moved away from the top
1032 // of the address space, so simply checking the stack address is not enough.
1033 // This should (does) work for both PowerPC64 Endian modes.
1034 // Similarly, aarch64 has multiple address space layouts: 39, 42 and 47-bit.
1035 return (1ULL << (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1)) - 1;
1036 # elif defined(__mips64)
1037 return (1ULL << 40) - 1; // 0x000000ffffffffffUL;
1038 # elif defined(__s390x__)
1039 return (1ULL << 53) - 1; // 0x001fffffffffffffUL;
1040 #elif defined(__sparc__)
1043 return (1ULL << 47) - 1; // 0x00007fffffffffffUL;
1045 #else // SANITIZER_WORDSIZE == 32
1046 # if defined(__s390__)
1047 return (1ULL << 31) - 1; // 0x7fffffff;
1049 return (1ULL << 32) - 1; // 0xffffffff;
1051 #endif // SANITIZER_WORDSIZE
1054 uptr GetMaxUserVirtualAddress() {
1055 uptr addr = GetMaxVirtualAddress();
1056 #if SANITIZER_WORDSIZE == 32 && !defined(__s390__)
1057 if (!common_flags()->full_address_space)
1058 addr -= GetKernelAreaSize();
1059 CHECK_LT(reinterpret_cast<uptr>(&addr), addr);
1064 #if !SANITIZER_ANDROID
1065 uptr GetPageSize() {
1066 #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__))
1067 return EXEC_PAGESIZE;
1068 #elif SANITIZER_FREEBSD || SANITIZER_NETBSD
1069 // Use sysctl as sysconf can trigger interceptors internally.
1071 uptr pzl = sizeof(pz);
1072 int mib[2] = {CTL_HW, HW_PAGESIZE};
1073 int rv = internal_sysctl(mib, 2, &pz, &pzl, nullptr, 0);
1076 #elif SANITIZER_USE_GETAUXVAL
1077 return getauxval(AT_PAGESZ);
1079 return sysconf(_SC_PAGESIZE); // EXEC_PAGESIZE may not be trustworthy.
1082 #endif // !SANITIZER_ANDROID
1084 #if !SANITIZER_OPENBSD
1085 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
1086 #if SANITIZER_SOLARIS
1087 const char *default_module_name = getexecname();
1088 CHECK_NE(default_module_name, NULL);
1089 return internal_snprintf(buf, buf_len, "%s", default_module_name);
1091 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
1092 #if SANITIZER_FREEBSD
1093 const int Mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
1095 const int Mib[4] = {CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME};
1097 const char *default_module_name = "kern.proc.pathname";
1098 uptr Size = buf_len;
1100 (internal_sysctl(Mib, ARRAY_SIZE(Mib), buf, &Size, NULL, 0) != 0);
1101 int readlink_error = IsErr ? errno : 0;
1102 uptr module_name_len = Size;
1104 const char *default_module_name = "/proc/self/exe";
1105 uptr module_name_len = internal_readlink(
1106 default_module_name, buf, buf_len);
1108 bool IsErr = internal_iserror(module_name_len, &readlink_error);
1109 #endif // SANITIZER_SOLARIS
1111 // We can't read binary name for some reason, assume it's unknown.
1112 Report("WARNING: reading executable name failed with errno %d, "
1113 "some stack frames may not be symbolized\n", readlink_error);
1114 module_name_len = internal_snprintf(buf, buf_len, "%s",
1115 default_module_name);
1116 CHECK_LT(module_name_len, buf_len);
1118 return module_name_len;
1121 #endif // !SANITIZER_OPENBSD
1123 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len) {
1128 if (ReadFileToBuffer("/proc/self/cmdline", &tmpbuf, &tmpsize, &tmplen,
1130 internal_strncpy(buf, tmpbuf, buf_len);
1131 UnmapOrDie(tmpbuf, tmpsize);
1132 return internal_strlen(buf);
1135 return ReadBinaryName(buf, buf_len);
1138 // Match full names of the form /path/to/base_name{-,.}*
1139 bool LibraryNameIs(const char *full_name, const char *base_name) {
1140 const char *name = full_name;
1142 while (*name != '\0') name++;
1143 while (name > full_name && *name != '/') name--;
1144 if (*name == '/') name++;
1145 uptr base_name_length = internal_strlen(base_name);
1146 if (internal_strncmp(name, base_name, base_name_length)) return false;
1147 return (name[base_name_length] == '-' || name[base_name_length] == '.');
1150 #if !SANITIZER_ANDROID
1151 // Call cb for each region mapped by map.
1152 void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr)) {
1153 CHECK_NE(map, nullptr);
1154 #if !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
1155 typedef ElfW(Phdr) Elf_Phdr;
1156 typedef ElfW(Ehdr) Elf_Ehdr;
1157 #endif // !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
1158 char *base = (char *)map->l_addr;
1159 Elf_Ehdr *ehdr = (Elf_Ehdr *)base;
1160 char *phdrs = base + ehdr->e_phoff;
1161 char *phdrs_end = phdrs + ehdr->e_phnum * ehdr->e_phentsize;
1163 // Find the segment with the minimum base so we can "relocate" the p_vaddr
1164 // fields. Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
1165 // objects have a non-zero base.
1166 uptr preferred_base = (uptr)-1;
1167 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
1168 Elf_Phdr *phdr = (Elf_Phdr *)iter;
1169 if (phdr->p_type == PT_LOAD && preferred_base > (uptr)phdr->p_vaddr)
1170 preferred_base = (uptr)phdr->p_vaddr;
1173 // Compute the delta from the real base to get a relocation delta.
1174 sptr delta = (uptr)base - preferred_base;
1175 // Now we can figure out what the loader really mapped.
1176 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
1177 Elf_Phdr *phdr = (Elf_Phdr *)iter;
1178 if (phdr->p_type == PT_LOAD) {
1179 uptr seg_start = phdr->p_vaddr + delta;
1180 uptr seg_end = seg_start + phdr->p_memsz;
1181 // None of these values are aligned. We consider the ragged edges of the
1182 // load command as defined, since they are mapped from the file.
1183 seg_start = RoundDownTo(seg_start, GetPageSizeCached());
1184 seg_end = RoundUpTo(seg_end, GetPageSizeCached());
1185 cb((void *)seg_start, seg_end - seg_start);
1191 #if defined(__x86_64__) && SANITIZER_LINUX
1192 // We cannot use glibc's clone wrapper, because it messes with the child
1193 // task's TLS. It writes the PID and TID of the child task to its thread
1194 // descriptor, but in our case the child task shares the thread descriptor with
1195 // the parent (because we don't know how to allocate a new thread
1196 // descriptor to keep glibc happy). So the stock version of clone(), when
1197 // used with CLONE_VM, would end up corrupting the parent's thread descriptor.
1198 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1199 int *parent_tidptr, void *newtls, int *child_tidptr) {
1201 if (!fn || !child_stack)
1203 CHECK_EQ(0, (uptr)child_stack % 16);
1204 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1205 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1206 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1207 register void *r8 __asm__("r8") = newtls;
1208 register int *r10 __asm__("r10") = child_tidptr;
1209 __asm__ __volatile__(
1210 /* %rax = syscall(%rax = SYSCALL(clone),
1212 * %rsi = child_stack,
1213 * %rdx = parent_tidptr,
1215 * %r10 = child_tidptr)
1222 "testq %%rax,%%rax\n"
1225 /* In the child. Terminate unwind chain. */
1226 // XXX: We should also terminate the CFI unwind chain
1227 // here. Unfortunately clang 3.2 doesn't support the
1228 // necessary CFI directives, so we skip that part.
1229 "xorq %%rbp,%%rbp\n"
1231 /* Call "fn(arg)". */
1236 /* Call _exit(%rax). */
1237 "movq %%rax,%%rdi\n"
1241 /* Return to parent. */
1244 : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
1250 : "memory", "r11", "rcx");
1253 #elif defined(__mips__)
1254 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1255 int *parent_tidptr, void *newtls, int *child_tidptr) {
1257 if (!fn || !child_stack)
1259 CHECK_EQ(0, (uptr)child_stack % 16);
1260 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1261 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1262 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1263 register void *a3 __asm__("$7") = newtls;
1264 register int *a4 __asm__("$8") = child_tidptr;
1265 // We don't have proper CFI directives here because it requires alot of code
1266 // for very marginal benefits.
1267 __asm__ __volatile__(
1268 /* $v0 = syscall($v0 = __NR_clone,
1270 * $a1 = child_stack,
1271 * $a2 = parent_tidptr,
1273 * $a4 = child_tidptr)
1280 /* Store the fifth argument on stack
1281 * if we are using 32-bit abi.
1283 #if SANITIZER_WORDSIZE == 32
1296 /* Call "fn(arg)". */
1297 #if SANITIZER_WORDSIZE == 32
1298 #ifdef __BIG_ENDIAN__
1311 /* Call _exit($v0). */
1316 /* Return to parent. */
1326 : "memory", "$29" );
1329 #elif defined(__aarch64__)
1330 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1331 int *parent_tidptr, void *newtls, int *child_tidptr) {
1333 if (!fn || !child_stack)
1335 CHECK_EQ(0, (uptr)child_stack % 16);
1336 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1337 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1338 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1340 register int (*__fn)(void *) __asm__("x0") = fn;
1341 register void *__stack __asm__("x1") = child_stack;
1342 register int __flags __asm__("x2") = flags;
1343 register void *__arg __asm__("x3") = arg;
1344 register int *__ptid __asm__("x4") = parent_tidptr;
1345 register void *__tls __asm__("x5") = newtls;
1346 register int *__ctid __asm__("x6") = child_tidptr;
1348 __asm__ __volatile__(
1349 "mov x0,x2\n" /* flags */
1350 "mov x2,x4\n" /* ptid */
1351 "mov x3,x5\n" /* tls */
1352 "mov x4,x6\n" /* ctid */
1353 "mov x8,%9\n" /* clone */
1363 /* In the child, now. Call "fn(arg)". */
1364 "ldp x1, x0, [sp], #16\n"
1367 /* Call _exit(%r0). */
1374 "r"(__fn), "r"(__stack), "r"(__flags), "r"(__arg),
1375 "r"(__ptid), "r"(__tls), "r"(__ctid),
1376 "i"(__NR_clone), "i"(__NR_exit)
1380 #elif defined(__powerpc64__)
1381 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1382 int *parent_tidptr, void *newtls, int *child_tidptr) {
1384 // Stack frame structure.
1385 #if SANITIZER_PPC64V1
1386 // Back chain == 0 (SP + 112)
1387 // Frame (112 bytes):
1388 // Parameter save area (SP + 48), 8 doublewords
1389 // TOC save area (SP + 40)
1390 // Link editor doubleword (SP + 32)
1391 // Compiler doubleword (SP + 24)
1392 // LR save area (SP + 16)
1393 // CR save area (SP + 8)
1394 // Back chain (SP + 0)
1395 # define FRAME_SIZE 112
1396 # define FRAME_TOC_SAVE_OFFSET 40
1397 #elif SANITIZER_PPC64V2
1398 // Back chain == 0 (SP + 32)
1399 // Frame (32 bytes):
1400 // TOC save area (SP + 24)
1401 // LR save area (SP + 16)
1402 // CR save area (SP + 8)
1403 // Back chain (SP + 0)
1404 # define FRAME_SIZE 32
1405 # define FRAME_TOC_SAVE_OFFSET 24
1407 # error "Unsupported PPC64 ABI"
1409 if (!fn || !child_stack)
1411 CHECK_EQ(0, (uptr)child_stack % 16);
1413 register int (*__fn)(void *) __asm__("r3") = fn;
1414 register void *__cstack __asm__("r4") = child_stack;
1415 register int __flags __asm__("r5") = flags;
1416 register void *__arg __asm__("r6") = arg;
1417 register int *__ptidptr __asm__("r7") = parent_tidptr;
1418 register void *__newtls __asm__("r8") = newtls;
1419 register int *__ctidptr __asm__("r9") = child_tidptr;
1421 __asm__ __volatile__(
1422 /* fn and arg are saved across the syscall */
1432 r7 == child_tidptr */
1440 /* Test if syscall was successful */
1441 "cmpdi cr1, 3, 0\n\t"
1442 "crandc cr1*4+eq, cr1*4+eq, cr0*4+so\n\t"
1445 /* Set up stack frame */
1447 "stdu 29, -8(1)\n\t"
1448 "stdu 1, -%12(1)\n\t"
1449 /* Do the function call */
1451 #if SANITIZER_PPC64V1
1455 #elif SANITIZER_PPC64V2
1459 # error "Unsupported PPC64 ABI"
1465 /* Call _exit(r3) */
1469 /* Return to parent */
1485 "i" (FRAME_TOC_SAVE_OFFSET)
1486 : "cr0", "cr1", "memory", "ctr", "r0", "r27", "r28", "r29");
1489 #elif defined(__i386__) && SANITIZER_LINUX
1490 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1491 int *parent_tidptr, void *newtls, int *child_tidptr) {
1493 if (!fn || !child_stack)
1495 CHECK_EQ(0, (uptr)child_stack % 16);
1496 child_stack = (char *)child_stack - 7 * sizeof(unsigned int);
1497 ((unsigned int *)child_stack)[0] = (uptr)flags;
1498 ((unsigned int *)child_stack)[1] = (uptr)0;
1499 ((unsigned int *)child_stack)[2] = (uptr)fn;
1500 ((unsigned int *)child_stack)[3] = (uptr)arg;
1501 __asm__ __volatile__(
1502 /* %eax = syscall(%eax = SYSCALL(clone),
1504 * %ecx = child_stack,
1505 * %edx = parent_tidptr,
1507 * %edi = child_tidptr)
1511 "movl (%%ecx), %%ebx\n"
1512 /* Do the system call */
1516 /* Remember the flag value. */
1517 "movl %%ebx, (%%ecx)\n"
1527 "test %%eax,%%eax\n"
1530 /* terminate the stack frame */
1531 "xorl %%ebp,%%ebp\n"
1538 "addl $_GLOBAL_OFFSET_TABLE_+[.-here], %%ebx\n"
1541 "movl %%eax, %%ebx\n"
1546 : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
1554 #elif defined(__arm__) && SANITIZER_LINUX
1555 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1556 int *parent_tidptr, void *newtls, int *child_tidptr) {
1558 if (!fn || !child_stack)
1560 child_stack = (char *)child_stack - 2 * sizeof(unsigned int);
1561 ((unsigned int *)child_stack)[0] = (uptr)fn;
1562 ((unsigned int *)child_stack)[1] = (uptr)arg;
1563 register int r0 __asm__("r0") = flags;
1564 register void *r1 __asm__("r1") = child_stack;
1565 register int *r2 __asm__("r2") = parent_tidptr;
1566 register void *r3 __asm__("r3") = newtls;
1567 register int *r4 __asm__("r4") = child_tidptr;
1568 register int r7 __asm__("r7") = __NR_clone;
1570 #if __ARM_ARCH > 4 || defined (__ARM_ARCH_4T__)
1571 # define ARCH_HAS_BX
1574 # define ARCH_HAS_BLX
1578 # ifdef ARCH_HAS_BLX
1579 # define BLX(R) "blx " #R "\n"
1581 # define BLX(R) "mov lr, pc; bx " #R "\n"
1584 # define BLX(R) "mov lr, pc; mov pc," #R "\n"
1587 __asm__ __volatile__(
1588 /* %r0 = syscall(%r7 = SYSCALL(clone),
1590 * %r1 = child_stack,
1591 * %r2 = parent_tidptr,
1593 * %r4 = child_tidptr)
1596 /* Do the system call */
1605 /* In the child, now. Call "fn(arg)". */
1606 "ldr r0, [sp, #4]\n"
1607 "ldr ip, [sp], #8\n"
1609 /* Call _exit(%r0). */
1615 : "r"(r0), "r"(r1), "r"(r2), "r"(r3), "r"(r4), "r"(r7),
1620 #endif // defined(__x86_64__) && SANITIZER_LINUX
1622 #if SANITIZER_ANDROID
1623 #if __ANDROID_API__ < 21
1624 extern "C" __attribute__((weak)) int dl_iterate_phdr(
1625 int (*)(struct dl_phdr_info *, size_t, void *), void *);
1628 static int dl_iterate_phdr_test_cb(struct dl_phdr_info *info, size_t size,
1630 // Any name starting with "lib" indicates a bug in L where library base names
1631 // are returned instead of paths.
1632 if (info->dlpi_name && info->dlpi_name[0] == 'l' &&
1633 info->dlpi_name[1] == 'i' && info->dlpi_name[2] == 'b') {
1634 *(bool *)data = true;
1640 static atomic_uint32_t android_api_level;
1642 static AndroidApiLevel AndroidDetectApiLevelStatic() {
1643 #if __ANDROID_API__ <= 19
1644 return ANDROID_KITKAT;
1645 #elif __ANDROID_API__ <= 22
1646 return ANDROID_LOLLIPOP_MR1;
1648 return ANDROID_POST_LOLLIPOP;
1652 static AndroidApiLevel AndroidDetectApiLevel() {
1653 if (!&dl_iterate_phdr)
1654 return ANDROID_KITKAT; // K or lower
1655 bool base_name_seen = false;
1656 dl_iterate_phdr(dl_iterate_phdr_test_cb, &base_name_seen);
1658 return ANDROID_LOLLIPOP_MR1; // L MR1
1659 return ANDROID_POST_LOLLIPOP; // post-L
1660 // Plain L (API level 21) is completely broken wrt ASan and not very
1661 // interesting to detect.
1664 extern "C" __attribute__((weak)) void* _DYNAMIC;
1666 AndroidApiLevel AndroidGetApiLevel() {
1667 AndroidApiLevel level =
1668 (AndroidApiLevel)atomic_load(&android_api_level, memory_order_relaxed);
1669 if (level) return level;
1670 level = &_DYNAMIC == nullptr ? AndroidDetectApiLevelStatic()
1671 : AndroidDetectApiLevel();
1672 atomic_store(&android_api_level, level, memory_order_relaxed);
1678 static HandleSignalMode GetHandleSignalModeImpl(int signum) {
1681 return common_flags()->handle_abort;
1683 return common_flags()->handle_sigill;
1685 return common_flags()->handle_sigtrap;
1687 return common_flags()->handle_sigfpe;
1689 return common_flags()->handle_segv;
1691 return common_flags()->handle_sigbus;
1693 return kHandleSignalNo;
1696 HandleSignalMode GetHandleSignalMode(int signum) {
1697 HandleSignalMode result = GetHandleSignalModeImpl(signum);
1698 if (result == kHandleSignalYes && !common_flags()->allow_user_segv_handler)
1699 return kHandleSignalExclusive;
1704 void *internal_start_thread(void(*func)(void *arg), void *arg) {
1705 // Start the thread with signals blocked, otherwise it can steal user signals.
1706 __sanitizer_sigset_t set, old;
1707 internal_sigfillset(&set);
1708 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1709 // Glibc uses SIGSETXID signal during setuid call. If this signal is blocked
1710 // on any thread, setuid call hangs (see test/tsan/setuid.c).
1711 internal_sigdelset(&set, 33);
1713 internal_sigprocmask(SIG_SETMASK, &set, &old);
1715 real_pthread_create(&th, nullptr, (void*(*)(void *arg))func, arg);
1716 internal_sigprocmask(SIG_SETMASK, &old, nullptr);
1720 void internal_join_thread(void *th) {
1721 real_pthread_join(th, nullptr);
1724 void *internal_start_thread(void (*func)(void *), void *arg) { return 0; }
1726 void internal_join_thread(void *th) {}
1729 #if defined(__aarch64__)
1730 // Android headers in the older NDK releases miss this definition.
1731 struct __sanitizer_esr_context {
1732 struct _aarch64_ctx head;
1736 static bool Aarch64GetESR(ucontext_t *ucontext, u64 *esr) {
1737 static const u32 kEsrMagic = 0x45535201;
1738 u8 *aux = ucontext->uc_mcontext.__reserved;
1740 _aarch64_ctx *ctx = (_aarch64_ctx *)aux;
1741 if (ctx->size == 0) break;
1742 if (ctx->magic == kEsrMagic) {
1743 *esr = ((__sanitizer_esr_context *)ctx)->esr;
1752 #if SANITIZER_OPENBSD
1753 using Context = sigcontext;
1755 using Context = ucontext_t;
1758 SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
1759 Context *ucontext = (Context *)context;
1760 #if defined(__x86_64__) || defined(__i386__)
1761 static const uptr PF_WRITE = 1U << 1;
1762 #if SANITIZER_FREEBSD
1763 uptr err = ucontext->uc_mcontext.mc_err;
1764 #elif SANITIZER_NETBSD
1765 uptr err = ucontext->uc_mcontext.__gregs[_REG_ERR];
1766 #elif SANITIZER_OPENBSD
1767 uptr err = ucontext->sc_err;
1768 #elif SANITIZER_SOLARIS && defined(__i386__)
1770 uptr err = ucontext->uc_mcontext.gregs[Err];
1772 uptr err = ucontext->uc_mcontext.gregs[REG_ERR];
1773 #endif // SANITIZER_FREEBSD
1774 return err & PF_WRITE ? WRITE : READ;
1775 #elif defined(__mips__)
1776 uint32_t *exception_source;
1777 uint32_t faulty_instruction;
1780 exception_source = (uint32_t *)ucontext->uc_mcontext.pc;
1781 faulty_instruction = (uint32_t)(*exception_source);
1783 op_code = (faulty_instruction >> 26) & 0x3f;
1785 // FIXME: Add support for FPU, microMIPS, DSP, MSA memory instructions.
1791 #if __mips_isa_rev < 6
1797 return SignalContext::WRITE;
1806 #if __mips_isa_rev < 6
1812 return SignalContext::READ;
1813 #if __mips_isa_rev == 6
1815 op_code = (faulty_instruction >> 19) & 0x3;
1819 return SignalContext::READ;
1823 return SignalContext::UNKNOWN;
1824 #elif defined(__arm__)
1825 static const uptr FSR_WRITE = 1U << 11;
1826 uptr fsr = ucontext->uc_mcontext.error_code;
1827 return fsr & FSR_WRITE ? WRITE : READ;
1828 #elif defined(__aarch64__)
1829 static const u64 ESR_ELx_WNR = 1U << 6;
1831 if (!Aarch64GetESR(ucontext, &esr)) return UNKNOWN;
1832 return esr & ESR_ELx_WNR ? WRITE : READ;
1833 #elif defined(__sparc__)
1834 // Decode the instruction to determine the access type.
1835 // From OpenSolaris $SRC/uts/sun4/os/trap.c (get_accesstype).
1836 #if SANITIZER_SOLARIS
1837 uptr pc = ucontext->uc_mcontext.gregs[REG_PC];
1839 // Historical BSDism here.
1840 struct sigcontext *scontext = (struct sigcontext *)context;
1841 #if defined(__arch64__)
1842 uptr pc = scontext->sigc_regs.tpc;
1844 uptr pc = scontext->si_regs.pc;
1847 u32 instr = *(u32 *)pc;
1848 return (instr >> 21) & 1 ? WRITE: READ;
1851 return UNKNOWN; // FIXME: Implement.
1855 bool SignalContext::IsTrueFaultingAddress() const {
1856 auto si = static_cast<const siginfo_t *>(siginfo);
1857 // SIGSEGV signals without a true fault address have si_code set to 128.
1858 return si->si_signo == SIGSEGV && si->si_code != 128;
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 #if defined(__arch64__) || defined(__sparcv9)
1944 #define STACK_BIAS 2047
1946 #define STACK_BIAS 0
1948 # if SANITIZER_SOLARIS
1949 ucontext_t *ucontext = (ucontext_t *)context;
1950 *pc = ucontext->uc_mcontext.gregs[REG_PC];
1951 *sp = ucontext->uc_mcontext.gregs[REG_O6] + STACK_BIAS;
1953 // Historical BSDism here.
1954 struct sigcontext *scontext = (struct sigcontext *)context;
1955 #if defined(__arch64__)
1956 *pc = scontext->sigc_regs.tpc;
1957 *sp = scontext->sigc_regs.u_regs[14] + STACK_BIAS;
1959 *pc = scontext->si_regs.pc;
1960 *sp = scontext->si_regs.u_regs[14];
1963 *bp = (uptr)((uhwptr *)*sp)[14] + STACK_BIAS;
1964 #elif defined(__mips__)
1965 ucontext_t *ucontext = (ucontext_t*)context;
1966 *pc = ucontext->uc_mcontext.pc;
1967 *bp = ucontext->uc_mcontext.gregs[30];
1968 *sp = ucontext->uc_mcontext.gregs[29];
1969 #elif defined(__s390__)
1970 ucontext_t *ucontext = (ucontext_t*)context;
1971 # if defined(__s390x__)
1972 *pc = ucontext->uc_mcontext.psw.addr;
1974 *pc = ucontext->uc_mcontext.psw.addr & 0x7fffffff;
1976 *bp = ucontext->uc_mcontext.gregs[11];
1977 *sp = ucontext->uc_mcontext.gregs[15];
1978 #elif defined(__riscv)
1979 ucontext_t *ucontext = (ucontext_t*)context;
1980 *pc = ucontext->uc_mcontext.__gregs[REG_PC];
1981 *bp = ucontext->uc_mcontext.__gregs[REG_S0];
1982 *sp = ucontext->uc_mcontext.__gregs[REG_SP];
1984 # error "Unsupported arch"
1988 void SignalContext::InitPcSpBp() { GetPcSpBp(context, &pc, &sp, &bp); }
1990 void InitializePlatformEarly() {
1994 void MaybeReexec() {
1995 // No need to re-exec on Linux.
1999 #if SANITIZER_NETBSD
2002 uptr len = sizeof(paxflags);
2005 mib[1] = internal_getpid();
2006 mib[2] = PROC_PID_PAXFLAGS;
2008 if (UNLIKELY(internal_sysctl(mib, 3, &paxflags, &len, NULL, 0) == -1)) {
2009 Printf("sysctl failed\n");
2013 if (UNLIKELY(paxflags & CTL_PROC_PAXFLAGS_ASLR)) {
2014 Printf("This sanitizer is not compatible with enabled ASLR\n");
2017 #elif SANITIZER_PPC64V2
2018 // Disable ASLR for Linux PPC64LE.
2019 int old_personality = personality(0xffffffff);
2020 if (old_personality != -1 && (old_personality & ADDR_NO_RANDOMIZE) == 0) {
2021 VReport(1, "WARNING: Program is being run with address space layout "
2022 "randomization (ASLR) enabled which prevents the thread and "
2023 "memory sanitizers from working on powerpc64le.\n"
2024 "ASLR will be disabled and the program re-executed.\n");
2025 CHECK_NE(personality(old_personality | ADDR_NO_RANDOMIZE), -1);
2028 #elif SANITIZER_FREEBSD
2030 uptr len = sizeof(aslr_pie);
2031 #if SANITIZER_WORDSIZE == 64
2032 if (UNLIKELY(internal_sysctlbyname("kern.elf64.aslr.pie_enable",
2033 &aslr_pie, &len, NULL, 0) == -1)) {
2034 // We're making things less 'dramatic' here since
2035 // the OID is not necessarily guaranteed to be here
2036 // just yet regarding FreeBSD release
2041 Printf("This sanitizer is not compatible with enabled ASLR "
2042 "and binaries compiled with PIE\n");
2046 // there might be 32 bits compat for 64 bits
2047 if (UNLIKELY(internal_sysctlbyname("kern.elf32.aslr.pie_enable",
2048 &aslr_pie, &len, NULL, 0) == -1)) {
2053 Printf("This sanitizer is not compatible with enabled ASLR "
2054 "and binaries compiled with PIE\n");
2062 void CheckMPROTECT() {
2063 #if SANITIZER_NETBSD
2066 uptr len = sizeof(paxflags);
2069 mib[1] = internal_getpid();
2070 mib[2] = PROC_PID_PAXFLAGS;
2072 if (UNLIKELY(internal_sysctl(mib, 3, &paxflags, &len, NULL, 0) == -1)) {
2073 Printf("sysctl failed\n");
2077 if (UNLIKELY(paxflags & CTL_PROC_PAXFLAGS_MPROTECT)) {
2078 Printf("This sanitizer is not compatible with enabled MPROTECT\n");
2086 void PrintModuleMap() { }
2088 void CheckNoDeepBind(const char *filename, int flag) {
2089 #ifdef RTLD_DEEPBIND
2090 if (flag & RTLD_DEEPBIND) {
2092 "You are trying to dlopen a %s shared library with RTLD_DEEPBIND flag"
2093 " which is incompatibe with sanitizer runtime "
2094 "(see https://github.com/google/sanitizers/issues/611 for details"
2095 "). If you want to run %s library under sanitizers please remove "
2096 "RTLD_DEEPBIND from dlopen flags.\n",
2097 filename, filename);
2103 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
2104 uptr *largest_gap_found,
2105 uptr *max_occupied_addr) {
2106 UNREACHABLE("FindAvailableMemoryRange is not available");
2110 bool GetRandom(void *buffer, uptr length, bool blocking) {
2111 if (!buffer || !length || length > 256)
2113 #if SANITIZER_USE_GETENTROPY
2114 uptr rnd = getentropy(buffer, length);
2116 if (internal_iserror(rnd, &rverrno) && rverrno == EFAULT)
2120 #endif // SANITIZER_USE_GETENTROPY
2122 #if SANITIZER_USE_GETRANDOM
2123 static atomic_uint8_t skip_getrandom_syscall;
2124 if (!atomic_load_relaxed(&skip_getrandom_syscall)) {
2125 // Up to 256 bytes, getrandom will not be interrupted.
2126 uptr res = internal_syscall(SYSCALL(getrandom), buffer, length,
2127 blocking ? 0 : GRND_NONBLOCK);
2129 if (internal_iserror(res, &rverrno) && rverrno == ENOSYS)
2130 atomic_store_relaxed(&skip_getrandom_syscall, 1);
2131 else if (res == length)
2134 #endif // SANITIZER_USE_GETRANDOM
2135 // Up to 256 bytes, a read off /dev/urandom will not be interrupted.
2136 // blocking is moot here, O_NONBLOCK has no effect when opening /dev/urandom.
2137 uptr fd = internal_open("/dev/urandom", O_RDONLY);
2138 if (internal_iserror(fd))
2140 uptr res = internal_read(fd, buffer, length);
2141 if (internal_iserror(res))
2147 } // namespace __sanitizer