1 //===-- sanitizer_linux.cpp -----------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file is shared between AddressSanitizer and ThreadSanitizer
10 // run-time libraries and implements linux-specific functions from
12 //===----------------------------------------------------------------------===//
14 #include "sanitizer_platform.h"
16 #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD || \
19 #include "sanitizer_common.h"
20 #include "sanitizer_flags.h"
21 #include "sanitizer_getauxval.h"
22 #include "sanitizer_internal_defs.h"
23 #include "sanitizer_libc.h"
24 #include "sanitizer_linux.h"
25 #include "sanitizer_mutex.h"
26 #include "sanitizer_placement_new.h"
27 #include "sanitizer_procmaps.h"
29 #if SANITIZER_LINUX && !SANITIZER_GO
30 #include <asm/param.h>
33 // For mips64, syscall(__NR_stat) fills the buffer in the 'struct kernel_stat'
34 // format. Struct kernel_stat is defined as 'struct stat' in asm/stat.h. To
35 // access stat from asm/stat.h, without conflicting with definition in
36 // sys/stat.h, we use this trick.
38 #include <asm/unistd.h>
39 #include <sys/types.h>
40 #define stat kernel_stat
45 #define st_atime st_atim
46 #define st_mtime st_mtim
47 #define st_ctime st_ctim
61 #include <sys/param.h>
62 #if !SANITIZER_SOLARIS
63 #include <sys/ptrace.h>
65 #include <sys/resource.h>
67 #include <sys/syscall.h>
69 #include <sys/types.h>
74 #include <sys/utsname.h>
77 #if SANITIZER_LINUX && !SANITIZER_ANDROID
78 #include <sys/personality.h>
83 #include <sys/procctl.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 const int FUTEX_PRIVATE_FLAG
= 128;
120 const int FUTEX_WAIT_PRIVATE
= FUTEX_WAIT
| FUTEX_PRIVATE_FLAG
;
121 const int FUTEX_WAKE_PRIVATE
= FUTEX_WAKE
| FUTEX_PRIVATE_FLAG
;
122 #endif // SANITIZER_LINUX
124 // Are we using 32-bit or 64-bit Linux syscalls?
125 // x32 (which defines __x86_64__) has SANITIZER_WORDSIZE == 32
126 // but it still needs to use 64-bit syscalls.
127 #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__powerpc64__) || \
128 SANITIZER_WORDSIZE == 64)
129 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 1
131 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 0
134 // Note : FreeBSD had implemented both
135 // Linux apis, available from
136 // future 12.x version most likely
137 #if SANITIZER_LINUX && defined(__NR_getrandom)
138 # if !defined(GRND_NONBLOCK)
139 # define GRND_NONBLOCK 1
141 # define SANITIZER_USE_GETRANDOM 1
143 # define SANITIZER_USE_GETRANDOM 0
144 #endif // SANITIZER_LINUX && defined(__NR_getrandom)
146 #if SANITIZER_FREEBSD && __FreeBSD_version >= 1200000
147 # define SANITIZER_USE_GETENTROPY 1
149 # define SANITIZER_USE_GETENTROPY 0
152 namespace __sanitizer
{
154 void SetSigProcMask(__sanitizer_sigset_t
*set
, __sanitizer_sigset_t
*old
) {
155 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK
, set
, old
));
158 ScopedBlockSignals::ScopedBlockSignals(__sanitizer_sigset_t
*copy
) {
159 __sanitizer_sigset_t set
;
160 internal_sigfillset(&set
);
161 # if SANITIZER_LINUX && !SANITIZER_ANDROID
162 // Glibc uses SIGSETXID signal during setuid call. If this signal is blocked
163 // on any thread, setuid call hangs.
164 // See test/sanitizer_common/TestCases/Linux/setuid.c.
165 internal_sigdelset(&set
, 33);
168 // Seccomp-BPF-sandboxed processes rely on SIGSYS to handle trapped syscalls.
169 // If this signal is blocked, such calls cannot be handled and the process may
171 internal_sigdelset(&set
, 31);
173 SetSigProcMask(&set
, &saved_
);
175 internal_memcpy(copy
, &saved_
, sizeof(saved_
));
178 ScopedBlockSignals::~ScopedBlockSignals() { SetSigProcMask(&saved_
, nullptr); }
180 # if SANITIZER_LINUX && defined(__x86_64__)
181 # include "sanitizer_syscall_linux_x86_64.inc"
182 # elif SANITIZER_LINUX && SANITIZER_RISCV64
183 # include "sanitizer_syscall_linux_riscv64.inc"
184 # elif SANITIZER_LINUX && defined(__aarch64__)
185 # include "sanitizer_syscall_linux_aarch64.inc"
186 # elif SANITIZER_LINUX && defined(__arm__)
187 # include "sanitizer_syscall_linux_arm.inc"
188 # elif SANITIZER_LINUX && defined(__hexagon__)
189 # include "sanitizer_syscall_linux_hexagon.inc"
191 # include "sanitizer_syscall_generic.inc"
194 // --------------- sanitizer_libc.h
195 #if !SANITIZER_SOLARIS && !SANITIZER_NETBSD
197 uptr
internal_mmap(void *addr
, uptr length
, int prot
, int flags
, int fd
,
199 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
200 return internal_syscall(SYSCALL(mmap
), (uptr
)addr
, length
, prot
, flags
, fd
,
203 // mmap2 specifies file offset in 4096-byte units.
204 CHECK(IsAligned(offset
, 4096));
205 return internal_syscall(SYSCALL(mmap2
), addr
, length
, prot
, flags
, fd
,
209 #endif // !SANITIZER_S390
211 uptr
internal_munmap(void *addr
, uptr length
) {
212 return internal_syscall(SYSCALL(munmap
), (uptr
)addr
, length
);
216 uptr
internal_mremap(void *old_address
, uptr old_size
, uptr new_size
, int flags
,
218 return internal_syscall(SYSCALL(mremap
), (uptr
)old_address
, old_size
,
219 new_size
, flags
, (uptr
)new_address
);
223 int internal_mprotect(void *addr
, uptr length
, int prot
) {
224 return internal_syscall(SYSCALL(mprotect
), (uptr
)addr
, length
, prot
);
227 int internal_madvise(uptr addr
, uptr length
, int advice
) {
228 return internal_syscall(SYSCALL(madvise
), addr
, length
, advice
);
231 uptr
internal_close(fd_t fd
) {
232 return internal_syscall(SYSCALL(close
), fd
);
235 uptr
internal_open(const char *filename
, int flags
) {
236 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
237 return internal_syscall(SYSCALL(openat
), AT_FDCWD
, (uptr
)filename
, flags
);
239 return internal_syscall(SYSCALL(open
), (uptr
)filename
, flags
);
243 uptr
internal_open(const char *filename
, int flags
, u32 mode
) {
244 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
245 return internal_syscall(SYSCALL(openat
), AT_FDCWD
, (uptr
)filename
, flags
,
248 return internal_syscall(SYSCALL(open
), (uptr
)filename
, flags
, mode
);
252 uptr
internal_read(fd_t fd
, void *buf
, uptr count
) {
255 (sptr
)internal_syscall(SYSCALL(read
), fd
, (uptr
)buf
, count
));
259 uptr
internal_write(fd_t fd
, const void *buf
, uptr count
) {
262 (sptr
)internal_syscall(SYSCALL(write
), fd
, (uptr
)buf
, count
));
266 uptr
internal_ftruncate(fd_t fd
, uptr size
) {
268 HANDLE_EINTR(res
, (sptr
)internal_syscall(SYSCALL(ftruncate
), fd
,
273 #if !SANITIZER_LINUX_USES_64BIT_SYSCALLS && SANITIZER_LINUX
274 static void stat64_to_stat(struct stat64
*in
, struct stat
*out
) {
275 internal_memset(out
, 0, sizeof(*out
));
276 out
->st_dev
= in
->st_dev
;
277 out
->st_ino
= in
->st_ino
;
278 out
->st_mode
= in
->st_mode
;
279 out
->st_nlink
= in
->st_nlink
;
280 out
->st_uid
= in
->st_uid
;
281 out
->st_gid
= in
->st_gid
;
282 out
->st_rdev
= in
->st_rdev
;
283 out
->st_size
= in
->st_size
;
284 out
->st_blksize
= in
->st_blksize
;
285 out
->st_blocks
= in
->st_blocks
;
286 out
->st_atime
= in
->st_atime
;
287 out
->st_mtime
= in
->st_mtime
;
288 out
->st_ctime
= in
->st_ctime
;
292 #if defined(__mips64)
293 // Undefine compatibility macros from <sys/stat.h>
294 // so that they would not clash with the kernel_stat
295 // st_[a|m|c]time fields
301 #if defined(SANITIZER_ANDROID)
302 // Bionic sys/stat.h defines additional macros
303 // for compatibility with the old NDKs and
304 // they clash with the kernel_stat structure
305 // st_[a|m|c]time_nsec fields.
310 static void kernel_stat_to_stat(struct kernel_stat
*in
, struct stat
*out
) {
311 internal_memset(out
, 0, sizeof(*out
));
312 out
->st_dev
= in
->st_dev
;
313 out
->st_ino
= in
->st_ino
;
314 out
->st_mode
= in
->st_mode
;
315 out
->st_nlink
= in
->st_nlink
;
316 out
->st_uid
= in
->st_uid
;
317 out
->st_gid
= in
->st_gid
;
318 out
->st_rdev
= in
->st_rdev
;
319 out
->st_size
= in
->st_size
;
320 out
->st_blksize
= in
->st_blksize
;
321 out
->st_blocks
= in
->st_blocks
;
322 #if defined(__USE_MISC) || \
323 defined(__USE_XOPEN2K8) || \
324 defined(SANITIZER_ANDROID)
325 out
->st_atim
.tv_sec
= in
->st_atime
;
326 out
->st_atim
.tv_nsec
= in
->st_atime_nsec
;
327 out
->st_mtim
.tv_sec
= in
->st_mtime
;
328 out
->st_mtim
.tv_nsec
= in
->st_mtime_nsec
;
329 out
->st_ctim
.tv_sec
= in
->st_ctime
;
330 out
->st_ctim
.tv_nsec
= in
->st_ctime_nsec
;
332 out
->st_atime
= in
->st_atime
;
333 out
->st_atimensec
= in
->st_atime_nsec
;
334 out
->st_mtime
= in
->st_mtime
;
335 out
->st_mtimensec
= in
->st_mtime_nsec
;
336 out
->st_ctime
= in
->st_ctime
;
337 out
->st_atimensec
= in
->st_ctime_nsec
;
342 uptr
internal_stat(const char *path
, void *buf
) {
343 #if SANITIZER_FREEBSD
344 return internal_syscall(SYSCALL(fstatat
), AT_FDCWD
, (uptr
)path
, (uptr
)buf
, 0);
345 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
346 return internal_syscall(SYSCALL(newfstatat
), AT_FDCWD
, (uptr
)path
, (uptr
)buf
,
348 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
349 # if defined(__mips64)
350 // For mips64, stat syscall fills buffer in the format of kernel_stat
351 struct kernel_stat kbuf
;
352 int res
= internal_syscall(SYSCALL(stat
), path
, &kbuf
);
353 kernel_stat_to_stat(&kbuf
, (struct stat
*)buf
);
356 return internal_syscall(SYSCALL(stat
), (uptr
)path
, (uptr
)buf
);
360 int res
= internal_syscall(SYSCALL(stat64
), path
, &buf64
);
361 stat64_to_stat(&buf64
, (struct stat
*)buf
);
366 uptr
internal_lstat(const char *path
, void *buf
) {
367 #if SANITIZER_FREEBSD
368 return internal_syscall(SYSCALL(fstatat
), AT_FDCWD
, (uptr
)path
, (uptr
)buf
,
369 AT_SYMLINK_NOFOLLOW
);
370 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
371 return internal_syscall(SYSCALL(newfstatat
), AT_FDCWD
, (uptr
)path
, (uptr
)buf
,
372 AT_SYMLINK_NOFOLLOW
);
373 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
374 # if SANITIZER_MIPS64
375 // For mips64, lstat syscall fills buffer in the format of kernel_stat
376 struct kernel_stat kbuf
;
377 int res
= internal_syscall(SYSCALL(lstat
), path
, &kbuf
);
378 kernel_stat_to_stat(&kbuf
, (struct stat
*)buf
);
381 return internal_syscall(SYSCALL(lstat
), (uptr
)path
, (uptr
)buf
);
385 int res
= internal_syscall(SYSCALL(lstat64
), path
, &buf64
);
386 stat64_to_stat(&buf64
, (struct stat
*)buf
);
391 uptr
internal_fstat(fd_t fd
, void *buf
) {
392 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
394 // For mips64, fstat syscall fills buffer in the format of kernel_stat
395 struct kernel_stat kbuf
;
396 int res
= internal_syscall(SYSCALL(fstat
), fd
, &kbuf
);
397 kernel_stat_to_stat(&kbuf
, (struct stat
*)buf
);
400 return internal_syscall(SYSCALL(fstat
), fd
, (uptr
)buf
);
404 int res
= internal_syscall(SYSCALL(fstat64
), fd
, &buf64
);
405 stat64_to_stat(&buf64
, (struct stat
*)buf
);
410 uptr
internal_filesize(fd_t fd
) {
412 if (internal_fstat(fd
, &st
))
414 return (uptr
)st
.st_size
;
417 uptr
internal_dup(int oldfd
) {
418 return internal_syscall(SYSCALL(dup
), oldfd
);
421 uptr
internal_dup2(int oldfd
, int newfd
) {
422 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
423 return internal_syscall(SYSCALL(dup3
), oldfd
, newfd
, 0);
425 return internal_syscall(SYSCALL(dup2
), oldfd
, newfd
);
429 uptr
internal_readlink(const char *path
, char *buf
, uptr bufsize
) {
430 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
431 return internal_syscall(SYSCALL(readlinkat
), AT_FDCWD
, (uptr
)path
, (uptr
)buf
,
434 return internal_syscall(SYSCALL(readlink
), (uptr
)path
, (uptr
)buf
, bufsize
);
438 uptr
internal_unlink(const char *path
) {
439 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
440 return internal_syscall(SYSCALL(unlinkat
), AT_FDCWD
, (uptr
)path
, 0);
442 return internal_syscall(SYSCALL(unlink
), (uptr
)path
);
446 uptr
internal_rename(const char *oldpath
, const char *newpath
) {
447 #if defined(__riscv) && defined(__linux__)
448 return internal_syscall(SYSCALL(renameat2
), AT_FDCWD
, (uptr
)oldpath
, AT_FDCWD
,
450 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
451 return internal_syscall(SYSCALL(renameat
), AT_FDCWD
, (uptr
)oldpath
, AT_FDCWD
,
454 return internal_syscall(SYSCALL(rename
), (uptr
)oldpath
, (uptr
)newpath
);
458 uptr
internal_sched_yield() {
459 return internal_syscall(SYSCALL(sched_yield
));
462 void internal_usleep(u64 useconds
) {
464 ts
.tv_sec
= useconds
/ 1000000;
465 ts
.tv_nsec
= (useconds
% 1000000) * 1000;
466 internal_syscall(SYSCALL(nanosleep
), &ts
, &ts
);
469 uptr
internal_execve(const char *filename
, char *const argv
[],
470 char *const envp
[]) {
471 return internal_syscall(SYSCALL(execve
), (uptr
)filename
, (uptr
)argv
,
474 #endif // !SANITIZER_SOLARIS && !SANITIZER_NETBSD
476 #if !SANITIZER_NETBSD
477 void internal__exit(int exitcode
) {
478 #if SANITIZER_FREEBSD || SANITIZER_SOLARIS
479 internal_syscall(SYSCALL(exit
), exitcode
);
481 internal_syscall(SYSCALL(exit_group
), exitcode
);
483 Die(); // Unreachable.
485 #endif // !SANITIZER_NETBSD
487 // ----------------- sanitizer_common.h
488 bool FileExists(const char *filename
) {
489 if (ShouldMockFailureToOpen(filename
))
492 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
493 if (internal_syscall(SYSCALL(newfstatat
), AT_FDCWD
, filename
, &st
, 0))
495 if (internal_stat(filename
, &st
))
498 // Sanity check: filename is a regular file.
499 return S_ISREG(st
.st_mode
);
502 bool DirExists(const char *path
) {
504 # if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
505 if (internal_syscall(SYSCALL(newfstatat
), AT_FDCWD
, path
, &st
, 0))
507 if (internal_stat(path
, &st
))
510 return S_ISDIR(st
.st_mode
);
513 # if !SANITIZER_NETBSD
515 #if SANITIZER_FREEBSD
519 #elif SANITIZER_SOLARIS
522 return internal_syscall(SYSCALL(gettid
));
526 int TgKill(pid_t pid
, tid_t tid
, int sig
) {
528 return internal_syscall(SYSCALL(tgkill
), pid
, tid
, sig
);
529 #elif SANITIZER_FREEBSD
530 return internal_syscall(SYSCALL(thr_kill2
), pid
, tid
, sig
);
531 #elif SANITIZER_SOLARIS
533 return thr_kill(tid
, sig
);
541 internal_memset(&tv
, 0, sizeof(tv
));
542 internal_syscall(SYSCALL(gettimeofday
), &tv
, 0);
543 return (u64
)tv
.tv_sec
* 1000 * 1000 * 1000 + tv
.tv_usec
* 1000;
545 // Used by real_clock_gettime.
546 uptr
internal_clock_gettime(__sanitizer_clockid_t clk_id
, void *tp
) {
547 return internal_syscall(SYSCALL(clock_gettime
), clk_id
, tp
);
549 #elif !SANITIZER_SOLARIS && !SANITIZER_NETBSD
552 clock_gettime(CLOCK_REALTIME
, &ts
);
553 return (u64
)ts
.tv_sec
* 1000 * 1000 * 1000 + ts
.tv_nsec
;
557 // Like getenv, but reads env directly from /proc (on Linux) or parses the
558 // 'environ' array (on some others) and does not use libc. This function
559 // should be called first inside __asan_init.
560 const char *GetEnv(const char *name
) {
561 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_SOLARIS
562 if (::environ
!= 0) {
563 uptr NameLen
= internal_strlen(name
);
564 for (char **Env
= ::environ
; *Env
!= 0; Env
++) {
565 if (internal_strncmp(*Env
, name
, NameLen
) == 0 && (*Env
)[NameLen
] == '=')
566 return (*Env
) + NameLen
+ 1;
569 return 0; // Not found.
570 #elif SANITIZER_LINUX
571 static char *environ
;
577 if (!ReadFileToBuffer("/proc/self/environ", &environ
, &environ_size
, &len
))
580 if (!environ
|| len
== 0) return nullptr;
581 uptr namelen
= internal_strlen(name
);
582 const char *p
= environ
;
583 while (*p
!= '\0') { // will happen at the \0\0 that terminates the buffer
584 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
586 (char*)internal_memchr(p
, '\0', len
- (p
- environ
));
587 if (!endp
) // this entry isn't NUL terminated
589 else if (!internal_memcmp(p
, name
, namelen
) && p
[namelen
] == '=') // Match.
590 return p
+ namelen
+ 1; // point after =
593 return nullptr; // Not found.
595 #error "Unsupported platform"
599 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD && !SANITIZER_GO
601 SANITIZER_WEAK_ATTRIBUTE
extern void *__libc_stack_end
;
605 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
606 static void ReadNullSepFileToArray(const char *path
, char ***arr
,
611 *arr
= (char **)MmapOrDie(arr_size
* sizeof(char *), "NullSepFileArray");
612 if (!ReadFileToBuffer(path
, &buff
, &buff_size
, &buff_len
, 1024 * 1024)) {
618 for (count
= 1, i
= 1; ; i
++) {
620 if (buff
[i
+1] == 0) break;
621 (*arr
)[count
] = &buff
[i
+1];
622 CHECK_LE(count
, arr_size
- 1); // FIXME: make this more flexible.
626 (*arr
)[count
] = nullptr;
630 static void GetArgsAndEnv(char ***argv
, char ***envp
) {
631 #if SANITIZER_FREEBSD
632 // On FreeBSD, retrieving the argument and environment arrays is done via the
633 // kern.ps_strings sysctl, which returns a pointer to a structure containing
634 // this information. See also <sys/exec.h>.
636 uptr sz
= sizeof(pss
);
637 if (internal_sysctlbyname("kern.ps_strings", &pss
, &sz
, NULL
, 0) == -1) {
638 Printf("sysctl kern.ps_strings failed\n");
641 *argv
= pss
->ps_argvstr
;
642 *envp
= pss
->ps_envstr
;
643 #elif SANITIZER_NETBSD
644 *argv
= __ps_strings
->ps_argvstr
;
645 *envp
= __ps_strings
->ps_envstr
;
646 #else // SANITIZER_FREEBSD
648 if (&__libc_stack_end
) {
649 uptr
* stack_end
= (uptr
*)__libc_stack_end
;
650 // Normally argc can be obtained from *stack_end, however, on ARM glibc's
651 // _start clobbers it:
652 // https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/arm/start.S;hb=refs/heads/release/2.31/master#l75
653 // Do not special-case ARM and infer argc from argv everywhere.
655 while (stack_end
[argc
+ 1]) argc
++;
656 *argv
= (char**)(stack_end
+ 1);
657 *envp
= (char**)(stack_end
+ argc
+ 2);
659 #endif // !SANITIZER_GO
660 static const int kMaxArgv
= 2000, kMaxEnvp
= 2000;
661 ReadNullSepFileToArray("/proc/self/cmdline", argv
, kMaxArgv
);
662 ReadNullSepFileToArray("/proc/self/environ", envp
, kMaxEnvp
);
665 #endif // !SANITIZER_GO
666 #endif // SANITIZER_FREEBSD
671 GetArgsAndEnv(&argv
, &envp
);
675 char **GetEnviron() {
677 GetArgsAndEnv(&argv
, &envp
);
681 #if !SANITIZER_SOLARIS
682 void FutexWait(atomic_uint32_t
*p
, u32 cmp
) {
683 # if SANITIZER_FREEBSD
684 _umtx_op(p
, UMTX_OP_WAIT_UINT
, cmp
, 0, 0);
685 # elif SANITIZER_NETBSD
686 sched_yield(); /* No userspace futex-like synchronization */
688 internal_syscall(SYSCALL(futex
), (uptr
)p
, FUTEX_WAIT_PRIVATE
, cmp
, 0, 0, 0);
692 void FutexWake(atomic_uint32_t
*p
, u32 count
) {
693 # if SANITIZER_FREEBSD
694 _umtx_op(p
, UMTX_OP_WAKE
, count
, 0, 0);
695 # elif SANITIZER_NETBSD
696 /* No userspace futex-like synchronization */
698 internal_syscall(SYSCALL(futex
), (uptr
)p
, FUTEX_WAKE_PRIVATE
, count
, 0, 0, 0);
702 # endif // !SANITIZER_SOLARIS
704 // ----------------- sanitizer_linux.h
705 // The actual size of this structure is specified by d_reclen.
706 // Note that getdents64 uses a different structure format. We only provide the
707 // 32-bit syscall here.
711 struct linux_dirent
{
712 #if SANITIZER_X32 || defined(__aarch64__) || SANITIZER_RISCV64
719 unsigned short d_reclen
;
720 #if defined(__aarch64__) || SANITIZER_RISCV64
721 unsigned char d_type
;
727 #if !SANITIZER_SOLARIS && !SANITIZER_NETBSD
729 uptr
internal_ptrace(int request
, int pid
, void *addr
, void *data
) {
730 return internal_syscall(SYSCALL(ptrace
), request
, pid
, (uptr
)addr
,
734 uptr
internal_waitpid(int pid
, int *status
, int options
) {
735 return internal_syscall(SYSCALL(wait4
), pid
, (uptr
)status
, options
,
739 uptr
internal_getpid() {
740 return internal_syscall(SYSCALL(getpid
));
743 uptr
internal_getppid() {
744 return internal_syscall(SYSCALL(getppid
));
747 int internal_dlinfo(void *handle
, int request
, void *p
) {
748 #if SANITIZER_FREEBSD
749 return dlinfo(handle
, request
, p
);
755 uptr
internal_getdents(fd_t fd
, struct linux_dirent
*dirp
, unsigned int count
) {
756 #if SANITIZER_FREEBSD
757 return internal_syscall(SYSCALL(getdirentries
), fd
, (uptr
)dirp
, count
, NULL
);
758 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
759 return internal_syscall(SYSCALL(getdents64
), fd
, (uptr
)dirp
, count
);
761 return internal_syscall(SYSCALL(getdents
), fd
, (uptr
)dirp
, count
);
765 uptr
internal_lseek(fd_t fd
, OFF_T offset
, int whence
) {
766 return internal_syscall(SYSCALL(lseek
), fd
, offset
, whence
);
770 uptr
internal_prctl(int option
, uptr arg2
, uptr arg3
, uptr arg4
, uptr arg5
) {
771 return internal_syscall(SYSCALL(prctl
), option
, arg2
, arg3
, arg4
, arg5
);
775 uptr
internal_sigaltstack(const void *ss
, void *oss
) {
776 return internal_syscall(SYSCALL(sigaltstack
), (uptr
)ss
, (uptr
)oss
);
779 int internal_fork() {
780 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
781 return internal_syscall(SYSCALL(clone
), SIGCHLD
, 0);
783 return internal_syscall(SYSCALL(fork
));
787 #if SANITIZER_FREEBSD
788 int internal_sysctl(const int *name
, unsigned int namelen
, void *oldp
,
789 uptr
*oldlenp
, const void *newp
, uptr newlen
) {
790 return internal_syscall(SYSCALL(__sysctl
), name
, namelen
, oldp
,
791 (size_t *)oldlenp
, newp
, (size_t)newlen
);
794 int internal_sysctlbyname(const char *sname
, void *oldp
, uptr
*oldlenp
,
795 const void *newp
, uptr newlen
) {
796 // Note: this function can be called during startup, so we need to avoid
797 // calling any interceptable functions. On FreeBSD >= 1300045 sysctlbyname()
798 // is a real syscall, but for older versions it calls sysctlnametomib()
799 // followed by sysctl(). To avoid calling the intercepted version and
800 // asserting if this happens during startup, call the real sysctlnametomib()
801 // followed by internal_sysctl() if the syscall is not available.
802 #ifdef SYS___sysctlbyname
803 return internal_syscall(SYSCALL(__sysctlbyname
), sname
,
804 internal_strlen(sname
), oldp
, (size_t *)oldlenp
, newp
,
807 static decltype(sysctlnametomib
) *real_sysctlnametomib
= nullptr;
808 if (!real_sysctlnametomib
)
809 real_sysctlnametomib
=
810 (decltype(sysctlnametomib
) *)dlsym(RTLD_NEXT
, "sysctlnametomib");
811 CHECK(real_sysctlnametomib
);
813 int oid
[CTL_MAXNAME
];
814 size_t len
= CTL_MAXNAME
;
815 if (real_sysctlnametomib(sname
, oid
, &len
) == -1)
817 return internal_sysctl(oid
, len
, oldp
, oldlenp
, newp
, newlen
);
823 #define SA_RESTORER 0x04000000
824 // Doesn't set sa_restorer if the caller did not set it, so use with caution
826 int internal_sigaction_norestorer(int signum
, const void *act
, void *oldact
) {
827 __sanitizer_kernel_sigaction_t k_act
, k_oldact
;
828 internal_memset(&k_act
, 0, sizeof(__sanitizer_kernel_sigaction_t
));
829 internal_memset(&k_oldact
, 0, sizeof(__sanitizer_kernel_sigaction_t
));
830 const __sanitizer_sigaction
*u_act
= (const __sanitizer_sigaction
*)act
;
831 __sanitizer_sigaction
*u_oldact
= (__sanitizer_sigaction
*)oldact
;
833 k_act
.handler
= u_act
->handler
;
834 k_act
.sigaction
= u_act
->sigaction
;
835 internal_memcpy(&k_act
.sa_mask
, &u_act
->sa_mask
,
836 sizeof(__sanitizer_kernel_sigset_t
));
837 // Without SA_RESTORER kernel ignores the calls (probably returns EINVAL).
838 k_act
.sa_flags
= u_act
->sa_flags
| SA_RESTORER
;
839 // FIXME: most often sa_restorer is unset, however the kernel requires it
840 // to point to a valid signal restorer that calls the rt_sigreturn syscall.
841 // If sa_restorer passed to the kernel is NULL, the program may crash upon
842 // signal delivery or fail to unwind the stack in the signal handler.
843 // libc implementation of sigaction() passes its own restorer to
844 // rt_sigaction, so we need to do the same (we'll need to reimplement the
845 // restorers; for x86_64 the restorer address can be obtained from
846 // oldact->sa_restorer upon a call to sigaction(xxx, NULL, oldact).
847 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
848 k_act
.sa_restorer
= u_act
->sa_restorer
;
852 uptr result
= internal_syscall(SYSCALL(rt_sigaction
), (uptr
)signum
,
853 (uptr
)(u_act
? &k_act
: nullptr),
854 (uptr
)(u_oldact
? &k_oldact
: nullptr),
855 (uptr
)sizeof(__sanitizer_kernel_sigset_t
));
857 if ((result
== 0) && u_oldact
) {
858 u_oldact
->handler
= k_oldact
.handler
;
859 u_oldact
->sigaction
= k_oldact
.sigaction
;
860 internal_memcpy(&u_oldact
->sa_mask
, &k_oldact
.sa_mask
,
861 sizeof(__sanitizer_kernel_sigset_t
));
862 u_oldact
->sa_flags
= k_oldact
.sa_flags
;
863 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
864 u_oldact
->sa_restorer
= k_oldact
.sa_restorer
;
869 #endif // SANITIZER_LINUX
871 uptr
internal_sigprocmask(int how
, __sanitizer_sigset_t
*set
,
872 __sanitizer_sigset_t
*oldset
) {
873 #if SANITIZER_FREEBSD
874 return internal_syscall(SYSCALL(sigprocmask
), how
, set
, oldset
);
876 __sanitizer_kernel_sigset_t
*k_set
= (__sanitizer_kernel_sigset_t
*)set
;
877 __sanitizer_kernel_sigset_t
*k_oldset
= (__sanitizer_kernel_sigset_t
*)oldset
;
878 return internal_syscall(SYSCALL(rt_sigprocmask
), (uptr
)how
, (uptr
)k_set
,
879 (uptr
)k_oldset
, sizeof(__sanitizer_kernel_sigset_t
));
883 void internal_sigfillset(__sanitizer_sigset_t
*set
) {
884 internal_memset(set
, 0xff, sizeof(*set
));
887 void internal_sigemptyset(__sanitizer_sigset_t
*set
) {
888 internal_memset(set
, 0, sizeof(*set
));
892 void internal_sigdelset(__sanitizer_sigset_t
*set
, int signum
) {
895 CHECK_LT(signum
, sizeof(*set
) * 8);
896 __sanitizer_kernel_sigset_t
*k_set
= (__sanitizer_kernel_sigset_t
*)set
;
897 const uptr idx
= signum
/ (sizeof(k_set
->sig
[0]) * 8);
898 const uptr bit
= signum
% (sizeof(k_set
->sig
[0]) * 8);
899 k_set
->sig
[idx
] &= ~((uptr
)1 << bit
);
902 bool internal_sigismember(__sanitizer_sigset_t
*set
, int signum
) {
905 CHECK_LT(signum
, sizeof(*set
) * 8);
906 __sanitizer_kernel_sigset_t
*k_set
= (__sanitizer_kernel_sigset_t
*)set
;
907 const uptr idx
= signum
/ (sizeof(k_set
->sig
[0]) * 8);
908 const uptr bit
= signum
% (sizeof(k_set
->sig
[0]) * 8);
909 return k_set
->sig
[idx
] & ((uptr
)1 << bit
);
911 #elif SANITIZER_FREEBSD
912 void internal_sigdelset(__sanitizer_sigset_t
*set
, int signum
) {
913 sigset_t
*rset
= reinterpret_cast<sigset_t
*>(set
);
914 sigdelset(rset
, signum
);
917 bool internal_sigismember(__sanitizer_sigset_t
*set
, int signum
) {
918 sigset_t
*rset
= reinterpret_cast<sigset_t
*>(set
);
919 return sigismember(rset
, signum
);
922 #endif // !SANITIZER_SOLARIS
924 #if !SANITIZER_NETBSD
925 // ThreadLister implementation.
926 ThreadLister::ThreadLister(pid_t pid
) : pid_(pid
), buffer_(4096) {
927 char task_directory_path
[80];
928 internal_snprintf(task_directory_path
, sizeof(task_directory_path
),
929 "/proc/%d/task/", pid
);
930 descriptor_
= internal_open(task_directory_path
, O_RDONLY
| O_DIRECTORY
);
931 if (internal_iserror(descriptor_
)) {
932 Report("Can't open /proc/%d/task for reading.\n", pid
);
936 ThreadLister::Result
ThreadLister::ListThreads(
937 InternalMmapVector
<tid_t
> *threads
) {
938 if (internal_iserror(descriptor_
))
940 internal_lseek(descriptor_
, 0, SEEK_SET
);
944 for (bool first_read
= true;; first_read
= false) {
945 // Resize to max capacity if it was downsized by IsAlive.
946 buffer_
.resize(buffer_
.capacity());
947 CHECK_GE(buffer_
.size(), 4096);
948 uptr read
= internal_getdents(
949 descriptor_
, (struct linux_dirent
*)buffer_
.data(), buffer_
.size());
952 if (internal_iserror(read
)) {
953 Report("Can't read directory entries from /proc/%d/task.\n", pid_
);
957 for (uptr begin
= (uptr
)buffer_
.data(), end
= begin
+ read
; begin
< end
;) {
958 struct linux_dirent
*entry
= (struct linux_dirent
*)begin
;
959 begin
+= entry
->d_reclen
;
960 if (entry
->d_ino
== 1) {
961 // Inode 1 is for bad blocks and also can be a reason for early return.
962 // Should be emitted if kernel tried to output terminating thread.
963 // See proc_task_readdir implementation in Linux.
966 if (entry
->d_ino
&& *entry
->d_name
>= '0' && *entry
->d_name
<= '9')
967 threads
->push_back(internal_atoll(entry
->d_name
));
970 // Now we are going to detect short-read or early EOF. In such cases Linux
971 // can return inconsistent list with missing alive threads.
972 // Code will just remember that the list can be incomplete but it will
973 // continue reads to return as much as possible.
975 // The first one was a short-read by definition.
977 } else if (read
> buffer_
.size() - 1024) {
978 // Read was close to the buffer size. So double the size and assume the
980 buffer_
.resize(buffer_
.size() * 2);
982 } else if (!threads
->empty() && !IsAlive(threads
->back())) {
983 // Maybe Linux early returned from read on terminated thread (!pid_alive)
984 // and failed to restore read position.
985 // See next_tid and proc_task_instantiate in Linux.
991 bool ThreadLister::IsAlive(int tid
) {
992 // /proc/%d/task/%d/status uses same call to detect alive threads as
993 // proc_task_readdir. See task_state implementation in Linux.
995 internal_snprintf(path
, sizeof(path
), "/proc/%d/task/%d/status", pid_
, tid
);
996 if (!ReadFileToVector(path
, &buffer_
) || buffer_
.empty())
998 buffer_
.push_back(0);
999 static const char kPrefix
[] = "\nPPid:";
1000 const char *field
= internal_strstr(buffer_
.data(), kPrefix
);
1003 field
+= internal_strlen(kPrefix
);
1004 return (int)internal_atoll(field
) != 0;
1007 ThreadLister::~ThreadLister() {
1008 if (!internal_iserror(descriptor_
))
1009 internal_close(descriptor_
);
1013 #if SANITIZER_WORDSIZE == 32
1014 // Take care of unusable kernel area in top gigabyte.
1015 static uptr
GetKernelAreaSize() {
1016 #if SANITIZER_LINUX && !SANITIZER_X32
1017 const uptr gbyte
= 1UL << 30;
1019 // Firstly check if there are writable segments
1020 // mapped to top gigabyte (e.g. stack).
1021 MemoryMappingLayout
proc_maps(/*cache_enabled*/true);
1022 if (proc_maps
.Error())
1024 MemoryMappedSegment segment
;
1025 while (proc_maps
.Next(&segment
)) {
1026 if ((segment
.end
>= 3 * gbyte
) && segment
.IsWritable()) return 0;
1029 #if !SANITIZER_ANDROID
1030 // Even if nothing is mapped, top Gb may still be accessible
1031 // if we are running on 64-bit kernel.
1032 // Uname may report misleading results if personality type
1033 // is modified (e.g. under schroot) so check this as well.
1034 struct utsname uname_info
;
1035 int pers
= personality(0xffffffffUL
);
1036 if (!(pers
& PER_MASK
) && internal_uname(&uname_info
) == 0 &&
1037 internal_strstr(uname_info
.machine
, "64"))
1039 #endif // SANITIZER_ANDROID
1041 // Top gigabyte is reserved for kernel.
1045 #endif // SANITIZER_LINUX && !SANITIZER_X32
1047 #endif // SANITIZER_WORDSIZE == 32
1049 uptr
GetMaxVirtualAddress() {
1050 #if SANITIZER_NETBSD && defined(__x86_64__)
1051 return 0x7f7ffffff000ULL
; // (0x00007f8000000000 - PAGE_SIZE)
1052 #elif SANITIZER_WORDSIZE == 64
1053 # if defined(__powerpc64__) || defined(__aarch64__)
1054 // On PowerPC64 we have two different address space layouts: 44- and 46-bit.
1055 // We somehow need to figure out which one we are using now and choose
1056 // one of 0x00000fffffffffffUL and 0x00003fffffffffffUL.
1057 // Note that with 'ulimit -s unlimited' the stack is moved away from the top
1058 // of the address space, so simply checking the stack address is not enough.
1059 // This should (does) work for both PowerPC64 Endian modes.
1060 // Similarly, aarch64 has multiple address space layouts: 39, 42 and 47-bit.
1061 return (1ULL << (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1)) - 1;
1062 #elif SANITIZER_RISCV64
1063 return (1ULL << 38) - 1;
1064 # elif defined(__mips64)
1065 return (1ULL << 40) - 1; // 0x000000ffffffffffUL;
1066 # elif defined(__s390x__)
1067 return (1ULL << 53) - 1; // 0x001fffffffffffffUL;
1068 #elif defined(__sparc__)
1071 return (1ULL << 47) - 1; // 0x00007fffffffffffUL;
1073 #else // SANITIZER_WORDSIZE == 32
1074 # if defined(__s390__)
1075 return (1ULL << 31) - 1; // 0x7fffffff;
1077 return (1ULL << 32) - 1; // 0xffffffff;
1079 #endif // SANITIZER_WORDSIZE
1082 uptr
GetMaxUserVirtualAddress() {
1083 uptr addr
= GetMaxVirtualAddress();
1084 #if SANITIZER_WORDSIZE == 32 && !defined(__s390__)
1085 if (!common_flags()->full_address_space
)
1086 addr
-= GetKernelAreaSize();
1087 CHECK_LT(reinterpret_cast<uptr
>(&addr
), addr
);
1092 #if !SANITIZER_ANDROID
1093 uptr
GetPageSize() {
1094 #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__)) && \
1095 defined(EXEC_PAGESIZE)
1096 return EXEC_PAGESIZE
;
1097 #elif SANITIZER_FREEBSD || SANITIZER_NETBSD
1098 // Use sysctl as sysconf can trigger interceptors internally.
1100 uptr pzl
= sizeof(pz
);
1101 int mib
[2] = {CTL_HW
, HW_PAGESIZE
};
1102 int rv
= internal_sysctl(mib
, 2, &pz
, &pzl
, nullptr, 0);
1105 #elif SANITIZER_USE_GETAUXVAL
1106 return getauxval(AT_PAGESZ
);
1108 return sysconf(_SC_PAGESIZE
); // EXEC_PAGESIZE may not be trustworthy.
1111 #endif // !SANITIZER_ANDROID
1113 uptr
ReadBinaryName(/*out*/char *buf
, uptr buf_len
) {
1114 #if SANITIZER_SOLARIS
1115 const char *default_module_name
= getexecname();
1116 CHECK_NE(default_module_name
, NULL
);
1117 return internal_snprintf(buf
, buf_len
, "%s", default_module_name
);
1119 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
1120 #if SANITIZER_FREEBSD
1121 const int Mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PATHNAME
, -1};
1123 const int Mib
[4] = {CTL_KERN
, KERN_PROC_ARGS
, -1, KERN_PROC_PATHNAME
};
1125 const char *default_module_name
= "kern.proc.pathname";
1126 uptr Size
= buf_len
;
1128 (internal_sysctl(Mib
, ARRAY_SIZE(Mib
), buf
, &Size
, NULL
, 0) != 0);
1129 int readlink_error
= IsErr
? errno
: 0;
1130 uptr module_name_len
= Size
;
1132 const char *default_module_name
= "/proc/self/exe";
1133 uptr module_name_len
= internal_readlink(
1134 default_module_name
, buf
, buf_len
);
1136 bool IsErr
= internal_iserror(module_name_len
, &readlink_error
);
1137 #endif // SANITIZER_SOLARIS
1139 // We can't read binary name for some reason, assume it's unknown.
1140 Report("WARNING: reading executable name failed with errno %d, "
1141 "some stack frames may not be symbolized\n", readlink_error
);
1142 module_name_len
= internal_snprintf(buf
, buf_len
, "%s",
1143 default_module_name
);
1144 CHECK_LT(module_name_len
, buf_len
);
1146 return module_name_len
;
1150 uptr
ReadLongProcessName(/*out*/ char *buf
, uptr buf_len
) {
1155 if (ReadFileToBuffer("/proc/self/cmdline", &tmpbuf
, &tmpsize
, &tmplen
,
1157 internal_strncpy(buf
, tmpbuf
, buf_len
);
1158 UnmapOrDie(tmpbuf
, tmpsize
);
1159 return internal_strlen(buf
);
1162 return ReadBinaryName(buf
, buf_len
);
1165 // Match full names of the form /path/to/base_name{-,.}*
1166 bool LibraryNameIs(const char *full_name
, const char *base_name
) {
1167 const char *name
= full_name
;
1169 while (*name
!= '\0') name
++;
1170 while (name
> full_name
&& *name
!= '/') name
--;
1171 if (*name
== '/') name
++;
1172 uptr base_name_length
= internal_strlen(base_name
);
1173 if (internal_strncmp(name
, base_name
, base_name_length
)) return false;
1174 return (name
[base_name_length
] == '-' || name
[base_name_length
] == '.');
1177 #if !SANITIZER_ANDROID
1178 // Call cb for each region mapped by map.
1179 void ForEachMappedRegion(link_map
*map
, void (*cb
)(const void *, uptr
)) {
1180 CHECK_NE(map
, nullptr);
1181 #if !SANITIZER_FREEBSD
1182 typedef ElfW(Phdr
) Elf_Phdr
;
1183 typedef ElfW(Ehdr
) Elf_Ehdr
;
1184 #endif // !SANITIZER_FREEBSD
1185 char *base
= (char *)map
->l_addr
;
1186 Elf_Ehdr
*ehdr
= (Elf_Ehdr
*)base
;
1187 char *phdrs
= base
+ ehdr
->e_phoff
;
1188 char *phdrs_end
= phdrs
+ ehdr
->e_phnum
* ehdr
->e_phentsize
;
1190 // Find the segment with the minimum base so we can "relocate" the p_vaddr
1191 // fields. Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
1192 // objects have a non-zero base.
1193 uptr preferred_base
= (uptr
)-1;
1194 for (char *iter
= phdrs
; iter
!= phdrs_end
; iter
+= ehdr
->e_phentsize
) {
1195 Elf_Phdr
*phdr
= (Elf_Phdr
*)iter
;
1196 if (phdr
->p_type
== PT_LOAD
&& preferred_base
> (uptr
)phdr
->p_vaddr
)
1197 preferred_base
= (uptr
)phdr
->p_vaddr
;
1200 // Compute the delta from the real base to get a relocation delta.
1201 sptr delta
= (uptr
)base
- preferred_base
;
1202 // Now we can figure out what the loader really mapped.
1203 for (char *iter
= phdrs
; iter
!= phdrs_end
; iter
+= ehdr
->e_phentsize
) {
1204 Elf_Phdr
*phdr
= (Elf_Phdr
*)iter
;
1205 if (phdr
->p_type
== PT_LOAD
) {
1206 uptr seg_start
= phdr
->p_vaddr
+ delta
;
1207 uptr seg_end
= seg_start
+ phdr
->p_memsz
;
1208 // None of these values are aligned. We consider the ragged edges of the
1209 // load command as defined, since they are mapped from the file.
1210 seg_start
= RoundDownTo(seg_start
, GetPageSizeCached());
1211 seg_end
= RoundUpTo(seg_end
, GetPageSizeCached());
1212 cb((void *)seg_start
, seg_end
- seg_start
);
1219 #if defined(__x86_64__)
1220 // We cannot use glibc's clone wrapper, because it messes with the child
1221 // task's TLS. It writes the PID and TID of the child task to its thread
1222 // descriptor, but in our case the child task shares the thread descriptor with
1223 // the parent (because we don't know how to allocate a new thread
1224 // descriptor to keep glibc happy). So the stock version of clone(), when
1225 // used with CLONE_VM, would end up corrupting the parent's thread descriptor.
1226 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1227 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1229 if (!fn
|| !child_stack
)
1231 CHECK_EQ(0, (uptr
)child_stack
% 16);
1232 child_stack
= (char *)child_stack
- 2 * sizeof(unsigned long long);
1233 ((unsigned long long *)child_stack
)[0] = (uptr
)fn
;
1234 ((unsigned long long *)child_stack
)[1] = (uptr
)arg
;
1235 register void *r8
__asm__("r8") = newtls
;
1236 register int *r10
__asm__("r10") = child_tidptr
;
1237 __asm__
__volatile__(
1238 /* %rax = syscall(%rax = SYSCALL(clone),
1240 * %rsi = child_stack,
1241 * %rdx = parent_tidptr,
1243 * %r10 = child_tidptr)
1250 "testq %%rax,%%rax\n"
1253 /* In the child. Terminate unwind chain. */
1254 // XXX: We should also terminate the CFI unwind chain
1255 // here. Unfortunately clang 3.2 doesn't support the
1256 // necessary CFI directives, so we skip that part.
1257 "xorq %%rbp,%%rbp\n"
1259 /* Call "fn(arg)". */
1264 /* Call _exit(%rax). */
1265 "movq %%rax,%%rdi\n"
1269 /* Return to parent. */
1272 : "a"(SYSCALL(clone
)), "i"(SYSCALL(exit
)),
1278 : "memory", "r11", "rcx");
1281 #elif defined(__mips__)
1282 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1283 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1285 if (!fn
|| !child_stack
)
1287 CHECK_EQ(0, (uptr
)child_stack
% 16);
1288 child_stack
= (char *)child_stack
- 2 * sizeof(unsigned long long);
1289 ((unsigned long long *)child_stack
)[0] = (uptr
)fn
;
1290 ((unsigned long long *)child_stack
)[1] = (uptr
)arg
;
1291 register void *a3
__asm__("$7") = newtls
;
1292 register int *a4
__asm__("$8") = child_tidptr
;
1293 // We don't have proper CFI directives here because it requires alot of code
1294 // for very marginal benefits.
1295 __asm__
__volatile__(
1296 /* $v0 = syscall($v0 = __NR_clone,
1298 * $a1 = child_stack,
1299 * $a2 = parent_tidptr,
1301 * $a4 = child_tidptr)
1308 /* Store the fifth argument on stack
1309 * if we are using 32-bit abi.
1311 #if SANITIZER_WORDSIZE == 32
1324 /* Call "fn(arg)". */
1325 #if SANITIZER_WORDSIZE == 32
1326 #ifdef __BIG_ENDIAN__
1339 /* Call _exit($v0). */
1344 /* Return to parent. */
1354 : "memory", "$29" );
1357 #elif SANITIZER_RISCV64
1358 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1359 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1360 if (!fn
|| !child_stack
)
1363 CHECK_EQ(0, (uptr
)child_stack
% 16);
1365 register int res
__asm__("a0");
1366 register int __flags
__asm__("a0") = flags
;
1367 register void *__stack
__asm__("a1") = child_stack
;
1368 register int *__ptid
__asm__("a2") = parent_tidptr
;
1369 register void *__tls
__asm__("a3") = newtls
;
1370 register int *__ctid
__asm__("a4") = child_tidptr
;
1371 register int (*__fn
)(void *) __asm__("a5") = fn
;
1372 register void *__arg
__asm__("a6") = arg
;
1373 register int nr_clone
__asm__("a7") = __NR_clone
;
1375 __asm__
__volatile__(
1383 // In the child, now. Call "fn(arg)".
1388 "addi a7, zero, %9\n"
1393 : "0"(__flags
), "r"(__stack
), "r"(__ptid
), "r"(__tls
), "r"(__ctid
),
1394 "r"(__fn
), "r"(__arg
), "r"(nr_clone
), "i"(__NR_exit
)
1398 #elif defined(__aarch64__)
1399 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1400 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1401 register long long res
__asm__("x0");
1402 if (!fn
|| !child_stack
)
1404 CHECK_EQ(0, (uptr
)child_stack
% 16);
1405 child_stack
= (char *)child_stack
- 2 * sizeof(unsigned long long);
1406 ((unsigned long long *)child_stack
)[0] = (uptr
)fn
;
1407 ((unsigned long long *)child_stack
)[1] = (uptr
)arg
;
1409 register int (*__fn
)(void *) __asm__("x0") = fn
;
1410 register void *__stack
__asm__("x1") = child_stack
;
1411 register int __flags
__asm__("x2") = flags
;
1412 register void *__arg
__asm__("x3") = arg
;
1413 register int *__ptid
__asm__("x4") = parent_tidptr
;
1414 register void *__tls
__asm__("x5") = newtls
;
1415 register int *__ctid
__asm__("x6") = child_tidptr
;
1417 __asm__
__volatile__(
1418 "mov x0,x2\n" /* flags */
1419 "mov x2,x4\n" /* ptid */
1420 "mov x3,x5\n" /* tls */
1421 "mov x4,x6\n" /* ctid */
1422 "mov x8,%9\n" /* clone */
1432 /* In the child, now. Call "fn(arg)". */
1433 "ldp x1, x0, [sp], #16\n"
1436 /* Call _exit(%r0). */
1443 "r"(__fn
), "r"(__stack
), "r"(__flags
), "r"(__arg
),
1444 "r"(__ptid
), "r"(__tls
), "r"(__ctid
),
1445 "i"(__NR_clone
), "i"(__NR_exit
)
1449 #elif defined(__powerpc64__)
1450 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1451 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1453 // Stack frame structure.
1454 #if SANITIZER_PPC64V1
1455 // Back chain == 0 (SP + 112)
1456 // Frame (112 bytes):
1457 // Parameter save area (SP + 48), 8 doublewords
1458 // TOC save area (SP + 40)
1459 // Link editor doubleword (SP + 32)
1460 // Compiler doubleword (SP + 24)
1461 // LR save area (SP + 16)
1462 // CR save area (SP + 8)
1463 // Back chain (SP + 0)
1464 # define FRAME_SIZE 112
1465 # define FRAME_TOC_SAVE_OFFSET 40
1466 #elif SANITIZER_PPC64V2
1467 // Back chain == 0 (SP + 32)
1468 // Frame (32 bytes):
1469 // TOC save area (SP + 24)
1470 // LR save area (SP + 16)
1471 // CR save area (SP + 8)
1472 // Back chain (SP + 0)
1473 # define FRAME_SIZE 32
1474 # define FRAME_TOC_SAVE_OFFSET 24
1476 # error "Unsupported PPC64 ABI"
1478 if (!fn
|| !child_stack
)
1480 CHECK_EQ(0, (uptr
)child_stack
% 16);
1482 register int (*__fn
)(void *) __asm__("r3") = fn
;
1483 register void *__cstack
__asm__("r4") = child_stack
;
1484 register int __flags
__asm__("r5") = flags
;
1485 register void *__arg
__asm__("r6") = arg
;
1486 register int *__ptidptr
__asm__("r7") = parent_tidptr
;
1487 register void *__newtls
__asm__("r8") = newtls
;
1488 register int *__ctidptr
__asm__("r9") = child_tidptr
;
1490 __asm__
__volatile__(
1491 /* fn and arg are saved across the syscall */
1501 r7 == child_tidptr */
1509 /* Test if syscall was successful */
1510 "cmpdi cr1, 3, 0\n\t"
1511 "crandc cr1*4+eq, cr1*4+eq, cr0*4+so\n\t"
1514 /* Set up stack frame */
1516 "stdu 29, -8(1)\n\t"
1517 "stdu 1, -%12(1)\n\t"
1518 /* Do the function call */
1520 #if SANITIZER_PPC64V1
1524 #elif SANITIZER_PPC64V2
1528 # error "Unsupported PPC64 ABI"
1534 /* Call _exit(r3) */
1538 /* Return to parent */
1554 "i" (FRAME_TOC_SAVE_OFFSET
)
1555 : "cr0", "cr1", "memory", "ctr", "r0", "r27", "r28", "r29");
1558 #elif defined(__i386__)
1559 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1560 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1562 if (!fn
|| !child_stack
)
1564 CHECK_EQ(0, (uptr
)child_stack
% 16);
1565 child_stack
= (char *)child_stack
- 7 * sizeof(unsigned int);
1566 ((unsigned int *)child_stack
)[0] = (uptr
)flags
;
1567 ((unsigned int *)child_stack
)[1] = (uptr
)0;
1568 ((unsigned int *)child_stack
)[2] = (uptr
)fn
;
1569 ((unsigned int *)child_stack
)[3] = (uptr
)arg
;
1570 __asm__
__volatile__(
1571 /* %eax = syscall(%eax = SYSCALL(clone),
1573 * %ecx = child_stack,
1574 * %edx = parent_tidptr,
1576 * %edi = child_tidptr)
1580 "movl (%%ecx), %%ebx\n"
1581 /* Do the system call */
1585 /* Remember the flag value. */
1586 "movl %%ebx, (%%ecx)\n"
1596 "test %%eax,%%eax\n"
1599 /* terminate the stack frame */
1600 "xorl %%ebp,%%ebp\n"
1607 "addl $_GLOBAL_OFFSET_TABLE_+[.-here], %%ebx\n"
1610 "movl %%eax, %%ebx\n"
1615 : "a"(SYSCALL(clone
)), "i"(SYSCALL(exit
)),
1623 #elif defined(__arm__)
1624 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1625 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1627 if (!fn
|| !child_stack
)
1629 child_stack
= (char *)child_stack
- 2 * sizeof(unsigned int);
1630 ((unsigned int *)child_stack
)[0] = (uptr
)fn
;
1631 ((unsigned int *)child_stack
)[1] = (uptr
)arg
;
1632 register int r0
__asm__("r0") = flags
;
1633 register void *r1
__asm__("r1") = child_stack
;
1634 register int *r2
__asm__("r2") = parent_tidptr
;
1635 register void *r3
__asm__("r3") = newtls
;
1636 register int *r4
__asm__("r4") = child_tidptr
;
1637 register int r7
__asm__("r7") = __NR_clone
;
1639 #if __ARM_ARCH > 4 || defined (__ARM_ARCH_4T__)
1640 # define ARCH_HAS_BX
1643 # define ARCH_HAS_BLX
1647 # ifdef ARCH_HAS_BLX
1648 # define BLX(R) "blx " #R "\n"
1650 # define BLX(R) "mov lr, pc; bx " #R "\n"
1653 # define BLX(R) "mov lr, pc; mov pc," #R "\n"
1656 __asm__
__volatile__(
1657 /* %r0 = syscall(%r7 = SYSCALL(clone),
1659 * %r1 = child_stack,
1660 * %r2 = parent_tidptr,
1662 * %r4 = child_tidptr)
1665 /* Do the system call */
1674 /* In the child, now. Call "fn(arg)". */
1675 "ldr r0, [sp, #4]\n"
1676 "ldr ip, [sp], #8\n"
1678 /* Call _exit(%r0). */
1684 : "r"(r0
), "r"(r1
), "r"(r2
), "r"(r3
), "r"(r4
), "r"(r7
),
1690 #endif // SANITIZER_LINUX
1693 int internal_uname(struct utsname
*buf
) {
1694 return internal_syscall(SYSCALL(uname
), buf
);
1698 #if SANITIZER_ANDROID
1699 #if __ANDROID_API__ < 21
1700 extern "C" __attribute__((weak
)) int dl_iterate_phdr(
1701 int (*)(struct dl_phdr_info
*, size_t, void *), void *);
1704 static int dl_iterate_phdr_test_cb(struct dl_phdr_info
*info
, size_t size
,
1706 // Any name starting with "lib" indicates a bug in L where library base names
1707 // are returned instead of paths.
1708 if (info
->dlpi_name
&& info
->dlpi_name
[0] == 'l' &&
1709 info
->dlpi_name
[1] == 'i' && info
->dlpi_name
[2] == 'b') {
1710 *(bool *)data
= true;
1716 static atomic_uint32_t android_api_level
;
1718 static AndroidApiLevel
AndroidDetectApiLevelStatic() {
1719 #if __ANDROID_API__ <= 19
1720 return ANDROID_KITKAT
;
1721 #elif __ANDROID_API__ <= 22
1722 return ANDROID_LOLLIPOP_MR1
;
1724 return ANDROID_POST_LOLLIPOP
;
1728 static AndroidApiLevel
AndroidDetectApiLevel() {
1729 if (!&dl_iterate_phdr
)
1730 return ANDROID_KITKAT
; // K or lower
1731 bool base_name_seen
= false;
1732 dl_iterate_phdr(dl_iterate_phdr_test_cb
, &base_name_seen
);
1734 return ANDROID_LOLLIPOP_MR1
; // L MR1
1735 return ANDROID_POST_LOLLIPOP
; // post-L
1736 // Plain L (API level 21) is completely broken wrt ASan and not very
1737 // interesting to detect.
1740 extern "C" __attribute__((weak
)) void* _DYNAMIC
;
1742 AndroidApiLevel
AndroidGetApiLevel() {
1743 AndroidApiLevel level
=
1744 (AndroidApiLevel
)atomic_load(&android_api_level
, memory_order_relaxed
);
1745 if (level
) return level
;
1746 level
= &_DYNAMIC
== nullptr ? AndroidDetectApiLevelStatic()
1747 : AndroidDetectApiLevel();
1748 atomic_store(&android_api_level
, level
, memory_order_relaxed
);
1754 static HandleSignalMode
GetHandleSignalModeImpl(int signum
) {
1757 return common_flags()->handle_abort
;
1759 return common_flags()->handle_sigill
;
1761 return common_flags()->handle_sigtrap
;
1763 return common_flags()->handle_sigfpe
;
1765 return common_flags()->handle_segv
;
1767 return common_flags()->handle_sigbus
;
1769 return kHandleSignalNo
;
1772 HandleSignalMode
GetHandleSignalMode(int signum
) {
1773 HandleSignalMode result
= GetHandleSignalModeImpl(signum
);
1774 if (result
== kHandleSignalYes
&& !common_flags()->allow_user_segv_handler
)
1775 return kHandleSignalExclusive
;
1780 void *internal_start_thread(void *(*func
)(void *arg
), void *arg
) {
1781 if (&real_pthread_create
== 0)
1783 // Start the thread with signals blocked, otherwise it can steal user signals.
1784 ScopedBlockSignals
block(nullptr);
1786 real_pthread_create(&th
, nullptr, func
, arg
);
1790 void internal_join_thread(void *th
) {
1791 if (&real_pthread_join
)
1792 real_pthread_join(th
, nullptr);
1795 void *internal_start_thread(void *(*func
)(void *), void *arg
) { return 0; }
1797 void internal_join_thread(void *th
) {}
1800 #if defined(__aarch64__)
1801 // Android headers in the older NDK releases miss this definition.
1802 struct __sanitizer_esr_context
{
1803 struct _aarch64_ctx head
;
1807 static bool Aarch64GetESR(ucontext_t
*ucontext
, u64
*esr
) {
1808 static const u32 kEsrMagic
= 0x45535201;
1809 u8
*aux
= reinterpret_cast<u8
*>(ucontext
->uc_mcontext
.__reserved
);
1811 _aarch64_ctx
*ctx
= (_aarch64_ctx
*)aux
;
1812 if (ctx
->size
== 0) break;
1813 if (ctx
->magic
== kEsrMagic
) {
1814 *esr
= ((__sanitizer_esr_context
*)ctx
)->esr
;
1823 using Context
= ucontext_t
;
1825 SignalContext::WriteFlag
SignalContext::GetWriteFlag() const {
1826 Context
*ucontext
= (Context
*)context
;
1827 #if defined(__x86_64__) || defined(__i386__)
1828 static const uptr PF_WRITE
= 1U << 1;
1829 #if SANITIZER_FREEBSD
1830 uptr err
= ucontext
->uc_mcontext
.mc_err
;
1831 #elif SANITIZER_NETBSD
1832 uptr err
= ucontext
->uc_mcontext
.__gregs
[_REG_ERR
];
1833 #elif SANITIZER_SOLARIS && defined(__i386__)
1835 uptr err
= ucontext
->uc_mcontext
.gregs
[Err
];
1837 uptr err
= ucontext
->uc_mcontext
.gregs
[REG_ERR
];
1838 #endif // SANITIZER_FREEBSD
1839 return err
& PF_WRITE
? Write
: Read
;
1840 #elif defined(__mips__)
1841 uint32_t *exception_source
;
1842 uint32_t faulty_instruction
;
1845 exception_source
= (uint32_t *)ucontext
->uc_mcontext
.pc
;
1846 faulty_instruction
= (uint32_t)(*exception_source
);
1848 op_code
= (faulty_instruction
>> 26) & 0x3f;
1850 // FIXME: Add support for FPU, microMIPS, DSP, MSA memory instructions.
1856 #if __mips_isa_rev < 6
1862 return SignalContext::Write
;
1871 #if __mips_isa_rev < 6
1877 return SignalContext::Read
;
1878 #if __mips_isa_rev == 6
1880 op_code
= (faulty_instruction
>> 19) & 0x3;
1884 return SignalContext::Read
;
1888 return SignalContext::Unknown
;
1889 #elif defined(__arm__)
1890 static const uptr FSR_WRITE
= 1U << 11;
1891 uptr fsr
= ucontext
->uc_mcontext
.error_code
;
1892 return fsr
& FSR_WRITE
? Write
: Read
;
1893 #elif defined(__aarch64__)
1894 static const u64 ESR_ELx_WNR
= 1U << 6;
1896 if (!Aarch64GetESR(ucontext
, &esr
)) return Unknown
;
1897 return esr
& ESR_ELx_WNR
? Write
: Read
;
1898 #elif defined(__sparc__)
1899 // Decode the instruction to determine the access type.
1900 // From OpenSolaris $SRC/uts/sun4/os/trap.c (get_accesstype).
1901 #if SANITIZER_SOLARIS
1902 uptr pc
= ucontext
->uc_mcontext
.gregs
[REG_PC
];
1904 // Historical BSDism here.
1905 struct sigcontext
*scontext
= (struct sigcontext
*)context
;
1906 #if defined(__arch64__)
1907 uptr pc
= scontext
->sigc_regs
.tpc
;
1909 uptr pc
= scontext
->si_regs
.pc
;
1912 u32 instr
= *(u32
*)pc
;
1913 return (instr
>> 21) & 1 ? Write
: Read
;
1914 #elif defined(__riscv)
1915 #if SANITIZER_FREEBSD
1916 unsigned long pc
= ucontext
->uc_mcontext
.mc_gpregs
.gp_sepc
;
1918 unsigned long pc
= ucontext
->uc_mcontext
.__gregs
[REG_PC
];
1920 unsigned faulty_instruction
= *(uint16_t *)pc
;
1922 #if defined(__riscv_compressed)
1923 if ((faulty_instruction
& 0x3) != 0x3) { // it's a compressed instruction
1924 // set op_bits to the instruction bits [1, 0, 15, 14, 13]
1926 ((faulty_instruction
& 0x3) << 3) | (faulty_instruction
>> 13);
1927 unsigned rd
= faulty_instruction
& 0xF80; // bits 7-11, inclusive
1929 case 0b10'010: // c.lwsp (rd != x0)
1930 #if __riscv_xlen == 64
1931 case 0b10'011: // c.ldsp (rd != x0)
1933 return rd
? SignalContext::Read
: SignalContext::Unknown
;
1934 case 0b00'010: // c.lw
1935 #if __riscv_flen >= 32 && __riscv_xlen == 32
1936 case 0b10'011: // c.flwsp
1938 #if __riscv_flen >= 32 || __riscv_xlen == 64
1939 case 0b00'011: // c.flw / c.ld
1941 #if __riscv_flen == 64
1942 case 0b00'001: // c.fld
1943 case 0b10'001: // c.fldsp
1945 return SignalContext::Read
;
1946 case 0b00'110: // c.sw
1947 case 0b10'110: // c.swsp
1948 #if __riscv_flen >= 32 || __riscv_xlen == 64
1949 case 0b00'111: // c.fsw / c.sd
1950 case 0b10'111: // c.fswsp / c.sdsp
1952 #if __riscv_flen == 64
1953 case 0b00'101: // c.fsd
1954 case 0b10'101: // c.fsdsp
1956 return SignalContext::Write
;
1958 return SignalContext::Unknown
;
1963 unsigned opcode
= faulty_instruction
& 0x7f; // lower 7 bits
1964 unsigned funct3
= (faulty_instruction
>> 12) & 0x7; // bits 12-14, inclusive
1966 case 0b0000011: // loads
1971 #if __riscv_xlen == 64
1976 return SignalContext::Read
;
1978 return SignalContext::Unknown
;
1980 case 0b0100011: // stores
1985 #if __riscv_xlen == 64
1988 return SignalContext::Write
;
1990 return SignalContext::Unknown
;
1992 #if __riscv_flen >= 32
1993 case 0b0000111: // floating-point loads
1996 #if __riscv_flen == 64
1999 return SignalContext::Read
;
2001 return SignalContext::Unknown
;
2003 case 0b0100111: // floating-point stores
2006 #if __riscv_flen == 64
2009 return SignalContext::Write
;
2011 return SignalContext::Unknown
;
2015 return SignalContext::Unknown
;
2019 return Unknown
; // FIXME: Implement.
2023 bool SignalContext::IsTrueFaultingAddress() const {
2024 auto si
= static_cast<const siginfo_t
*>(siginfo
);
2025 // SIGSEGV signals without a true fault address have si_code set to 128.
2026 return si
->si_signo
== SIGSEGV
&& si
->si_code
!= 128;
2029 void SignalContext::DumpAllRegisters(void *context
) {
2030 // FIXME: Implement this.
2033 static void GetPcSpBp(void *context
, uptr
*pc
, uptr
*sp
, uptr
*bp
) {
2034 #if SANITIZER_NETBSD
2035 // This covers all NetBSD architectures
2036 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2037 *pc
= _UC_MACHINE_PC(ucontext
);
2038 *bp
= _UC_MACHINE_FP(ucontext
);
2039 *sp
= _UC_MACHINE_SP(ucontext
);
2040 #elif defined(__arm__)
2041 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2042 *pc
= ucontext
->uc_mcontext
.arm_pc
;
2043 *bp
= ucontext
->uc_mcontext
.arm_fp
;
2044 *sp
= ucontext
->uc_mcontext
.arm_sp
;
2045 #elif defined(__aarch64__)
2046 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2047 *pc
= ucontext
->uc_mcontext
.pc
;
2048 *bp
= ucontext
->uc_mcontext
.regs
[29];
2049 *sp
= ucontext
->uc_mcontext
.sp
;
2050 #elif defined(__hppa__)
2051 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2052 *pc
= ucontext
->uc_mcontext
.sc_iaoq
[0];
2053 /* GCC uses %r3 whenever a frame pointer is needed. */
2054 *bp
= ucontext
->uc_mcontext
.sc_gr
[3];
2055 *sp
= ucontext
->uc_mcontext
.sc_gr
[30];
2056 #elif defined(__x86_64__)
2057 # if SANITIZER_FREEBSD
2058 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2059 *pc
= ucontext
->uc_mcontext
.mc_rip
;
2060 *bp
= ucontext
->uc_mcontext
.mc_rbp
;
2061 *sp
= ucontext
->uc_mcontext
.mc_rsp
;
2063 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2064 *pc
= ucontext
->uc_mcontext
.gregs
[REG_RIP
];
2065 *bp
= ucontext
->uc_mcontext
.gregs
[REG_RBP
];
2066 *sp
= ucontext
->uc_mcontext
.gregs
[REG_RSP
];
2068 #elif defined(__i386__)
2069 # if SANITIZER_FREEBSD
2070 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2071 *pc
= ucontext
->uc_mcontext
.mc_eip
;
2072 *bp
= ucontext
->uc_mcontext
.mc_ebp
;
2073 *sp
= ucontext
->uc_mcontext
.mc_esp
;
2075 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2076 # if SANITIZER_SOLARIS
2077 /* Use the numeric values: the symbolic ones are undefined by llvm
2078 include/llvm/Support/Solaris.h. */
2080 # define REG_EIP 14 // REG_PC
2083 # define REG_EBP 6 // REG_FP
2086 # define REG_UESP 17 // REG_SP
2089 *pc
= ucontext
->uc_mcontext
.gregs
[REG_EIP
];
2090 *bp
= ucontext
->uc_mcontext
.gregs
[REG_EBP
];
2091 *sp
= ucontext
->uc_mcontext
.gregs
[REG_UESP
];
2093 #elif defined(__powerpc__) || defined(__powerpc64__)
2094 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2095 *pc
= ucontext
->uc_mcontext
.regs
->nip
;
2096 *sp
= ucontext
->uc_mcontext
.regs
->gpr
[PT_R1
];
2097 // The powerpc{,64}-linux ABIs do not specify r31 as the frame
2098 // pointer, but GCC always uses r31 when we need a frame pointer.
2099 *bp
= ucontext
->uc_mcontext
.regs
->gpr
[PT_R31
];
2100 #elif defined(__sparc__)
2101 #if defined(__arch64__) || defined(__sparcv9)
2102 #define STACK_BIAS 2047
2104 #define STACK_BIAS 0
2106 # if SANITIZER_SOLARIS
2107 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2108 *pc
= ucontext
->uc_mcontext
.gregs
[REG_PC
];
2109 *sp
= ucontext
->uc_mcontext
.gregs
[REG_O6
] + STACK_BIAS
;
2111 // Historical BSDism here.
2112 struct sigcontext
*scontext
= (struct sigcontext
*)context
;
2113 #if defined(__arch64__)
2114 *pc
= scontext
->sigc_regs
.tpc
;
2115 *sp
= scontext
->sigc_regs
.u_regs
[14] + STACK_BIAS
;
2117 *pc
= scontext
->si_regs
.pc
;
2118 *sp
= scontext
->si_regs
.u_regs
[14];
2121 *bp
= (uptr
)((uhwptr
*)*sp
)[14] + STACK_BIAS
;
2122 #elif defined(__mips__)
2123 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2124 *pc
= ucontext
->uc_mcontext
.pc
;
2125 *bp
= ucontext
->uc_mcontext
.gregs
[30];
2126 *sp
= ucontext
->uc_mcontext
.gregs
[29];
2127 #elif defined(__s390__)
2128 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2129 # if defined(__s390x__)
2130 *pc
= ucontext
->uc_mcontext
.psw
.addr
;
2132 *pc
= ucontext
->uc_mcontext
.psw
.addr
& 0x7fffffff;
2134 *bp
= ucontext
->uc_mcontext
.gregs
[11];
2135 *sp
= ucontext
->uc_mcontext
.gregs
[15];
2136 #elif defined(__riscv)
2137 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2138 # if SANITIZER_FREEBSD
2139 *pc
= ucontext
->uc_mcontext
.mc_gpregs
.gp_sepc
;
2140 *bp
= ucontext
->uc_mcontext
.mc_gpregs
.gp_s
[0];
2141 *sp
= ucontext
->uc_mcontext
.mc_gpregs
.gp_sp
;
2143 *pc
= ucontext
->uc_mcontext
.__gregs
[REG_PC
];
2144 *bp
= ucontext
->uc_mcontext
.__gregs
[REG_S0
];
2145 *sp
= ucontext
->uc_mcontext
.__gregs
[REG_SP
];
2147 # elif defined(__hexagon__)
2148 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2149 *pc
= ucontext
->uc_mcontext
.pc
;
2150 *bp
= ucontext
->uc_mcontext
.r30
;
2151 *sp
= ucontext
->uc_mcontext
.r29
;
2153 # error "Unsupported arch"
2157 void SignalContext::InitPcSpBp() { GetPcSpBp(context
, &pc
, &sp
, &bp
); }
2159 void InitializePlatformEarly() {
2163 void MaybeReexec() {
2164 // No need to re-exec on Linux.
2168 #if SANITIZER_NETBSD
2171 uptr len
= sizeof(paxflags
);
2174 mib
[1] = internal_getpid();
2175 mib
[2] = PROC_PID_PAXFLAGS
;
2177 if (UNLIKELY(internal_sysctl(mib
, 3, &paxflags
, &len
, NULL
, 0) == -1)) {
2178 Printf("sysctl failed\n");
2182 if (UNLIKELY(paxflags
& CTL_PROC_PAXFLAGS_ASLR
)) {
2183 Printf("This sanitizer is not compatible with enabled ASLR.\n"
2184 "To disable ASLR, please run \"paxctl +a %s\" and try again.\n",
2188 #elif SANITIZER_PPC64V2
2189 // Disable ASLR for Linux PPC64LE.
2190 int old_personality
= personality(0xffffffff);
2191 if (old_personality
!= -1 && (old_personality
& ADDR_NO_RANDOMIZE
) == 0) {
2192 VReport(1, "WARNING: Program is being run with address space layout "
2193 "randomization (ASLR) enabled which prevents the thread and "
2194 "memory sanitizers from working on powerpc64le.\n"
2195 "ASLR will be disabled and the program re-executed.\n");
2196 CHECK_NE(personality(old_personality
| ADDR_NO_RANDOMIZE
), -1);
2199 #elif SANITIZER_FREEBSD
2201 if (UNLIKELY(procctl(P_PID
, 0, PROC_ASLR_STATUS
, &aslr_status
) == -1)) {
2202 // We're making things less 'dramatic' here since
2203 // the cmd is not necessarily guaranteed to be here
2204 // just yet regarding FreeBSD release
2207 if ((aslr_status
& PROC_ASLR_ACTIVE
) != 0) {
2208 Printf("This sanitizer is not compatible with enabled ASLR "
2209 "and binaries compiled with PIE\n");
2217 void CheckMPROTECT() {
2218 #if SANITIZER_NETBSD
2221 uptr len
= sizeof(paxflags
);
2224 mib
[1] = internal_getpid();
2225 mib
[2] = PROC_PID_PAXFLAGS
;
2227 if (UNLIKELY(internal_sysctl(mib
, 3, &paxflags
, &len
, NULL
, 0) == -1)) {
2228 Printf("sysctl failed\n");
2232 if (UNLIKELY(paxflags
& CTL_PROC_PAXFLAGS_MPROTECT
)) {
2233 Printf("This sanitizer is not compatible with enabled MPROTECT\n");
2241 void CheckNoDeepBind(const char *filename
, int flag
) {
2242 #ifdef RTLD_DEEPBIND
2243 if (flag
& RTLD_DEEPBIND
) {
2245 "You are trying to dlopen a %s shared library with RTLD_DEEPBIND flag"
2246 " which is incompatible with sanitizer runtime "
2247 "(see https://github.com/google/sanitizers/issues/611 for details"
2248 "). If you want to run %s library under sanitizers please remove "
2249 "RTLD_DEEPBIND from dlopen flags.\n",
2250 filename
, filename
);
2256 uptr
FindAvailableMemoryRange(uptr size
, uptr alignment
, uptr left_padding
,
2257 uptr
*largest_gap_found
,
2258 uptr
*max_occupied_addr
) {
2259 UNREACHABLE("FindAvailableMemoryRange is not available");
2263 bool GetRandom(void *buffer
, uptr length
, bool blocking
) {
2264 if (!buffer
|| !length
|| length
> 256)
2266 #if SANITIZER_USE_GETENTROPY
2267 uptr rnd
= getentropy(buffer
, length
);
2269 if (internal_iserror(rnd
, &rverrno
) && rverrno
== EFAULT
)
2273 #endif // SANITIZER_USE_GETENTROPY
2275 #if SANITIZER_USE_GETRANDOM
2276 static atomic_uint8_t skip_getrandom_syscall
;
2277 if (!atomic_load_relaxed(&skip_getrandom_syscall
)) {
2278 // Up to 256 bytes, getrandom will not be interrupted.
2279 uptr res
= internal_syscall(SYSCALL(getrandom
), buffer
, length
,
2280 blocking
? 0 : GRND_NONBLOCK
);
2282 if (internal_iserror(res
, &rverrno
) && rverrno
== ENOSYS
)
2283 atomic_store_relaxed(&skip_getrandom_syscall
, 1);
2284 else if (res
== length
)
2287 #endif // SANITIZER_USE_GETRANDOM
2288 // Up to 256 bytes, a read off /dev/urandom will not be interrupted.
2289 // blocking is moot here, O_NONBLOCK has no effect when opening /dev/urandom.
2290 uptr fd
= internal_open("/dev/urandom", O_RDONLY
);
2291 if (internal_iserror(fd
))
2293 uptr res
= internal_read(fd
, buffer
, length
);
2294 if (internal_iserror(res
))
2300 } // namespace __sanitizer