1 //===-- sanitizer_linux.cc ------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is shared between AddressSanitizer and ThreadSanitizer
11 // run-time libraries and implements linux-specific functions from
13 //===----------------------------------------------------------------------===//
15 #include "sanitizer_platform.h"
17 #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD || \
18 SANITIZER_OPENBSD || SANITIZER_SOLARIS
20 #include "sanitizer_common.h"
21 #include "sanitizer_flags.h"
22 #include "sanitizer_getauxval.h"
23 #include "sanitizer_internal_defs.h"
24 #include "sanitizer_libc.h"
25 #include "sanitizer_linux.h"
26 #include "sanitizer_mutex.h"
27 #include "sanitizer_placement_new.h"
28 #include "sanitizer_procmaps.h"
31 #include <asm/param.h>
38 // For mips64, syscall(__NR_stat) fills the buffer in the 'struct kernel_stat'
39 // format. Struct kernel_stat is defined as 'struct stat' in asm/stat.h. To
40 // access stat from asm/stat.h, without conflicting with definition in
41 // sys/stat.h, we use this trick.
43 #include <asm/unistd.h>
44 #include <sys/types.h>
45 #define stat kernel_stat
58 #if !SANITIZER_SOLARIS
59 #include <sys/ptrace.h>
61 #include <sys/resource.h>
63 #include <sys/syscall.h>
65 #include <sys/types.h>
66 #if !SANITIZER_OPENBSD
70 #include <sys/futex.h>
75 #include <sys/utsname.h>
78 #if SANITIZER_LINUX && !SANITIZER_ANDROID
79 #include <sys/personality.h>
84 #include <sys/sysctl.h>
85 #include <machine/atomic.h>
87 // <sys/umtx.h> must be included after <errno.h> and <sys/types.h> on
88 // FreeBSD 9.2 and 10.0.
92 #endif // SANITIZER_FREEBSD
95 #include <limits.h> // For NAME_MAX
96 #include <sys/sysctl.h>
98 extern struct ps_strings *__ps_strings;
99 #endif // SANITIZER_NETBSD
101 #if SANITIZER_SOLARIS
104 #define environ _environ
107 extern char **environ;
111 struct kernel_timeval {
116 // <linux/futex.h> is broken on some linux distributions.
117 const int FUTEX_WAIT = 0;
118 const int FUTEX_WAKE = 1;
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 #if defined(__x86_64__) || SANITIZER_MIPS64
133 extern void internal_sigreturn();
137 // Note : FreeBSD had implemented both
138 // Linux and OpenBSD apis, available from
139 // future 12.x version most likely
140 #if SANITIZER_LINUX && defined(__NR_getrandom)
141 # if !defined(GRND_NONBLOCK)
142 # define GRND_NONBLOCK 1
144 # define SANITIZER_USE_GETRANDOM 1
146 # define SANITIZER_USE_GETRANDOM 0
147 #endif // SANITIZER_LINUX && defined(__NR_getrandom)
149 #if SANITIZER_OPENBSD
150 # define SANITIZER_USE_GETENTROPY 1
152 # define SANITIZER_USE_GETENTROPY 0
153 #endif // SANITIZER_USE_GETENTROPY
155 namespace __sanitizer {
157 #if SANITIZER_LINUX && defined(__x86_64__)
158 #include "sanitizer_syscall_linux_x86_64.inc"
159 #elif SANITIZER_LINUX && defined(__aarch64__)
160 #include "sanitizer_syscall_linux_aarch64.inc"
161 #elif SANITIZER_LINUX && defined(__arm__)
162 #include "sanitizer_syscall_linux_arm.inc"
164 #include "sanitizer_syscall_generic.inc"
167 // --------------- sanitizer_libc.h
168 #if !SANITIZER_SOLARIS
169 #if !SANITIZER_S390 && !SANITIZER_OPENBSD
170 uptr internal_mmap(void *addr, uptr length, int prot, int flags, int fd,
173 return internal_syscall64(SYSCALL(mmap), addr, length, prot, flags, fd,
175 #elif SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
176 return internal_syscall(SYSCALL(mmap), (uptr)addr, length, prot, flags, fd,
179 // mmap2 specifies file offset in 4096-byte units.
180 CHECK(IsAligned(offset, 4096));
181 return internal_syscall(SYSCALL(mmap2), addr, length, prot, flags, fd,
185 #endif // !SANITIZER_S390 && !SANITIZER_OPENBSD
187 #if !SANITIZER_OPENBSD
188 uptr internal_munmap(void *addr, uptr length) {
189 return internal_syscall_ptr(SYSCALL(munmap), (uptr)addr, length);
192 int internal_mprotect(void *addr, uptr length, int prot) {
193 return internal_syscall_ptr(SYSCALL(mprotect), (uptr)addr, length, prot);
197 uptr internal_close(fd_t fd) {
198 return internal_syscall(SYSCALL(close), fd);
201 uptr internal_open(const char *filename, int flags) {
202 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
203 return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags);
205 return internal_syscall_ptr(SYSCALL(open), (uptr)filename, flags);
209 uptr internal_open(const char *filename, int flags, u32 mode) {
210 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
211 return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags,
214 return internal_syscall_ptr(SYSCALL(open), (uptr)filename, flags, mode);
218 uptr internal_read(fd_t fd, void *buf, uptr count) {
220 HANDLE_EINTR(res, (sptr)internal_syscall_ptr(SYSCALL(read), fd, (uptr)buf,
225 uptr internal_write(fd_t fd, const void *buf, uptr count) {
227 HANDLE_EINTR(res, (sptr)internal_syscall_ptr(SYSCALL(write), fd, (uptr)buf,
232 uptr internal_ftruncate(fd_t fd, uptr size) {
235 HANDLE_EINTR(res, internal_syscall64(SYSCALL(ftruncate), fd, 0, (s64)size));
237 HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(ftruncate), fd,
243 #if !SANITIZER_LINUX_USES_64BIT_SYSCALLS && SANITIZER_LINUX
244 static void stat64_to_stat(struct stat64 *in, struct stat *out) {
245 internal_memset(out, 0, sizeof(*out));
246 out->st_dev = in->st_dev;
247 out->st_ino = in->st_ino;
248 out->st_mode = in->st_mode;
249 out->st_nlink = in->st_nlink;
250 out->st_uid = in->st_uid;
251 out->st_gid = in->st_gid;
252 out->st_rdev = in->st_rdev;
253 out->st_size = in->st_size;
254 out->st_blksize = in->st_blksize;
255 out->st_blocks = in->st_blocks;
256 out->st_atime = in->st_atime;
257 out->st_mtime = in->st_mtime;
258 out->st_ctime = in->st_ctime;
262 #if defined(__mips64)
263 // Undefine compatibility macros from <sys/stat.h>
264 // so that they would not clash with the kernel_stat
265 // st_[a|m|c]time fields
269 #if defined(SANITIZER_ANDROID)
270 // Bionic sys/stat.h defines additional macros
271 // for compatibility with the old NDKs and
272 // they clash with the kernel_stat structure
273 // st_[a|m|c]time_nsec fields.
278 static void kernel_stat_to_stat(struct kernel_stat *in, struct stat *out) {
279 internal_memset(out, 0, sizeof(*out));
280 out->st_dev = in->st_dev;
281 out->st_ino = in->st_ino;
282 out->st_mode = in->st_mode;
283 out->st_nlink = in->st_nlink;
284 out->st_uid = in->st_uid;
285 out->st_gid = in->st_gid;
286 out->st_rdev = in->st_rdev;
287 out->st_size = in->st_size;
288 out->st_blksize = in->st_blksize;
289 out->st_blocks = in->st_blocks;
290 #if defined(__USE_MISC) || \
291 defined(__USE_XOPEN2K8) || \
292 defined(SANITIZER_ANDROID)
293 out->st_atim.tv_sec = in->st_atime;
294 out->st_atim.tv_nsec = in->st_atime_nsec;
295 out->st_mtim.tv_sec = in->st_mtime;
296 out->st_mtim.tv_nsec = in->st_mtime_nsec;
297 out->st_ctim.tv_sec = in->st_ctime;
298 out->st_ctim.tv_nsec = in->st_ctime_nsec;
300 out->st_atime = in->st_atime;
301 out->st_atimensec = in->st_atime_nsec;
302 out->st_mtime = in->st_mtime;
303 out->st_mtimensec = in->st_mtime_nsec;
304 out->st_ctime = in->st_ctime;
305 out->st_atimensec = in->st_ctime_nsec;
310 uptr internal_stat(const char *path, void *buf) {
311 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD
312 return internal_syscall_ptr(SYSCALL(fstatat), AT_FDCWD, (uptr)path, (uptr)buf,
314 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
315 return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path, (uptr)buf,
317 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
318 # if defined(__mips64)
319 // For mips64, stat syscall fills buffer in the format of kernel_stat
320 struct kernel_stat kbuf;
321 int res = internal_syscall(SYSCALL(stat), path, &kbuf);
322 kernel_stat_to_stat(&kbuf, (struct stat *)buf);
325 return internal_syscall(SYSCALL(stat), (uptr)path, (uptr)buf);
329 int res = internal_syscall(SYSCALL(stat64), path, &buf64);
330 stat64_to_stat(&buf64, (struct stat *)buf);
335 uptr internal_lstat(const char *path, void *buf) {
337 return internal_syscall_ptr(SYSCALL(lstat), path, buf);
338 #elif SANITIZER_FREEBSD || SANITIZER_OPENBSD
339 return internal_syscall(SYSCALL(fstatat), AT_FDCWD, (uptr)path, (uptr)buf,
340 AT_SYMLINK_NOFOLLOW);
341 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
342 return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path, (uptr)buf,
343 AT_SYMLINK_NOFOLLOW);
344 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
345 # if SANITIZER_MIPS64
346 // For mips64, lstat syscall fills buffer in the format of kernel_stat
347 struct kernel_stat kbuf;
348 int res = internal_syscall(SYSCALL(lstat), path, &kbuf);
349 kernel_stat_to_stat(&kbuf, (struct stat *)buf);
352 return internal_syscall(SYSCALL(lstat), (uptr)path, (uptr)buf);
356 int res = internal_syscall(SYSCALL(lstat64), path, &buf64);
357 stat64_to_stat(&buf64, (struct stat *)buf);
362 uptr internal_fstat(fd_t fd, void *buf) {
363 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD || \
364 SANITIZER_LINUX_USES_64BIT_SYSCALLS
365 #if SANITIZER_MIPS64 && !SANITIZER_NETBSD && !SANITIZER_OPENBSD
366 // For mips64, fstat syscall fills buffer in the format of kernel_stat
367 struct kernel_stat kbuf;
368 int res = internal_syscall(SYSCALL(fstat), fd, &kbuf);
369 kernel_stat_to_stat(&kbuf, (struct stat *)buf);
372 return internal_syscall_ptr(SYSCALL(fstat), fd, (uptr)buf);
376 int res = internal_syscall(SYSCALL(fstat64), fd, &buf64);
377 stat64_to_stat(&buf64, (struct stat *)buf);
382 uptr internal_filesize(fd_t fd) {
384 if (internal_fstat(fd, &st))
386 return (uptr)st.st_size;
389 uptr internal_dup2(int oldfd, int newfd) {
390 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
391 return internal_syscall(SYSCALL(dup3), oldfd, newfd, 0);
393 return internal_syscall(SYSCALL(dup2), oldfd, newfd);
397 uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
398 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
399 return internal_syscall(SYSCALL(readlinkat), AT_FDCWD, (uptr)path, (uptr)buf,
401 #elif SANITIZER_OPENBSD
402 return internal_syscall_ptr(SYSCALL(readlinkat), AT_FDCWD, (uptr)path,
405 return internal_syscall_ptr(SYSCALL(readlink), path, buf, bufsize);
409 uptr internal_unlink(const char *path) {
410 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS || SANITIZER_OPENBSD
411 return internal_syscall(SYSCALL(unlinkat), AT_FDCWD, (uptr)path, 0);
413 return internal_syscall_ptr(SYSCALL(unlink), (uptr)path);
417 uptr internal_rename(const char *oldpath, const char *newpath) {
418 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS || SANITIZER_OPENBSD
419 return internal_syscall(SYSCALL(renameat), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
422 return internal_syscall_ptr(SYSCALL(rename), (uptr)oldpath, (uptr)newpath);
426 uptr internal_sched_yield() {
427 return internal_syscall(SYSCALL(sched_yield));
430 void internal__exit(int exitcode) {
431 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD
432 internal_syscall(SYSCALL(exit), exitcode);
434 internal_syscall(SYSCALL(exit_group), exitcode);
436 Die(); // Unreachable.
439 unsigned int internal_sleep(unsigned int seconds) {
443 int res = internal_syscall_ptr(SYSCALL(nanosleep), &ts, &ts);
444 if (res) return ts.tv_sec;
448 uptr internal_execve(const char *filename, char *const argv[],
449 char *const envp[]) {
450 return internal_syscall_ptr(SYSCALL(execve), (uptr)filename, (uptr)argv,
453 #endif // !SANITIZER_SOLARIS
455 // ----------------- sanitizer_common.h
456 bool FileExists(const char *filename) {
458 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
459 if (internal_syscall(SYSCALL(newfstatat), AT_FDCWD, filename, &st, 0))
461 if (internal_stat(filename, &st))
464 // Sanity check: filename is a regular file.
465 return S_ISREG(st.st_mode);
469 #if SANITIZER_FREEBSD
473 #elif SANITIZER_OPENBSD
474 return internal_syscall(SYSCALL(getthrid));
475 #elif SANITIZER_NETBSD
477 #elif SANITIZER_SOLARIS
480 return internal_syscall(SYSCALL(gettid));
484 #if !SANITIZER_SOLARIS
486 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD
491 internal_memset(&tv, 0, sizeof(tv));
492 internal_syscall_ptr(SYSCALL(gettimeofday), &tv, 0);
493 return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
496 uptr internal_clock_gettime(__sanitizer_clockid_t clk_id, void *tp) {
497 return internal_syscall_ptr(SYSCALL(clock_gettime), clk_id, tp);
499 #endif // !SANITIZER_SOLARIS
501 // Like getenv, but reads env directly from /proc (on Linux) or parses the
502 // 'environ' array (on some others) and does not use libc. This function
503 // should be called first inside __asan_init.
504 const char *GetEnv(const char *name) {
505 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD || \
507 if (::environ != 0) {
508 uptr NameLen = internal_strlen(name);
509 for (char **Env = ::environ; *Env != 0; Env++) {
510 if (internal_strncmp(*Env, name, NameLen) == 0 && (*Env)[NameLen] == '=')
511 return (*Env) + NameLen + 1;
514 return 0; // Not found.
515 #elif SANITIZER_LINUX
516 static char *environ;
522 if (!ReadFileToBuffer("/proc/self/environ", &environ, &environ_size, &len))
525 if (!environ || len == 0) return nullptr;
526 uptr namelen = internal_strlen(name);
527 const char *p = environ;
528 while (*p != '\0') { // will happen at the \0\0 that terminates the buffer
529 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
531 (char*)internal_memchr(p, '\0', len - (p - environ));
532 if (!endp) // this entry isn't NUL terminated
534 else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') // Match.
535 return p + namelen + 1; // point after =
538 return nullptr; // Not found.
540 #error "Unsupported platform"
544 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD && !SANITIZER_OPENBSD
546 SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
550 #if !SANITIZER_GO && !SANITIZER_FREEBSD && !SANITIZER_NETBSD && \
552 static void ReadNullSepFileToArray(const char *path, char ***arr,
557 *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
558 if (!ReadFileToBuffer(path, &buff, &buff_size, &buff_len, 1024 * 1024)) {
564 for (count = 1, i = 1; ; i++) {
566 if (buff[i+1] == 0) break;
567 (*arr)[count] = &buff[i+1];
568 CHECK_LE(count, arr_size - 1); // FIXME: make this more flexible.
572 (*arr)[count] = nullptr;
576 #if !SANITIZER_OPENBSD
577 static void GetArgsAndEnv(char ***argv, char ***envp) {
578 #if SANITIZER_FREEBSD
579 // On FreeBSD, retrieving the argument and environment arrays is done via the
580 // kern.ps_strings sysctl, which returns a pointer to a structure containing
581 // this information. See also <sys/exec.h>.
583 size_t sz = sizeof(pss);
584 if (sysctlbyname("kern.ps_strings", &pss, &sz, NULL, 0) == -1) {
585 Printf("sysctl kern.ps_strings failed\n");
588 *argv = pss->ps_argvstr;
589 *envp = pss->ps_envstr;
590 #elif SANITIZER_NETBSD
591 *argv = __ps_strings->ps_argvstr;
592 *envp = __ps_strings->ps_envstr;
593 #else // SANITIZER_FREEBSD
595 if (&__libc_stack_end) {
596 #endif // !SANITIZER_GO
597 uptr* stack_end = (uptr*)__libc_stack_end;
598 int argc = *stack_end;
599 *argv = (char**)(stack_end + 1);
600 *envp = (char**)(stack_end + argc + 2);
603 static const int kMaxArgv = 2000, kMaxEnvp = 2000;
604 ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
605 ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
607 #endif // !SANITIZER_GO
608 #endif // SANITIZER_FREEBSD
613 GetArgsAndEnv(&argv, &envp);
619 const char *pathname = "/proc/self/exe";
622 static const int name[] = {
623 CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME,
629 if (sysctl(name, ARRAY_SIZE(name), path, &len, NULL, 0) != -1)
631 #elif SANITIZER_SOLARIS
632 pathname = getexecname();
633 CHECK_NE(pathname, NULL);
636 GetArgsAndEnv(&argv, &envp);
637 uptr rv = internal_execve(pathname, argv, envp);
639 CHECK_EQ(internal_iserror(rv, &rverrno), true);
640 Printf("execve failed, errno %d\n", rverrno);
645 #if !SANITIZER_SOLARIS
652 BlockingMutex::BlockingMutex() {
653 internal_memset(this, 0, sizeof(*this));
656 void BlockingMutex::Lock() {
658 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
659 if (atomic_exchange(m, MtxLocked, memory_order_acquire) == MtxUnlocked)
661 while (atomic_exchange(m, MtxSleeping, memory_order_acquire) != MtxUnlocked) {
662 #if SANITIZER_FREEBSD
663 _umtx_op(m, UMTX_OP_WAIT_UINT, MtxSleeping, 0, 0);
664 #elif SANITIZER_NETBSD
665 sched_yield(); /* No userspace futex-like synchronization */
667 internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAIT, MtxSleeping, 0, 0, 0);
672 void BlockingMutex::Unlock() {
673 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
674 u32 v = atomic_exchange(m, MtxUnlocked, memory_order_release);
675 CHECK_NE(v, MtxUnlocked);
676 if (v == MtxSleeping) {
677 #if SANITIZER_FREEBSD
678 _umtx_op(m, UMTX_OP_WAKE, 1, 0, 0);
679 #elif SANITIZER_NETBSD
680 /* No userspace futex-like synchronization */
682 internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAKE, 1, 0, 0, 0);
687 void BlockingMutex::CheckLocked() {
688 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
689 CHECK_NE(MtxUnlocked, atomic_load(m, memory_order_relaxed));
691 #endif // !SANITIZER_SOLARIS
693 // ----------------- sanitizer_linux.h
694 // The actual size of this structure is specified by d_reclen.
695 // Note that getdents64 uses a different structure format. We only provide the
696 // 32-bit syscall here.
697 #if SANITIZER_NETBSD || SANITIZER_OPENBSD
698 // struct dirent is different for Linux and us. At this moment, we use only
699 // d_fileno (Linux call this d_ino), d_reclen, and d_name.
700 struct linux_dirent {
701 u64 d_ino; // d_fileno
703 u16 d_namlen; // not used
704 u8 d_type; // not used
705 char d_name[NAME_MAX + 1];
708 struct linux_dirent {
709 #if SANITIZER_X32 || defined(__aarch64__)
716 unsigned short d_reclen;
718 unsigned char d_type;
724 #if !SANITIZER_SOLARIS
726 uptr internal_ptrace(int request, int pid, void *addr, void *data) {
728 // XXX We need additional work for ptrace:
729 // - for request, we use PT_FOO whereas Linux uses PTRACE_FOO
730 // - data is int for us, but void * for Linux
731 // - Linux sometimes uses data in the case where we use addr instead
732 // At this moment, this function is used only within
733 // "#if SANITIZER_LINUX && defined(__x86_64__)" block in
734 // sanitizer_stoptheworld_linux_libcdep.cc.
735 return internal_syscall_ptr(SYSCALL(ptrace), request, pid, (uptr)addr,
738 return internal_syscall(SYSCALL(ptrace), request, pid, (uptr)addr,
743 uptr internal_waitpid(int pid, int *status, int options) {
744 return internal_syscall_ptr(SYSCALL(wait4), pid, (uptr)status, options,
748 uptr internal_getpid() {
749 return internal_syscall(SYSCALL(getpid));
752 uptr internal_getppid() {
753 return internal_syscall(SYSCALL(getppid));
756 uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) {
757 #if SANITIZER_FREEBSD
758 return internal_syscall(SYSCALL(getdirentries), fd, (uptr)dirp, count, NULL);
759 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
760 return internal_syscall(SYSCALL(getdents64), fd, (uptr)dirp, count);
762 return internal_syscall_ptr(SYSCALL(getdents), fd, (uptr)dirp, count);
766 uptr internal_lseek(fd_t fd, OFF_T offset, int whence) {
768 return internal_syscall64(SYSCALL(lseek), fd, 0, offset, whence);
770 return internal_syscall(SYSCALL(lseek), fd, offset, whence);
775 uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
776 return internal_syscall(SYSCALL(prctl), option, arg2, arg3, arg4, arg5);
780 uptr internal_sigaltstack(const void *ss, void *oss) {
781 return internal_syscall_ptr(SYSCALL(sigaltstack), (uptr)ss, (uptr)oss);
784 int internal_fork() {
785 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
786 return internal_syscall(SYSCALL(clone), SIGCHLD, 0);
788 return internal_syscall(SYSCALL(fork));
793 #define SA_RESTORER 0x04000000
794 // Doesn't set sa_restorer if the caller did not set it, so use with caution
796 int internal_sigaction_norestorer(int signum, const void *act, void *oldact) {
797 __sanitizer_kernel_sigaction_t k_act, k_oldact;
798 internal_memset(&k_act, 0, sizeof(__sanitizer_kernel_sigaction_t));
799 internal_memset(&k_oldact, 0, sizeof(__sanitizer_kernel_sigaction_t));
800 const __sanitizer_sigaction *u_act = (const __sanitizer_sigaction *)act;
801 __sanitizer_sigaction *u_oldact = (__sanitizer_sigaction *)oldact;
803 k_act.handler = u_act->handler;
804 k_act.sigaction = u_act->sigaction;
805 internal_memcpy(&k_act.sa_mask, &u_act->sa_mask,
806 sizeof(__sanitizer_kernel_sigset_t));
807 // Without SA_RESTORER kernel ignores the calls (probably returns EINVAL).
808 k_act.sa_flags = u_act->sa_flags | SA_RESTORER;
809 // FIXME: most often sa_restorer is unset, however the kernel requires it
810 // to point to a valid signal restorer that calls the rt_sigreturn syscall.
811 // If sa_restorer passed to the kernel is NULL, the program may crash upon
812 // signal delivery or fail to unwind the stack in the signal handler.
813 // libc implementation of sigaction() passes its own restorer to
814 // rt_sigaction, so we need to do the same (we'll need to reimplement the
815 // restorers; for x86_64 the restorer address can be obtained from
816 // oldact->sa_restorer upon a call to sigaction(xxx, NULL, oldact).
817 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
818 k_act.sa_restorer = u_act->sa_restorer;
822 uptr result = internal_syscall(SYSCALL(rt_sigaction), (uptr)signum,
823 (uptr)(u_act ? &k_act : nullptr),
824 (uptr)(u_oldact ? &k_oldact : nullptr),
825 (uptr)sizeof(__sanitizer_kernel_sigset_t));
827 if ((result == 0) && u_oldact) {
828 u_oldact->handler = k_oldact.handler;
829 u_oldact->sigaction = k_oldact.sigaction;
830 internal_memcpy(&u_oldact->sa_mask, &k_oldact.sa_mask,
831 sizeof(__sanitizer_kernel_sigset_t));
832 u_oldact->sa_flags = k_oldact.sa_flags;
833 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
834 u_oldact->sa_restorer = k_oldact.sa_restorer;
840 // Invokes sigaction via a raw syscall with a restorer, but does not support
841 // all platforms yet.
842 // We disable for Go simply because we have not yet added to buildgo.sh.
843 #if (defined(__x86_64__) || SANITIZER_MIPS64) && !SANITIZER_GO
844 int internal_sigaction_syscall(int signum, const void *act, void *oldact) {
846 return internal_sigaction_norestorer(signum, act, oldact);
847 __sanitizer_sigaction u_adjust;
848 internal_memcpy(&u_adjust, act, sizeof(u_adjust));
849 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
850 if (u_adjust.sa_restorer == nullptr) {
851 u_adjust.sa_restorer = internal_sigreturn;
854 return internal_sigaction_norestorer(signum, (const void *)&u_adjust, oldact);
856 #endif // defined(__x86_64__) && !SANITIZER_GO
857 #endif // SANITIZER_LINUX
859 uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
860 __sanitizer_sigset_t *oldset) {
861 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD
862 return internal_syscall_ptr(SYSCALL(sigprocmask), how, set, oldset);
864 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
865 __sanitizer_kernel_sigset_t *k_oldset = (__sanitizer_kernel_sigset_t *)oldset;
866 return internal_syscall(SYSCALL(rt_sigprocmask), (uptr)how,
867 (uptr)&k_set->sig[0], (uptr)&k_oldset->sig[0],
868 sizeof(__sanitizer_kernel_sigset_t));
872 void internal_sigfillset(__sanitizer_sigset_t *set) {
873 internal_memset(set, 0xff, sizeof(*set));
876 void internal_sigemptyset(__sanitizer_sigset_t *set) {
877 internal_memset(set, 0, sizeof(*set));
881 void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
884 CHECK_LT(signum, sizeof(*set) * 8);
885 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
886 const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
887 const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
888 k_set->sig[idx] &= ~(1 << bit);
891 bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
894 CHECK_LT(signum, sizeof(*set) * 8);
895 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
896 const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
897 const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
898 return k_set->sig[idx] & (1 << bit);
900 #endif // SANITIZER_LINUX
901 #endif // !SANITIZER_SOLARIS
903 // ThreadLister implementation.
904 ThreadLister::ThreadLister(pid_t pid) : pid_(pid), buffer_(4096) {
905 char task_directory_path[80];
906 internal_snprintf(task_directory_path, sizeof(task_directory_path),
907 "/proc/%d/task/", pid);
908 descriptor_ = internal_open(task_directory_path, O_RDONLY | O_DIRECTORY);
909 if (internal_iserror(descriptor_)) {
910 Report("Can't open /proc/%d/task for reading.\n", pid);
914 ThreadLister::Result ThreadLister::ListThreads(
915 InternalMmapVector<tid_t> *threads) {
916 if (internal_iserror(descriptor_))
918 internal_lseek(descriptor_, 0, SEEK_SET);
922 for (bool first_read = true;; first_read = false) {
923 // Resize to max capacity if it was downsized by IsAlive.
924 buffer_.resize(buffer_.capacity());
925 CHECK_GE(buffer_.size(), 4096);
926 uptr read = internal_getdents(
927 descriptor_, (struct linux_dirent *)buffer_.data(), buffer_.size());
930 if (internal_iserror(read)) {
931 Report("Can't read directory entries from /proc/%d/task.\n", pid_);
935 for (uptr begin = (uptr)buffer_.data(), end = begin + read; begin < end;) {
936 struct linux_dirent *entry = (struct linux_dirent *)begin;
937 begin += entry->d_reclen;
938 if (entry->d_ino == 1) {
939 // Inode 1 is for bad blocks and also can be a reason for early return.
940 // Should be emitted if kernel tried to output terminating thread.
941 // See proc_task_readdir implementation in Linux.
944 if (entry->d_ino && *entry->d_name >= '0' && *entry->d_name <= '9')
945 threads->push_back(internal_atoll(entry->d_name));
948 // Now we are going to detect short-read or early EOF. In such cases Linux
949 // can return inconsistent list with missing alive threads.
950 // Code will just remember that the list can be incomplete but it will
951 // continue reads to return as much as possible.
953 // The first one was a short-read by definition.
955 } else if (read > buffer_.size() - 1024) {
956 // Read was close to the buffer size. So double the size and assume the
958 buffer_.resize(buffer_.size() * 2);
960 } else if (!threads->empty() && !IsAlive(threads->back())) {
961 // Maybe Linux early returned from read on terminated thread (!pid_alive)
962 // and failed to restore read position.
963 // See next_tid and proc_task_instantiate in Linux.
969 bool ThreadLister::IsAlive(int tid) {
970 // /proc/%d/task/%d/status uses same call to detect alive threads as
971 // proc_task_readdir. See task_state implementation in Linux.
973 internal_snprintf(path, sizeof(path), "/proc/%d/task/%d/status", pid_, tid);
974 if (!ReadFileToVector(path, &buffer_) || buffer_.empty())
976 buffer_.push_back(0);
977 static const char kPrefix[] = "\nPPid:";
978 const char *field = internal_strstr(buffer_.data(), kPrefix);
981 field += internal_strlen(kPrefix);
982 return (int)internal_atoll(field) != 0;
985 ThreadLister::~ThreadLister() {
986 if (!internal_iserror(descriptor_))
987 internal_close(descriptor_);
990 #if SANITIZER_WORDSIZE == 32
991 // Take care of unusable kernel area in top gigabyte.
992 static uptr GetKernelAreaSize() {
993 #if SANITIZER_LINUX && !SANITIZER_X32
994 const uptr gbyte = 1UL << 30;
996 // Firstly check if there are writable segments
997 // mapped to top gigabyte (e.g. stack).
998 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
999 MemoryMappedSegment segment;
1000 while (proc_maps.Next(&segment)) {
1001 if ((segment.end >= 3 * gbyte) && segment.IsWritable()) return 0;
1004 #if !SANITIZER_ANDROID
1005 // Even if nothing is mapped, top Gb may still be accessible
1006 // if we are running on 64-bit kernel.
1007 // Uname may report misleading results if personality type
1008 // is modified (e.g. under schroot) so check this as well.
1009 struct utsname uname_info;
1010 int pers = personality(0xffffffffUL);
1011 if (!(pers & PER_MASK)
1012 && uname(&uname_info) == 0
1013 && internal_strstr(uname_info.machine, "64"))
1015 #endif // SANITIZER_ANDROID
1017 // Top gigabyte is reserved for kernel.
1021 #endif // SANITIZER_LINUX && !SANITIZER_X32
1023 #endif // SANITIZER_WORDSIZE == 32
1025 uptr GetMaxVirtualAddress() {
1026 #if (SANITIZER_NETBSD || SANITIZER_OPENBSD) && defined(__x86_64__)
1027 return 0x7f7ffffff000ULL; // (0x00007f8000000000 - PAGE_SIZE)
1028 #elif SANITIZER_WORDSIZE == 64
1029 # if defined(__powerpc64__) || defined(__aarch64__)
1030 // On PowerPC64 we have two different address space layouts: 44- and 46-bit.
1031 // We somehow need to figure out which one we are using now and choose
1032 // one of 0x00000fffffffffffUL and 0x00003fffffffffffUL.
1033 // Note that with 'ulimit -s unlimited' the stack is moved away from the top
1034 // of the address space, so simply checking the stack address is not enough.
1035 // This should (does) work for both PowerPC64 Endian modes.
1036 // Similarly, aarch64 has multiple address space layouts: 39, 42 and 47-bit.
1037 return (1ULL << (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1)) - 1;
1038 # elif defined(__mips64)
1039 return (1ULL << 40) - 1; // 0x000000ffffffffffUL;
1040 # elif defined(__s390x__)
1041 return (1ULL << 53) - 1; // 0x001fffffffffffffUL;
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 uptr GetPageSize() {
1065 // Android post-M sysconf(_SC_PAGESIZE) crashes if called from .preinit_array.
1066 #if SANITIZER_ANDROID
1068 #elif SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__))
1069 return EXEC_PAGESIZE;
1070 #elif SANITIZER_USE_GETAUXVAL
1071 return getauxval(AT_PAGESZ);
1073 return sysconf(_SC_PAGESIZE); // EXEC_PAGESIZE may not be trustworthy.
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 size_t Size = buf_len;
1092 bool IsErr = (sysctl(Mib, ARRAY_SIZE(Mib), buf, &Size, NULL, 0) != 0);
1093 int readlink_error = IsErr ? errno : 0;
1094 uptr module_name_len = Size;
1096 const char *default_module_name = "/proc/self/exe";
1097 uptr module_name_len = internal_readlink(
1098 default_module_name, buf, buf_len);
1100 bool IsErr = internal_iserror(module_name_len, &readlink_error);
1101 #endif // SANITIZER_SOLARIS
1103 // We can't read binary name for some reason, assume it's unknown.
1104 Report("WARNING: reading executable name failed with errno %d, "
1105 "some stack frames may not be symbolized\n", readlink_error);
1106 module_name_len = internal_snprintf(buf, buf_len, "%s",
1107 default_module_name);
1108 CHECK_LT(module_name_len, buf_len);
1110 return module_name_len;
1113 #endif // !SANITIZER_OPENBSD
1115 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len) {
1120 if (ReadFileToBuffer("/proc/self/cmdline", &tmpbuf, &tmpsize, &tmplen,
1122 internal_strncpy(buf, tmpbuf, buf_len);
1123 UnmapOrDie(tmpbuf, tmpsize);
1124 return internal_strlen(buf);
1127 return ReadBinaryName(buf, buf_len);
1130 // Match full names of the form /path/to/base_name{-,.}*
1131 bool LibraryNameIs(const char *full_name, const char *base_name) {
1132 const char *name = full_name;
1134 while (*name != '\0') name++;
1135 while (name > full_name && *name != '/') name--;
1136 if (*name == '/') name++;
1137 uptr base_name_length = internal_strlen(base_name);
1138 if (internal_strncmp(name, base_name, base_name_length)) return false;
1139 return (name[base_name_length] == '-' || name[base_name_length] == '.');
1142 #if !SANITIZER_ANDROID
1143 // Call cb for each region mapped by map.
1144 void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr)) {
1145 CHECK_NE(map, nullptr);
1146 #if !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
1147 typedef ElfW(Phdr) Elf_Phdr;
1148 typedef ElfW(Ehdr) Elf_Ehdr;
1149 #endif // !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
1150 char *base = (char *)map->l_addr;
1151 Elf_Ehdr *ehdr = (Elf_Ehdr *)base;
1152 char *phdrs = base + ehdr->e_phoff;
1153 char *phdrs_end = phdrs + ehdr->e_phnum * ehdr->e_phentsize;
1155 // Find the segment with the minimum base so we can "relocate" the p_vaddr
1156 // fields. Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
1157 // objects have a non-zero base.
1158 uptr preferred_base = (uptr)-1;
1159 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
1160 Elf_Phdr *phdr = (Elf_Phdr *)iter;
1161 if (phdr->p_type == PT_LOAD && preferred_base > (uptr)phdr->p_vaddr)
1162 preferred_base = (uptr)phdr->p_vaddr;
1165 // Compute the delta from the real base to get a relocation delta.
1166 sptr delta = (uptr)base - preferred_base;
1167 // Now we can figure out what the loader really mapped.
1168 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
1169 Elf_Phdr *phdr = (Elf_Phdr *)iter;
1170 if (phdr->p_type == PT_LOAD) {
1171 uptr seg_start = phdr->p_vaddr + delta;
1172 uptr seg_end = seg_start + phdr->p_memsz;
1173 // None of these values are aligned. We consider the ragged edges of the
1174 // load command as defined, since they are mapped from the file.
1175 seg_start = RoundDownTo(seg_start, GetPageSizeCached());
1176 seg_end = RoundUpTo(seg_end, GetPageSizeCached());
1177 cb((void *)seg_start, seg_end - seg_start);
1183 #if defined(__x86_64__) && SANITIZER_LINUX
1184 // We cannot use glibc's clone wrapper, because it messes with the child
1185 // task's TLS. It writes the PID and TID of the child task to its thread
1186 // descriptor, but in our case the child task shares the thread descriptor with
1187 // the parent (because we don't know how to allocate a new thread
1188 // descriptor to keep glibc happy). So the stock version of clone(), when
1189 // used with CLONE_VM, would end up corrupting the parent's thread descriptor.
1190 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1191 int *parent_tidptr, void *newtls, int *child_tidptr) {
1193 if (!fn || !child_stack)
1195 CHECK_EQ(0, (uptr)child_stack % 16);
1196 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1197 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1198 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1199 register void *r8 __asm__("r8") = newtls;
1200 register int *r10 __asm__("r10") = child_tidptr;
1201 __asm__ __volatile__(
1202 /* %rax = syscall(%rax = SYSCALL(clone),
1204 * %rsi = child_stack,
1205 * %rdx = parent_tidptr,
1207 * %r10 = child_tidptr)
1214 "testq %%rax,%%rax\n"
1217 /* In the child. Terminate unwind chain. */
1218 // XXX: We should also terminate the CFI unwind chain
1219 // here. Unfortunately clang 3.2 doesn't support the
1220 // necessary CFI directives, so we skip that part.
1221 "xorq %%rbp,%%rbp\n"
1223 /* Call "fn(arg)". */
1228 /* Call _exit(%rax). */
1229 "movq %%rax,%%rdi\n"
1233 /* Return to parent. */
1236 : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
1242 : "rsp", "memory", "r11", "rcx");
1245 #elif defined(__mips__)
1246 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1247 int *parent_tidptr, void *newtls, int *child_tidptr) {
1249 if (!fn || !child_stack)
1251 CHECK_EQ(0, (uptr)child_stack % 16);
1252 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1253 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1254 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1255 register void *a3 __asm__("$7") = newtls;
1256 register int *a4 __asm__("$8") = child_tidptr;
1257 // We don't have proper CFI directives here because it requires alot of code
1258 // for very marginal benefits.
1259 __asm__ __volatile__(
1260 /* $v0 = syscall($v0 = __NR_clone,
1262 * $a1 = child_stack,
1263 * $a2 = parent_tidptr,
1265 * $a4 = child_tidptr)
1272 /* Store the fifth argument on stack
1273 * if we are using 32-bit abi.
1275 #if SANITIZER_WORDSIZE == 32
1288 /* Call "fn(arg)". */
1289 #if SANITIZER_WORDSIZE == 32
1290 #ifdef __BIG_ENDIAN__
1303 /* Call _exit($v0). */
1308 /* Return to parent. */
1318 : "memory", "$29" );
1321 #elif defined(__aarch64__)
1322 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1323 int *parent_tidptr, void *newtls, int *child_tidptr) {
1325 if (!fn || !child_stack)
1327 CHECK_EQ(0, (uptr)child_stack % 16);
1328 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1329 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1330 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1332 register int (*__fn)(void *) __asm__("x0") = fn;
1333 register void *__stack __asm__("x1") = child_stack;
1334 register int __flags __asm__("x2") = flags;
1335 register void *__arg __asm__("x3") = arg;
1336 register int *__ptid __asm__("x4") = parent_tidptr;
1337 register void *__tls __asm__("x5") = newtls;
1338 register int *__ctid __asm__("x6") = child_tidptr;
1340 __asm__ __volatile__(
1341 "mov x0,x2\n" /* flags */
1342 "mov x2,x4\n" /* ptid */
1343 "mov x3,x5\n" /* tls */
1344 "mov x4,x6\n" /* ctid */
1345 "mov x8,%9\n" /* clone */
1355 /* In the child, now. Call "fn(arg)". */
1356 "ldp x1, x0, [sp], #16\n"
1359 /* Call _exit(%r0). */
1366 "r"(__fn), "r"(__stack), "r"(__flags), "r"(__arg),
1367 "r"(__ptid), "r"(__tls), "r"(__ctid),
1368 "i"(__NR_clone), "i"(__NR_exit)
1372 #elif defined(__powerpc64__)
1373 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1374 int *parent_tidptr, void *newtls, int *child_tidptr) {
1376 // Stack frame structure.
1377 #if SANITIZER_PPC64V1
1378 // Back chain == 0 (SP + 112)
1379 // Frame (112 bytes):
1380 // Parameter save area (SP + 48), 8 doublewords
1381 // TOC save area (SP + 40)
1382 // Link editor doubleword (SP + 32)
1383 // Compiler doubleword (SP + 24)
1384 // LR save area (SP + 16)
1385 // CR save area (SP + 8)
1386 // Back chain (SP + 0)
1387 # define FRAME_SIZE 112
1388 # define FRAME_TOC_SAVE_OFFSET 40
1389 #elif SANITIZER_PPC64V2
1390 // Back chain == 0 (SP + 32)
1391 // Frame (32 bytes):
1392 // TOC save area (SP + 24)
1393 // LR save area (SP + 16)
1394 // CR save area (SP + 8)
1395 // Back chain (SP + 0)
1396 # define FRAME_SIZE 32
1397 # define FRAME_TOC_SAVE_OFFSET 24
1399 # error "Unsupported PPC64 ABI"
1401 if (!fn || !child_stack)
1403 CHECK_EQ(0, (uptr)child_stack % 16);
1405 register int (*__fn)(void *) __asm__("r3") = fn;
1406 register void *__cstack __asm__("r4") = child_stack;
1407 register int __flags __asm__("r5") = flags;
1408 register void *__arg __asm__("r6") = arg;
1409 register int *__ptidptr __asm__("r7") = parent_tidptr;
1410 register void *__newtls __asm__("r8") = newtls;
1411 register int *__ctidptr __asm__("r9") = child_tidptr;
1413 __asm__ __volatile__(
1414 /* fn and arg are saved across the syscall */
1424 r7 == child_tidptr */
1432 /* Test if syscall was successful */
1433 "cmpdi cr1, 3, 0\n\t"
1434 "crandc cr1*4+eq, cr1*4+eq, cr0*4+so\n\t"
1437 /* Set up stack frame */
1439 "stdu 29, -8(1)\n\t"
1440 "stdu 1, -%12(1)\n\t"
1441 /* Do the function call */
1443 #if SANITIZER_PPC64V1
1447 #elif SANITIZER_PPC64V2
1451 # error "Unsupported PPC64 ABI"
1457 /* Call _exit(r3) */
1461 /* Return to parent */
1477 "i" (FRAME_TOC_SAVE_OFFSET)
1478 : "cr0", "cr1", "memory", "ctr", "r0", "r27", "r28", "r29");
1481 #elif defined(__i386__) && SANITIZER_LINUX
1482 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1483 int *parent_tidptr, void *newtls, int *child_tidptr) {
1485 if (!fn || !child_stack)
1487 CHECK_EQ(0, (uptr)child_stack % 16);
1488 child_stack = (char *)child_stack - 7 * sizeof(unsigned int);
1489 ((unsigned int *)child_stack)[0] = (uptr)flags;
1490 ((unsigned int *)child_stack)[1] = (uptr)0;
1491 ((unsigned int *)child_stack)[2] = (uptr)fn;
1492 ((unsigned int *)child_stack)[3] = (uptr)arg;
1493 __asm__ __volatile__(
1494 /* %eax = syscall(%eax = SYSCALL(clone),
1496 * %ecx = child_stack,
1497 * %edx = parent_tidptr,
1499 * %edi = child_tidptr)
1503 "movl (%%ecx), %%ebx\n"
1504 /* Do the system call */
1508 /* Remember the flag value. */
1509 "movl %%ebx, (%%ecx)\n"
1519 "test %%eax,%%eax\n"
1522 /* terminate the stack frame */
1523 "xorl %%ebp,%%ebp\n"
1530 "addl $_GLOBAL_OFFSET_TABLE_+[.-here], %%ebx\n"
1533 "movl %%eax, %%ebx\n"
1538 : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
1546 #elif defined(__arm__) && SANITIZER_LINUX
1547 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1548 int *parent_tidptr, void *newtls, int *child_tidptr) {
1550 if (!fn || !child_stack)
1552 child_stack = (char *)child_stack - 2 * sizeof(unsigned int);
1553 ((unsigned int *)child_stack)[0] = (uptr)fn;
1554 ((unsigned int *)child_stack)[1] = (uptr)arg;
1555 register int r0 __asm__("r0") = flags;
1556 register void *r1 __asm__("r1") = child_stack;
1557 register int *r2 __asm__("r2") = parent_tidptr;
1558 register void *r3 __asm__("r3") = newtls;
1559 register int *r4 __asm__("r4") = child_tidptr;
1560 register int r7 __asm__("r7") = __NR_clone;
1562 #if __ARM_ARCH > 4 || defined (__ARM_ARCH_4T__)
1563 # define ARCH_HAS_BX
1566 # define ARCH_HAS_BLX
1570 # ifdef ARCH_HAS_BLX
1571 # define BLX(R) "blx " #R "\n"
1573 # define BLX(R) "mov lr, pc; bx " #R "\n"
1576 # define BLX(R) "mov lr, pc; mov pc," #R "\n"
1579 __asm__ __volatile__(
1580 /* %r0 = syscall(%r7 = SYSCALL(clone),
1582 * %r1 = child_stack,
1583 * %r2 = parent_tidptr,
1585 * %r4 = child_tidptr)
1588 /* Do the system call */
1597 /* In the child, now. Call "fn(arg)". */
1598 "ldr r0, [sp, #4]\n"
1599 "ldr ip, [sp], #8\n"
1601 /* Call _exit(%r0). */
1607 : "r"(r0), "r"(r1), "r"(r2), "r"(r3), "r"(r4), "r"(r7),
1612 #endif // defined(__x86_64__) && SANITIZER_LINUX
1614 #if SANITIZER_ANDROID
1615 #if __ANDROID_API__ < 21
1616 extern "C" __attribute__((weak)) int dl_iterate_phdr(
1617 int (*)(struct dl_phdr_info *, size_t, void *), void *);
1620 static int dl_iterate_phdr_test_cb(struct dl_phdr_info *info, size_t size,
1622 // Any name starting with "lib" indicates a bug in L where library base names
1623 // are returned instead of paths.
1624 if (info->dlpi_name && info->dlpi_name[0] == 'l' &&
1625 info->dlpi_name[1] == 'i' && info->dlpi_name[2] == 'b') {
1626 *(bool *)data = true;
1632 static atomic_uint32_t android_api_level;
1634 static AndroidApiLevel AndroidDetectApiLevel() {
1635 if (!&dl_iterate_phdr)
1636 return ANDROID_KITKAT; // K or lower
1637 bool base_name_seen = false;
1638 dl_iterate_phdr(dl_iterate_phdr_test_cb, &base_name_seen);
1640 return ANDROID_LOLLIPOP_MR1; // L MR1
1641 return ANDROID_POST_LOLLIPOP; // post-L
1642 // Plain L (API level 21) is completely broken wrt ASan and not very
1643 // interesting to detect.
1646 AndroidApiLevel AndroidGetApiLevel() {
1647 AndroidApiLevel level =
1648 (AndroidApiLevel)atomic_load(&android_api_level, memory_order_relaxed);
1649 if (level) return level;
1650 level = AndroidDetectApiLevel();
1651 atomic_store(&android_api_level, level, memory_order_relaxed);
1657 static HandleSignalMode GetHandleSignalModeImpl(int signum) {
1660 return common_flags()->handle_abort;
1662 return common_flags()->handle_sigill;
1664 return common_flags()->handle_sigtrap;
1666 return common_flags()->handle_sigfpe;
1668 return common_flags()->handle_segv;
1670 return common_flags()->handle_sigbus;
1672 return kHandleSignalNo;
1675 HandleSignalMode GetHandleSignalMode(int signum) {
1676 HandleSignalMode result = GetHandleSignalModeImpl(signum);
1677 if (result == kHandleSignalYes && !common_flags()->allow_user_segv_handler)
1678 return kHandleSignalExclusive;
1683 void *internal_start_thread(void(*func)(void *arg), void *arg) {
1684 // Start the thread with signals blocked, otherwise it can steal user signals.
1685 __sanitizer_sigset_t set, old;
1686 internal_sigfillset(&set);
1687 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1688 // Glibc uses SIGSETXID signal during setuid call. If this signal is blocked
1689 // on any thread, setuid call hangs (see test/tsan/setuid.c).
1690 internal_sigdelset(&set, 33);
1692 internal_sigprocmask(SIG_SETMASK, &set, &old);
1694 real_pthread_create(&th, nullptr, (void*(*)(void *arg))func, arg);
1695 internal_sigprocmask(SIG_SETMASK, &old, nullptr);
1699 void internal_join_thread(void *th) {
1700 real_pthread_join(th, nullptr);
1703 void *internal_start_thread(void (*func)(void *), void *arg) { return 0; }
1705 void internal_join_thread(void *th) {}
1708 #if defined(__aarch64__)
1709 // Android headers in the older NDK releases miss this definition.
1710 struct __sanitizer_esr_context {
1711 struct _aarch64_ctx head;
1715 static bool Aarch64GetESR(ucontext_t *ucontext, u64 *esr) {
1716 static const u32 kEsrMagic = 0x45535201;
1717 u8 *aux = ucontext->uc_mcontext.__reserved;
1719 _aarch64_ctx *ctx = (_aarch64_ctx *)aux;
1720 if (ctx->size == 0) break;
1721 if (ctx->magic == kEsrMagic) {
1722 *esr = ((__sanitizer_esr_context *)ctx)->esr;
1731 #if SANITIZER_OPENBSD
1732 using Context = sigcontext;
1734 using Context = ucontext_t;
1737 SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
1738 Context *ucontext = (Context *)context;
1739 #if defined(__x86_64__) || defined(__i386__)
1740 static const uptr PF_WRITE = 1U << 1;
1741 #if SANITIZER_FREEBSD
1742 uptr err = ucontext->uc_mcontext.mc_err;
1743 #elif SANITIZER_NETBSD
1744 uptr err = ucontext->uc_mcontext.__gregs[_REG_ERR];
1745 #elif SANITIZER_OPENBSD
1746 uptr err = ucontext->sc_err;
1747 #elif SANITIZER_SOLARIS && defined(__i386__)
1749 uptr err = ucontext->uc_mcontext.gregs[Err];
1751 uptr err = ucontext->uc_mcontext.gregs[REG_ERR];
1752 #endif // SANITIZER_FREEBSD
1753 return err & PF_WRITE ? WRITE : READ;
1754 #elif defined(__mips__)
1755 uint32_t *exception_source;
1756 uint32_t faulty_instruction;
1759 exception_source = (uint32_t *)ucontext->uc_mcontext.pc;
1760 faulty_instruction = (uint32_t)(*exception_source);
1762 op_code = (faulty_instruction >> 26) & 0x3f;
1764 // FIXME: Add support for FPU, microMIPS, DSP, MSA memory instructions.
1770 #if __mips_isa_rev < 6
1776 return SignalContext::WRITE;
1785 #if __mips_isa_rev < 6
1791 return SignalContext::READ;
1792 #if __mips_isa_rev == 6
1794 op_code = (faulty_instruction >> 19) & 0x3;
1798 return SignalContext::READ;
1802 return SignalContext::UNKNOWN;
1803 #elif defined(__arm__)
1804 static const uptr FSR_WRITE = 1U << 11;
1805 uptr fsr = ucontext->uc_mcontext.error_code;
1806 return fsr & FSR_WRITE ? WRITE : READ;
1807 #elif defined(__aarch64__)
1808 static const u64 ESR_ELx_WNR = 1U << 6;
1810 if (!Aarch64GetESR(ucontext, &esr)) return UNKNOWN;
1811 return esr & ESR_ELx_WNR ? WRITE : READ;
1812 #elif SANITIZER_SOLARIS && defined(__sparc__)
1813 // Decode the instruction to determine the access type.
1814 // From OpenSolaris $SRC/uts/sun4/os/trap.c (get_accesstype).
1815 uptr pc = ucontext->uc_mcontext.gregs[REG_PC];
1816 u32 instr = *(u32 *)pc;
1817 return (instr >> 21) & 1 ? WRITE: READ;
1820 return UNKNOWN; // FIXME: Implement.
1824 void SignalContext::DumpAllRegisters(void *context) {
1825 // FIXME: Implement this.
1828 static void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
1829 #if SANITIZER_NETBSD
1830 // This covers all NetBSD architectures
1831 ucontext_t *ucontext = (ucontext_t *)context;
1832 *pc = _UC_MACHINE_PC(ucontext);
1833 *bp = _UC_MACHINE_FP(ucontext);
1834 *sp = _UC_MACHINE_SP(ucontext);
1835 #elif defined(__arm__)
1836 ucontext_t *ucontext = (ucontext_t*)context;
1837 *pc = ucontext->uc_mcontext.arm_pc;
1838 *bp = ucontext->uc_mcontext.arm_fp;
1839 *sp = ucontext->uc_mcontext.arm_sp;
1840 #elif defined(__aarch64__)
1841 ucontext_t *ucontext = (ucontext_t*)context;
1842 *pc = ucontext->uc_mcontext.pc;
1843 *bp = ucontext->uc_mcontext.regs[29];
1844 *sp = ucontext->uc_mcontext.sp;
1845 #elif defined(__hppa__)
1846 ucontext_t *ucontext = (ucontext_t*)context;
1847 *pc = ucontext->uc_mcontext.sc_iaoq[0];
1848 /* GCC uses %r3 whenever a frame pointer is needed. */
1849 *bp = ucontext->uc_mcontext.sc_gr[3];
1850 *sp = ucontext->uc_mcontext.sc_gr[30];
1851 #elif defined(__x86_64__)
1852 # if SANITIZER_FREEBSD
1853 ucontext_t *ucontext = (ucontext_t*)context;
1854 *pc = ucontext->uc_mcontext.mc_rip;
1855 *bp = ucontext->uc_mcontext.mc_rbp;
1856 *sp = ucontext->uc_mcontext.mc_rsp;
1857 #elif SANITIZER_OPENBSD
1858 sigcontext *ucontext = (sigcontext *)context;
1859 *pc = ucontext->sc_rip;
1860 *bp = ucontext->sc_rbp;
1861 *sp = ucontext->sc_rsp;
1863 ucontext_t *ucontext = (ucontext_t*)context;
1864 *pc = ucontext->uc_mcontext.gregs[REG_RIP];
1865 *bp = ucontext->uc_mcontext.gregs[REG_RBP];
1866 *sp = ucontext->uc_mcontext.gregs[REG_RSP];
1868 #elif defined(__i386__)
1869 # if SANITIZER_FREEBSD
1870 ucontext_t *ucontext = (ucontext_t*)context;
1871 *pc = ucontext->uc_mcontext.mc_eip;
1872 *bp = ucontext->uc_mcontext.mc_ebp;
1873 *sp = ucontext->uc_mcontext.mc_esp;
1874 #elif SANITIZER_OPENBSD
1875 sigcontext *ucontext = (sigcontext *)context;
1876 *pc = ucontext->sc_eip;
1877 *bp = ucontext->sc_ebp;
1878 *sp = ucontext->sc_esp;
1880 ucontext_t *ucontext = (ucontext_t*)context;
1881 # if SANITIZER_SOLARIS
1882 /* Use the numeric values: the symbolic ones are undefined by llvm
1883 include/llvm/Support/Solaris.h. */
1885 # define REG_EIP 14 // REG_PC
1888 # define REG_EBP 6 // REG_FP
1891 # define REG_ESP 17 // REG_SP
1894 *pc = ucontext->uc_mcontext.gregs[REG_EIP];
1895 *bp = ucontext->uc_mcontext.gregs[REG_EBP];
1896 *sp = ucontext->uc_mcontext.gregs[REG_ESP];
1898 #elif defined(__powerpc__) || defined(__powerpc64__)
1899 ucontext_t *ucontext = (ucontext_t*)context;
1900 *pc = ucontext->uc_mcontext.regs->nip;
1901 *sp = ucontext->uc_mcontext.regs->gpr[PT_R1];
1902 // The powerpc{,64}-linux ABIs do not specify r31 as the frame
1903 // pointer, but GCC always uses r31 when we need a frame pointer.
1904 *bp = ucontext->uc_mcontext.regs->gpr[PT_R31];
1905 #elif defined(__sparc__)
1906 ucontext_t *ucontext = (ucontext_t*)context;
1908 # if defined (__sparcv9)
1910 # define MC_PC REG_PC
1913 # define MC_O6 REG_O6
1915 # ifdef SANITIZER_SOLARIS
1916 # define mc_gregs gregs
1918 *pc = ucontext->uc_mcontext.mc_gregs[MC_PC];
1919 *sp = ucontext->uc_mcontext.mc_gregs[MC_O6];
1920 stk_ptr = (uptr *) (*sp + 2047);
1923 *pc = ucontext->uc_mcontext.gregs[REG_PC];
1924 *sp = ucontext->uc_mcontext.gregs[REG_O6];
1925 stk_ptr = (uptr *) *sp;
1928 #elif defined(__mips__)
1929 ucontext_t *ucontext = (ucontext_t*)context;
1930 *pc = ucontext->uc_mcontext.pc;
1931 *bp = ucontext->uc_mcontext.gregs[30];
1932 *sp = ucontext->uc_mcontext.gregs[29];
1933 #elif defined(__s390__)
1934 ucontext_t *ucontext = (ucontext_t*)context;
1935 # if defined(__s390x__)
1936 *pc = ucontext->uc_mcontext.psw.addr;
1938 *pc = ucontext->uc_mcontext.psw.addr & 0x7fffffff;
1940 *bp = ucontext->uc_mcontext.gregs[11];
1941 *sp = ucontext->uc_mcontext.gregs[15];
1943 # error "Unsupported arch"
1947 void SignalContext::InitPcSpBp() { GetPcSpBp(context, &pc, &sp, &bp); }
1949 void MaybeReexec() {
1950 // No need to re-exec on Linux.
1954 #if SANITIZER_NETBSD
1957 size_t len = sizeof(paxflags);
1960 mib[1] = internal_getpid();
1961 mib[2] = PROC_PID_PAXFLAGS;
1963 if (UNLIKELY(sysctl(mib, 3, &paxflags, &len, NULL, 0) == -1)) {
1964 Printf("sysctl failed\n");
1968 if (UNLIKELY(paxflags & CTL_PROC_PAXFLAGS_ASLR)) {
1969 Printf("This sanitizer is not compatible with enabled ASLR\n");
1977 void PrintModuleMap() { }
1979 void CheckNoDeepBind(const char *filename, int flag) {
1980 #ifdef RTLD_DEEPBIND
1981 if (flag & RTLD_DEEPBIND) {
1983 "You are trying to dlopen a %s shared library with RTLD_DEEPBIND flag"
1984 " which is incompatibe with sanitizer runtime "
1985 "(see https://github.com/google/sanitizers/issues/611 for details"
1986 "). If you want to run %s library under sanitizers please remove "
1987 "RTLD_DEEPBIND from dlopen flags.\n",
1988 filename, filename);
1994 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
1995 uptr *largest_gap_found,
1996 uptr *max_occupied_addr) {
1997 UNREACHABLE("FindAvailableMemoryRange is not available");
2001 bool GetRandom(void *buffer, uptr length, bool blocking) {
2002 if (!buffer || !length || length > 256)
2004 #if SANITIZER_USE_GETENTROPY
2005 uptr rnd = getentropy(buffer, length);
2007 if (internal_iserror(rnd, &rverrno) && rverrno == EFAULT)
2011 #endif // SANITIZER_USE_GETENTROPY
2013 #if SANITIZER_USE_GETRANDOM
2014 static atomic_uint8_t skip_getrandom_syscall;
2015 if (!atomic_load_relaxed(&skip_getrandom_syscall)) {
2016 // Up to 256 bytes, getrandom will not be interrupted.
2017 uptr res = internal_syscall(SYSCALL(getrandom), buffer, length,
2018 blocking ? 0 : GRND_NONBLOCK);
2020 if (internal_iserror(res, &rverrno) && rverrno == ENOSYS)
2021 atomic_store_relaxed(&skip_getrandom_syscall, 1);
2022 else if (res == length)
2025 #endif // SANITIZER_USE_GETRANDOM
2026 // Up to 256 bytes, a read off /dev/urandom will not be interrupted.
2027 // blocking is moot here, O_NONBLOCK has no effect when opening /dev/urandom.
2028 uptr fd = internal_open("/dev/urandom", O_RDONLY);
2029 if (internal_iserror(fd))
2031 uptr res = internal_read(fd, buffer, length);
2032 if (internal_iserror(res))
2038 } // namespace __sanitizer