1 //===-- sanitizer_linux.cc ------------------------------------------------===//
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
6 //===----------------------------------------------------------------------===//
8 // This file is shared between AddressSanitizer and ThreadSanitizer
9 // run-time libraries and implements linux-specific functions from
11 //===----------------------------------------------------------------------===//
13 #include "sanitizer_platform.h"
15 #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD
17 #include "sanitizer_common.h"
18 #include "sanitizer_flags.h"
19 #include "sanitizer_internal_defs.h"
20 #include "sanitizer_libc.h"
21 #include "sanitizer_linux.h"
22 #include "sanitizer_mutex.h"
23 #include "sanitizer_placement_new.h"
24 #include "sanitizer_procmaps.h"
25 #include "sanitizer_stacktrace.h"
26 #include "sanitizer_symbolizer.h"
29 #include <asm/param.h>
36 // For mips64, syscall(__NR_stat) fills the buffer in the 'struct kernel_stat'
37 // format. Struct kernel_stat is defined as 'struct stat' in asm/stat.h. To
38 // access stat from asm/stat.h, without conflicting with definition in
39 // sys/stat.h, we use this trick.
41 #include <asm/unistd.h>
42 #include <sys/types.h>
43 #define stat kernel_stat
55 #include <sys/ptrace.h>
56 #include <sys/resource.h>
58 #include <sys/syscall.h>
60 #include <sys/types.h>
65 #include <sys/utsname.h>
68 #if SANITIZER_LINUX && !SANITIZER_ANDROID
69 #include <sys/personality.h>
74 #include <sys/sysctl.h>
75 #include <machine/atomic.h>
77 // <sys/umtx.h> must be included after <errno.h> and <sys/types.h> on
78 // FreeBSD 9.2 and 10.0.
81 extern char **environ
; // provided by crt1
82 #endif // SANITIZER_FREEBSD
85 #include <limits.h> // For NAME_MAX
86 #include <sys/sysctl.h>
87 extern char **environ
; // provided by crt1
88 #endif // SANITIZER_NETBSD
90 #if !SANITIZER_ANDROID
91 #include <sys/signal.h>
94 #ifndef __GLIBC_PREREQ
95 #define __GLIBC_PREREQ(x, y) 0
98 #if SANITIZER_LINUX && __GLIBC_PREREQ(2, 16)
99 # define SANITIZER_USE_GETAUXVAL 1
101 # define SANITIZER_USE_GETAUXVAL 0
104 #if SANITIZER_USE_GETAUXVAL
105 #include <sys/auxv.h>
110 struct kernel_timeval
{
115 // <linux/futex.h> is broken on some linux distributions.
116 const int FUTEX_WAIT
= 0;
117 const int FUTEX_WAKE
= 1;
118 #endif // SANITIZER_LINUX
120 // Are we using 32-bit or 64-bit Linux syscalls?
121 // x32 (which defines __x86_64__) has SANITIZER_WORDSIZE == 32
122 // but it still needs to use 64-bit syscalls.
123 #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__powerpc64__) || \
124 SANITIZER_WORDSIZE == 64)
125 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 1
127 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 0
130 #if defined(__x86_64__) || SANITIZER_MIPS64
132 extern void internal_sigreturn();
136 #if SANITIZER_LINUX && defined(__NR_getrandom)
137 # if !defined(GRND_NONBLOCK)
138 # define GRND_NONBLOCK 1
140 # define SANITIZER_USE_GETRANDOM 1
142 # define SANITIZER_USE_GETRANDOM 0
143 #endif // SANITIZER_LINUX && defined(__NR_getrandom)
145 namespace __sanitizer
{
147 #if SANITIZER_LINUX && defined(__x86_64__)
148 #include "sanitizer_syscall_linux_x86_64.inc"
149 #elif SANITIZER_LINUX && defined(__aarch64__)
150 #include "sanitizer_syscall_linux_aarch64.inc"
152 #include "sanitizer_syscall_generic.inc"
155 // --------------- sanitizer_libc.h
157 uptr
internal_mmap(void *addr
, uptr length
, int prot
, int flags
, int fd
,
160 return internal_syscall_ptr(SYSCALL(mmap
), addr
, length
, prot
, flags
, fd
,
162 #elif SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
163 return internal_syscall(SYSCALL(mmap
), (uptr
)addr
, length
, prot
, flags
, fd
,
166 // mmap2 specifies file offset in 4096-byte units.
167 CHECK(IsAligned(offset
, 4096));
168 return internal_syscall(SYSCALL(mmap2
), addr
, length
, prot
, flags
, fd
,
172 #endif // !SANITIZER_S390
174 uptr
internal_munmap(void *addr
, uptr length
) {
175 return internal_syscall(SYSCALL(munmap
), (uptr
)addr
, length
);
178 int internal_mprotect(void *addr
, uptr length
, int prot
) {
179 return internal_syscall(SYSCALL(mprotect
), (uptr
)addr
, length
, prot
);
182 uptr
internal_close(fd_t fd
) {
183 return internal_syscall(SYSCALL(close
), fd
);
186 uptr
internal_open(const char *filename
, int flags
) {
187 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
188 return internal_syscall(SYSCALL(openat
), AT_FDCWD
, (uptr
)filename
, flags
);
190 return internal_syscall(SYSCALL(open
), (uptr
)filename
, flags
);
194 uptr
internal_open(const char *filename
, int flags
, u32 mode
) {
195 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
196 return internal_syscall(SYSCALL(openat
), AT_FDCWD
, (uptr
)filename
, flags
,
199 return internal_syscall(SYSCALL(open
), (uptr
)filename
, flags
, mode
);
203 uptr
internal_read(fd_t fd
, void *buf
, uptr count
) {
206 HANDLE_EINTR(res
, internal_syscall_ptr(SYSCALL(read
), fd
, buf
, count
));
208 HANDLE_EINTR(res
, (sptr
)internal_syscall(SYSCALL(read
), fd
, (uptr
)buf
,
214 uptr
internal_write(fd_t fd
, const void *buf
, uptr count
) {
217 HANDLE_EINTR(res
, internal_syscall_ptr(SYSCALL(write
), fd
, buf
, count
));
219 HANDLE_EINTR(res
, (sptr
)internal_syscall(SYSCALL(write
), fd
, (uptr
)buf
,
225 uptr
internal_ftruncate(fd_t fd
, uptr size
) {
228 HANDLE_EINTR(res
, internal_syscall(SYSCALL(ftruncate
), fd
, 0, (s64
)size
));
230 HANDLE_EINTR(res
, (sptr
)internal_syscall(SYSCALL(ftruncate
), fd
,
236 #if !SANITIZER_LINUX_USES_64BIT_SYSCALLS && SANITIZER_LINUX
237 static void stat64_to_stat(struct stat64
*in
, struct stat
*out
) {
238 internal_memset(out
, 0, sizeof(*out
));
239 out
->st_dev
= in
->st_dev
;
240 out
->st_ino
= in
->st_ino
;
241 out
->st_mode
= in
->st_mode
;
242 out
->st_nlink
= in
->st_nlink
;
243 out
->st_uid
= in
->st_uid
;
244 out
->st_gid
= in
->st_gid
;
245 out
->st_rdev
= in
->st_rdev
;
246 out
->st_size
= in
->st_size
;
247 out
->st_blksize
= in
->st_blksize
;
248 out
->st_blocks
= in
->st_blocks
;
249 out
->st_atime
= in
->st_atime
;
250 out
->st_mtime
= in
->st_mtime
;
251 out
->st_ctime
= in
->st_ctime
;
255 #if defined(__mips64)
256 // Undefine compatibility macros from <sys/stat.h>
257 // so that they would not clash with the kernel_stat
258 // st_[a|m|c]time fields
262 #if defined(SANITIZER_ANDROID)
263 // Bionic sys/stat.h defines additional macros
264 // for compatibility with the old NDKs and
265 // they clash with the kernel_stat structure
266 // st_[a|m|c]time_nsec fields.
271 static void kernel_stat_to_stat(struct kernel_stat
*in
, struct stat
*out
) {
272 internal_memset(out
, 0, sizeof(*out
));
273 out
->st_dev
= in
->st_dev
;
274 out
->st_ino
= in
->st_ino
;
275 out
->st_mode
= in
->st_mode
;
276 out
->st_nlink
= in
->st_nlink
;
277 out
->st_uid
= in
->st_uid
;
278 out
->st_gid
= in
->st_gid
;
279 out
->st_rdev
= in
->st_rdev
;
280 out
->st_size
= in
->st_size
;
281 out
->st_blksize
= in
->st_blksize
;
282 out
->st_blocks
= in
->st_blocks
;
283 #if defined(__USE_MISC) || \
284 defined(__USE_XOPEN2K8) || \
285 defined(SANITIZER_ANDROID)
286 out
->st_atim
.tv_sec
= in
->st_atime
;
287 out
->st_atim
.tv_nsec
= in
->st_atime_nsec
;
288 out
->st_mtim
.tv_sec
= in
->st_mtime
;
289 out
->st_mtim
.tv_nsec
= in
->st_mtime_nsec
;
290 out
->st_ctim
.tv_sec
= in
->st_ctime
;
291 out
->st_ctim
.tv_nsec
= in
->st_ctime_nsec
;
293 out
->st_atime
= in
->st_atime
;
294 out
->st_atimensec
= in
->st_atime_nsec
;
295 out
->st_mtime
= in
->st_mtime
;
296 out
->st_mtimensec
= in
->st_mtime_nsec
;
297 out
->st_ctime
= in
->st_ctime
;
298 out
->st_atimensec
= in
->st_ctime_nsec
;
303 uptr
internal_stat(const char *path
, void *buf
) {
304 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
305 return internal_syscall(SYSCALL(fstatat
), AT_FDCWD
, (uptr
)path
,
307 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
308 return internal_syscall(SYSCALL(newfstatat
), AT_FDCWD
, (uptr
)path
,
310 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
311 # if defined(__mips64)
312 // For mips64, stat syscall fills buffer in the format of kernel_stat
313 struct kernel_stat kbuf
;
314 int res
= internal_syscall(SYSCALL(stat
), path
, &kbuf
);
315 kernel_stat_to_stat(&kbuf
, (struct stat
*)buf
);
318 return internal_syscall(SYSCALL(stat
), (uptr
)path
, (uptr
)buf
);
322 int res
= internal_syscall(SYSCALL(stat64
), path
, &buf64
);
323 stat64_to_stat(&buf64
, (struct stat
*)buf
);
328 uptr
internal_lstat(const char *path
, void *buf
) {
330 return internal_syscall(SYSCALL(lstat
), path
, buf
);
331 #elif SANITIZER_FREEBSD
332 return internal_syscall(SYSCALL(fstatat
), AT_FDCWD
, (uptr
)path
,
333 (uptr
)buf
, AT_SYMLINK_NOFOLLOW
);
334 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
335 return internal_syscall(SYSCALL(newfstatat
), AT_FDCWD
, (uptr
)path
,
336 (uptr
)buf
, AT_SYMLINK_NOFOLLOW
);
337 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
338 # if SANITIZER_MIPS64
339 // For mips64, lstat syscall fills buffer in the format of kernel_stat
340 struct kernel_stat kbuf
;
341 int res
= internal_syscall(SYSCALL(lstat
), path
, &kbuf
);
342 kernel_stat_to_stat(&kbuf
, (struct stat
*)buf
);
345 return internal_syscall(SYSCALL(lstat
), (uptr
)path
, (uptr
)buf
);
349 int res
= internal_syscall(SYSCALL(lstat64
), path
, &buf64
);
350 stat64_to_stat(&buf64
, (struct stat
*)buf
);
355 uptr
internal_fstat(fd_t fd
, void *buf
) {
356 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS || SANITIZER_NETBSD
357 # if SANITIZER_MIPS64
358 // For mips64, fstat syscall fills buffer in the format of kernel_stat
359 struct kernel_stat kbuf
;
360 int res
= internal_syscall(SYSCALL(fstat
), fd
, &kbuf
);
361 kernel_stat_to_stat(&kbuf
, (struct stat
*)buf
);
364 return internal_syscall(SYSCALL(fstat
), fd
, (uptr
)buf
);
368 int res
= internal_syscall(SYSCALL(fstat64
), fd
, &buf64
);
369 stat64_to_stat(&buf64
, (struct stat
*)buf
);
374 uptr
internal_filesize(fd_t fd
) {
376 if (internal_fstat(fd
, &st
))
378 return (uptr
)st
.st_size
;
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
) {
391 return internal_syscall_ptr(SYSCALL(readlink
), path
, buf
, bufsize
);
392 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
393 return internal_syscall(SYSCALL(readlinkat
), AT_FDCWD
,
394 (uptr
)path
, (uptr
)buf
, bufsize
);
396 return internal_syscall(SYSCALL(readlink
), (uptr
)path
, (uptr
)buf
, bufsize
);
400 uptr
internal_unlink(const char *path
) {
401 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
402 return internal_syscall(SYSCALL(unlinkat
), AT_FDCWD
, (uptr
)path
, 0);
404 return internal_syscall(SYSCALL(unlink
), (uptr
)path
);
408 uptr
internal_rename(const char *oldpath
, const char *newpath
) {
409 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
410 return internal_syscall(SYSCALL(renameat
), AT_FDCWD
, (uptr
)oldpath
, AT_FDCWD
,
413 return internal_syscall(SYSCALL(rename
), (uptr
)oldpath
, (uptr
)newpath
);
417 uptr
internal_sched_yield() {
418 return internal_syscall(SYSCALL(sched_yield
));
421 void internal__exit(int exitcode
) {
422 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
423 internal_syscall(SYSCALL(exit
), exitcode
);
425 internal_syscall(SYSCALL(exit_group
), exitcode
);
427 Die(); // Unreachable.
430 unsigned int internal_sleep(unsigned int seconds
) {
434 int res
= internal_syscall(SYSCALL(nanosleep
), &ts
, &ts
);
435 if (res
) return ts
.tv_sec
;
439 uptr
internal_execve(const char *filename
, char *const argv
[],
440 char *const envp
[]) {
441 return internal_syscall(SYSCALL(execve
), (uptr
)filename
, (uptr
)argv
,
445 // ----------------- sanitizer_common.h
446 bool FileExists(const char *filename
) {
448 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
449 if (internal_syscall(SYSCALL(newfstatat
), AT_FDCWD
, filename
, &st
, 0))
451 if (internal_stat(filename
, &st
))
454 // Sanity check: filename is a regular file.
455 return S_ISREG(st
.st_mode
);
459 #if SANITIZER_FREEBSD
460 return (uptr
)pthread_self();
461 #elif SANITIZER_NETBSD
464 return internal_syscall(SYSCALL(gettid
));
469 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
474 internal_memset(&tv
, 0, sizeof(tv
));
476 internal_syscall_ptr(SYSCALL(gettimeofday
), &tv
, NULL
);
478 internal_syscall(SYSCALL(gettimeofday
), (uptr
)&tv
, 0);
480 return (u64
)tv
.tv_sec
* 1000*1000*1000 + tv
.tv_usec
* 1000;
483 // Like getenv, but reads env directly from /proc (on Linux) or parses the
484 // 'environ' array (on FreeBSD) and does not use libc. This function should be
485 // called first inside __asan_init.
486 const char *GetEnv(const char *name
) {
487 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
488 if (::environ
!= 0) {
489 uptr NameLen
= internal_strlen(name
);
490 for (char **Env
= ::environ
; *Env
!= 0; Env
++) {
491 if (internal_strncmp(*Env
, name
, NameLen
) == 0 && (*Env
)[NameLen
] == '=')
492 return (*Env
) + NameLen
+ 1;
495 return 0; // Not found.
496 #elif SANITIZER_LINUX
497 static char *environ
;
503 if (!ReadFileToBuffer("/proc/self/environ", &environ
, &environ_size
, &len
))
506 if (!environ
|| len
== 0) return nullptr;
507 uptr namelen
= internal_strlen(name
);
508 const char *p
= environ
;
509 while (*p
!= '\0') { // will happen at the \0\0 that terminates the buffer
510 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
512 (char*)internal_memchr(p
, '\0', len
- (p
- environ
));
513 if (!endp
) // this entry isn't NUL terminated
515 else if (!internal_memcmp(p
, name
, namelen
) && p
[namelen
] == '=') // Match.
516 return p
+ namelen
+ 1; // point after =
519 return nullptr; // Not found.
521 #error "Unsupported platform"
525 #if !SANITIZER_FREEBSD
527 SANITIZER_WEAK_ATTRIBUTE
extern void *__libc_stack_end
;
531 #if !SANITIZER_GO && !SANITIZER_FREEBSD
532 static void ReadNullSepFileToArray(const char *path
, char ***arr
,
537 *arr
= (char **)MmapOrDie(arr_size
* sizeof(char *), "NullSepFileArray");
538 if (!ReadFileToBuffer(path
, &buff
, &buff_size
, &buff_len
, 1024 * 1024)) {
544 for (count
= 1, i
= 1; ; i
++) {
546 if (buff
[i
+1] == 0) break;
547 (*arr
)[count
] = &buff
[i
+1];
548 CHECK_LE(count
, arr_size
- 1); // FIXME: make this more flexible.
552 (*arr
)[count
] = nullptr;
556 static void GetArgsAndEnv(char ***argv
, char ***envp
) {
557 #if !SANITIZER_FREEBSD
559 if (&__libc_stack_end
) {
561 uptr
* stack_end
= (uptr
*)__libc_stack_end
;
562 int argc
= *stack_end
;
563 *argv
= (char**)(stack_end
+ 1);
564 *envp
= (char**)(stack_end
+ argc
+ 2);
567 static const int kMaxArgv
= 2000, kMaxEnvp
= 2000;
568 ReadNullSepFileToArray("/proc/self/cmdline", argv
, kMaxArgv
);
569 ReadNullSepFileToArray("/proc/self/environ", envp
, kMaxEnvp
);
573 // On FreeBSD, retrieving the argument and environment arrays is done via the
574 // kern.ps_strings sysctl, which returns a pointer to a structure containing
575 // this information. See also <sys/exec.h>.
577 size_t sz
= sizeof(pss
);
578 if (sysctlbyname("kern.ps_strings", &pss
, &sz
, NULL
, 0) == -1) {
579 Printf("sysctl kern.ps_strings failed\n");
582 *argv
= pss
->ps_argvstr
;
583 *envp
= pss
->ps_envstr
;
589 GetArgsAndEnv(&argv
, &envp
);
595 GetArgsAndEnv(&argv
, &envp
);
596 uptr rv
= internal_execve("/proc/self/exe", argv
, envp
);
598 CHECK_EQ(internal_iserror(rv
, &rverrno
), true);
599 Printf("execve failed, errno %d\n", rverrno
);
609 BlockingMutex::BlockingMutex() {
610 internal_memset(this, 0, sizeof(*this));
613 void BlockingMutex::Lock() {
615 atomic_uint32_t
*m
= reinterpret_cast<atomic_uint32_t
*>(&opaque_storage_
);
616 if (atomic_exchange(m
, MtxLocked
, memory_order_acquire
) == MtxUnlocked
)
618 while (atomic_exchange(m
, MtxSleeping
, memory_order_acquire
) != MtxUnlocked
) {
619 #if SANITIZER_FREEBSD
620 _umtx_op(m
, UMTX_OP_WAIT_UINT
, MtxSleeping
, 0, 0);
621 #elif SANITIZER_NETBSD
622 sched_yield(); /* No userspace futex-like synchromization */
624 internal_syscall(SYSCALL(futex
), (uptr
)m
, FUTEX_WAIT
, MtxSleeping
, 0, 0, 0);
629 void BlockingMutex::Unlock() {
630 atomic_uint32_t
*m
= reinterpret_cast<atomic_uint32_t
*>(&opaque_storage_
);
631 u32 v
= atomic_exchange(m
, MtxUnlocked
, memory_order_release
);
632 CHECK_NE(v
, MtxUnlocked
);
633 if (v
== MtxSleeping
) {
634 #if SANITIZER_FREEBSD
635 _umtx_op(m
, UMTX_OP_WAKE
, 1, 0, 0);
636 #elif SANITIZER_NETBSD
637 /* No userspace futex-like synchromization */
639 internal_syscall(SYSCALL(futex
), (uptr
)m
, FUTEX_WAKE
, 1, 0, 0, 0);
644 void BlockingMutex::CheckLocked() {
645 atomic_uint32_t
*m
= reinterpret_cast<atomic_uint32_t
*>(&opaque_storage_
);
646 CHECK_NE(MtxUnlocked
, atomic_load(m
, memory_order_relaxed
));
649 // ----------------- sanitizer_linux.h
650 // The actual size of this structure is specified by d_reclen.
651 // Note that getdents64 uses a different structure format. We only provide the
652 // 32-bit syscall here.
654 // struct dirent is different for Linux and us. At this moment, we use only
655 // d_fileno (Linux call this d_ino), d_reclen, and d_name.
656 struct linux_dirent
{
657 u64 d_ino
; // d_fileno
659 u16 d_namlen
; // not used
660 u8 d_type
; // not used
661 char d_name
[NAME_MAX
+ 1];
664 struct linux_dirent
{
665 #if SANITIZER_X32 || defined(__aarch64__)
672 unsigned short d_reclen
;
674 unsigned char d_type
;
681 uptr
internal_ptrace(int request
, int pid
, void *addr
, void *data
) {
683 // XXX We need additional work for ptrace:
684 // - for request, we use PT_FOO whereas Linux uses PTRACE_FOO
685 // - data is int for us, but void * for Linux
686 // - Linux sometimes uses data in the case where we use addr instead
687 // At this moment, this function is used only within
688 // "#if SANITIZER_LINUX && defined(__x86_64__)" block in
689 // sanitizer_stoptheworld_linux_libcdep.cc.
690 return internal_syscall_ptr(SYSCALL(ptrace
), request
, pid
, (uptr
)addr
,
693 return internal_syscall(SYSCALL(ptrace
), request
, pid
, (uptr
)addr
,
698 uptr
internal_waitpid(int pid
, int *status
, int options
) {
700 return internal_syscall(SYSCALL(wait4
), pid
, status
, options
,
703 return internal_syscall(SYSCALL(wait4
), pid
, (uptr
)status
, options
,
708 uptr
internal_getpid() {
709 return internal_syscall(SYSCALL(getpid
));
712 uptr
internal_getppid() {
713 return internal_syscall(SYSCALL(getppid
));
716 uptr
internal_getdents(fd_t fd
, struct linux_dirent
*dirp
, unsigned int count
) {
718 return internal_syscall(SYSCALL(getdents
), fd
, dirp
, (uptr
)count
);
719 #elif SANITIZER_FREEBSD
720 return internal_syscall(SYSCALL(getdirentries
), fd
, (uptr
)dirp
, count
, NULL
);
721 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
722 return internal_syscall(SYSCALL(getdents64
), fd
, (uptr
)dirp
, count
);
724 return internal_syscall(SYSCALL(getdents
), fd
, (uptr
)dirp
, count
);
728 uptr
internal_lseek(fd_t fd
, OFF_T offset
, int whence
) {
730 return internal_syscall64(SYSCALL(lseek
), fd
, 0, offset
, whence
);
732 return internal_syscall(SYSCALL(lseek
), fd
, offset
, whence
);
737 uptr
internal_prctl(int option
, uptr arg2
, uptr arg3
, uptr arg4
, uptr arg5
) {
738 return internal_syscall(SYSCALL(prctl
), option
, arg2
, arg3
, arg4
, arg5
);
742 uptr
internal_sigaltstack(const void *ss
, void *oss
) {
743 return internal_syscall(SYSCALL(sigaltstack
), (uptr
)ss
, (uptr
)oss
);
746 int internal_fork() {
747 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
748 return internal_syscall(SYSCALL(clone
), SIGCHLD
, 0);
750 return internal_syscall(SYSCALL(fork
));
755 #define SA_RESTORER 0x04000000
756 // Doesn't set sa_restorer if the caller did not set it, so use with caution
758 int internal_sigaction_norestorer(int signum
, const void *act
, void *oldact
) {
759 __sanitizer_kernel_sigaction_t k_act
, k_oldact
;
760 internal_memset(&k_act
, 0, sizeof(__sanitizer_kernel_sigaction_t
));
761 internal_memset(&k_oldact
, 0, sizeof(__sanitizer_kernel_sigaction_t
));
762 const __sanitizer_sigaction
*u_act
= (const __sanitizer_sigaction
*)act
;
763 __sanitizer_sigaction
*u_oldact
= (__sanitizer_sigaction
*)oldact
;
765 k_act
.handler
= u_act
->handler
;
766 k_act
.sigaction
= u_act
->sigaction
;
767 internal_memcpy(&k_act
.sa_mask
, &u_act
->sa_mask
,
768 sizeof(__sanitizer_kernel_sigset_t
));
769 // Without SA_RESTORER kernel ignores the calls (probably returns EINVAL).
770 k_act
.sa_flags
= u_act
->sa_flags
| SA_RESTORER
;
771 // FIXME: most often sa_restorer is unset, however the kernel requires it
772 // to point to a valid signal restorer that calls the rt_sigreturn syscall.
773 // If sa_restorer passed to the kernel is NULL, the program may crash upon
774 // signal delivery or fail to unwind the stack in the signal handler.
775 // libc implementation of sigaction() passes its own restorer to
776 // rt_sigaction, so we need to do the same (we'll need to reimplement the
777 // restorers; for x86_64 the restorer address can be obtained from
778 // oldact->sa_restorer upon a call to sigaction(xxx, NULL, oldact).
779 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
780 k_act
.sa_restorer
= u_act
->sa_restorer
;
784 uptr result
= internal_syscall(SYSCALL(rt_sigaction
), (uptr
)signum
,
785 (uptr
)(u_act
? &k_act
: nullptr),
786 (uptr
)(u_oldact
? &k_oldact
: nullptr),
787 (uptr
)sizeof(__sanitizer_kernel_sigset_t
));
789 if ((result
== 0) && u_oldact
) {
790 u_oldact
->handler
= k_oldact
.handler
;
791 u_oldact
->sigaction
= k_oldact
.sigaction
;
792 internal_memcpy(&u_oldact
->sa_mask
, &k_oldact
.sa_mask
,
793 sizeof(__sanitizer_kernel_sigset_t
));
794 u_oldact
->sa_flags
= k_oldact
.sa_flags
;
795 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
796 u_oldact
->sa_restorer
= k_oldact
.sa_restorer
;
802 // Invokes sigaction via a raw syscall with a restorer, but does not support
803 // all platforms yet.
804 // We disable for Go simply because we have not yet added to buildgo.sh.
805 #if (defined(__x86_64__) || SANITIZER_MIPS64) && !SANITIZER_GO
806 int internal_sigaction_syscall(int signum
, const void *act
, void *oldact
) {
808 return internal_sigaction_norestorer(signum
, act
, oldact
);
809 __sanitizer_sigaction u_adjust
;
810 internal_memcpy(&u_adjust
, act
, sizeof(u_adjust
));
811 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
812 if (u_adjust
.sa_restorer
== nullptr) {
813 u_adjust
.sa_restorer
= internal_sigreturn
;
816 return internal_sigaction_norestorer(signum
, (const void *)&u_adjust
,
819 #endif // defined(__x86_64__) && !SANITIZER_GO
820 #endif // SANITIZER_LINUX
822 uptr
internal_sigprocmask(int how
, __sanitizer_sigset_t
*set
,
823 __sanitizer_sigset_t
*oldset
) {
824 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
825 return internal_syscall(SYSCALL(sigprocmask
), how
, set
, oldset
);
827 __sanitizer_kernel_sigset_t
*k_set
= (__sanitizer_kernel_sigset_t
*)set
;
828 __sanitizer_kernel_sigset_t
*k_oldset
= (__sanitizer_kernel_sigset_t
*)oldset
;
829 return internal_syscall(SYSCALL(rt_sigprocmask
), (uptr
)how
,
830 (uptr
)&k_set
->sig
[0], (uptr
)&k_oldset
->sig
[0],
831 sizeof(__sanitizer_kernel_sigset_t
));
835 void internal_sigfillset(__sanitizer_sigset_t
*set
) {
836 internal_memset(set
, 0xff, sizeof(*set
));
839 void internal_sigemptyset(__sanitizer_sigset_t
*set
) {
840 internal_memset(set
, 0, sizeof(*set
));
844 void internal_sigdelset(__sanitizer_sigset_t
*set
, int signum
) {
847 CHECK_LT(signum
, sizeof(*set
) * 8);
848 __sanitizer_kernel_sigset_t
*k_set
= (__sanitizer_kernel_sigset_t
*)set
;
849 const uptr idx
= signum
/ (sizeof(k_set
->sig
[0]) * 8);
850 const uptr bit
= signum
% (sizeof(k_set
->sig
[0]) * 8);
851 k_set
->sig
[idx
] &= ~(1 << bit
);
854 bool internal_sigismember(__sanitizer_sigset_t
*set
, int signum
) {
857 CHECK_LT(signum
, sizeof(*set
) * 8);
858 __sanitizer_kernel_sigset_t
*k_set
= (__sanitizer_kernel_sigset_t
*)set
;
859 const uptr idx
= signum
/ (sizeof(k_set
->sig
[0]) * 8);
860 const uptr bit
= signum
% (sizeof(k_set
->sig
[0]) * 8);
861 return k_set
->sig
[idx
] & (1 << bit
);
863 #endif // SANITIZER_LINUX
865 // ThreadLister implementation.
866 ThreadLister::ThreadLister(int pid
)
871 entry_((struct linux_dirent
*)buffer_
.data()),
873 char task_directory_path
[80];
874 internal_snprintf(task_directory_path
, sizeof(task_directory_path
),
875 "/proc/%d/task/", pid
);
876 uptr openrv
= internal_open(task_directory_path
, O_RDONLY
| O_DIRECTORY
);
877 if (internal_iserror(openrv
)) {
879 Report("Can't open /proc/%d/task for reading.\n", pid
);
882 descriptor_
= openrv
;
886 int ThreadLister::GetNextTID() {
891 if ((char *)entry_
>= &buffer_
[bytes_read_
] && !GetDirectoryEntries())
893 if (entry_
->d_ino
!= 0 && entry_
->d_name
[0] >= '0' &&
894 entry_
->d_name
[0] <= '9') {
895 // Found a valid tid.
896 tid
= (int)internal_atoll(entry_
->d_name
);
898 entry_
= (struct linux_dirent
*)(((char *)entry_
) + entry_
->d_reclen
);
903 void ThreadLister::Reset() {
904 if (error_
|| descriptor_
< 0)
906 internal_lseek(descriptor_
, 0, SEEK_SET
);
909 ThreadLister::~ThreadLister() {
910 if (descriptor_
>= 0)
911 internal_close(descriptor_
);
914 bool ThreadLister::error() { return error_
; }
916 bool ThreadLister::GetDirectoryEntries() {
917 CHECK_GE(descriptor_
, 0);
918 CHECK_NE(error_
, true);
919 bytes_read_
= internal_getdents(descriptor_
,
920 (struct linux_dirent
*)buffer_
.data(),
922 if (internal_iserror(bytes_read_
)) {
923 Report("Can't read directory entries from /proc/%d/task.\n", pid_
);
926 } else if (bytes_read_
== 0) {
929 entry_
= (struct linux_dirent
*)buffer_
.data();
933 #if SANITIZER_WORDSIZE == 32
934 // Take care of unusable kernel area in top gigabyte.
935 static uptr
GetKernelAreaSize() {
936 #if SANITIZER_LINUX && !SANITIZER_X32
937 const uptr gbyte
= 1UL << 30;
939 // Firstly check if there are writable segments
940 // mapped to top gigabyte (e.g. stack).
941 MemoryMappingLayout
proc_maps(/*cache_enabled*/true);
942 MemoryMappedSegment segment
;
943 while (proc_maps
.Next(&segment
)) {
944 if ((segment
.end
>= 3 * gbyte
) && segment
.IsWritable()) return 0;
947 #if !SANITIZER_ANDROID
948 // Even if nothing is mapped, top Gb may still be accessible
949 // if we are running on 64-bit kernel.
950 // Uname may report misleading results if personality type
951 // is modified (e.g. under schroot) so check this as well.
952 struct utsname uname_info
;
953 int pers
= personality(0xffffffffUL
);
954 if (!(pers
& PER_MASK
)
955 && uname(&uname_info
) == 0
956 && internal_strstr(uname_info
.machine
, "64"))
958 #endif // SANITIZER_ANDROID
960 // Top gigabyte is reserved for kernel.
964 #endif // SANITIZER_LINUX && !SANITIZER_X32
966 #endif // SANITIZER_WORDSIZE == 32
968 uptr
GetMaxVirtualAddress() {
969 #if SANITIZER_NETBSD && defined(__x86_64__)
970 return 0x7f7ffffff000ULL
; // (0x00007f8000000000 - PAGE_SIZE)
971 #elif SANITIZER_WORDSIZE == 64
972 # if defined(__powerpc64__) || defined(__aarch64__)
973 // On PowerPC64 we have two different address space layouts: 44- and 46-bit.
974 // We somehow need to figure out which one we are using now and choose
975 // one of 0x00000fffffffffffUL and 0x00003fffffffffffUL.
976 // Note that with 'ulimit -s unlimited' the stack is moved away from the top
977 // of the address space, so simply checking the stack address is not enough.
978 // This should (does) work for both PowerPC64 Endian modes.
979 // Similarly, aarch64 has multiple address space layouts: 39, 42 and 47-bit.
980 return (1ULL << (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1)) - 1;
981 # elif defined(__mips64)
982 return (1ULL << 40) - 1; // 0x000000ffffffffffUL;
983 # elif defined(__s390x__)
984 return (1ULL << 53) - 1; // 0x001fffffffffffffUL;
986 return (1ULL << 47) - 1; // 0x00007fffffffffffUL;
988 #else // SANITIZER_WORDSIZE == 32
989 # if defined(__s390__)
990 return (1ULL << 31) - 1; // 0x7fffffff;
992 uptr res
= (1ULL << 32) - 1; // 0xffffffff;
993 if (!common_flags()->full_address_space
)
994 res
-= GetKernelAreaSize();
995 CHECK_LT(reinterpret_cast<uptr
>(&res
), res
);
998 #endif // SANITIZER_WORDSIZE
1001 uptr
GetPageSize() {
1002 // Android post-M sysconf(_SC_PAGESIZE) crashes if called from .preinit_array.
1003 #if SANITIZER_ANDROID
1005 #elif SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__))
1006 return EXEC_PAGESIZE
;
1007 #elif SANITIZER_USE_GETAUXVAL
1008 return getauxval(AT_PAGESZ
);
1010 return sysconf(_SC_PAGESIZE
); // EXEC_PAGESIZE may not be trustworthy.
1014 uptr
ReadBinaryName(/*out*/char *buf
, uptr buf_len
) {
1015 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
1016 #if SANITIZER_FREEBSD
1017 const int Mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PATHNAME
, -1};
1019 const int Mib
[4] = {CTL_KERN
, KERN_PROC_ARGS
, -1, KERN_PROC_PATHNAME
};
1021 const char *default_module_name
= "kern.proc.pathname";
1022 size_t Size
= buf_len
;
1023 bool IsErr
= (sysctl(Mib
, ARRAY_SIZE(Mib
), buf
, &Size
, NULL
, 0) != 0);
1024 int readlink_error
= IsErr
? errno
: 0;
1025 uptr module_name_len
= Size
;
1027 const char *default_module_name
= "/proc/self/exe";
1028 uptr module_name_len
= internal_readlink(
1029 default_module_name
, buf
, buf_len
);
1031 bool IsErr
= internal_iserror(module_name_len
, &readlink_error
);
1034 // We can't read binary name for some reason, assume it's unknown.
1035 Report("WARNING: reading executable name failed with errno %d, "
1036 "some stack frames may not be symbolized\n", readlink_error
);
1037 module_name_len
= internal_snprintf(buf
, buf_len
, "%s",
1038 default_module_name
);
1039 CHECK_LT(module_name_len
, buf_len
);
1041 return module_name_len
;
1044 uptr
ReadLongProcessName(/*out*/ char *buf
, uptr buf_len
) {
1049 if (ReadFileToBuffer("/proc/self/cmdline", &tmpbuf
, &tmpsize
, &tmplen
,
1051 internal_strncpy(buf
, tmpbuf
, buf_len
);
1052 UnmapOrDie(tmpbuf
, tmpsize
);
1053 return internal_strlen(buf
);
1056 return ReadBinaryName(buf
, buf_len
);
1059 // Match full names of the form /path/to/base_name{-,.}*
1060 bool LibraryNameIs(const char *full_name
, const char *base_name
) {
1061 const char *name
= full_name
;
1063 while (*name
!= '\0') name
++;
1064 while (name
> full_name
&& *name
!= '/') name
--;
1065 if (*name
== '/') name
++;
1066 uptr base_name_length
= internal_strlen(base_name
);
1067 if (internal_strncmp(name
, base_name
, base_name_length
)) return false;
1068 return (name
[base_name_length
] == '-' || name
[base_name_length
] == '.');
1071 #if !SANITIZER_ANDROID
1072 // Call cb for each region mapped by map.
1073 void ForEachMappedRegion(link_map
*map
, void (*cb
)(const void *, uptr
)) {
1074 CHECK_NE(map
, nullptr);
1075 #if !SANITIZER_FREEBSD
1076 typedef ElfW(Phdr
) Elf_Phdr
;
1077 typedef ElfW(Ehdr
) Elf_Ehdr
;
1078 #endif // !SANITIZER_FREEBSD
1079 char *base
= (char *)map
->l_addr
;
1080 Elf_Ehdr
*ehdr
= (Elf_Ehdr
*)base
;
1081 char *phdrs
= base
+ ehdr
->e_phoff
;
1082 char *phdrs_end
= phdrs
+ ehdr
->e_phnum
* ehdr
->e_phentsize
;
1084 // Find the segment with the minimum base so we can "relocate" the p_vaddr
1085 // fields. Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
1086 // objects have a non-zero base.
1087 uptr preferred_base
= (uptr
)-1;
1088 for (char *iter
= phdrs
; iter
!= phdrs_end
; iter
+= ehdr
->e_phentsize
) {
1089 Elf_Phdr
*phdr
= (Elf_Phdr
*)iter
;
1090 if (phdr
->p_type
== PT_LOAD
&& preferred_base
> (uptr
)phdr
->p_vaddr
)
1091 preferred_base
= (uptr
)phdr
->p_vaddr
;
1094 // Compute the delta from the real base to get a relocation delta.
1095 sptr delta
= (uptr
)base
- preferred_base
;
1096 // Now we can figure out what the loader really mapped.
1097 for (char *iter
= phdrs
; iter
!= phdrs_end
; iter
+= ehdr
->e_phentsize
) {
1098 Elf_Phdr
*phdr
= (Elf_Phdr
*)iter
;
1099 if (phdr
->p_type
== PT_LOAD
) {
1100 uptr seg_start
= phdr
->p_vaddr
+ delta
;
1101 uptr seg_end
= seg_start
+ phdr
->p_memsz
;
1102 // None of these values are aligned. We consider the ragged edges of the
1103 // load command as defined, since they are mapped from the file.
1104 seg_start
= RoundDownTo(seg_start
, GetPageSizeCached());
1105 seg_end
= RoundUpTo(seg_end
, GetPageSizeCached());
1106 cb((void *)seg_start
, seg_end
- seg_start
);
1112 #if defined(__x86_64__) && SANITIZER_LINUX
1113 // We cannot use glibc's clone wrapper, because it messes with the child
1114 // task's TLS. It writes the PID and TID of the child task to its thread
1115 // descriptor, but in our case the child task shares the thread descriptor with
1116 // the parent (because we don't know how to allocate a new thread
1117 // descriptor to keep glibc happy). So the stock version of clone(), when
1118 // used with CLONE_VM, would end up corrupting the parent's thread descriptor.
1119 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1120 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1122 if (!fn
|| !child_stack
)
1124 CHECK_EQ(0, (uptr
)child_stack
% 16);
1125 child_stack
= (char *)child_stack
- 2 * sizeof(unsigned long long);
1126 ((unsigned long long *)child_stack
)[0] = (uptr
)fn
;
1127 ((unsigned long long *)child_stack
)[1] = (uptr
)arg
;
1128 register void *r8
__asm__("r8") = newtls
;
1129 register int *r10
__asm__("r10") = child_tidptr
;
1130 __asm__
__volatile__(
1131 /* %rax = syscall(%rax = SYSCALL(clone),
1133 * %rsi = child_stack,
1134 * %rdx = parent_tidptr,
1136 * %r10 = child_tidptr)
1143 "testq %%rax,%%rax\n"
1146 /* In the child. Terminate unwind chain. */
1147 // XXX: We should also terminate the CFI unwind chain
1148 // here. Unfortunately clang 3.2 doesn't support the
1149 // necessary CFI directives, so we skip that part.
1150 "xorq %%rbp,%%rbp\n"
1152 /* Call "fn(arg)". */
1157 /* Call _exit(%rax). */
1158 "movq %%rax,%%rdi\n"
1162 /* Return to parent. */
1165 : "a"(SYSCALL(clone
)), "i"(SYSCALL(exit
)),
1171 : "rsp", "memory", "r11", "rcx");
1174 #elif defined(__mips__)
1175 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1176 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1178 if (!fn
|| !child_stack
)
1180 CHECK_EQ(0, (uptr
)child_stack
% 16);
1181 child_stack
= (char *)child_stack
- 2 * sizeof(unsigned long long);
1182 ((unsigned long long *)child_stack
)[0] = (uptr
)fn
;
1183 ((unsigned long long *)child_stack
)[1] = (uptr
)arg
;
1184 register void *a3
__asm__("$7") = newtls
;
1185 register int *a4
__asm__("$8") = child_tidptr
;
1186 // We don't have proper CFI directives here because it requires alot of code
1187 // for very marginal benefits.
1188 __asm__
__volatile__(
1189 /* $v0 = syscall($v0 = __NR_clone,
1191 * $a1 = child_stack,
1192 * $a2 = parent_tidptr,
1194 * $a4 = child_tidptr)
1201 /* Store the fifth argument on stack
1202 * if we are using 32-bit abi.
1204 #if SANITIZER_WORDSIZE == 32
1217 /* Call "fn(arg)". */
1218 #if SANITIZER_WORDSIZE == 32
1219 #ifdef __BIG_ENDIAN__
1232 /* Call _exit($v0). */
1237 /* Return to parent. */
1247 : "memory", "$29" );
1250 #elif defined(__aarch64__)
1251 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1252 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1254 if (!fn
|| !child_stack
)
1256 CHECK_EQ(0, (uptr
)child_stack
% 16);
1257 child_stack
= (char *)child_stack
- 2 * sizeof(unsigned long long);
1258 ((unsigned long long *)child_stack
)[0] = (uptr
)fn
;
1259 ((unsigned long long *)child_stack
)[1] = (uptr
)arg
;
1261 register int (*__fn
)(void *) __asm__("x0") = fn
;
1262 register void *__stack
__asm__("x1") = child_stack
;
1263 register int __flags
__asm__("x2") = flags
;
1264 register void *__arg
__asm__("x3") = arg
;
1265 register int *__ptid
__asm__("x4") = parent_tidptr
;
1266 register void *__tls
__asm__("x5") = newtls
;
1267 register int *__ctid
__asm__("x6") = child_tidptr
;
1269 __asm__
__volatile__(
1270 "mov x0,x2\n" /* flags */
1271 "mov x2,x4\n" /* ptid */
1272 "mov x3,x5\n" /* tls */
1273 "mov x4,x6\n" /* ctid */
1274 "mov x8,%9\n" /* clone */
1284 /* In the child, now. Call "fn(arg)". */
1285 "ldp x1, x0, [sp], #16\n"
1288 /* Call _exit(%r0). */
1295 "r"(__fn
), "r"(__stack
), "r"(__flags
), "r"(__arg
),
1296 "r"(__ptid
), "r"(__tls
), "r"(__ctid
),
1297 "i"(__NR_clone
), "i"(__NR_exit
)
1301 #elif defined(__powerpc64__)
1302 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1303 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1305 // Stack frame structure.
1306 #if SANITIZER_PPC64V1
1307 // Back chain == 0 (SP + 112)
1308 // Frame (112 bytes):
1309 // Parameter save area (SP + 48), 8 doublewords
1310 // TOC save area (SP + 40)
1311 // Link editor doubleword (SP + 32)
1312 // Compiler doubleword (SP + 24)
1313 // LR save area (SP + 16)
1314 // CR save area (SP + 8)
1315 // Back chain (SP + 0)
1316 # define FRAME_SIZE 112
1317 # define FRAME_TOC_SAVE_OFFSET 40
1318 #elif SANITIZER_PPC64V2
1319 // Back chain == 0 (SP + 32)
1320 // Frame (32 bytes):
1321 // TOC save area (SP + 24)
1322 // LR save area (SP + 16)
1323 // CR save area (SP + 8)
1324 // Back chain (SP + 0)
1325 # define FRAME_SIZE 32
1326 # define FRAME_TOC_SAVE_OFFSET 24
1328 # error "Unsupported PPC64 ABI"
1330 if (!fn
|| !child_stack
)
1332 CHECK_EQ(0, (uptr
)child_stack
% 16);
1334 register int (*__fn
)(void *) __asm__("r3") = fn
;
1335 register void *__cstack
__asm__("r4") = child_stack
;
1336 register int __flags
__asm__("r5") = flags
;
1337 register void *__arg
__asm__("r6") = arg
;
1338 register int *__ptidptr
__asm__("r7") = parent_tidptr
;
1339 register void *__newtls
__asm__("r8") = newtls
;
1340 register int *__ctidptr
__asm__("r9") = child_tidptr
;
1342 __asm__
__volatile__(
1343 /* fn and arg are saved across the syscall */
1353 r7 == child_tidptr */
1361 /* Test if syscall was successful */
1362 "cmpdi cr1, 3, 0\n\t"
1363 "crandc cr1*4+eq, cr1*4+eq, cr0*4+so\n\t"
1366 /* Set up stack frame */
1368 "stdu 29, -8(1)\n\t"
1369 "stdu 1, -%12(1)\n\t"
1370 /* Do the function call */
1372 #if SANITIZER_PPC64V1
1376 #elif SANITIZER_PPC64V2
1380 # error "Unsupported PPC64 ABI"
1386 /* Call _exit(r3) */
1390 /* Return to parent */
1406 "i" (FRAME_TOC_SAVE_OFFSET
)
1407 : "cr0", "cr1", "memory", "ctr", "r0", "r27", "r28", "r29");
1410 #elif defined(__i386__) && SANITIZER_LINUX
1411 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1412 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1414 if (!fn
|| !child_stack
)
1416 CHECK_EQ(0, (uptr
)child_stack
% 16);
1417 child_stack
= (char *)child_stack
- 7 * sizeof(unsigned int);
1418 ((unsigned int *)child_stack
)[0] = (uptr
)flags
;
1419 ((unsigned int *)child_stack
)[1] = (uptr
)0;
1420 ((unsigned int *)child_stack
)[2] = (uptr
)fn
;
1421 ((unsigned int *)child_stack
)[3] = (uptr
)arg
;
1422 __asm__
__volatile__(
1423 /* %eax = syscall(%eax = SYSCALL(clone),
1425 * %ecx = child_stack,
1426 * %edx = parent_tidptr,
1428 * %edi = child_tidptr)
1432 "movl (%%ecx), %%ebx\n"
1433 /* Do the system call */
1437 /* Remember the flag value. */
1438 "movl %%ebx, (%%ecx)\n"
1448 "test %%eax,%%eax\n"
1451 /* terminate the stack frame */
1452 "xorl %%ebp,%%ebp\n"
1459 "addl $_GLOBAL_OFFSET_TABLE_+[.-here], %%ebx\n"
1462 "movl %%eax, %%ebx\n"
1467 : "a"(SYSCALL(clone
)), "i"(SYSCALL(exit
)),
1475 #elif defined(__arm__) && SANITIZER_LINUX
1476 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1477 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1479 if (!fn
|| !child_stack
)
1481 child_stack
= (char *)child_stack
- 2 * sizeof(unsigned int);
1482 ((unsigned int *)child_stack
)[0] = (uptr
)fn
;
1483 ((unsigned int *)child_stack
)[1] = (uptr
)arg
;
1484 register int r0
__asm__("r0") = flags
;
1485 register void *r1
__asm__("r1") = child_stack
;
1486 register int *r2
__asm__("r2") = parent_tidptr
;
1487 register void *r3
__asm__("r3") = newtls
;
1488 register int *r4
__asm__("r4") = child_tidptr
;
1489 register int r7
__asm__("r7") = __NR_clone
;
1491 #if __ARM_ARCH > 4 || defined (__ARM_ARCH_4T__)
1492 # define ARCH_HAS_BX
1495 # define ARCH_HAS_BLX
1499 # ifdef ARCH_HAS_BLX
1500 # define BLX(R) "blx " #R "\n"
1502 # define BLX(R) "mov lr, pc; bx " #R "\n"
1505 # define BLX(R) "mov lr, pc; mov pc," #R "\n"
1508 __asm__
__volatile__(
1509 /* %r0 = syscall(%r7 = SYSCALL(clone),
1511 * %r1 = child_stack,
1512 * %r2 = parent_tidptr,
1514 * %r4 = child_tidptr)
1517 /* Do the system call */
1526 /* In the child, now. Call "fn(arg)". */
1527 "ldr r0, [sp, #4]\n"
1528 "ldr ip, [sp], #8\n"
1530 /* Call _exit(%r0). */
1536 : "r"(r0
), "r"(r1
), "r"(r2
), "r"(r3
), "r"(r4
), "r"(r7
),
1541 #endif // defined(__x86_64__) && SANITIZER_LINUX
1543 #if SANITIZER_ANDROID
1544 #if __ANDROID_API__ < 21
1545 extern "C" __attribute__((weak
)) int dl_iterate_phdr(
1546 int (*)(struct dl_phdr_info
*, size_t, void *), void *);
1549 static int dl_iterate_phdr_test_cb(struct dl_phdr_info
*info
, size_t size
,
1551 // Any name starting with "lib" indicates a bug in L where library base names
1552 // are returned instead of paths.
1553 if (info
->dlpi_name
&& info
->dlpi_name
[0] == 'l' &&
1554 info
->dlpi_name
[1] == 'i' && info
->dlpi_name
[2] == 'b') {
1555 *(bool *)data
= true;
1561 static atomic_uint32_t android_api_level
;
1563 static AndroidApiLevel
AndroidDetectApiLevel() {
1564 if (!&dl_iterate_phdr
)
1565 return ANDROID_KITKAT
; // K or lower
1566 bool base_name_seen
= false;
1567 dl_iterate_phdr(dl_iterate_phdr_test_cb
, &base_name_seen
);
1569 return ANDROID_LOLLIPOP_MR1
; // L MR1
1570 return ANDROID_POST_LOLLIPOP
; // post-L
1571 // Plain L (API level 21) is completely broken wrt ASan and not very
1572 // interesting to detect.
1575 AndroidApiLevel
AndroidGetApiLevel() {
1576 AndroidApiLevel level
=
1577 (AndroidApiLevel
)atomic_load(&android_api_level
, memory_order_relaxed
);
1578 if (level
) return level
;
1579 level
= AndroidDetectApiLevel();
1580 atomic_store(&android_api_level
, level
, memory_order_relaxed
);
1586 static HandleSignalMode
GetHandleSignalModeImpl(int signum
) {
1589 return common_flags()->handle_abort
;
1591 return common_flags()->handle_sigill
;
1593 return common_flags()->handle_sigfpe
;
1595 return common_flags()->handle_segv
;
1597 return common_flags()->handle_sigbus
;
1599 return kHandleSignalNo
;
1602 HandleSignalMode
GetHandleSignalMode(int signum
) {
1603 HandleSignalMode result
= GetHandleSignalModeImpl(signum
);
1604 if (result
== kHandleSignalYes
&& !common_flags()->allow_user_segv_handler
)
1605 return kHandleSignalExclusive
;
1610 void *internal_start_thread(void(*func
)(void *arg
), void *arg
) {
1611 // Start the thread with signals blocked, otherwise it can steal user signals.
1612 __sanitizer_sigset_t set
, old
;
1613 internal_sigfillset(&set
);
1614 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1615 // Glibc uses SIGSETXID signal during setuid call. If this signal is blocked
1616 // on any thread, setuid call hangs (see test/tsan/setuid.c).
1617 internal_sigdelset(&set
, 33);
1619 internal_sigprocmask(SIG_SETMASK
, &set
, &old
);
1621 real_pthread_create(&th
, nullptr, (void*(*)(void *arg
))func
, arg
);
1622 internal_sigprocmask(SIG_SETMASK
, &old
, nullptr);
1626 void internal_join_thread(void *th
) {
1627 real_pthread_join(th
, nullptr);
1630 void *internal_start_thread(void (*func
)(void *), void *arg
) { return 0; }
1632 void internal_join_thread(void *th
) {}
1635 #if defined(__aarch64__)
1636 // Android headers in the older NDK releases miss this definition.
1637 struct __sanitizer_esr_context
{
1638 struct _aarch64_ctx head
;
1642 static bool Aarch64GetESR(ucontext_t
*ucontext
, u64
*esr
) {
1643 static const u32 kEsrMagic
= 0x45535201;
1644 u8
*aux
= ucontext
->uc_mcontext
.__reserved
;
1646 _aarch64_ctx
*ctx
= (_aarch64_ctx
*)aux
;
1647 if (ctx
->size
== 0) break;
1648 if (ctx
->magic
== kEsrMagic
) {
1649 *esr
= ((__sanitizer_esr_context
*)ctx
)->esr
;
1658 SignalContext::WriteFlag
SignalContext::GetWriteFlag() const {
1659 ucontext_t
*ucontext
= (ucontext_t
*)context
;
1660 #if defined(__x86_64__) || defined(__i386__)
1661 static const uptr PF_WRITE
= 1U << 1;
1662 #if SANITIZER_FREEBSD
1663 uptr err
= ucontext
->uc_mcontext
.mc_err
;
1664 #elif SANITIZER_NETBSD
1665 uptr err
= ucontext
->uc_mcontext
.__gregs
[_REG_ERR
];
1667 uptr err
= ucontext
->uc_mcontext
.gregs
[REG_ERR
];
1669 return err
& PF_WRITE
? WRITE
: READ
;
1670 #elif defined(__arm__)
1671 static const uptr FSR_WRITE
= 1U << 11;
1672 uptr fsr
= ucontext
->uc_mcontext
.error_code
;
1673 return fsr
& FSR_WRITE
? WRITE
: READ
;
1674 #elif defined(__aarch64__)
1675 static const u64 ESR_ELx_WNR
= 1U << 6;
1677 if (!Aarch64GetESR(ucontext
, &esr
)) return UNKNOWN
;
1678 return esr
& ESR_ELx_WNR
? WRITE
: READ
;
1681 return UNKNOWN
; // FIXME: Implement.
1685 void SignalContext::DumpAllRegisters(void *context
) {
1686 // FIXME: Implement this.
1689 static void GetPcSpBp(void *context
, uptr
*pc
, uptr
*sp
, uptr
*bp
) {
1690 #if defined(__arm__)
1691 ucontext_t
*ucontext
= (ucontext_t
*)context
;
1692 *pc
= ucontext
->uc_mcontext
.arm_pc
;
1693 *bp
= ucontext
->uc_mcontext
.arm_fp
;
1694 *sp
= ucontext
->uc_mcontext
.arm_sp
;
1695 #elif defined(__aarch64__)
1696 ucontext_t
*ucontext
= (ucontext_t
*)context
;
1697 *pc
= ucontext
->uc_mcontext
.pc
;
1698 *bp
= ucontext
->uc_mcontext
.regs
[29];
1699 *sp
= ucontext
->uc_mcontext
.sp
;
1700 #elif defined(__hppa__)
1701 ucontext_t
*ucontext
= (ucontext_t
*)context
;
1702 *pc
= ucontext
->uc_mcontext
.sc_iaoq
[0];
1703 /* GCC uses %r3 whenever a frame pointer is needed. */
1704 *bp
= ucontext
->uc_mcontext
.sc_gr
[3];
1705 *sp
= ucontext
->uc_mcontext
.sc_gr
[30];
1706 #elif defined(__x86_64__)
1707 # if SANITIZER_FREEBSD
1708 ucontext_t
*ucontext
= (ucontext_t
*)context
;
1709 *pc
= ucontext
->uc_mcontext
.mc_rip
;
1710 *bp
= ucontext
->uc_mcontext
.mc_rbp
;
1711 *sp
= ucontext
->uc_mcontext
.mc_rsp
;
1712 #elif SANITIZER_NETBSD
1713 ucontext_t
*ucontext
= (ucontext_t
*)context
;
1714 *pc
= ucontext
->uc_mcontext
.__gregs
[_REG_RIP
];
1715 *bp
= ucontext
->uc_mcontext
.__gregs
[_REG_RBP
];
1716 *sp
= ucontext
->uc_mcontext
.__gregs
[_REG_RSP
];
1718 ucontext_t
*ucontext
= (ucontext_t
*)context
;
1719 *pc
= ucontext
->uc_mcontext
.gregs
[REG_RIP
];
1720 *bp
= ucontext
->uc_mcontext
.gregs
[REG_RBP
];
1721 *sp
= ucontext
->uc_mcontext
.gregs
[REG_RSP
];
1723 #elif defined(__i386__)
1724 # if SANITIZER_FREEBSD
1725 ucontext_t
*ucontext
= (ucontext_t
*)context
;
1726 *pc
= ucontext
->uc_mcontext
.mc_eip
;
1727 *bp
= ucontext
->uc_mcontext
.mc_ebp
;
1728 *sp
= ucontext
->uc_mcontext
.mc_esp
;
1729 #elif SANITIZER_NETBSD
1730 ucontext_t
*ucontext
= (ucontext_t
*)context
;
1731 *pc
= ucontext
->uc_mcontext
.__gregs
[_REG_EIP
];
1732 *bp
= ucontext
->uc_mcontext
.__gregs
[_REG_EBP
];
1733 *sp
= ucontext
->uc_mcontext
.__gregs
[_REG_ESP
];
1735 ucontext_t
*ucontext
= (ucontext_t
*)context
;
1736 *pc
= ucontext
->uc_mcontext
.gregs
[REG_EIP
];
1737 *bp
= ucontext
->uc_mcontext
.gregs
[REG_EBP
];
1738 *sp
= ucontext
->uc_mcontext
.gregs
[REG_ESP
];
1740 #elif defined(__powerpc__) || defined(__powerpc64__)
1741 ucontext_t
*ucontext
= (ucontext_t
*)context
;
1742 *pc
= ucontext
->uc_mcontext
.regs
->nip
;
1743 *sp
= ucontext
->uc_mcontext
.regs
->gpr
[PT_R1
];
1744 // The powerpc{,64}-linux ABIs do not specify r31 as the frame
1745 // pointer, but GCC always uses r31 when we need a frame pointer.
1746 *bp
= ucontext
->uc_mcontext
.regs
->gpr
[PT_R31
];
1747 #elif defined(__sparc__)
1748 ucontext_t
*ucontext
= (ucontext_t
*)context
;
1750 # if defined (__arch64__)
1751 *pc
= ucontext
->uc_mcontext
.mc_gregs
[MC_PC
];
1752 *sp
= ucontext
->uc_mcontext
.mc_gregs
[MC_O6
];
1753 stk_ptr
= (uptr
*) (*sp
+ 2047);
1756 *pc
= ucontext
->uc_mcontext
.gregs
[REG_PC
];
1757 *sp
= ucontext
->uc_mcontext
.gregs
[REG_O6
];
1758 stk_ptr
= (uptr
*) *sp
;
1761 #elif defined(__mips__)
1762 ucontext_t
*ucontext
= (ucontext_t
*)context
;
1763 *pc
= ucontext
->uc_mcontext
.pc
;
1764 *bp
= ucontext
->uc_mcontext
.gregs
[30];
1765 *sp
= ucontext
->uc_mcontext
.gregs
[29];
1766 #elif defined(__s390__)
1767 ucontext_t
*ucontext
= (ucontext_t
*)context
;
1768 # if defined(__s390x__)
1769 *pc
= ucontext
->uc_mcontext
.psw
.addr
;
1771 *pc
= ucontext
->uc_mcontext
.psw
.addr
& 0x7fffffff;
1773 *bp
= ucontext
->uc_mcontext
.gregs
[11];
1774 *sp
= ucontext
->uc_mcontext
.gregs
[15];
1776 # error "Unsupported arch"
1780 void SignalContext::InitPcSpBp() { GetPcSpBp(context
, &pc
, &sp
, &bp
); }
1782 void MaybeReexec() {
1783 // No need to re-exec on Linux.
1786 void PrintModuleMap() { }
1788 void CheckNoDeepBind(const char *filename
, int flag
) {
1789 #ifdef RTLD_DEEPBIND
1790 if (flag
& RTLD_DEEPBIND
) {
1792 "You are trying to dlopen a %s shared library with RTLD_DEEPBIND flag"
1793 " which is incompatibe with sanitizer runtime "
1794 "(see https://github.com/google/sanitizers/issues/611 for details"
1795 "). If you want to run %s library under sanitizers please remove "
1796 "RTLD_DEEPBIND from dlopen flags.\n",
1797 filename
, filename
);
1803 uptr
FindAvailableMemoryRange(uptr size
, uptr alignment
, uptr left_padding
,
1804 uptr
*largest_gap_found
) {
1805 UNREACHABLE("FindAvailableMemoryRange is not available");
1809 bool GetRandom(void *buffer
, uptr length
, bool blocking
) {
1810 if (!buffer
|| !length
|| length
> 256)
1812 #if SANITIZER_USE_GETRANDOM
1813 static atomic_uint8_t skip_getrandom_syscall
;
1814 if (!atomic_load_relaxed(&skip_getrandom_syscall
)) {
1815 // Up to 256 bytes, getrandom will not be interrupted.
1816 uptr res
= internal_syscall(SYSCALL(getrandom
), buffer
, length
,
1817 blocking
? 0 : GRND_NONBLOCK
);
1819 if (internal_iserror(res
, &rverrno
) && rverrno
== ENOSYS
)
1820 atomic_store_relaxed(&skip_getrandom_syscall
, 1);
1821 else if (res
== length
)
1824 #endif // SANITIZER_USE_GETRANDOM
1825 // Up to 256 bytes, a read off /dev/urandom will not be interrupted.
1826 // blocking is moot here, O_NONBLOCK has no effect when opening /dev/urandom.
1827 uptr fd
= internal_open("/dev/urandom", O_RDONLY
);
1828 if (internal_iserror(fd
))
1830 uptr res
= internal_read(fd
, buffer
, length
);
1831 if (internal_iserror(res
))
1837 } // namespace __sanitizer
1839 #endif // SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD