[clang][extract-api] Emit "navigator" property of "name" in SymbolGraph
[llvm-project.git] / compiler-rt / lib / sanitizer_common / sanitizer_linux.cpp
blob84a46b51e1e95ca6f4257149a79edbc79e61fd83
1 //===-- sanitizer_linux.cpp -----------------------------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is shared between AddressSanitizer and ThreadSanitizer
10 // run-time libraries and implements linux-specific functions from
11 // sanitizer_libc.h.
12 //===----------------------------------------------------------------------===//
14 #include "sanitizer_platform.h"
16 #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD || \
17 SANITIZER_SOLARIS
19 #include "sanitizer_common.h"
20 #include "sanitizer_flags.h"
21 #include "sanitizer_getauxval.h"
22 #include "sanitizer_internal_defs.h"
23 #include "sanitizer_libc.h"
24 #include "sanitizer_linux.h"
25 #include "sanitizer_mutex.h"
26 #include "sanitizer_placement_new.h"
27 #include "sanitizer_procmaps.h"
29 #if SANITIZER_LINUX && !SANITIZER_GO
30 #include <asm/param.h>
31 #endif
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.
37 #if defined(__mips64)
38 #include <asm/unistd.h>
39 #include <sys/types.h>
40 #define stat kernel_stat
41 #if SANITIZER_GO
42 #undef st_atime
43 #undef st_mtime
44 #undef st_ctime
45 #define st_atime st_atim
46 #define st_mtime st_mtim
47 #define st_ctime st_ctim
48 #endif
49 #include <asm/stat.h>
50 #undef stat
51 #endif
53 #include <dlfcn.h>
54 #include <errno.h>
55 #include <fcntl.h>
56 #include <link.h>
57 #include <pthread.h>
58 #include <sched.h>
59 #include <signal.h>
60 #include <sys/mman.h>
61 #include <sys/param.h>
62 #if !SANITIZER_SOLARIS
63 #include <sys/ptrace.h>
64 #endif
65 #include <sys/resource.h>
66 #include <sys/stat.h>
67 #include <sys/syscall.h>
68 #include <sys/time.h>
69 #include <sys/types.h>
70 #include <ucontext.h>
71 #include <unistd.h>
73 #if SANITIZER_LINUX
74 #include <sys/utsname.h>
75 #endif
77 #if SANITIZER_LINUX && !SANITIZER_ANDROID
78 #include <sys/personality.h>
79 #endif
81 #if SANITIZER_FREEBSD
82 #include <sys/exec.h>
83 #include <sys/procctl.h>
84 #include <sys/sysctl.h>
85 #include <machine/atomic.h>
86 extern "C" {
87 // <sys/umtx.h> must be included after <errno.h> and <sys/types.h> on
88 // FreeBSD 9.2 and 10.0.
89 #include <sys/umtx.h>
91 #include <sys/thr.h>
92 #endif // SANITIZER_FREEBSD
94 #if SANITIZER_NETBSD
95 #include <limits.h> // For NAME_MAX
96 #include <sys/sysctl.h>
97 #include <sys/exec.h>
98 extern struct ps_strings *__ps_strings;
99 #endif // SANITIZER_NETBSD
101 #if SANITIZER_SOLARIS
102 #include <stdlib.h>
103 #include <thread.h>
104 #define environ _environ
105 #endif
107 extern char **environ;
109 #if SANITIZER_LINUX
110 // <linux/time.h>
111 struct kernel_timeval {
112 long tv_sec;
113 long tv_usec;
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
130 #else
131 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 0
132 #endif
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
140 # endif
141 # define SANITIZER_USE_GETRANDOM 1
142 #else
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
148 #else
149 # define SANITIZER_USE_GETENTROPY 0
150 #endif
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);
166 # endif
167 # if SANITIZER_LINUX
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
170 // hang.
171 internal_sigdelset(&set, 31);
172 # endif
173 SetSigProcMask(&set, &saved_);
174 if (copy)
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"
190 # else
191 # include "sanitizer_syscall_generic.inc"
192 # endif
194 // --------------- sanitizer_libc.h
195 #if !SANITIZER_SOLARIS && !SANITIZER_NETBSD
196 #if !SANITIZER_S390
197 uptr internal_mmap(void *addr, uptr length, int prot, int flags, int fd,
198 u64 offset) {
199 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
200 return internal_syscall(SYSCALL(mmap), (uptr)addr, length, prot, flags, fd,
201 offset);
202 #else
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,
206 offset / 4096);
207 #endif
209 #endif // !SANITIZER_S390
211 uptr internal_munmap(void *addr, uptr length) {
212 return internal_syscall(SYSCALL(munmap), (uptr)addr, length);
215 #if SANITIZER_LINUX
216 uptr internal_mremap(void *old_address, uptr old_size, uptr new_size, int flags,
217 void *new_address) {
218 return internal_syscall(SYSCALL(mremap), (uptr)old_address, old_size,
219 new_size, flags, (uptr)new_address);
221 #endif
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);
238 #else
239 return internal_syscall(SYSCALL(open), (uptr)filename, flags);
240 #endif
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,
246 mode);
247 #else
248 return internal_syscall(SYSCALL(open), (uptr)filename, flags, mode);
249 #endif
252 uptr internal_read(fd_t fd, void *buf, uptr count) {
253 sptr res;
254 HANDLE_EINTR(res,
255 (sptr)internal_syscall(SYSCALL(read), fd, (uptr)buf, count));
256 return res;
259 uptr internal_write(fd_t fd, const void *buf, uptr count) {
260 sptr res;
261 HANDLE_EINTR(res,
262 (sptr)internal_syscall(SYSCALL(write), fd, (uptr)buf, count));
263 return res;
266 uptr internal_ftruncate(fd_t fd, uptr size) {
267 sptr res;
268 HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(ftruncate), fd,
269 (OFF_T)size));
270 return res;
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;
290 #endif
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
296 #if !SANITIZER_GO
297 #undef st_atime
298 #undef st_mtime
299 #undef st_ctime
300 #endif
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.
306 #undef st_atime_nsec
307 #undef st_mtime_nsec
308 #undef st_ctime_nsec
309 #endif
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;
331 #else
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;
338 #endif
340 #endif
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);
354 return res;
355 # else
356 return internal_syscall(SYSCALL(stat), (uptr)path, (uptr)buf);
357 # endif
358 #else
359 struct stat64 buf64;
360 int res = internal_syscall(SYSCALL(stat64), path, &buf64);
361 stat64_to_stat(&buf64, (struct stat *)buf);
362 return res;
363 #endif
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);
379 return res;
380 # else
381 return internal_syscall(SYSCALL(lstat), (uptr)path, (uptr)buf);
382 # endif
383 #else
384 struct stat64 buf64;
385 int res = internal_syscall(SYSCALL(lstat64), path, &buf64);
386 stat64_to_stat(&buf64, (struct stat *)buf);
387 return res;
388 #endif
391 uptr internal_fstat(fd_t fd, void *buf) {
392 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
393 #if SANITIZER_MIPS64
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);
398 return res;
399 # else
400 return internal_syscall(SYSCALL(fstat), fd, (uptr)buf);
401 # endif
402 #else
403 struct stat64 buf64;
404 int res = internal_syscall(SYSCALL(fstat64), fd, &buf64);
405 stat64_to_stat(&buf64, (struct stat *)buf);
406 return res;
407 #endif
410 uptr internal_filesize(fd_t fd) {
411 struct stat st;
412 if (internal_fstat(fd, &st))
413 return -1;
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);
424 #else
425 return internal_syscall(SYSCALL(dup2), oldfd, newfd);
426 #endif
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,
432 bufsize);
433 #else
434 return internal_syscall(SYSCALL(readlink), (uptr)path, (uptr)buf, bufsize);
435 #endif
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);
441 #else
442 return internal_syscall(SYSCALL(unlink), (uptr)path);
443 #endif
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,
449 (uptr)newpath, 0);
450 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
451 return internal_syscall(SYSCALL(renameat), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
452 (uptr)newpath);
453 #else
454 return internal_syscall(SYSCALL(rename), (uptr)oldpath, (uptr)newpath);
455 #endif
458 uptr internal_sched_yield() {
459 return internal_syscall(SYSCALL(sched_yield));
462 void internal_usleep(u64 useconds) {
463 struct timespec ts;
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,
472 (uptr)envp);
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);
480 #else
481 internal_syscall(SYSCALL(exit_group), exitcode);
482 #endif
483 Die(); // Unreachable.
485 #endif // !SANITIZER_NETBSD
487 // ----------------- sanitizer_common.h
488 bool FileExists(const char *filename) {
489 if (ShouldMockFailureToOpen(filename))
490 return false;
491 struct stat st;
492 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
493 if (internal_syscall(SYSCALL(newfstatat), AT_FDCWD, filename, &st, 0))
494 #else
495 if (internal_stat(filename, &st))
496 #endif
497 return false;
498 // Sanity check: filename is a regular file.
499 return S_ISREG(st.st_mode);
502 bool DirExists(const char *path) {
503 struct stat st;
504 # if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
505 if (internal_syscall(SYSCALL(newfstatat), AT_FDCWD, path, &st, 0))
506 # else
507 if (internal_stat(path, &st))
508 # endif
509 return false;
510 return S_ISDIR(st.st_mode);
513 # if !SANITIZER_NETBSD
514 tid_t GetTid() {
515 #if SANITIZER_FREEBSD
516 long Tid;
517 thr_self(&Tid);
518 return Tid;
519 #elif SANITIZER_SOLARIS
520 return thr_self();
521 #else
522 return internal_syscall(SYSCALL(gettid));
523 #endif
526 int TgKill(pid_t pid, tid_t tid, int sig) {
527 #if SANITIZER_LINUX
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
532 (void)pid;
533 return thr_kill(tid, sig);
534 #endif
536 #endif
538 #if SANITIZER_GLIBC
539 u64 NanoTime() {
540 kernel_timeval tv;
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
550 u64 NanoTime() {
551 struct timespec ts;
552 clock_gettime(CLOCK_REALTIME, &ts);
553 return (u64)ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec;
555 #endif
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;
572 static uptr len;
573 static bool inited;
574 if (!inited) {
575 inited = true;
576 uptr environ_size;
577 if (!ReadFileToBuffer("/proc/self/environ", &environ, &environ_size, &len))
578 environ = nullptr;
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...
585 const char* endp =
586 (char*)internal_memchr(p, '\0', len - (p - environ));
587 if (!endp) // this entry isn't NUL terminated
588 return nullptr;
589 else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') // Match.
590 return p + namelen + 1; // point after =
591 p = endp + 1;
593 return nullptr; // Not found.
594 #else
595 #error "Unsupported platform"
596 #endif
599 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD && !SANITIZER_GO
600 extern "C" {
601 SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
603 #endif
605 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
606 static void ReadNullSepFileToArray(const char *path, char ***arr,
607 int arr_size) {
608 char *buff;
609 uptr buff_size;
610 uptr buff_len;
611 *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
612 if (!ReadFileToBuffer(path, &buff, &buff_size, &buff_len, 1024 * 1024)) {
613 (*arr)[0] = nullptr;
614 return;
616 (*arr)[0] = buff;
617 int count, i;
618 for (count = 1, i = 1; ; i++) {
619 if (buff[i] == 0) {
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.
623 count++;
626 (*arr)[count] = nullptr;
628 #endif
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>.
635 ps_strings *pss;
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");
639 Die();
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
647 #if !SANITIZER_GO
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.
654 int argc = 0;
655 while (stack_end[argc + 1]) argc++;
656 *argv = (char**)(stack_end + 1);
657 *envp = (char**)(stack_end + argc + 2);
658 } else {
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);
663 #if !SANITIZER_GO
665 #endif // !SANITIZER_GO
666 #endif // SANITIZER_FREEBSD
669 char **GetArgv() {
670 char **argv, **envp;
671 GetArgsAndEnv(&argv, &envp);
672 return argv;
675 char **GetEnviron() {
676 char **argv, **envp;
677 GetArgsAndEnv(&argv, &envp);
678 return 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 */
687 # else
688 internal_syscall(SYSCALL(futex), (uptr)p, FUTEX_WAIT_PRIVATE, cmp, 0, 0, 0);
689 # endif
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 */
697 # else
698 internal_syscall(SYSCALL(futex), (uptr)p, FUTEX_WAKE_PRIVATE, count, 0, 0, 0);
699 # endif
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.
708 #if SANITIZER_NETBSD
709 // Not used
710 #else
711 struct linux_dirent {
712 #if SANITIZER_X32 || defined(__aarch64__) || SANITIZER_RISCV64
713 u64 d_ino;
714 u64 d_off;
715 #else
716 unsigned long d_ino;
717 unsigned long d_off;
718 #endif
719 unsigned short d_reclen;
720 #if defined(__aarch64__) || SANITIZER_RISCV64
721 unsigned char d_type;
722 #endif
723 char d_name[256];
725 #endif
727 #if !SANITIZER_SOLARIS && !SANITIZER_NETBSD
728 // Syscall wrappers.
729 uptr internal_ptrace(int request, int pid, void *addr, void *data) {
730 return internal_syscall(SYSCALL(ptrace), request, pid, (uptr)addr,
731 (uptr)data);
734 uptr internal_waitpid(int pid, int *status, int options) {
735 return internal_syscall(SYSCALL(wait4), pid, (uptr)status, options,
736 0 /* rusage */);
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);
750 #else
751 UNIMPLEMENTED();
752 #endif
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);
760 #else
761 return internal_syscall(SYSCALL(getdents), fd, (uptr)dirp, count);
762 #endif
765 uptr internal_lseek(fd_t fd, OFF_T offset, int whence) {
766 return internal_syscall(SYSCALL(lseek), fd, offset, whence);
769 #if SANITIZER_LINUX
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);
773 #endif
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);
782 #else
783 return internal_syscall(SYSCALL(fork));
784 #endif
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,
805 (size_t)newlen);
806 #else
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)
816 return (-1);
817 return internal_sysctl(oid, len, oldp, oldlenp, newp, newlen);
818 #endif
820 #endif
822 #if SANITIZER_LINUX
823 #define SA_RESTORER 0x04000000
824 // Doesn't set sa_restorer if the caller did not set it, so use with caution
825 //(see below).
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;
832 if (u_act) {
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;
849 #endif
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;
865 #endif
867 return result;
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);
875 #else
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));
880 #endif
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));
891 #if SANITIZER_LINUX
892 void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
893 signum -= 1;
894 CHECK_GE(signum, 0);
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) {
903 signum -= 1;
904 CHECK_GE(signum, 0);
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);
921 #endif
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_))
939 return Error;
940 internal_lseek(descriptor_, 0, SEEK_SET);
941 threads->clear();
943 Result result = Ok;
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());
950 if (!read)
951 return result;
952 if (internal_iserror(read)) {
953 Report("Can't read directory entries from /proc/%d/task.\n", pid_);
954 return Error;
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.
964 result = Incomplete;
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.
974 if (!first_read) {
975 // The first one was a short-read by definition.
976 result = Incomplete;
977 } else if (read > buffer_.size() - 1024) {
978 // Read was close to the buffer size. So double the size and assume the
979 // worst.
980 buffer_.resize(buffer_.size() * 2);
981 result = Incomplete;
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.
986 result = Incomplete;
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.
994 char path[80];
995 internal_snprintf(path, sizeof(path), "/proc/%d/task/%d/status", pid_, tid);
996 if (!ReadFileToVector(path, &buffer_) || buffer_.empty())
997 return false;
998 buffer_.push_back(0);
999 static const char kPrefix[] = "\nPPid:";
1000 const char *field = internal_strstr(buffer_.data(), kPrefix);
1001 if (!field)
1002 return false;
1003 field += internal_strlen(kPrefix);
1004 return (int)internal_atoll(field) != 0;
1007 ThreadLister::~ThreadLister() {
1008 if (!internal_iserror(descriptor_))
1009 internal_close(descriptor_);
1011 #endif
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())
1023 return 0;
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"))
1038 return 0;
1039 #endif // SANITIZER_ANDROID
1041 // Top gigabyte is reserved for kernel.
1042 return gbyte;
1043 #else
1044 return 0;
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__)
1069 return ~(uptr)0;
1070 # else
1071 return (1ULL << 47) - 1; // 0x00007fffffffffffUL;
1072 # endif
1073 #else // SANITIZER_WORDSIZE == 32
1074 # if defined(__s390__)
1075 return (1ULL << 31) - 1; // 0x7fffffff;
1076 # else
1077 return (1ULL << 32) - 1; // 0xffffffff;
1078 # endif
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);
1088 #endif
1089 return 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.
1099 int pz = 0;
1100 uptr pzl = sizeof(pz);
1101 int mib[2] = {CTL_HW, HW_PAGESIZE};
1102 int rv = internal_sysctl(mib, 2, &pz, &pzl, nullptr, 0);
1103 CHECK_EQ(rv, 0);
1104 return (uptr)pz;
1105 #elif SANITIZER_USE_GETAUXVAL
1106 return getauxval(AT_PAGESZ);
1107 #else
1108 return sysconf(_SC_PAGESIZE); // EXEC_PAGESIZE may not be trustworthy.
1109 #endif
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);
1118 #else
1119 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
1120 #if SANITIZER_FREEBSD
1121 const int Mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
1122 #else
1123 const int Mib[4] = {CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME};
1124 #endif
1125 const char *default_module_name = "kern.proc.pathname";
1126 uptr Size = buf_len;
1127 bool IsErr =
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;
1131 #else
1132 const char *default_module_name = "/proc/self/exe";
1133 uptr module_name_len = internal_readlink(
1134 default_module_name, buf, buf_len);
1135 int readlink_error;
1136 bool IsErr = internal_iserror(module_name_len, &readlink_error);
1137 #endif // SANITIZER_SOLARIS
1138 if (IsErr) {
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;
1147 #endif
1150 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len) {
1151 #if SANITIZER_LINUX
1152 char *tmpbuf;
1153 uptr tmpsize;
1154 uptr tmplen;
1155 if (ReadFileToBuffer("/proc/self/cmdline", &tmpbuf, &tmpsize, &tmplen,
1156 1024 * 1024)) {
1157 internal_strncpy(buf, tmpbuf, buf_len);
1158 UnmapOrDie(tmpbuf, tmpsize);
1159 return internal_strlen(buf);
1161 #endif
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;
1168 // Strip path.
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);
1216 #endif
1218 #if SANITIZER_LINUX
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) {
1228 long long res;
1229 if (!fn || !child_stack)
1230 return -EINVAL;
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),
1239 * %rdi = flags,
1240 * %rsi = child_stack,
1241 * %rdx = parent_tidptr,
1242 * %r8 = new_tls,
1243 * %r10 = child_tidptr)
1245 "syscall\n"
1247 /* if (%rax != 0)
1248 * return;
1250 "testq %%rax,%%rax\n"
1251 "jnz 1f\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)". */
1260 "popq %%rax\n"
1261 "popq %%rdi\n"
1262 "call *%%rax\n"
1264 /* Call _exit(%rax). */
1265 "movq %%rax,%%rdi\n"
1266 "movq %2,%%rax\n"
1267 "syscall\n"
1269 /* Return to parent. */
1270 "1:\n"
1271 : "=a" (res)
1272 : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
1273 "S"(child_stack),
1274 "D"(flags),
1275 "d"(parent_tidptr),
1276 "r"(r8),
1277 "r"(r10)
1278 : "memory", "r11", "rcx");
1279 return res;
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) {
1284 long long res;
1285 if (!fn || !child_stack)
1286 return -EINVAL;
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,
1297 * $a0 = flags,
1298 * $a1 = child_stack,
1299 * $a2 = parent_tidptr,
1300 * $a3 = new_tls,
1301 * $a4 = child_tidptr)
1303 ".cprestore 16;\n"
1304 "move $4,%1;\n"
1305 "move $5,%2;\n"
1306 "move $6,%3;\n"
1307 "move $7,%4;\n"
1308 /* Store the fifth argument on stack
1309 * if we are using 32-bit abi.
1311 #if SANITIZER_WORDSIZE == 32
1312 "lw %5,16($29);\n"
1313 #else
1314 "move $8,%5;\n"
1315 #endif
1316 "li $2,%6;\n"
1317 "syscall;\n"
1319 /* if ($v0 != 0)
1320 * return;
1322 "bnez $2,1f;\n"
1324 /* Call "fn(arg)". */
1325 #if SANITIZER_WORDSIZE == 32
1326 #ifdef __BIG_ENDIAN__
1327 "lw $25,4($29);\n"
1328 "lw $4,12($29);\n"
1329 #else
1330 "lw $25,0($29);\n"
1331 "lw $4,8($29);\n"
1332 #endif
1333 #else
1334 "ld $25,0($29);\n"
1335 "ld $4,8($29);\n"
1336 #endif
1337 "jal $25;\n"
1339 /* Call _exit($v0). */
1340 "move $4,$2;\n"
1341 "li $2,%7;\n"
1342 "syscall;\n"
1344 /* Return to parent. */
1345 "1:\n"
1346 : "=r" (res)
1347 : "r"(flags),
1348 "r"(child_stack),
1349 "r"(parent_tidptr),
1350 "r"(a3),
1351 "r"(a4),
1352 "i"(__NR_clone),
1353 "i"(__NR_exit)
1354 : "memory", "$29" );
1355 return res;
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)
1361 return -EINVAL;
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__(
1376 "ecall\n"
1378 /* if (a0 != 0)
1379 * return a0;
1381 "bnez a0, 1f\n"
1383 // In the child, now. Call "fn(arg)".
1384 "mv a0, a6\n"
1385 "jalr a5\n"
1387 // Call _exit(a0).
1388 "addi a7, zero, %9\n"
1389 "ecall\n"
1390 "1:\n"
1392 : "=r"(res)
1393 : "0"(__flags), "r"(__stack), "r"(__ptid), "r"(__tls), "r"(__ctid),
1394 "r"(__fn), "r"(__arg), "r"(nr_clone), "i"(__NR_exit)
1395 : "memory");
1396 return res;
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)
1403 return -EINVAL;
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 */
1424 "svc 0x0\n"
1426 /* if (%r0 != 0)
1427 * return %r0;
1429 "cmp x0, #0\n"
1430 "bne 1f\n"
1432 /* In the child, now. Call "fn(arg)". */
1433 "ldp x1, x0, [sp], #16\n"
1434 "blr x1\n"
1436 /* Call _exit(%r0). */
1437 "mov x8, %10\n"
1438 "svc 0x0\n"
1439 "1:\n"
1441 : "=r" (res)
1442 : "i"(-EINVAL),
1443 "r"(__fn), "r"(__stack), "r"(__flags), "r"(__arg),
1444 "r"(__ptid), "r"(__tls), "r"(__ctid),
1445 "i"(__NR_clone), "i"(__NR_exit)
1446 : "x30", "memory");
1447 return res;
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) {
1452 long long res;
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
1475 #else
1476 # error "Unsupported PPC64 ABI"
1477 #endif
1478 if (!fn || !child_stack)
1479 return -EINVAL;
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 */
1492 "mr 28, %5\n\t"
1493 "mr 27, %8\n\t"
1495 /* syscall
1496 r0 == __NR_clone
1497 r3 == flags
1498 r4 == child_stack
1499 r5 == parent_tidptr
1500 r6 == newtls
1501 r7 == child_tidptr */
1502 "mr 3, %7\n\t"
1503 "mr 5, %9\n\t"
1504 "mr 6, %10\n\t"
1505 "mr 7, %11\n\t"
1506 "li 0, %3\n\t"
1507 "sc\n\t"
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"
1512 "bne- cr1, 1f\n\t"
1514 /* Set up stack frame */
1515 "li 29, 0\n\t"
1516 "stdu 29, -8(1)\n\t"
1517 "stdu 1, -%12(1)\n\t"
1518 /* Do the function call */
1519 "std 2, %13(1)\n\t"
1520 #if SANITIZER_PPC64V1
1521 "ld 0, 0(28)\n\t"
1522 "ld 2, 8(28)\n\t"
1523 "mtctr 0\n\t"
1524 #elif SANITIZER_PPC64V2
1525 "mr 12, 28\n\t"
1526 "mtctr 12\n\t"
1527 #else
1528 # error "Unsupported PPC64 ABI"
1529 #endif
1530 "mr 3, 27\n\t"
1531 "bctrl\n\t"
1532 "ld 2, %13(1)\n\t"
1534 /* Call _exit(r3) */
1535 "li 0, %4\n\t"
1536 "sc\n\t"
1538 /* Return to parent */
1539 "1:\n\t"
1540 "mr %0, 3\n\t"
1541 : "=r" (res)
1542 : "0" (-1),
1543 "i" (EINVAL),
1544 "i" (__NR_clone),
1545 "i" (__NR_exit),
1546 "r" (__fn),
1547 "r" (__cstack),
1548 "r" (__flags),
1549 "r" (__arg),
1550 "r" (__ptidptr),
1551 "r" (__newtls),
1552 "r" (__ctidptr),
1553 "i" (FRAME_SIZE),
1554 "i" (FRAME_TOC_SAVE_OFFSET)
1555 : "cr0", "cr1", "memory", "ctr", "r0", "r27", "r28", "r29");
1556 return res;
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) {
1561 int res;
1562 if (!fn || !child_stack)
1563 return -EINVAL;
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),
1572 * %ebx = flags,
1573 * %ecx = child_stack,
1574 * %edx = parent_tidptr,
1575 * %esi = new_tls,
1576 * %edi = child_tidptr)
1579 /* Obtain flags */
1580 "movl (%%ecx), %%ebx\n"
1581 /* Do the system call */
1582 "pushl %%ebx\n"
1583 "pushl %%esi\n"
1584 "pushl %%edi\n"
1585 /* Remember the flag value. */
1586 "movl %%ebx, (%%ecx)\n"
1587 "int $0x80\n"
1588 "popl %%edi\n"
1589 "popl %%esi\n"
1590 "popl %%ebx\n"
1592 /* if (%eax != 0)
1593 * return;
1596 "test %%eax,%%eax\n"
1597 "jnz 1f\n"
1599 /* terminate the stack frame */
1600 "xorl %%ebp,%%ebp\n"
1601 /* Call FN. */
1602 "call *%%ebx\n"
1603 #ifdef PIC
1604 "call here\n"
1605 "here:\n"
1606 "popl %%ebx\n"
1607 "addl $_GLOBAL_OFFSET_TABLE_+[.-here], %%ebx\n"
1608 #endif
1609 /* Call exit */
1610 "movl %%eax, %%ebx\n"
1611 "movl %2, %%eax\n"
1612 "int $0x80\n"
1613 "1:\n"
1614 : "=a" (res)
1615 : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
1616 "c"(child_stack),
1617 "d"(parent_tidptr),
1618 "S"(newtls),
1619 "D"(child_tidptr)
1620 : "memory");
1621 return res;
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) {
1626 unsigned int res;
1627 if (!fn || !child_stack)
1628 return -EINVAL;
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
1641 #endif
1642 #if __ARM_ARCH > 4
1643 # define ARCH_HAS_BLX
1644 #endif
1646 #ifdef ARCH_HAS_BX
1647 # ifdef ARCH_HAS_BLX
1648 # define BLX(R) "blx " #R "\n"
1649 # else
1650 # define BLX(R) "mov lr, pc; bx " #R "\n"
1651 # endif
1652 #else
1653 # define BLX(R) "mov lr, pc; mov pc," #R "\n"
1654 #endif
1656 __asm__ __volatile__(
1657 /* %r0 = syscall(%r7 = SYSCALL(clone),
1658 * %r0 = flags,
1659 * %r1 = child_stack,
1660 * %r2 = parent_tidptr,
1661 * %r3 = new_tls,
1662 * %r4 = child_tidptr)
1665 /* Do the system call */
1666 "swi 0x0\n"
1668 /* if (%r0 != 0)
1669 * return %r0;
1671 "cmp r0, #0\n"
1672 "bne 1f\n"
1674 /* In the child, now. Call "fn(arg)". */
1675 "ldr r0, [sp, #4]\n"
1676 "ldr ip, [sp], #8\n"
1677 BLX(ip)
1678 /* Call _exit(%r0). */
1679 "mov r7, %7\n"
1680 "swi 0x0\n"
1681 "1:\n"
1682 "mov %0, r0\n"
1683 : "=r"(res)
1684 : "r"(r0), "r"(r1), "r"(r2), "r"(r3), "r"(r4), "r"(r7),
1685 "i"(__NR_exit)
1686 : "memory");
1687 return res;
1689 #endif
1690 #endif // SANITIZER_LINUX
1692 #if SANITIZER_LINUX
1693 int internal_uname(struct utsname *buf) {
1694 return internal_syscall(SYSCALL(uname), buf);
1696 #endif
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 *);
1702 #endif
1704 static int dl_iterate_phdr_test_cb(struct dl_phdr_info *info, size_t size,
1705 void *data) {
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;
1711 return 1;
1713 return 0;
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;
1723 #else
1724 return ANDROID_POST_LOLLIPOP;
1725 #endif
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);
1733 if (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);
1749 return level;
1752 #endif
1754 static HandleSignalMode GetHandleSignalModeImpl(int signum) {
1755 switch (signum) {
1756 case SIGABRT:
1757 return common_flags()->handle_abort;
1758 case SIGILL:
1759 return common_flags()->handle_sigill;
1760 case SIGTRAP:
1761 return common_flags()->handle_sigtrap;
1762 case SIGFPE:
1763 return common_flags()->handle_sigfpe;
1764 case SIGSEGV:
1765 return common_flags()->handle_segv;
1766 case SIGBUS:
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;
1776 return result;
1779 #if !SANITIZER_GO
1780 void *internal_start_thread(void *(*func)(void *arg), void *arg) {
1781 if (&real_pthread_create == 0)
1782 return nullptr;
1783 // Start the thread with signals blocked, otherwise it can steal user signals.
1784 ScopedBlockSignals block(nullptr);
1785 void *th;
1786 real_pthread_create(&th, nullptr, func, arg);
1787 return th;
1790 void internal_join_thread(void *th) {
1791 if (&real_pthread_join)
1792 real_pthread_join(th, nullptr);
1794 #else
1795 void *internal_start_thread(void *(*func)(void *), void *arg) { return 0; }
1797 void internal_join_thread(void *th) {}
1798 #endif
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;
1804 uint64_t esr;
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);
1810 while (true) {
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;
1815 return true;
1817 aux += ctx->size;
1819 return false;
1821 #endif
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__)
1834 const int Err = 13;
1835 uptr err = ucontext->uc_mcontext.gregs[Err];
1836 #else
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;
1843 uint32_t op_code;
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.
1851 switch (op_code) {
1852 case 0x28: // sb
1853 case 0x29: // sh
1854 case 0x2b: // sw
1855 case 0x3f: // sd
1856 #if __mips_isa_rev < 6
1857 case 0x2c: // sdl
1858 case 0x2d: // sdr
1859 case 0x2a: // swl
1860 case 0x2e: // swr
1861 #endif
1862 return SignalContext::Write;
1864 case 0x20: // lb
1865 case 0x24: // lbu
1866 case 0x21: // lh
1867 case 0x25: // lhu
1868 case 0x23: // lw
1869 case 0x27: // lwu
1870 case 0x37: // ld
1871 #if __mips_isa_rev < 6
1872 case 0x1a: // ldl
1873 case 0x1b: // ldr
1874 case 0x22: // lwl
1875 case 0x26: // lwr
1876 #endif
1877 return SignalContext::Read;
1878 #if __mips_isa_rev == 6
1879 case 0x3b: // pcrel
1880 op_code = (faulty_instruction >> 19) & 0x3;
1881 switch (op_code) {
1882 case 0x1: // lwpc
1883 case 0x2: // lwupc
1884 return SignalContext::Read;
1886 #endif
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;
1895 u64 esr;
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];
1903 #else
1904 // Historical BSDism here.
1905 struct sigcontext *scontext = (struct sigcontext *)context;
1906 #if defined(__arch64__)
1907 uptr pc = scontext->sigc_regs.tpc;
1908 #else
1909 uptr pc = scontext->si_regs.pc;
1910 #endif
1911 #endif
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;
1917 #else
1918 unsigned long pc = ucontext->uc_mcontext.__gregs[REG_PC];
1919 #endif
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]
1925 unsigned op_bits =
1926 ((faulty_instruction & 0x3) << 3) | (faulty_instruction >> 13);
1927 unsigned rd = faulty_instruction & 0xF80; // bits 7-11, inclusive
1928 switch (op_bits) {
1929 case 0b10'010: // c.lwsp (rd != x0)
1930 #if __riscv_xlen == 64
1931 case 0b10'011: // c.ldsp (rd != x0)
1932 #endif
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
1937 #endif
1938 #if __riscv_flen >= 32 || __riscv_xlen == 64
1939 case 0b00'011: // c.flw / c.ld
1940 #endif
1941 #if __riscv_flen == 64
1942 case 0b00'001: // c.fld
1943 case 0b10'001: // c.fldsp
1944 #endif
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
1951 #endif
1952 #if __riscv_flen == 64
1953 case 0b00'101: // c.fsd
1954 case 0b10'101: // c.fsdsp
1955 #endif
1956 return SignalContext::Write;
1957 default:
1958 return SignalContext::Unknown;
1961 #endif
1963 unsigned opcode = faulty_instruction & 0x7f; // lower 7 bits
1964 unsigned funct3 = (faulty_instruction >> 12) & 0x7; // bits 12-14, inclusive
1965 switch (opcode) {
1966 case 0b0000011: // loads
1967 switch (funct3) {
1968 case 0b000: // lb
1969 case 0b001: // lh
1970 case 0b010: // lw
1971 #if __riscv_xlen == 64
1972 case 0b011: // ld
1973 #endif
1974 case 0b100: // lbu
1975 case 0b101: // lhu
1976 return SignalContext::Read;
1977 default:
1978 return SignalContext::Unknown;
1980 case 0b0100011: // stores
1981 switch (funct3) {
1982 case 0b000: // sb
1983 case 0b001: // sh
1984 case 0b010: // sw
1985 #if __riscv_xlen == 64
1986 case 0b011: // sd
1987 #endif
1988 return SignalContext::Write;
1989 default:
1990 return SignalContext::Unknown;
1992 #if __riscv_flen >= 32
1993 case 0b0000111: // floating-point loads
1994 switch (funct3) {
1995 case 0b010: // flw
1996 #if __riscv_flen == 64
1997 case 0b011: // fld
1998 #endif
1999 return SignalContext::Read;
2000 default:
2001 return SignalContext::Unknown;
2003 case 0b0100111: // floating-point stores
2004 switch (funct3) {
2005 case 0b010: // fsw
2006 #if __riscv_flen == 64
2007 case 0b011: // fsd
2008 #endif
2009 return SignalContext::Write;
2010 default:
2011 return SignalContext::Unknown;
2013 #endif
2014 default:
2015 return SignalContext::Unknown;
2017 #else
2018 (void)ucontext;
2019 return Unknown; // FIXME: Implement.
2020 #endif
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;
2062 # else
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];
2067 # endif
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;
2074 # else
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. */
2079 # ifndef REG_EIP
2080 # define REG_EIP 14 // REG_PC
2081 # endif
2082 # ifndef REG_EBP
2083 # define REG_EBP 6 // REG_FP
2084 # endif
2085 # ifndef REG_UESP
2086 # define REG_UESP 17 // REG_SP
2087 # endif
2088 # endif
2089 *pc = ucontext->uc_mcontext.gregs[REG_EIP];
2090 *bp = ucontext->uc_mcontext.gregs[REG_EBP];
2091 *sp = ucontext->uc_mcontext.gregs[REG_UESP];
2092 # endif
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
2103 #else
2104 #define STACK_BIAS 0
2105 # endif
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;
2110 #else
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;
2116 #else
2117 *pc = scontext->si_regs.pc;
2118 *sp = scontext->si_regs.u_regs[14];
2119 #endif
2120 # endif
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;
2131 # else
2132 *pc = ucontext->uc_mcontext.psw.addr & 0x7fffffff;
2133 # endif
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;
2142 # else
2143 *pc = ucontext->uc_mcontext.__gregs[REG_PC];
2144 *bp = ucontext->uc_mcontext.__gregs[REG_S0];
2145 *sp = ucontext->uc_mcontext.__gregs[REG_SP];
2146 # endif
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;
2152 # else
2153 # error "Unsupported arch"
2154 # endif
2157 void SignalContext::InitPcSpBp() { GetPcSpBp(context, &pc, &sp, &bp); }
2159 void InitializePlatformEarly() {
2160 // Do nothing.
2163 void MaybeReexec() {
2164 // No need to re-exec on Linux.
2167 void CheckASLR() {
2168 #if SANITIZER_NETBSD
2169 int mib[3];
2170 int paxflags;
2171 uptr len = sizeof(paxflags);
2173 mib[0] = CTL_PROC;
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");
2179 Die();
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",
2185 GetArgv()[0]);
2186 Die();
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);
2197 ReExec();
2199 #elif SANITIZER_FREEBSD
2200 int aslr_status;
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
2205 return;
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");
2210 Die();
2212 #else
2213 // Do nothing
2214 #endif
2217 void CheckMPROTECT() {
2218 #if SANITIZER_NETBSD
2219 int mib[3];
2220 int paxflags;
2221 uptr len = sizeof(paxflags);
2223 mib[0] = CTL_PROC;
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");
2229 Die();
2232 if (UNLIKELY(paxflags & CTL_PROC_PAXFLAGS_MPROTECT)) {
2233 Printf("This sanitizer is not compatible with enabled MPROTECT\n");
2234 Die();
2236 #else
2237 // Do nothing
2238 #endif
2241 void CheckNoDeepBind(const char *filename, int flag) {
2242 #ifdef RTLD_DEEPBIND
2243 if (flag & RTLD_DEEPBIND) {
2244 Report(
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);
2251 Die();
2253 #endif
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");
2260 return 0;
2263 bool GetRandom(void *buffer, uptr length, bool blocking) {
2264 if (!buffer || !length || length > 256)
2265 return false;
2266 #if SANITIZER_USE_GETENTROPY
2267 uptr rnd = getentropy(buffer, length);
2268 int rverrno = 0;
2269 if (internal_iserror(rnd, &rverrno) && rverrno == EFAULT)
2270 return false;
2271 else if (rnd == 0)
2272 return true;
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);
2281 int rverrno = 0;
2282 if (internal_iserror(res, &rverrno) && rverrno == ENOSYS)
2283 atomic_store_relaxed(&skip_getrandom_syscall, 1);
2284 else if (res == length)
2285 return true;
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))
2292 return false;
2293 uptr res = internal_read(fd, buffer, length);
2294 if (internal_iserror(res))
2295 return false;
2296 internal_close(fd);
2297 return true;
2300 } // namespace __sanitizer
2302 #endif