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>
81 #if SANITIZER_LINUX && defined(__loongarch__)
82 # include <sys/sysmacros.h>
87 #include <sys/procctl.h>
88 #include <sys/sysctl.h>
89 #include <machine/atomic.h>
91 // <sys/umtx.h> must be included after <errno.h> and <sys/types.h> on
92 // FreeBSD 9.2 and 10.0.
96 #endif // SANITIZER_FREEBSD
99 #include <limits.h> // For NAME_MAX
100 #include <sys/sysctl.h>
101 #include <sys/exec.h>
102 extern struct ps_strings
*__ps_strings
;
103 #endif // SANITIZER_NETBSD
105 #if SANITIZER_SOLARIS
108 #define environ _environ
111 extern char **environ
;
115 struct kernel_timeval
{
120 // <linux/futex.h> is broken on some linux distributions.
121 const int FUTEX_WAIT
= 0;
122 const int FUTEX_WAKE
= 1;
123 const int FUTEX_PRIVATE_FLAG
= 128;
124 const int FUTEX_WAIT_PRIVATE
= FUTEX_WAIT
| FUTEX_PRIVATE_FLAG
;
125 const int FUTEX_WAKE_PRIVATE
= FUTEX_WAKE
| FUTEX_PRIVATE_FLAG
;
126 #endif // SANITIZER_LINUX
128 // Are we using 32-bit or 64-bit Linux syscalls?
129 // x32 (which defines __x86_64__) has SANITIZER_WORDSIZE == 32
130 // but it still needs to use 64-bit syscalls.
131 #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__powerpc64__) || \
132 SANITIZER_WORDSIZE == 64 || \
133 (defined(__mips__) && _MIPS_SIM == _ABIN32))
134 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 1
136 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 0
139 // Note : FreeBSD had implemented both
140 // Linux apis, available from
141 // future 12.x version most likely
142 #if SANITIZER_LINUX && defined(__NR_getrandom)
143 # if !defined(GRND_NONBLOCK)
144 # define GRND_NONBLOCK 1
146 # define SANITIZER_USE_GETRANDOM 1
148 # define SANITIZER_USE_GETRANDOM 0
149 #endif // SANITIZER_LINUX && defined(__NR_getrandom)
151 #if SANITIZER_FREEBSD && __FreeBSD_version >= 1200000
152 # define SANITIZER_USE_GETENTROPY 1
154 # define SANITIZER_USE_GETENTROPY 0
157 namespace __sanitizer
{
159 void SetSigProcMask(__sanitizer_sigset_t
*set
, __sanitizer_sigset_t
*oldset
) {
160 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK
, set
, oldset
));
163 void BlockSignals(__sanitizer_sigset_t
*oldset
) {
164 __sanitizer_sigset_t set
;
165 internal_sigfillset(&set
);
166 # if SANITIZER_LINUX && !SANITIZER_ANDROID
167 // Glibc uses SIGSETXID signal during setuid call. If this signal is blocked
168 // on any thread, setuid call hangs.
169 // See test/sanitizer_common/TestCases/Linux/setuid.c.
170 internal_sigdelset(&set
, 33);
173 // Seccomp-BPF-sandboxed processes rely on SIGSYS to handle trapped syscalls.
174 // If this signal is blocked, such calls cannot be handled and the process may
176 internal_sigdelset(&set
, 31);
178 SetSigProcMask(&set
, oldset
);
181 ScopedBlockSignals::ScopedBlockSignals(__sanitizer_sigset_t
*copy
) {
182 BlockSignals(&saved_
);
184 internal_memcpy(copy
, &saved_
, sizeof(saved_
));
187 ScopedBlockSignals::~ScopedBlockSignals() { SetSigProcMask(&saved_
, nullptr); }
189 # if SANITIZER_LINUX && defined(__x86_64__)
190 # include "sanitizer_syscall_linux_x86_64.inc"
191 # elif SANITIZER_LINUX && SANITIZER_RISCV64
192 # include "sanitizer_syscall_linux_riscv64.inc"
193 # elif SANITIZER_LINUX && defined(__aarch64__)
194 # include "sanitizer_syscall_linux_aarch64.inc"
195 # elif SANITIZER_LINUX && defined(__arm__)
196 # include "sanitizer_syscall_linux_arm.inc"
197 # elif SANITIZER_LINUX && defined(__hexagon__)
198 # include "sanitizer_syscall_linux_hexagon.inc"
199 # elif SANITIZER_LINUX && SANITIZER_LOONGARCH64
200 # include "sanitizer_syscall_linux_loongarch64.inc"
202 # include "sanitizer_syscall_generic.inc"
205 // --------------- sanitizer_libc.h
206 #if !SANITIZER_SOLARIS && !SANITIZER_NETBSD
208 uptr
internal_mmap(void *addr
, uptr length
, int prot
, int flags
, int fd
,
210 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
211 return internal_syscall(SYSCALL(mmap
), (uptr
)addr
, length
, prot
, flags
, fd
,
214 // mmap2 specifies file offset in 4096-byte units.
215 CHECK(IsAligned(offset
, 4096));
216 return internal_syscall(SYSCALL(mmap2
), addr
, length
, prot
, flags
, fd
,
220 #endif // !SANITIZER_S390
222 uptr
internal_munmap(void *addr
, uptr length
) {
223 return internal_syscall(SYSCALL(munmap
), (uptr
)addr
, length
);
227 uptr
internal_mremap(void *old_address
, uptr old_size
, uptr new_size
, int flags
,
229 return internal_syscall(SYSCALL(mremap
), (uptr
)old_address
, old_size
,
230 new_size
, flags
, (uptr
)new_address
);
234 int internal_mprotect(void *addr
, uptr length
, int prot
) {
235 return internal_syscall(SYSCALL(mprotect
), (uptr
)addr
, length
, prot
);
238 int internal_madvise(uptr addr
, uptr length
, int advice
) {
239 return internal_syscall(SYSCALL(madvise
), addr
, length
, advice
);
242 uptr
internal_close(fd_t fd
) {
243 return internal_syscall(SYSCALL(close
), fd
);
246 uptr
internal_open(const char *filename
, int flags
) {
248 return internal_syscall(SYSCALL(openat
), AT_FDCWD
, (uptr
)filename
, flags
);
250 return internal_syscall(SYSCALL(open
), (uptr
)filename
, flags
);
254 uptr
internal_open(const char *filename
, int flags
, u32 mode
) {
256 return internal_syscall(SYSCALL(openat
), AT_FDCWD
, (uptr
)filename
, flags
,
259 return internal_syscall(SYSCALL(open
), (uptr
)filename
, flags
, mode
);
263 uptr
internal_read(fd_t fd
, void *buf
, uptr count
) {
266 (sptr
)internal_syscall(SYSCALL(read
), fd
, (uptr
)buf
, count
));
270 uptr
internal_write(fd_t fd
, const void *buf
, uptr count
) {
273 (sptr
)internal_syscall(SYSCALL(write
), fd
, (uptr
)buf
, count
));
277 uptr
internal_ftruncate(fd_t fd
, uptr size
) {
279 HANDLE_EINTR(res
, (sptr
)internal_syscall(SYSCALL(ftruncate
), fd
,
284 #if (!SANITIZER_LINUX_USES_64BIT_SYSCALLS || SANITIZER_SPARC) && SANITIZER_LINUX
285 static void stat64_to_stat(struct stat64
*in
, struct stat
*out
) {
286 internal_memset(out
, 0, sizeof(*out
));
287 out
->st_dev
= in
->st_dev
;
288 out
->st_ino
= in
->st_ino
;
289 out
->st_mode
= in
->st_mode
;
290 out
->st_nlink
= in
->st_nlink
;
291 out
->st_uid
= in
->st_uid
;
292 out
->st_gid
= in
->st_gid
;
293 out
->st_rdev
= in
->st_rdev
;
294 out
->st_size
= in
->st_size
;
295 out
->st_blksize
= in
->st_blksize
;
296 out
->st_blocks
= in
->st_blocks
;
297 out
->st_atime
= in
->st_atime
;
298 out
->st_mtime
= in
->st_mtime
;
299 out
->st_ctime
= in
->st_ctime
;
303 #if SANITIZER_LINUX && defined(__loongarch__)
304 static void statx_to_stat(struct statx
*in
, struct stat
*out
) {
305 internal_memset(out
, 0, sizeof(*out
));
306 out
->st_dev
= makedev(in
->stx_dev_major
, in
->stx_dev_minor
);
307 out
->st_ino
= in
->stx_ino
;
308 out
->st_mode
= in
->stx_mode
;
309 out
->st_nlink
= in
->stx_nlink
;
310 out
->st_uid
= in
->stx_uid
;
311 out
->st_gid
= in
->stx_gid
;
312 out
->st_rdev
= makedev(in
->stx_rdev_major
, in
->stx_rdev_minor
);
313 out
->st_size
= in
->stx_size
;
314 out
->st_blksize
= in
->stx_blksize
;
315 out
->st_blocks
= in
->stx_blocks
;
316 out
->st_atime
= in
->stx_atime
.tv_sec
;
317 out
->st_atim
.tv_nsec
= in
->stx_atime
.tv_nsec
;
318 out
->st_mtime
= in
->stx_mtime
.tv_sec
;
319 out
->st_mtim
.tv_nsec
= in
->stx_mtime
.tv_nsec
;
320 out
->st_ctime
= in
->stx_ctime
.tv_sec
;
321 out
->st_ctim
.tv_nsec
= in
->stx_ctime
.tv_nsec
;
326 // Undefine compatibility macros from <sys/stat.h>
327 // so that they would not clash with the kernel_stat
328 // st_[a|m|c]time fields
334 #if defined(SANITIZER_ANDROID)
335 // Bionic sys/stat.h defines additional macros
336 // for compatibility with the old NDKs and
337 // they clash with the kernel_stat structure
338 // st_[a|m|c]time_nsec fields.
343 static void kernel_stat_to_stat(struct kernel_stat
*in
, struct stat
*out
) {
344 internal_memset(out
, 0, sizeof(*out
));
345 out
->st_dev
= in
->st_dev
;
346 out
->st_ino
= in
->st_ino
;
347 out
->st_mode
= in
->st_mode
;
348 out
->st_nlink
= in
->st_nlink
;
349 out
->st_uid
= in
->st_uid
;
350 out
->st_gid
= in
->st_gid
;
351 out
->st_rdev
= in
->st_rdev
;
352 out
->st_size
= in
->st_size
;
353 out
->st_blksize
= in
->st_blksize
;
354 out
->st_blocks
= in
->st_blocks
;
355 #if defined(__USE_MISC) || \
356 defined(__USE_XOPEN2K8) || \
357 defined(SANITIZER_ANDROID)
358 out
->st_atim
.tv_sec
= in
->st_atime
;
359 out
->st_atim
.tv_nsec
= in
->st_atime_nsec
;
360 out
->st_mtim
.tv_sec
= in
->st_mtime
;
361 out
->st_mtim
.tv_nsec
= in
->st_mtime_nsec
;
362 out
->st_ctim
.tv_sec
= in
->st_ctime
;
363 out
->st_ctim
.tv_nsec
= in
->st_ctime_nsec
;
365 out
->st_atime
= in
->st_atime
;
366 out
->st_atimensec
= in
->st_atime_nsec
;
367 out
->st_mtime
= in
->st_mtime
;
368 out
->st_mtimensec
= in
->st_mtime_nsec
;
369 out
->st_ctime
= in
->st_ctime
;
370 out
->st_atimensec
= in
->st_ctime_nsec
;
375 uptr
internal_stat(const char *path
, void *buf
) {
376 # if SANITIZER_FREEBSD
377 return internal_syscall(SYSCALL(fstatat
), AT_FDCWD
, (uptr
)path
, (uptr
)buf
, 0);
378 # elif SANITIZER_LINUX
379 # if defined(__loongarch__)
381 int res
= internal_syscall(SYSCALL(statx
), AT_FDCWD
, (uptr
)path
,
382 AT_NO_AUTOMOUNT
, STATX_BASIC_STATS
, (uptr
)&bufx
);
383 statx_to_stat(&bufx
, (struct stat
*)buf
);
385 # elif (SANITIZER_WORDSIZE == 64 || SANITIZER_X32 || \
386 (defined(__mips__) && _MIPS_SIM == _ABIN32)) && \
388 return internal_syscall(SYSCALL(newfstatat
), AT_FDCWD
, (uptr
)path
, (uptr
)buf
,
392 int res
= internal_syscall(SYSCALL(fstatat64
), AT_FDCWD
, (uptr
)path
,
394 stat64_to_stat(&buf64
, (struct stat
*)buf
);
399 int res
= internal_syscall(SYSCALL(stat64
), path
, &buf64
);
400 stat64_to_stat(&buf64
, (struct stat
*)buf
);
405 uptr
internal_lstat(const char *path
, void *buf
) {
406 # if SANITIZER_FREEBSD
407 return internal_syscall(SYSCALL(fstatat
), AT_FDCWD
, (uptr
)path
, (uptr
)buf
,
408 AT_SYMLINK_NOFOLLOW
);
409 # elif SANITIZER_LINUX
410 # if defined(__loongarch__)
412 int res
= internal_syscall(SYSCALL(statx
), AT_FDCWD
, (uptr
)path
,
413 AT_SYMLINK_NOFOLLOW
| AT_NO_AUTOMOUNT
,
414 STATX_BASIC_STATS
, (uptr
)&bufx
);
415 statx_to_stat(&bufx
, (struct stat
*)buf
);
417 # elif (defined(_LP64) || SANITIZER_X32 || \
418 (defined(__mips__) && _MIPS_SIM == _ABIN32)) && \
420 return internal_syscall(SYSCALL(newfstatat
), AT_FDCWD
, (uptr
)path
, (uptr
)buf
,
421 AT_SYMLINK_NOFOLLOW
);
424 int res
= internal_syscall(SYSCALL(fstatat64
), AT_FDCWD
, (uptr
)path
,
425 (uptr
)&buf64
, AT_SYMLINK_NOFOLLOW
);
426 stat64_to_stat(&buf64
, (struct stat
*)buf
);
431 int res
= internal_syscall(SYSCALL(lstat64
), path
, &buf64
);
432 stat64_to_stat(&buf64
, (struct stat
*)buf
);
437 uptr
internal_fstat(fd_t fd
, void *buf
) {
438 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
440 // For mips64, fstat syscall fills buffer in the format of kernel_stat
441 struct kernel_stat kbuf
;
442 int res
= internal_syscall(SYSCALL(fstat
), fd
, &kbuf
);
443 kernel_stat_to_stat(&kbuf
, (struct stat
*)buf
);
445 # elif SANITIZER_LINUX && defined(__loongarch__)
447 int res
= internal_syscall(SYSCALL(statx
), fd
, "", AT_EMPTY_PATH
,
448 STATX_BASIC_STATS
, (uptr
)&bufx
);
449 statx_to_stat(&bufx
, (struct stat
*)buf
);
452 return internal_syscall(SYSCALL(fstat
), fd
, (uptr
)buf
);
456 int res
= internal_syscall(SYSCALL(fstat64
), fd
, &buf64
);
457 stat64_to_stat(&buf64
, (struct stat
*)buf
);
462 uptr
internal_filesize(fd_t fd
) {
464 if (internal_fstat(fd
, &st
))
466 return (uptr
)st
.st_size
;
469 uptr
internal_dup(int oldfd
) {
470 return internal_syscall(SYSCALL(dup
), oldfd
);
473 uptr
internal_dup2(int oldfd
, int newfd
) {
475 return internal_syscall(SYSCALL(dup3
), oldfd
, newfd
, 0);
477 return internal_syscall(SYSCALL(dup2
), oldfd
, newfd
);
481 uptr
internal_readlink(const char *path
, char *buf
, uptr bufsize
) {
483 return internal_syscall(SYSCALL(readlinkat
), AT_FDCWD
, (uptr
)path
, (uptr
)buf
,
486 return internal_syscall(SYSCALL(readlink
), (uptr
)path
, (uptr
)buf
, bufsize
);
490 uptr
internal_unlink(const char *path
) {
492 return internal_syscall(SYSCALL(unlinkat
), AT_FDCWD
, (uptr
)path
, 0);
494 return internal_syscall(SYSCALL(unlink
), (uptr
)path
);
498 uptr
internal_rename(const char *oldpath
, const char *newpath
) {
499 # if (defined(__riscv) || defined(__loongarch__)) && defined(__linux__)
500 return internal_syscall(SYSCALL(renameat2
), AT_FDCWD
, (uptr
)oldpath
, AT_FDCWD
,
502 # elif SANITIZER_LINUX
503 return internal_syscall(SYSCALL(renameat
), AT_FDCWD
, (uptr
)oldpath
, AT_FDCWD
,
506 return internal_syscall(SYSCALL(rename
), (uptr
)oldpath
, (uptr
)newpath
);
510 uptr
internal_sched_yield() {
511 return internal_syscall(SYSCALL(sched_yield
));
514 void internal_usleep(u64 useconds
) {
516 ts
.tv_sec
= useconds
/ 1000000;
517 ts
.tv_nsec
= (useconds
% 1000000) * 1000;
518 internal_syscall(SYSCALL(nanosleep
), &ts
, &ts
);
521 uptr
internal_execve(const char *filename
, char *const argv
[],
522 char *const envp
[]) {
523 return internal_syscall(SYSCALL(execve
), (uptr
)filename
, (uptr
)argv
,
526 #endif // !SANITIZER_SOLARIS && !SANITIZER_NETBSD
528 #if !SANITIZER_NETBSD
529 void internal__exit(int exitcode
) {
530 #if SANITIZER_FREEBSD || SANITIZER_SOLARIS
531 internal_syscall(SYSCALL(exit
), exitcode
);
533 internal_syscall(SYSCALL(exit_group
), exitcode
);
535 Die(); // Unreachable.
537 #endif // !SANITIZER_NETBSD
539 // ----------------- sanitizer_common.h
540 bool FileExists(const char *filename
) {
541 if (ShouldMockFailureToOpen(filename
))
544 if (internal_stat(filename
, &st
))
546 // Sanity check: filename is a regular file.
547 return S_ISREG(st
.st_mode
);
550 bool DirExists(const char *path
) {
552 if (internal_stat(path
, &st
))
554 return S_ISDIR(st
.st_mode
);
557 # if !SANITIZER_NETBSD
559 #if SANITIZER_FREEBSD
563 #elif SANITIZER_SOLARIS
566 return internal_syscall(SYSCALL(gettid
));
570 int TgKill(pid_t pid
, tid_t tid
, int sig
) {
572 return internal_syscall(SYSCALL(tgkill
), pid
, tid
, sig
);
573 #elif SANITIZER_FREEBSD
574 return internal_syscall(SYSCALL(thr_kill2
), pid
, tid
, sig
);
575 #elif SANITIZER_SOLARIS
577 return thr_kill(tid
, sig
);
585 internal_memset(&tv
, 0, sizeof(tv
));
586 internal_syscall(SYSCALL(gettimeofday
), &tv
, 0);
587 return (u64
)tv
.tv_sec
* 1000 * 1000 * 1000 + tv
.tv_usec
* 1000;
589 // Used by real_clock_gettime.
590 uptr
internal_clock_gettime(__sanitizer_clockid_t clk_id
, void *tp
) {
591 return internal_syscall(SYSCALL(clock_gettime
), clk_id
, tp
);
593 #elif !SANITIZER_SOLARIS && !SANITIZER_NETBSD
596 clock_gettime(CLOCK_REALTIME
, &ts
);
597 return (u64
)ts
.tv_sec
* 1000 * 1000 * 1000 + ts
.tv_nsec
;
601 // Like getenv, but reads env directly from /proc (on Linux) or parses the
602 // 'environ' array (on some others) and does not use libc. This function
603 // should be called first inside __asan_init.
604 const char *GetEnv(const char *name
) {
605 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_SOLARIS
606 if (::environ
!= 0) {
607 uptr NameLen
= internal_strlen(name
);
608 for (char **Env
= ::environ
; *Env
!= 0; Env
++) {
609 if (internal_strncmp(*Env
, name
, NameLen
) == 0 && (*Env
)[NameLen
] == '=')
610 return (*Env
) + NameLen
+ 1;
613 return 0; // Not found.
614 #elif SANITIZER_LINUX
615 static char *environ
;
621 if (!ReadFileToBuffer("/proc/self/environ", &environ
, &environ_size
, &len
))
624 if (!environ
|| len
== 0) return nullptr;
625 uptr namelen
= internal_strlen(name
);
626 const char *p
= environ
;
627 while (*p
!= '\0') { // will happen at the \0\0 that terminates the buffer
628 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
630 (char*)internal_memchr(p
, '\0', len
- (p
- environ
));
631 if (!endp
) // this entry isn't NUL terminated
633 else if (!internal_memcmp(p
, name
, namelen
) && p
[namelen
] == '=') // Match.
634 return p
+ namelen
+ 1; // point after =
637 return nullptr; // Not found.
639 #error "Unsupported platform"
643 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD && !SANITIZER_GO
645 SANITIZER_WEAK_ATTRIBUTE
extern void *__libc_stack_end
;
649 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
650 static void ReadNullSepFileToArray(const char *path
, char ***arr
,
655 *arr
= (char **)MmapOrDie(arr_size
* sizeof(char *), "NullSepFileArray");
656 if (!ReadFileToBuffer(path
, &buff
, &buff_size
, &buff_len
, 1024 * 1024)) {
662 for (count
= 1, i
= 1; ; i
++) {
664 if (buff
[i
+1] == 0) break;
665 (*arr
)[count
] = &buff
[i
+1];
666 CHECK_LE(count
, arr_size
- 1); // FIXME: make this more flexible.
670 (*arr
)[count
] = nullptr;
674 static void GetArgsAndEnv(char ***argv
, char ***envp
) {
675 #if SANITIZER_FREEBSD
676 // On FreeBSD, retrieving the argument and environment arrays is done via the
677 // kern.ps_strings sysctl, which returns a pointer to a structure containing
678 // this information. See also <sys/exec.h>.
680 uptr sz
= sizeof(pss
);
681 if (internal_sysctlbyname("kern.ps_strings", &pss
, &sz
, NULL
, 0) == -1) {
682 Printf("sysctl kern.ps_strings failed\n");
685 *argv
= pss
->ps_argvstr
;
686 *envp
= pss
->ps_envstr
;
687 #elif SANITIZER_NETBSD
688 *argv
= __ps_strings
->ps_argvstr
;
689 *envp
= __ps_strings
->ps_envstr
;
690 #else // SANITIZER_FREEBSD
692 if (&__libc_stack_end
) {
693 uptr
* stack_end
= (uptr
*)__libc_stack_end
;
694 // Normally argc can be obtained from *stack_end, however, on ARM glibc's
695 // _start clobbers it:
696 // https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/arm/start.S;hb=refs/heads/release/2.31/master#l75
697 // Do not special-case ARM and infer argc from argv everywhere.
699 while (stack_end
[argc
+ 1]) argc
++;
700 *argv
= (char**)(stack_end
+ 1);
701 *envp
= (char**)(stack_end
+ argc
+ 2);
703 #endif // !SANITIZER_GO
704 static const int kMaxArgv
= 2000, kMaxEnvp
= 2000;
705 ReadNullSepFileToArray("/proc/self/cmdline", argv
, kMaxArgv
);
706 ReadNullSepFileToArray("/proc/self/environ", envp
, kMaxEnvp
);
709 #endif // !SANITIZER_GO
710 #endif // SANITIZER_FREEBSD
715 GetArgsAndEnv(&argv
, &envp
);
719 char **GetEnviron() {
721 GetArgsAndEnv(&argv
, &envp
);
725 #if !SANITIZER_SOLARIS
726 void FutexWait(atomic_uint32_t
*p
, u32 cmp
) {
727 # if SANITIZER_FREEBSD
728 _umtx_op(p
, UMTX_OP_WAIT_UINT
, cmp
, 0, 0);
729 # elif SANITIZER_NETBSD
730 sched_yield(); /* No userspace futex-like synchronization */
732 internal_syscall(SYSCALL(futex
), (uptr
)p
, FUTEX_WAIT_PRIVATE
, cmp
, 0, 0, 0);
736 void FutexWake(atomic_uint32_t
*p
, u32 count
) {
737 # if SANITIZER_FREEBSD
738 _umtx_op(p
, UMTX_OP_WAKE
, count
, 0, 0);
739 # elif SANITIZER_NETBSD
740 /* No userspace futex-like synchronization */
742 internal_syscall(SYSCALL(futex
), (uptr
)p
, FUTEX_WAKE_PRIVATE
, count
, 0, 0, 0);
746 # endif // !SANITIZER_SOLARIS
748 // ----------------- sanitizer_linux.h
749 // The actual size of this structure is specified by d_reclen.
750 // Note that getdents64 uses a different structure format. We only provide the
751 // 32-bit syscall here.
755 struct linux_dirent
{
756 # if SANITIZER_X32 || SANITIZER_LINUX
763 unsigned short d_reclen
;
765 unsigned char d_type
;
771 #if !SANITIZER_SOLARIS && !SANITIZER_NETBSD
773 uptr
internal_ptrace(int request
, int pid
, void *addr
, void *data
) {
774 return internal_syscall(SYSCALL(ptrace
), request
, pid
, (uptr
)addr
,
778 uptr
internal_waitpid(int pid
, int *status
, int options
) {
779 return internal_syscall(SYSCALL(wait4
), pid
, (uptr
)status
, options
,
783 uptr
internal_getpid() {
784 return internal_syscall(SYSCALL(getpid
));
787 uptr
internal_getppid() {
788 return internal_syscall(SYSCALL(getppid
));
791 int internal_dlinfo(void *handle
, int request
, void *p
) {
792 #if SANITIZER_FREEBSD
793 return dlinfo(handle
, request
, p
);
799 uptr
internal_getdents(fd_t fd
, struct linux_dirent
*dirp
, unsigned int count
) {
800 #if SANITIZER_FREEBSD
801 return internal_syscall(SYSCALL(getdirentries
), fd
, (uptr
)dirp
, count
, NULL
);
802 # elif SANITIZER_LINUX
803 return internal_syscall(SYSCALL(getdents64
), fd
, (uptr
)dirp
, count
);
805 return internal_syscall(SYSCALL(getdents
), fd
, (uptr
)dirp
, count
);
809 uptr
internal_lseek(fd_t fd
, OFF_T offset
, int whence
) {
810 return internal_syscall(SYSCALL(lseek
), fd
, offset
, whence
);
814 uptr
internal_prctl(int option
, uptr arg2
, uptr arg3
, uptr arg4
, uptr arg5
) {
815 return internal_syscall(SYSCALL(prctl
), option
, arg2
, arg3
, arg4
, arg5
);
817 # if defined(__x86_64__)
818 # include <asm/unistd_64.h>
819 // Currently internal_arch_prctl() is only needed on x86_64.
820 uptr
internal_arch_prctl(int option
, uptr arg2
) {
821 return internal_syscall(__NR_arch_prctl
, option
, arg2
);
826 uptr
internal_sigaltstack(const void *ss
, void *oss
) {
827 return internal_syscall(SYSCALL(sigaltstack
), (uptr
)ss
, (uptr
)oss
);
830 int internal_fork() {
833 return internal_syscall(SYSCALL(clone
), 0, SIGCHLD
);
835 return internal_syscall(SYSCALL(clone
), SIGCHLD
, 0);
838 return internal_syscall(SYSCALL(fork
));
842 #if SANITIZER_FREEBSD
843 int internal_sysctl(const int *name
, unsigned int namelen
, void *oldp
,
844 uptr
*oldlenp
, const void *newp
, uptr newlen
) {
845 return internal_syscall(SYSCALL(__sysctl
), name
, namelen
, oldp
,
846 (size_t *)oldlenp
, newp
, (size_t)newlen
);
849 int internal_sysctlbyname(const char *sname
, void *oldp
, uptr
*oldlenp
,
850 const void *newp
, uptr newlen
) {
851 // Note: this function can be called during startup, so we need to avoid
852 // calling any interceptable functions. On FreeBSD >= 1300045 sysctlbyname()
853 // is a real syscall, but for older versions it calls sysctlnametomib()
854 // followed by sysctl(). To avoid calling the intercepted version and
855 // asserting if this happens during startup, call the real sysctlnametomib()
856 // followed by internal_sysctl() if the syscall is not available.
857 #ifdef SYS___sysctlbyname
858 return internal_syscall(SYSCALL(__sysctlbyname
), sname
,
859 internal_strlen(sname
), oldp
, (size_t *)oldlenp
, newp
,
862 static decltype(sysctlnametomib
) *real_sysctlnametomib
= nullptr;
863 if (!real_sysctlnametomib
)
864 real_sysctlnametomib
=
865 (decltype(sysctlnametomib
) *)dlsym(RTLD_NEXT
, "sysctlnametomib");
866 CHECK(real_sysctlnametomib
);
868 int oid
[CTL_MAXNAME
];
869 size_t len
= CTL_MAXNAME
;
870 if (real_sysctlnametomib(sname
, oid
, &len
) == -1)
872 return internal_sysctl(oid
, len
, oldp
, oldlenp
, newp
, newlen
);
878 #define SA_RESTORER 0x04000000
879 // Doesn't set sa_restorer if the caller did not set it, so use with caution
881 int internal_sigaction_norestorer(int signum
, const void *act
, void *oldact
) {
882 __sanitizer_kernel_sigaction_t k_act
, k_oldact
;
883 internal_memset(&k_act
, 0, sizeof(__sanitizer_kernel_sigaction_t
));
884 internal_memset(&k_oldact
, 0, sizeof(__sanitizer_kernel_sigaction_t
));
885 const __sanitizer_sigaction
*u_act
= (const __sanitizer_sigaction
*)act
;
886 __sanitizer_sigaction
*u_oldact
= (__sanitizer_sigaction
*)oldact
;
888 k_act
.handler
= u_act
->handler
;
889 k_act
.sigaction
= u_act
->sigaction
;
890 internal_memcpy(&k_act
.sa_mask
, &u_act
->sa_mask
,
891 sizeof(__sanitizer_kernel_sigset_t
));
892 // Without SA_RESTORER kernel ignores the calls (probably returns EINVAL).
893 k_act
.sa_flags
= u_act
->sa_flags
| SA_RESTORER
;
894 // FIXME: most often sa_restorer is unset, however the kernel requires it
895 // to point to a valid signal restorer that calls the rt_sigreturn syscall.
896 // If sa_restorer passed to the kernel is NULL, the program may crash upon
897 // signal delivery or fail to unwind the stack in the signal handler.
898 // libc implementation of sigaction() passes its own restorer to
899 // rt_sigaction, so we need to do the same (we'll need to reimplement the
900 // restorers; for x86_64 the restorer address can be obtained from
901 // oldact->sa_restorer upon a call to sigaction(xxx, NULL, oldact).
902 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
903 k_act
.sa_restorer
= u_act
->sa_restorer
;
907 uptr result
= internal_syscall(SYSCALL(rt_sigaction
), (uptr
)signum
,
908 (uptr
)(u_act
? &k_act
: nullptr),
909 (uptr
)(u_oldact
? &k_oldact
: nullptr),
910 (uptr
)sizeof(__sanitizer_kernel_sigset_t
));
912 if ((result
== 0) && u_oldact
) {
913 u_oldact
->handler
= k_oldact
.handler
;
914 u_oldact
->sigaction
= k_oldact
.sigaction
;
915 internal_memcpy(&u_oldact
->sa_mask
, &k_oldact
.sa_mask
,
916 sizeof(__sanitizer_kernel_sigset_t
));
917 u_oldact
->sa_flags
= k_oldact
.sa_flags
;
918 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
919 u_oldact
->sa_restorer
= k_oldact
.sa_restorer
;
924 #endif // SANITIZER_LINUX
926 uptr
internal_sigprocmask(int how
, __sanitizer_sigset_t
*set
,
927 __sanitizer_sigset_t
*oldset
) {
928 #if SANITIZER_FREEBSD
929 return internal_syscall(SYSCALL(sigprocmask
), how
, set
, oldset
);
931 __sanitizer_kernel_sigset_t
*k_set
= (__sanitizer_kernel_sigset_t
*)set
;
932 __sanitizer_kernel_sigset_t
*k_oldset
= (__sanitizer_kernel_sigset_t
*)oldset
;
933 return internal_syscall(SYSCALL(rt_sigprocmask
), (uptr
)how
, (uptr
)k_set
,
934 (uptr
)k_oldset
, sizeof(__sanitizer_kernel_sigset_t
));
938 void internal_sigfillset(__sanitizer_sigset_t
*set
) {
939 internal_memset(set
, 0xff, sizeof(*set
));
942 void internal_sigemptyset(__sanitizer_sigset_t
*set
) {
943 internal_memset(set
, 0, sizeof(*set
));
947 void internal_sigdelset(__sanitizer_sigset_t
*set
, int signum
) {
950 CHECK_LT(signum
, sizeof(*set
) * 8);
951 __sanitizer_kernel_sigset_t
*k_set
= (__sanitizer_kernel_sigset_t
*)set
;
952 const uptr idx
= signum
/ (sizeof(k_set
->sig
[0]) * 8);
953 const uptr bit
= signum
% (sizeof(k_set
->sig
[0]) * 8);
954 k_set
->sig
[idx
] &= ~((uptr
)1 << bit
);
957 bool internal_sigismember(__sanitizer_sigset_t
*set
, int signum
) {
960 CHECK_LT(signum
, sizeof(*set
) * 8);
961 __sanitizer_kernel_sigset_t
*k_set
= (__sanitizer_kernel_sigset_t
*)set
;
962 const uptr idx
= signum
/ (sizeof(k_set
->sig
[0]) * 8);
963 const uptr bit
= signum
% (sizeof(k_set
->sig
[0]) * 8);
964 return k_set
->sig
[idx
] & ((uptr
)1 << bit
);
966 #elif SANITIZER_FREEBSD
967 uptr
internal_procctl(int type
, int id
, int cmd
, void *data
) {
968 return internal_syscall(SYSCALL(procctl
), type
, id
, cmd
, data
);
971 void internal_sigdelset(__sanitizer_sigset_t
*set
, int signum
) {
972 sigset_t
*rset
= reinterpret_cast<sigset_t
*>(set
);
973 sigdelset(rset
, signum
);
976 bool internal_sigismember(__sanitizer_sigset_t
*set
, int signum
) {
977 sigset_t
*rset
= reinterpret_cast<sigset_t
*>(set
);
978 return sigismember(rset
, signum
);
981 #endif // !SANITIZER_SOLARIS
983 #if !SANITIZER_NETBSD
984 // ThreadLister implementation.
985 ThreadLister::ThreadLister(pid_t pid
) : pid_(pid
), buffer_(4096) {
986 char task_directory_path
[80];
987 internal_snprintf(task_directory_path
, sizeof(task_directory_path
),
988 "/proc/%d/task/", pid
);
989 descriptor_
= internal_open(task_directory_path
, O_RDONLY
| O_DIRECTORY
);
990 if (internal_iserror(descriptor_
)) {
991 Report("Can't open /proc/%d/task for reading.\n", pid
);
995 ThreadLister::Result
ThreadLister::ListThreads(
996 InternalMmapVector
<tid_t
> *threads
) {
997 if (internal_iserror(descriptor_
))
999 internal_lseek(descriptor_
, 0, SEEK_SET
);
1003 for (bool first_read
= true;; first_read
= false) {
1004 // Resize to max capacity if it was downsized by IsAlive.
1005 buffer_
.resize(buffer_
.capacity());
1006 CHECK_GE(buffer_
.size(), 4096);
1007 uptr read
= internal_getdents(
1008 descriptor_
, (struct linux_dirent
*)buffer_
.data(), buffer_
.size());
1011 if (internal_iserror(read
)) {
1012 Report("Can't read directory entries from /proc/%d/task.\n", pid_
);
1016 for (uptr begin
= (uptr
)buffer_
.data(), end
= begin
+ read
; begin
< end
;) {
1017 struct linux_dirent
*entry
= (struct linux_dirent
*)begin
;
1018 begin
+= entry
->d_reclen
;
1019 if (entry
->d_ino
== 1) {
1020 // Inode 1 is for bad blocks and also can be a reason for early return.
1021 // Should be emitted if kernel tried to output terminating thread.
1022 // See proc_task_readdir implementation in Linux.
1023 result
= Incomplete
;
1025 if (entry
->d_ino
&& *entry
->d_name
>= '0' && *entry
->d_name
<= '9')
1026 threads
->push_back(internal_atoll(entry
->d_name
));
1029 // Now we are going to detect short-read or early EOF. In such cases Linux
1030 // can return inconsistent list with missing alive threads.
1031 // Code will just remember that the list can be incomplete but it will
1032 // continue reads to return as much as possible.
1034 // The first one was a short-read by definition.
1035 result
= Incomplete
;
1036 } else if (read
> buffer_
.size() - 1024) {
1037 // Read was close to the buffer size. So double the size and assume the
1039 buffer_
.resize(buffer_
.size() * 2);
1040 result
= Incomplete
;
1041 } else if (!threads
->empty() && !IsAlive(threads
->back())) {
1042 // Maybe Linux early returned from read on terminated thread (!pid_alive)
1043 // and failed to restore read position.
1044 // See next_tid and proc_task_instantiate in Linux.
1045 result
= Incomplete
;
1050 bool ThreadLister::IsAlive(int tid
) {
1051 // /proc/%d/task/%d/status uses same call to detect alive threads as
1052 // proc_task_readdir. See task_state implementation in Linux.
1054 internal_snprintf(path
, sizeof(path
), "/proc/%d/task/%d/status", pid_
, tid
);
1055 if (!ReadFileToVector(path
, &buffer_
) || buffer_
.empty())
1057 buffer_
.push_back(0);
1058 static const char kPrefix
[] = "\nPPid:";
1059 const char *field
= internal_strstr(buffer_
.data(), kPrefix
);
1062 field
+= internal_strlen(kPrefix
);
1063 return (int)internal_atoll(field
) != 0;
1066 ThreadLister::~ThreadLister() {
1067 if (!internal_iserror(descriptor_
))
1068 internal_close(descriptor_
);
1072 #if SANITIZER_WORDSIZE == 32
1073 // Take care of unusable kernel area in top gigabyte.
1074 static uptr
GetKernelAreaSize() {
1075 #if SANITIZER_LINUX && !SANITIZER_X32
1076 const uptr gbyte
= 1UL << 30;
1078 // Firstly check if there are writable segments
1079 // mapped to top gigabyte (e.g. stack).
1080 MemoryMappingLayout
proc_maps(/*cache_enabled*/true);
1081 if (proc_maps
.Error())
1083 MemoryMappedSegment segment
;
1084 while (proc_maps
.Next(&segment
)) {
1085 if ((segment
.end
>= 3 * gbyte
) && segment
.IsWritable()) return 0;
1088 #if !SANITIZER_ANDROID
1089 // Even if nothing is mapped, top Gb may still be accessible
1090 // if we are running on 64-bit kernel.
1091 // Uname may report misleading results if personality type
1092 // is modified (e.g. under schroot) so check this as well.
1093 struct utsname uname_info
;
1094 int pers
= personality(0xffffffffUL
);
1095 if (!(pers
& PER_MASK
) && internal_uname(&uname_info
) == 0 &&
1096 internal_strstr(uname_info
.machine
, "64"))
1098 #endif // SANITIZER_ANDROID
1100 // Top gigabyte is reserved for kernel.
1104 #endif // SANITIZER_LINUX && !SANITIZER_X32
1106 #endif // SANITIZER_WORDSIZE == 32
1108 uptr
GetMaxVirtualAddress() {
1109 #if SANITIZER_NETBSD && defined(__x86_64__)
1110 return 0x7f7ffffff000ULL
; // (0x00007f8000000000 - PAGE_SIZE)
1111 #elif SANITIZER_WORDSIZE == 64
1112 # if defined(__powerpc64__) || defined(__aarch64__) || defined(__loongarch__)
1113 // On PowerPC64 we have two different address space layouts: 44- and 46-bit.
1114 // We somehow need to figure out which one we are using now and choose
1115 // one of 0x00000fffffffffffUL and 0x00003fffffffffffUL.
1116 // Note that with 'ulimit -s unlimited' the stack is moved away from the top
1117 // of the address space, so simply checking the stack address is not enough.
1118 // This should (does) work for both PowerPC64 Endian modes.
1119 // Similarly, aarch64 has multiple address space layouts: 39, 42 and 47-bit.
1120 // loongarch64 also has multiple address space layouts: default is 47-bit.
1121 return (1ULL << (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1)) - 1;
1122 #elif SANITIZER_RISCV64
1123 return (1ULL << 38) - 1;
1124 # elif SANITIZER_MIPS64
1125 return (1ULL << 40) - 1; // 0x000000ffffffffffUL;
1126 # elif defined(__s390x__)
1127 return (1ULL << 53) - 1; // 0x001fffffffffffffUL;
1128 #elif defined(__sparc__)
1131 return (1ULL << 47) - 1; // 0x00007fffffffffffUL;
1133 #else // SANITIZER_WORDSIZE == 32
1134 # if defined(__s390__)
1135 return (1ULL << 31) - 1; // 0x7fffffff;
1137 return (1ULL << 32) - 1; // 0xffffffff;
1139 #endif // SANITIZER_WORDSIZE
1142 uptr
GetMaxUserVirtualAddress() {
1143 uptr addr
= GetMaxVirtualAddress();
1144 #if SANITIZER_WORDSIZE == 32 && !defined(__s390__)
1145 if (!common_flags()->full_address_space
)
1146 addr
-= GetKernelAreaSize();
1147 CHECK_LT(reinterpret_cast<uptr
>(&addr
), addr
);
1152 #if !SANITIZER_ANDROID
1153 uptr
GetPageSize() {
1154 #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__)) && \
1155 defined(EXEC_PAGESIZE)
1156 return EXEC_PAGESIZE
;
1157 #elif SANITIZER_FREEBSD || SANITIZER_NETBSD
1158 // Use sysctl as sysconf can trigger interceptors internally.
1160 uptr pzl
= sizeof(pz
);
1161 int mib
[2] = {CTL_HW
, HW_PAGESIZE
};
1162 int rv
= internal_sysctl(mib
, 2, &pz
, &pzl
, nullptr, 0);
1165 #elif SANITIZER_USE_GETAUXVAL
1166 return getauxval(AT_PAGESZ
);
1168 return sysconf(_SC_PAGESIZE
); // EXEC_PAGESIZE may not be trustworthy.
1171 #endif // !SANITIZER_ANDROID
1173 uptr
ReadBinaryName(/*out*/char *buf
, uptr buf_len
) {
1174 #if SANITIZER_SOLARIS
1175 const char *default_module_name
= getexecname();
1176 CHECK_NE(default_module_name
, NULL
);
1177 return internal_snprintf(buf
, buf_len
, "%s", default_module_name
);
1179 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
1180 #if SANITIZER_FREEBSD
1181 const int Mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PATHNAME
, -1};
1183 const int Mib
[4] = {CTL_KERN
, KERN_PROC_ARGS
, -1, KERN_PROC_PATHNAME
};
1185 const char *default_module_name
= "kern.proc.pathname";
1186 uptr Size
= buf_len
;
1188 (internal_sysctl(Mib
, ARRAY_SIZE(Mib
), buf
, &Size
, NULL
, 0) != 0);
1189 int readlink_error
= IsErr
? errno
: 0;
1190 uptr module_name_len
= Size
;
1192 const char *default_module_name
= "/proc/self/exe";
1193 uptr module_name_len
= internal_readlink(
1194 default_module_name
, buf
, buf_len
);
1196 bool IsErr
= internal_iserror(module_name_len
, &readlink_error
);
1197 #endif // SANITIZER_SOLARIS
1199 // We can't read binary name for some reason, assume it's unknown.
1200 Report("WARNING: reading executable name failed with errno %d, "
1201 "some stack frames may not be symbolized\n", readlink_error
);
1202 module_name_len
= internal_snprintf(buf
, buf_len
, "%s",
1203 default_module_name
);
1204 CHECK_LT(module_name_len
, buf_len
);
1206 return module_name_len
;
1210 uptr
ReadLongProcessName(/*out*/ char *buf
, uptr buf_len
) {
1215 if (ReadFileToBuffer("/proc/self/cmdline", &tmpbuf
, &tmpsize
, &tmplen
,
1217 internal_strncpy(buf
, tmpbuf
, buf_len
);
1218 UnmapOrDie(tmpbuf
, tmpsize
);
1219 return internal_strlen(buf
);
1222 return ReadBinaryName(buf
, buf_len
);
1225 // Match full names of the form /path/to/base_name{-,.}*
1226 bool LibraryNameIs(const char *full_name
, const char *base_name
) {
1227 const char *name
= full_name
;
1229 while (*name
!= '\0') name
++;
1230 while (name
> full_name
&& *name
!= '/') name
--;
1231 if (*name
== '/') name
++;
1232 uptr base_name_length
= internal_strlen(base_name
);
1233 if (internal_strncmp(name
, base_name
, base_name_length
)) return false;
1234 return (name
[base_name_length
] == '-' || name
[base_name_length
] == '.');
1237 #if !SANITIZER_ANDROID
1238 // Call cb for each region mapped by map.
1239 void ForEachMappedRegion(link_map
*map
, void (*cb
)(const void *, uptr
)) {
1240 CHECK_NE(map
, nullptr);
1241 #if !SANITIZER_FREEBSD
1242 typedef ElfW(Phdr
) Elf_Phdr
;
1243 typedef ElfW(Ehdr
) Elf_Ehdr
;
1244 #endif // !SANITIZER_FREEBSD
1245 char *base
= (char *)map
->l_addr
;
1246 Elf_Ehdr
*ehdr
= (Elf_Ehdr
*)base
;
1247 char *phdrs
= base
+ ehdr
->e_phoff
;
1248 char *phdrs_end
= phdrs
+ ehdr
->e_phnum
* ehdr
->e_phentsize
;
1250 // Find the segment with the minimum base so we can "relocate" the p_vaddr
1251 // fields. Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
1252 // objects have a non-zero base.
1253 uptr preferred_base
= (uptr
)-1;
1254 for (char *iter
= phdrs
; iter
!= phdrs_end
; iter
+= ehdr
->e_phentsize
) {
1255 Elf_Phdr
*phdr
= (Elf_Phdr
*)iter
;
1256 if (phdr
->p_type
== PT_LOAD
&& preferred_base
> (uptr
)phdr
->p_vaddr
)
1257 preferred_base
= (uptr
)phdr
->p_vaddr
;
1260 // Compute the delta from the real base to get a relocation delta.
1261 sptr delta
= (uptr
)base
- preferred_base
;
1262 // Now we can figure out what the loader really mapped.
1263 for (char *iter
= phdrs
; iter
!= phdrs_end
; iter
+= ehdr
->e_phentsize
) {
1264 Elf_Phdr
*phdr
= (Elf_Phdr
*)iter
;
1265 if (phdr
->p_type
== PT_LOAD
) {
1266 uptr seg_start
= phdr
->p_vaddr
+ delta
;
1267 uptr seg_end
= seg_start
+ phdr
->p_memsz
;
1268 // None of these values are aligned. We consider the ragged edges of the
1269 // load command as defined, since they are mapped from the file.
1270 seg_start
= RoundDownTo(seg_start
, GetPageSizeCached());
1271 seg_end
= RoundUpTo(seg_end
, GetPageSizeCached());
1272 cb((void *)seg_start
, seg_end
- seg_start
);
1279 #if defined(__x86_64__)
1280 // We cannot use glibc's clone wrapper, because it messes with the child
1281 // task's TLS. It writes the PID and TID of the child task to its thread
1282 // descriptor, but in our case the child task shares the thread descriptor with
1283 // the parent (because we don't know how to allocate a new thread
1284 // descriptor to keep glibc happy). So the stock version of clone(), when
1285 // used with CLONE_VM, would end up corrupting the parent's thread descriptor.
1286 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1287 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1289 if (!fn
|| !child_stack
)
1291 CHECK_EQ(0, (uptr
)child_stack
% 16);
1292 child_stack
= (char *)child_stack
- 2 * sizeof(unsigned long long);
1293 ((unsigned long long *)child_stack
)[0] = (uptr
)fn
;
1294 ((unsigned long long *)child_stack
)[1] = (uptr
)arg
;
1295 register void *r8
__asm__("r8") = newtls
;
1296 register int *r10
__asm__("r10") = child_tidptr
;
1297 __asm__
__volatile__(
1298 /* %rax = syscall(%rax = SYSCALL(clone),
1300 * %rsi = child_stack,
1301 * %rdx = parent_tidptr,
1303 * %r10 = child_tidptr)
1310 "testq %%rax,%%rax\n"
1313 /* In the child. Terminate unwind chain. */
1314 // XXX: We should also terminate the CFI unwind chain
1315 // here. Unfortunately clang 3.2 doesn't support the
1316 // necessary CFI directives, so we skip that part.
1317 "xorq %%rbp,%%rbp\n"
1319 /* Call "fn(arg)". */
1324 /* Call _exit(%rax). */
1325 "movq %%rax,%%rdi\n"
1329 /* Return to parent. */
1332 : "a"(SYSCALL(clone
)), "i"(SYSCALL(exit
)),
1338 : "memory", "r11", "rcx");
1341 #elif defined(__mips__)
1342 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1343 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1345 if (!fn
|| !child_stack
)
1347 CHECK_EQ(0, (uptr
)child_stack
% 16);
1348 child_stack
= (char *)child_stack
- 2 * sizeof(unsigned long long);
1349 ((unsigned long long *)child_stack
)[0] = (uptr
)fn
;
1350 ((unsigned long long *)child_stack
)[1] = (uptr
)arg
;
1351 register void *a3
__asm__("$7") = newtls
;
1352 register int *a4
__asm__("$8") = child_tidptr
;
1353 // We don't have proper CFI directives here because it requires alot of code
1354 // for very marginal benefits.
1355 __asm__
__volatile__(
1356 /* $v0 = syscall($v0 = __NR_clone,
1358 * $a1 = child_stack,
1359 * $a2 = parent_tidptr,
1361 * $a4 = child_tidptr)
1368 /* Store the fifth argument on stack
1369 * if we are using 32-bit abi.
1371 #if SANITIZER_WORDSIZE == 32
1384 /* Call "fn(arg)". */
1385 #if SANITIZER_WORDSIZE == 32
1386 #ifdef __BIG_ENDIAN__
1399 /* Call _exit($v0). */
1404 /* Return to parent. */
1414 : "memory", "$29" );
1417 #elif SANITIZER_RISCV64
1418 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1419 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1420 if (!fn
|| !child_stack
)
1423 CHECK_EQ(0, (uptr
)child_stack
% 16);
1425 register int res
__asm__("a0");
1426 register int __flags
__asm__("a0") = flags
;
1427 register void *__stack
__asm__("a1") = child_stack
;
1428 register int *__ptid
__asm__("a2") = parent_tidptr
;
1429 register void *__tls
__asm__("a3") = newtls
;
1430 register int *__ctid
__asm__("a4") = child_tidptr
;
1431 register int (*__fn
)(void *) __asm__("a5") = fn
;
1432 register void *__arg
__asm__("a6") = arg
;
1433 register int nr_clone
__asm__("a7") = __NR_clone
;
1435 __asm__
__volatile__(
1443 // In the child, now. Call "fn(arg)".
1448 "addi a7, zero, %9\n"
1453 : "0"(__flags
), "r"(__stack
), "r"(__ptid
), "r"(__tls
), "r"(__ctid
),
1454 "r"(__fn
), "r"(__arg
), "r"(nr_clone
), "i"(__NR_exit
)
1458 #elif defined(__aarch64__)
1459 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1460 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1461 register long long res
__asm__("x0");
1462 if (!fn
|| !child_stack
)
1464 CHECK_EQ(0, (uptr
)child_stack
% 16);
1465 child_stack
= (char *)child_stack
- 2 * sizeof(unsigned long long);
1466 ((unsigned long long *)child_stack
)[0] = (uptr
)fn
;
1467 ((unsigned long long *)child_stack
)[1] = (uptr
)arg
;
1469 register int (*__fn
)(void *) __asm__("x0") = fn
;
1470 register void *__stack
__asm__("x1") = child_stack
;
1471 register int __flags
__asm__("x2") = flags
;
1472 register void *__arg
__asm__("x3") = arg
;
1473 register int *__ptid
__asm__("x4") = parent_tidptr
;
1474 register void *__tls
__asm__("x5") = newtls
;
1475 register int *__ctid
__asm__("x6") = child_tidptr
;
1477 __asm__
__volatile__(
1478 "mov x0,x2\n" /* flags */
1479 "mov x2,x4\n" /* ptid */
1480 "mov x3,x5\n" /* tls */
1481 "mov x4,x6\n" /* ctid */
1482 "mov x8,%9\n" /* clone */
1492 /* In the child, now. Call "fn(arg)". */
1493 "ldp x1, x0, [sp], #16\n"
1496 /* Call _exit(%r0). */
1503 "r"(__fn
), "r"(__stack
), "r"(__flags
), "r"(__arg
),
1504 "r"(__ptid
), "r"(__tls
), "r"(__ctid
),
1505 "i"(__NR_clone
), "i"(__NR_exit
)
1509 #elif SANITIZER_LOONGARCH64
1510 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1511 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1512 if (!fn
|| !child_stack
)
1515 CHECK_EQ(0, (uptr
)child_stack
% 16);
1517 register int res
__asm__("$a0");
1518 register int __flags
__asm__("$a0") = flags
;
1519 register void *__stack
__asm__("$a1") = child_stack
;
1520 register int *__ptid
__asm__("$a2") = parent_tidptr
;
1521 register int *__ctid
__asm__("$a3") = child_tidptr
;
1522 register void *__tls
__asm__("$a4") = newtls
;
1523 register int (*__fn
)(void *) __asm__("$a5") = fn
;
1524 register void *__arg
__asm__("$a6") = arg
;
1525 register int nr_clone
__asm__("$a7") = __NR_clone
;
1527 __asm__
__volatile__(
1534 // In the child, now. Call "fn(arg)".
1536 "jirl $ra, $a5, 0\n"
1539 "addi.d $a7, $zero, %9\n"
1545 : "0"(__flags
), "r"(__stack
), "r"(__ptid
), "r"(__ctid
), "r"(__tls
),
1546 "r"(__fn
), "r"(__arg
), "r"(nr_clone
), "i"(__NR_exit
)
1547 : "memory", "$t0", "$t1", "$t2", "$t3", "$t4", "$t5", "$t6", "$t7", "$t8");
1550 #elif defined(__powerpc64__)
1551 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1552 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1554 // Stack frame structure.
1555 #if SANITIZER_PPC64V1
1556 // Back chain == 0 (SP + 112)
1557 // Frame (112 bytes):
1558 // Parameter save area (SP + 48), 8 doublewords
1559 // TOC save area (SP + 40)
1560 // Link editor doubleword (SP + 32)
1561 // Compiler doubleword (SP + 24)
1562 // LR save area (SP + 16)
1563 // CR save area (SP + 8)
1564 // Back chain (SP + 0)
1565 # define FRAME_SIZE 112
1566 # define FRAME_TOC_SAVE_OFFSET 40
1567 #elif SANITIZER_PPC64V2
1568 // Back chain == 0 (SP + 32)
1569 // Frame (32 bytes):
1570 // TOC save area (SP + 24)
1571 // LR save area (SP + 16)
1572 // CR save area (SP + 8)
1573 // Back chain (SP + 0)
1574 # define FRAME_SIZE 32
1575 # define FRAME_TOC_SAVE_OFFSET 24
1577 # error "Unsupported PPC64 ABI"
1579 if (!fn
|| !child_stack
)
1581 CHECK_EQ(0, (uptr
)child_stack
% 16);
1583 register int (*__fn
)(void *) __asm__("r3") = fn
;
1584 register void *__cstack
__asm__("r4") = child_stack
;
1585 register int __flags
__asm__("r5") = flags
;
1586 register void *__arg
__asm__("r6") = arg
;
1587 register int *__ptidptr
__asm__("r7") = parent_tidptr
;
1588 register void *__newtls
__asm__("r8") = newtls
;
1589 register int *__ctidptr
__asm__("r9") = child_tidptr
;
1591 __asm__
__volatile__(
1592 /* fn and arg are saved across the syscall */
1602 r7 == child_tidptr */
1610 /* Test if syscall was successful */
1611 "cmpdi cr1, 3, 0\n\t"
1612 "crandc cr1*4+eq, cr1*4+eq, cr0*4+so\n\t"
1615 /* Set up stack frame */
1617 "stdu 29, -8(1)\n\t"
1618 "stdu 1, -%12(1)\n\t"
1619 /* Do the function call */
1621 #if SANITIZER_PPC64V1
1625 #elif SANITIZER_PPC64V2
1629 # error "Unsupported PPC64 ABI"
1635 /* Call _exit(r3) */
1639 /* Return to parent */
1655 "i" (FRAME_TOC_SAVE_OFFSET
)
1656 : "cr0", "cr1", "memory", "ctr", "r0", "r27", "r28", "r29");
1659 #elif defined(__i386__)
1660 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1661 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1663 if (!fn
|| !child_stack
)
1665 CHECK_EQ(0, (uptr
)child_stack
% 16);
1666 child_stack
= (char *)child_stack
- 7 * sizeof(unsigned int);
1667 ((unsigned int *)child_stack
)[0] = (uptr
)flags
;
1668 ((unsigned int *)child_stack
)[1] = (uptr
)0;
1669 ((unsigned int *)child_stack
)[2] = (uptr
)fn
;
1670 ((unsigned int *)child_stack
)[3] = (uptr
)arg
;
1671 __asm__
__volatile__(
1672 /* %eax = syscall(%eax = SYSCALL(clone),
1674 * %ecx = child_stack,
1675 * %edx = parent_tidptr,
1677 * %edi = child_tidptr)
1681 "movl (%%ecx), %%ebx\n"
1682 /* Do the system call */
1686 /* Remember the flag value. */
1687 "movl %%ebx, (%%ecx)\n"
1697 "test %%eax,%%eax\n"
1700 /* terminate the stack frame */
1701 "xorl %%ebp,%%ebp\n"
1708 "addl $_GLOBAL_OFFSET_TABLE_+[.-here], %%ebx\n"
1711 "movl %%eax, %%ebx\n"
1716 : "a"(SYSCALL(clone
)), "i"(SYSCALL(exit
)),
1724 #elif defined(__arm__)
1725 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
1726 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
1728 if (!fn
|| !child_stack
)
1730 child_stack
= (char *)child_stack
- 2 * sizeof(unsigned int);
1731 ((unsigned int *)child_stack
)[0] = (uptr
)fn
;
1732 ((unsigned int *)child_stack
)[1] = (uptr
)arg
;
1733 register int r0
__asm__("r0") = flags
;
1734 register void *r1
__asm__("r1") = child_stack
;
1735 register int *r2
__asm__("r2") = parent_tidptr
;
1736 register void *r3
__asm__("r3") = newtls
;
1737 register int *r4
__asm__("r4") = child_tidptr
;
1738 register int r7
__asm__("r7") = __NR_clone
;
1740 #if __ARM_ARCH > 4 || defined (__ARM_ARCH_4T__)
1741 # define ARCH_HAS_BX
1744 # define ARCH_HAS_BLX
1748 # ifdef ARCH_HAS_BLX
1749 # define BLX(R) "blx " #R "\n"
1751 # define BLX(R) "mov lr, pc; bx " #R "\n"
1754 # define BLX(R) "mov lr, pc; mov pc," #R "\n"
1757 __asm__
__volatile__(
1758 /* %r0 = syscall(%r7 = SYSCALL(clone),
1760 * %r1 = child_stack,
1761 * %r2 = parent_tidptr,
1763 * %r4 = child_tidptr)
1766 /* Do the system call */
1775 /* In the child, now. Call "fn(arg)". */
1776 "ldr r0, [sp, #4]\n"
1777 "ldr ip, [sp], #8\n"
1779 /* Call _exit(%r0). */
1785 : "r"(r0
), "r"(r1
), "r"(r2
), "r"(r3
), "r"(r4
), "r"(r7
),
1791 #endif // SANITIZER_LINUX
1794 int internal_uname(struct utsname
*buf
) {
1795 return internal_syscall(SYSCALL(uname
), buf
);
1799 #if SANITIZER_ANDROID
1800 #if __ANDROID_API__ < 21
1801 extern "C" __attribute__((weak
)) int dl_iterate_phdr(
1802 int (*)(struct dl_phdr_info
*, size_t, void *), void *);
1805 static int dl_iterate_phdr_test_cb(struct dl_phdr_info
*info
, size_t size
,
1807 // Any name starting with "lib" indicates a bug in L where library base names
1808 // are returned instead of paths.
1809 if (info
->dlpi_name
&& info
->dlpi_name
[0] == 'l' &&
1810 info
->dlpi_name
[1] == 'i' && info
->dlpi_name
[2] == 'b') {
1811 *(bool *)data
= true;
1817 static atomic_uint32_t android_api_level
;
1819 static AndroidApiLevel
AndroidDetectApiLevelStatic() {
1820 #if __ANDROID_API__ <= 19
1821 return ANDROID_KITKAT
;
1822 #elif __ANDROID_API__ <= 22
1823 return ANDROID_LOLLIPOP_MR1
;
1825 return ANDROID_POST_LOLLIPOP
;
1829 static AndroidApiLevel
AndroidDetectApiLevel() {
1830 if (!&dl_iterate_phdr
)
1831 return ANDROID_KITKAT
; // K or lower
1832 bool base_name_seen
= false;
1833 dl_iterate_phdr(dl_iterate_phdr_test_cb
, &base_name_seen
);
1835 return ANDROID_LOLLIPOP_MR1
; // L MR1
1836 return ANDROID_POST_LOLLIPOP
; // post-L
1837 // Plain L (API level 21) is completely broken wrt ASan and not very
1838 // interesting to detect.
1841 extern "C" __attribute__((weak
)) void* _DYNAMIC
;
1843 AndroidApiLevel
AndroidGetApiLevel() {
1844 AndroidApiLevel level
=
1845 (AndroidApiLevel
)atomic_load(&android_api_level
, memory_order_relaxed
);
1846 if (level
) return level
;
1847 level
= &_DYNAMIC
== nullptr ? AndroidDetectApiLevelStatic()
1848 : AndroidDetectApiLevel();
1849 atomic_store(&android_api_level
, level
, memory_order_relaxed
);
1855 static HandleSignalMode
GetHandleSignalModeImpl(int signum
) {
1858 return common_flags()->handle_abort
;
1860 return common_flags()->handle_sigill
;
1862 return common_flags()->handle_sigtrap
;
1864 return common_flags()->handle_sigfpe
;
1866 return common_flags()->handle_segv
;
1868 return common_flags()->handle_sigbus
;
1870 return kHandleSignalNo
;
1873 HandleSignalMode
GetHandleSignalMode(int signum
) {
1874 HandleSignalMode result
= GetHandleSignalModeImpl(signum
);
1875 if (result
== kHandleSignalYes
&& !common_flags()->allow_user_segv_handler
)
1876 return kHandleSignalExclusive
;
1881 void *internal_start_thread(void *(*func
)(void *arg
), void *arg
) {
1882 if (&real_pthread_create
== 0)
1884 // Start the thread with signals blocked, otherwise it can steal user signals.
1885 ScopedBlockSignals
block(nullptr);
1887 real_pthread_create(&th
, nullptr, func
, arg
);
1891 void internal_join_thread(void *th
) {
1892 if (&real_pthread_join
)
1893 real_pthread_join(th
, nullptr);
1896 void *internal_start_thread(void *(*func
)(void *), void *arg
) { return 0; }
1898 void internal_join_thread(void *th
) {}
1901 #if SANITIZER_LINUX && defined(__aarch64__)
1902 // Android headers in the older NDK releases miss this definition.
1903 struct __sanitizer_esr_context
{
1904 struct _aarch64_ctx head
;
1908 static bool Aarch64GetESR(ucontext_t
*ucontext
, u64
*esr
) {
1909 static const u32 kEsrMagic
= 0x45535201;
1910 u8
*aux
= reinterpret_cast<u8
*>(ucontext
->uc_mcontext
.__reserved
);
1912 _aarch64_ctx
*ctx
= (_aarch64_ctx
*)aux
;
1913 if (ctx
->size
== 0) break;
1914 if (ctx
->magic
== kEsrMagic
) {
1915 *esr
= ((__sanitizer_esr_context
*)ctx
)->esr
;
1922 #elif SANITIZER_FREEBSD && defined(__aarch64__)
1923 // FreeBSD doesn't provide ESR in the ucontext.
1924 static bool Aarch64GetESR(ucontext_t
*ucontext
, u64
*esr
) {
1929 using Context
= ucontext_t
;
1931 SignalContext::WriteFlag
SignalContext::GetWriteFlag() const {
1932 Context
*ucontext
= (Context
*)context
;
1933 #if defined(__x86_64__) || defined(__i386__)
1934 static const uptr PF_WRITE
= 1U << 1;
1935 #if SANITIZER_FREEBSD
1936 uptr err
= ucontext
->uc_mcontext
.mc_err
;
1937 #elif SANITIZER_NETBSD
1938 uptr err
= ucontext
->uc_mcontext
.__gregs
[_REG_ERR
];
1939 #elif SANITIZER_SOLARIS && defined(__i386__)
1941 uptr err
= ucontext
->uc_mcontext
.gregs
[Err
];
1943 uptr err
= ucontext
->uc_mcontext
.gregs
[REG_ERR
];
1944 #endif // SANITIZER_FREEBSD
1945 return err
& PF_WRITE
? Write
: Read
;
1946 #elif defined(__mips__)
1947 uint32_t *exception_source
;
1948 uint32_t faulty_instruction
;
1951 exception_source
= (uint32_t *)ucontext
->uc_mcontext
.pc
;
1952 faulty_instruction
= (uint32_t)(*exception_source
);
1954 op_code
= (faulty_instruction
>> 26) & 0x3f;
1956 // FIXME: Add support for FPU, microMIPS, DSP, MSA memory instructions.
1962 #if __mips_isa_rev < 6
1968 return SignalContext::Write
;
1977 #if __mips_isa_rev < 6
1983 return SignalContext::Read
;
1984 #if __mips_isa_rev == 6
1986 op_code
= (faulty_instruction
>> 19) & 0x3;
1990 return SignalContext::Read
;
1994 return SignalContext::Unknown
;
1995 #elif defined(__arm__)
1996 static const uptr FSR_WRITE
= 1U << 11;
1997 uptr fsr
= ucontext
->uc_mcontext
.error_code
;
1998 return fsr
& FSR_WRITE
? Write
: Read
;
1999 #elif defined(__aarch64__)
2000 static const u64 ESR_ELx_WNR
= 1U << 6;
2002 if (!Aarch64GetESR(ucontext
, &esr
)) return Unknown
;
2003 return esr
& ESR_ELx_WNR
? Write
: Read
;
2004 #elif defined(__loongarch__)
2005 u32 flags
= ucontext
->uc_mcontext
.__flags
;
2006 if (flags
& SC_ADDRERR_RD
)
2007 return SignalContext::Read
;
2008 if (flags
& SC_ADDRERR_WR
)
2009 return SignalContext::Write
;
2010 return SignalContext::Unknown
;
2011 #elif defined(__sparc__)
2012 // Decode the instruction to determine the access type.
2013 // From OpenSolaris $SRC/uts/sun4/os/trap.c (get_accesstype).
2014 #if SANITIZER_SOLARIS
2015 uptr pc
= ucontext
->uc_mcontext
.gregs
[REG_PC
];
2017 // Historical BSDism here.
2018 struct sigcontext
*scontext
= (struct sigcontext
*)context
;
2019 #if defined(__arch64__)
2020 uptr pc
= scontext
->sigc_regs
.tpc
;
2022 uptr pc
= scontext
->si_regs
.pc
;
2025 u32 instr
= *(u32
*)pc
;
2026 return (instr
>> 21) & 1 ? Write
: Read
;
2027 #elif defined(__riscv)
2028 #if SANITIZER_FREEBSD
2029 unsigned long pc
= ucontext
->uc_mcontext
.mc_gpregs
.gp_sepc
;
2031 unsigned long pc
= ucontext
->uc_mcontext
.__gregs
[REG_PC
];
2033 unsigned faulty_instruction
= *(uint16_t *)pc
;
2035 #if defined(__riscv_compressed)
2036 if ((faulty_instruction
& 0x3) != 0x3) { // it's a compressed instruction
2037 // set op_bits to the instruction bits [1, 0, 15, 14, 13]
2039 ((faulty_instruction
& 0x3) << 3) | (faulty_instruction
>> 13);
2040 unsigned rd
= faulty_instruction
& 0xF80; // bits 7-11, inclusive
2042 case 0b10'010: // c.lwsp (rd != x0)
2043 #if __riscv_xlen == 64
2044 case 0b10'011: // c.ldsp (rd != x0)
2046 return rd
? SignalContext::Read
: SignalContext::Unknown
;
2047 case 0b00'010: // c.lw
2048 #if __riscv_flen >= 32 && __riscv_xlen == 32
2049 case 0b10'011: // c.flwsp
2051 #if __riscv_flen >= 32 || __riscv_xlen == 64
2052 case 0b00'011: // c.flw / c.ld
2054 #if __riscv_flen == 64
2055 case 0b00'001: // c.fld
2056 case 0b10'001: // c.fldsp
2058 return SignalContext::Read
;
2059 case 0b00'110: // c.sw
2060 case 0b10'110: // c.swsp
2061 #if __riscv_flen >= 32 || __riscv_xlen == 64
2062 case 0b00'111: // c.fsw / c.sd
2063 case 0b10'111: // c.fswsp / c.sdsp
2065 #if __riscv_flen == 64
2066 case 0b00'101: // c.fsd
2067 case 0b10'101: // c.fsdsp
2069 return SignalContext::Write
;
2071 return SignalContext::Unknown
;
2076 unsigned opcode
= faulty_instruction
& 0x7f; // lower 7 bits
2077 unsigned funct3
= (faulty_instruction
>> 12) & 0x7; // bits 12-14, inclusive
2079 case 0b0000011: // loads
2084 #if __riscv_xlen == 64
2089 return SignalContext::Read
;
2091 return SignalContext::Unknown
;
2093 case 0b0100011: // stores
2098 #if __riscv_xlen == 64
2101 return SignalContext::Write
;
2103 return SignalContext::Unknown
;
2105 #if __riscv_flen >= 32
2106 case 0b0000111: // floating-point loads
2109 #if __riscv_flen == 64
2112 return SignalContext::Read
;
2114 return SignalContext::Unknown
;
2116 case 0b0100111: // floating-point stores
2119 #if __riscv_flen == 64
2122 return SignalContext::Write
;
2124 return SignalContext::Unknown
;
2128 return SignalContext::Unknown
;
2132 return Unknown
; // FIXME: Implement.
2136 bool SignalContext::IsTrueFaultingAddress() const {
2137 auto si
= static_cast<const siginfo_t
*>(siginfo
);
2138 // SIGSEGV signals without a true fault address have si_code set to 128.
2139 return si
->si_signo
== SIGSEGV
&& si
->si_code
!= 128;
2142 void SignalContext::DumpAllRegisters(void *context
) {
2143 // FIXME: Implement this.
2146 static void GetPcSpBp(void *context
, uptr
*pc
, uptr
*sp
, uptr
*bp
) {
2147 #if SANITIZER_NETBSD
2148 // This covers all NetBSD architectures
2149 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2150 *pc
= _UC_MACHINE_PC(ucontext
);
2151 *bp
= _UC_MACHINE_FP(ucontext
);
2152 *sp
= _UC_MACHINE_SP(ucontext
);
2153 #elif defined(__arm__)
2154 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2155 *pc
= ucontext
->uc_mcontext
.arm_pc
;
2156 *bp
= ucontext
->uc_mcontext
.arm_fp
;
2157 *sp
= ucontext
->uc_mcontext
.arm_sp
;
2158 #elif defined(__aarch64__)
2159 # if SANITIZER_FREEBSD
2160 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2161 *pc
= ucontext
->uc_mcontext
.mc_gpregs
.gp_elr
;
2162 *bp
= ucontext
->uc_mcontext
.mc_gpregs
.gp_x
[29];
2163 *sp
= ucontext
->uc_mcontext
.mc_gpregs
.gp_sp
;
2165 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2166 *pc
= ucontext
->uc_mcontext
.pc
;
2167 *bp
= ucontext
->uc_mcontext
.regs
[29];
2168 *sp
= ucontext
->uc_mcontext
.sp
;
2170 #elif defined(__hppa__)
2171 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2172 *pc
= ucontext
->uc_mcontext
.sc_iaoq
[0];
2173 /* GCC uses %r3 whenever a frame pointer is needed. */
2174 *bp
= ucontext
->uc_mcontext
.sc_gr
[3];
2175 *sp
= ucontext
->uc_mcontext
.sc_gr
[30];
2176 #elif defined(__x86_64__)
2177 # if SANITIZER_FREEBSD
2178 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2179 *pc
= ucontext
->uc_mcontext
.mc_rip
;
2180 *bp
= ucontext
->uc_mcontext
.mc_rbp
;
2181 *sp
= ucontext
->uc_mcontext
.mc_rsp
;
2183 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2184 *pc
= ucontext
->uc_mcontext
.gregs
[REG_RIP
];
2185 *bp
= ucontext
->uc_mcontext
.gregs
[REG_RBP
];
2186 *sp
= ucontext
->uc_mcontext
.gregs
[REG_RSP
];
2188 #elif defined(__i386__)
2189 # if SANITIZER_FREEBSD
2190 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2191 *pc
= ucontext
->uc_mcontext
.mc_eip
;
2192 *bp
= ucontext
->uc_mcontext
.mc_ebp
;
2193 *sp
= ucontext
->uc_mcontext
.mc_esp
;
2195 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2196 # if SANITIZER_SOLARIS
2197 /* Use the numeric values: the symbolic ones are undefined by llvm
2198 include/llvm/Support/Solaris.h. */
2200 # define REG_EIP 14 // REG_PC
2203 # define REG_EBP 6 // REG_FP
2206 # define REG_UESP 17 // REG_SP
2209 *pc
= ucontext
->uc_mcontext
.gregs
[REG_EIP
];
2210 *bp
= ucontext
->uc_mcontext
.gregs
[REG_EBP
];
2211 *sp
= ucontext
->uc_mcontext
.gregs
[REG_UESP
];
2213 #elif defined(__powerpc__) || defined(__powerpc64__)
2214 # if SANITIZER_FREEBSD
2215 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2216 *pc
= ucontext
->uc_mcontext
.mc_srr0
;
2217 *sp
= ucontext
->uc_mcontext
.mc_frame
[1];
2218 *bp
= ucontext
->uc_mcontext
.mc_frame
[31];
2220 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2221 *pc
= ucontext
->uc_mcontext
.regs
->nip
;
2222 *sp
= ucontext
->uc_mcontext
.regs
->gpr
[PT_R1
];
2223 // The powerpc{,64}-linux ABIs do not specify r31 as the frame
2224 // pointer, but GCC always uses r31 when we need a frame pointer.
2225 *bp
= ucontext
->uc_mcontext
.regs
->gpr
[PT_R31
];
2227 #elif defined(__sparc__)
2228 #if defined(__arch64__) || defined(__sparcv9)
2229 #define STACK_BIAS 2047
2231 #define STACK_BIAS 0
2233 # if SANITIZER_SOLARIS
2234 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2235 *pc
= ucontext
->uc_mcontext
.gregs
[REG_PC
];
2236 *sp
= ucontext
->uc_mcontext
.gregs
[REG_O6
] + STACK_BIAS
;
2238 // Historical BSDism here.
2239 struct sigcontext
*scontext
= (struct sigcontext
*)context
;
2240 #if defined(__arch64__)
2241 *pc
= scontext
->sigc_regs
.tpc
;
2242 *sp
= scontext
->sigc_regs
.u_regs
[14] + STACK_BIAS
;
2244 *pc
= scontext
->si_regs
.pc
;
2245 *sp
= scontext
->si_regs
.u_regs
[14];
2248 *bp
= (uptr
)((uhwptr
*)*sp
)[14] + STACK_BIAS
;
2249 #elif defined(__mips__)
2250 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2251 *pc
= ucontext
->uc_mcontext
.pc
;
2252 *bp
= ucontext
->uc_mcontext
.gregs
[30];
2253 *sp
= ucontext
->uc_mcontext
.gregs
[29];
2254 #elif defined(__s390__)
2255 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2256 # if defined(__s390x__)
2257 *pc
= ucontext
->uc_mcontext
.psw
.addr
;
2259 *pc
= ucontext
->uc_mcontext
.psw
.addr
& 0x7fffffff;
2261 *bp
= ucontext
->uc_mcontext
.gregs
[11];
2262 *sp
= ucontext
->uc_mcontext
.gregs
[15];
2263 #elif defined(__riscv)
2264 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2265 # if SANITIZER_FREEBSD
2266 *pc
= ucontext
->uc_mcontext
.mc_gpregs
.gp_sepc
;
2267 *bp
= ucontext
->uc_mcontext
.mc_gpregs
.gp_s
[0];
2268 *sp
= ucontext
->uc_mcontext
.mc_gpregs
.gp_sp
;
2270 *pc
= ucontext
->uc_mcontext
.__gregs
[REG_PC
];
2271 *bp
= ucontext
->uc_mcontext
.__gregs
[REG_S0
];
2272 *sp
= ucontext
->uc_mcontext
.__gregs
[REG_SP
];
2274 # elif defined(__hexagon__)
2275 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2276 *pc
= ucontext
->uc_mcontext
.pc
;
2277 *bp
= ucontext
->uc_mcontext
.r30
;
2278 *sp
= ucontext
->uc_mcontext
.r29
;
2279 # elif defined(__loongarch__)
2280 ucontext_t
*ucontext
= (ucontext_t
*)context
;
2281 *pc
= ucontext
->uc_mcontext
.__pc
;
2282 *bp
= ucontext
->uc_mcontext
.__gregs
[22];
2283 *sp
= ucontext
->uc_mcontext
.__gregs
[3];
2285 # error "Unsupported arch"
2289 void SignalContext::InitPcSpBp() { GetPcSpBp(context
, &pc
, &sp
, &bp
); }
2291 void InitializePlatformEarly() {
2296 #if SANITIZER_NETBSD
2299 uptr len
= sizeof(paxflags
);
2302 mib
[1] = internal_getpid();
2303 mib
[2] = PROC_PID_PAXFLAGS
;
2305 if (UNLIKELY(internal_sysctl(mib
, 3, &paxflags
, &len
, NULL
, 0) == -1)) {
2306 Printf("sysctl failed\n");
2310 if (UNLIKELY(paxflags
& CTL_PROC_PAXFLAGS_ASLR
)) {
2311 Printf("This sanitizer is not compatible with enabled ASLR.\n"
2312 "To disable ASLR, please run \"paxctl +a %s\" and try again.\n",
2316 #elif SANITIZER_FREEBSD
2318 int r
= internal_procctl(P_PID
, 0, PROC_ASLR_STATUS
, &aslr_status
);
2319 if (UNLIKELY(r
== -1)) {
2320 // We're making things less 'dramatic' here since
2321 // the cmd is not necessarily guaranteed to be here
2322 // just yet regarding FreeBSD release
2325 if ((aslr_status
& PROC_ASLR_ACTIVE
) != 0) {
2326 Printf("This sanitizer is not compatible with enabled ASLR "
2327 "and binaries compiled with PIE\n");
2330 # elif SANITIZER_PPC64V2
2331 // Disable ASLR for Linux PPC64LE.
2332 int old_personality
= personality(0xffffffff);
2333 if (old_personality
!= -1 && (old_personality
& ADDR_NO_RANDOMIZE
) == 0) {
2335 "WARNING: Program is being run with address space layout "
2336 "randomization (ASLR) enabled which prevents the thread and "
2337 "memory sanitizers from working on powerpc64le.\n"
2338 "ASLR will be disabled and the program re-executed.\n");
2339 CHECK_NE(personality(old_personality
| ADDR_NO_RANDOMIZE
), -1);
2347 void CheckMPROTECT() {
2348 #if SANITIZER_NETBSD
2351 uptr len
= sizeof(paxflags
);
2354 mib
[1] = internal_getpid();
2355 mib
[2] = PROC_PID_PAXFLAGS
;
2357 if (UNLIKELY(internal_sysctl(mib
, 3, &paxflags
, &len
, NULL
, 0) == -1)) {
2358 Printf("sysctl failed\n");
2362 if (UNLIKELY(paxflags
& CTL_PROC_PAXFLAGS_MPROTECT
)) {
2363 Printf("This sanitizer is not compatible with enabled MPROTECT\n");
2371 void CheckNoDeepBind(const char *filename
, int flag
) {
2372 #ifdef RTLD_DEEPBIND
2373 if (flag
& RTLD_DEEPBIND
) {
2375 "You are trying to dlopen a %s shared library with RTLD_DEEPBIND flag"
2376 " which is incompatible with sanitizer runtime "
2377 "(see https://github.com/google/sanitizers/issues/611 for details"
2378 "). If you want to run %s library under sanitizers please remove "
2379 "RTLD_DEEPBIND from dlopen flags.\n",
2380 filename
, filename
);
2386 uptr
FindAvailableMemoryRange(uptr size
, uptr alignment
, uptr left_padding
,
2387 uptr
*largest_gap_found
,
2388 uptr
*max_occupied_addr
) {
2389 UNREACHABLE("FindAvailableMemoryRange is not available");
2393 bool GetRandom(void *buffer
, uptr length
, bool blocking
) {
2394 if (!buffer
|| !length
|| length
> 256)
2396 #if SANITIZER_USE_GETENTROPY
2397 uptr rnd
= getentropy(buffer
, length
);
2399 if (internal_iserror(rnd
, &rverrno
) && rverrno
== EFAULT
)
2403 #endif // SANITIZER_USE_GETENTROPY
2405 #if SANITIZER_USE_GETRANDOM
2406 static atomic_uint8_t skip_getrandom_syscall
;
2407 if (!atomic_load_relaxed(&skip_getrandom_syscall
)) {
2408 // Up to 256 bytes, getrandom will not be interrupted.
2409 uptr res
= internal_syscall(SYSCALL(getrandom
), buffer
, length
,
2410 blocking
? 0 : GRND_NONBLOCK
);
2412 if (internal_iserror(res
, &rverrno
) && rverrno
== ENOSYS
)
2413 atomic_store_relaxed(&skip_getrandom_syscall
, 1);
2414 else if (res
== length
)
2417 #endif // SANITIZER_USE_GETRANDOM
2418 // Up to 256 bytes, a read off /dev/urandom will not be interrupted.
2419 // blocking is moot here, O_NONBLOCK has no effect when opening /dev/urandom.
2420 uptr fd
= internal_open("/dev/urandom", O_RDONLY
);
2421 if (internal_iserror(fd
))
2423 uptr res
= internal_read(fd
, buffer
, length
);
2424 if (internal_iserror(res
))
2430 } // namespace __sanitizer