master
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//===----------------------------------------------------------------------===//
13
14#include "sanitizer_platform.h"
15
16#if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD || \
17 SANITIZER_SOLARIS || SANITIZER_HAIKU
18
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"
28
29# if SANITIZER_LINUX && !SANITIZER_GO
30# include <asm/param.h>
31# endif
32
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. sparc64 is similar, using
37// syscall(__NR_stat64) and struct kernel_stat64.
38# if SANITIZER_LINUX && (SANITIZER_MIPS64 || SANITIZER_SPARC64)
39# include <asm/unistd.h>
40# include <sys/types.h>
41# define stat kernel_stat
42# if SANITIZER_SPARC64
43# define stat64 kernel_stat64
44# endif
45# if SANITIZER_GO
46# undef st_atime
47# undef st_mtime
48# undef st_ctime
49# define st_atime st_atim
50# define st_mtime st_mtim
51# define st_ctime st_ctim
52# endif
53# include <asm/stat.h>
54# undef stat
55# undef stat64
56# endif
57
58# include <dlfcn.h>
59# include <errno.h>
60# include <fcntl.h>
61# include <link.h>
62# include <pthread.h>
63# include <sched.h>
64# include <signal.h>
65# include <sys/mman.h>
66# if !SANITIZER_SOLARIS && !SANITIZER_HAIKU
67# include <sys/ptrace.h>
68# endif
69# include <sys/resource.h>
70# include <sys/stat.h>
71# if !SANITIZER_HAIKU
72# include <sys/syscall.h>
73# include <ucontext.h>
74# endif
75# include <sys/time.h>
76# include <sys/types.h>
77# include <unistd.h>
78
79# if SANITIZER_LINUX
80# include <sys/utsname.h>
81# endif
82
83# if SANITIZER_LINUX && !SANITIZER_ANDROID
84# include <sys/personality.h>
85# endif
86
87# if SANITIZER_ANDROID && __ANDROID_API__ < 35
88// The weak `strerrorname_np` (introduced in API level 35) definition,
89// allows for checking the API level at runtime.
90extern "C" SANITIZER_WEAK_ATTRIBUTE const char *strerrorname_np(int);
91# endif
92
93# if SANITIZER_LINUX && defined(__loongarch__)
94# include <sys/sysmacros.h>
95# endif
96
97# if SANITIZER_LINUX && defined(__powerpc64__)
98# include <asm/ptrace.h>
99# endif
100
101# if SANITIZER_FREEBSD
102# include <machine/atomic.h>
103# include <sys/exec.h>
104# include <sys/procctl.h>
105# include <sys/sysctl.h>
106extern "C" {
107// <sys/umtx.h> must be included after <errno.h> and <sys/types.h> on
108// FreeBSD 9.2 and 10.0.
109# include <sys/umtx.h>
110}
111# include <sys/thr.h>
112# endif // SANITIZER_FREEBSD
113
114# if SANITIZER_NETBSD
115# include <limits.h> // For NAME_MAX
116# include <sys/exec.h>
117# include <sys/sysctl.h>
118extern struct ps_strings *__ps_strings;
119# endif // SANITIZER_NETBSD
120
121# if SANITIZER_SOLARIS
122# include <stddef.h>
123# include <stdlib.h>
124# include <sys/frame.h>
125# include <thread.h>
126# define environ _environ
127# endif
128
129# if SANITIZER_HAIKU
130# include <OS.h>
131# include <elf.h>
132# include <image.h>
133extern "C" char **__libc_argv;
134# endif
135
136extern char **environ;
137
138# if SANITIZER_LINUX
139// <linux/time.h>
140struct kernel_timeval {
141 long tv_sec;
142 long tv_usec;
143};
144
145// <linux/futex.h> is broken on some linux distributions.
146const int FUTEX_WAIT = 0;
147const int FUTEX_WAKE = 1;
148const int FUTEX_PRIVATE_FLAG = 128;
149const int FUTEX_WAIT_PRIVATE = FUTEX_WAIT | FUTEX_PRIVATE_FLAG;
150const int FUTEX_WAKE_PRIVATE = FUTEX_WAKE | FUTEX_PRIVATE_FLAG;
151# endif // SANITIZER_LINUX
152
153// Are we using 32-bit or 64-bit Linux syscalls?
154// x32 (which defines __x86_64__) has SANITIZER_WORDSIZE == 32
155// but it still needs to use 64-bit syscalls.
156# if SANITIZER_LINUX && \
157 (defined(__x86_64__) || defined(__powerpc64__) || \
158 SANITIZER_WORDSIZE == 64 || \
159 (defined(__mips__) && defined(_ABIN32) && _MIPS_SIM == _ABIN32))
160# define SANITIZER_LINUX_USES_64BIT_SYSCALLS 1
161# else
162# define SANITIZER_LINUX_USES_64BIT_SYSCALLS 0
163# endif
164
165// Note : FreeBSD implemented both Linux and OpenBSD apis.
166# if SANITIZER_LINUX && defined(__NR_getrandom)
167# if !defined(GRND_NONBLOCK)
168# define GRND_NONBLOCK 1
169# endif
170# define SANITIZER_USE_GETRANDOM 1
171# else
172# define SANITIZER_USE_GETRANDOM 0
173# endif // SANITIZER_LINUX && defined(__NR_getrandom)
174
175# if SANITIZER_FREEBSD
176# define SANITIZER_USE_GETENTROPY 1
177# endif
178
179namespace __sanitizer {
180
181void SetSigProcMask(__sanitizer_sigset_t *set, __sanitizer_sigset_t *oldset) {
182 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, set, oldset));
183}
184
185# if SANITIZER_LINUX
186// Deletes the specified signal from newset, if it is not present in oldset
187// Equivalently: newset[signum] = newset[signum] & oldset[signum]
188static void KeepUnblocked(__sanitizer_sigset_t &newset,
189 __sanitizer_sigset_t &oldset, int signum) {
190 // FIXME: https://github.com/google/sanitizers/issues/1816
191 if (SANITIZER_ANDROID || !internal_sigismember(&oldset, signum))
192 internal_sigdelset(&newset, signum);
193}
194# endif
195
196// Block asynchronous signals
197void BlockSignals(__sanitizer_sigset_t *oldset) {
198 __sanitizer_sigset_t newset;
199 internal_sigfillset(&newset);
200
201# if SANITIZER_LINUX
202 __sanitizer_sigset_t currentset;
203
204# if !SANITIZER_ANDROID
205 // FIXME: https://github.com/google/sanitizers/issues/1816
206 SetSigProcMask(NULL, ¤tset);
207
208 // Glibc uses SIGSETXID signal during setuid call. If this signal is blocked
209 // on any thread, setuid call hangs.
210 // See test/sanitizer_common/TestCases/Linux/setuid.c.
211 KeepUnblocked(newset, currentset, 33);
212# endif // !SANITIZER_ANDROID
213
214 // Seccomp-BPF-sandboxed processes rely on SIGSYS to handle trapped syscalls.
215 // If this signal is blocked, such calls cannot be handled and the process may
216 // hang.
217 KeepUnblocked(newset, currentset, 31);
218
219# if !SANITIZER_ANDROID
220 // Don't block synchronous signals
221 // but also don't unblock signals that the user had deliberately blocked.
222 // FIXME: https://github.com/google/sanitizers/issues/1816
223 KeepUnblocked(newset, currentset, SIGSEGV);
224 KeepUnblocked(newset, currentset, SIGBUS);
225 KeepUnblocked(newset, currentset, SIGILL);
226 KeepUnblocked(newset, currentset, SIGTRAP);
227 KeepUnblocked(newset, currentset, SIGABRT);
228 KeepUnblocked(newset, currentset, SIGFPE);
229 KeepUnblocked(newset, currentset, SIGPIPE);
230# endif //! SANITIZER_ANDROID
231
232# endif // SANITIZER_LINUX
233
234 SetSigProcMask(&newset, oldset);
235}
236
237ScopedBlockSignals::ScopedBlockSignals(__sanitizer_sigset_t *copy) {
238 BlockSignals(&saved_);
239 if (copy)
240 internal_memcpy(copy, &saved_, sizeof(saved_));
241}
242
243ScopedBlockSignals::~ScopedBlockSignals() { SetSigProcMask(&saved_, nullptr); }
244
245# if SANITIZER_LINUX && defined(__x86_64__)
246# include "sanitizer_syscall_linux_x86_64.inc"
247# elif SANITIZER_LINUX && SANITIZER_RISCV64
248# include "sanitizer_syscall_linux_riscv64.inc"
249# elif SANITIZER_LINUX && defined(__aarch64__)
250# include "sanitizer_syscall_linux_aarch64.inc"
251# elif SANITIZER_LINUX && defined(__arm__)
252# include "sanitizer_syscall_linux_arm.inc"
253# elif SANITIZER_LINUX && defined(__hexagon__)
254# include "sanitizer_syscall_linux_hexagon.inc"
255# elif SANITIZER_LINUX && SANITIZER_LOONGARCH64
256# include "sanitizer_syscall_linux_loongarch64.inc"
257# else
258# include "sanitizer_syscall_generic.inc"
259# endif
260
261// --------------- sanitizer_libc.h
262# if !SANITIZER_SOLARIS && !SANITIZER_NETBSD && !SANITIZER_HAIKU
263# if !SANITIZER_S390
264uptr internal_mmap(void *addr, uptr length, int prot, int flags, int fd,
265 u64 offset) {
266 /* zig patch: use direct syscall for freebsd mmap */
267# if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
268 return internal_syscall(SYSCALL(mmap), (uptr)addr, length, prot, flags, fd,
269 offset);
270# else
271 // mmap2 specifies file offset in 4096-byte units.
272 CHECK(IsAligned(offset, 4096));
273 return internal_syscall(SYSCALL(mmap2), addr, length, prot, flags, fd,
274 (OFF_T)(offset / 4096));
275# endif
276}
277# endif // !SANITIZER_S390
278
279uptr internal_munmap(void *addr, uptr length) {
280 return internal_syscall(SYSCALL(munmap), (uptr)addr, length);
281}
282
283# if SANITIZER_LINUX
284uptr internal_mremap(void *old_address, uptr old_size, uptr new_size, int flags,
285 void *new_address) {
286 return internal_syscall(SYSCALL(mremap), (uptr)old_address, old_size,
287 new_size, flags, (uptr)new_address);
288}
289# endif
290
291int internal_mprotect(void *addr, uptr length, int prot) {
292 return internal_syscall(SYSCALL(mprotect), (uptr)addr, length, prot);
293}
294
295int internal_madvise(uptr addr, uptr length, int advice) {
296 return internal_syscall(SYSCALL(madvise), addr, length, advice);
297}
298
299# if SANITIZER_FREEBSD
300uptr internal_close_range(fd_t lowfd, fd_t highfd, int flags) {
301 return internal_syscall(SYSCALL(close_range), lowfd, highfd, flags);
302}
303# endif
304uptr internal_close(fd_t fd) { return internal_syscall(SYSCALL(close), fd); }
305
306uptr internal_open(const char *filename, int flags) {
307# if SANITIZER_LINUX
308 return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags);
309# else
310 return internal_syscall(SYSCALL(open), (uptr)filename, flags);
311# endif
312}
313
314uptr internal_open(const char *filename, int flags, u32 mode) {
315# if SANITIZER_LINUX
316 return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags,
317 mode);
318# else
319 return internal_syscall(SYSCALL(open), (uptr)filename, flags, mode);
320# endif
321}
322
323uptr internal_read(fd_t fd, void *buf, uptr count) {
324 sptr res;
325 HANDLE_EINTR(res,
326 (sptr)internal_syscall(SYSCALL(read), fd, (uptr)buf, count));
327 return res;
328}
329
330uptr internal_write(fd_t fd, const void *buf, uptr count) {
331 sptr res;
332 HANDLE_EINTR(res,
333 (sptr)internal_syscall(SYSCALL(write), fd, (uptr)buf, count));
334 return res;
335}
336
337uptr internal_ftruncate(fd_t fd, uptr size) {
338 sptr res;
339 HANDLE_EINTR(res,
340 (sptr)internal_syscall(SYSCALL(ftruncate), fd, (OFF_T)size));
341 return res;
342}
343
344# if !SANITIZER_LINUX_USES_64BIT_SYSCALLS && SANITIZER_LINUX
345static void stat64_to_stat(struct stat64 *in, struct stat *out) {
346 internal_memset(out, 0, sizeof(*out));
347 out->st_dev = in->st_dev;
348 out->st_ino = in->st_ino;
349 out->st_mode = in->st_mode;
350 out->st_nlink = in->st_nlink;
351 out->st_uid = in->st_uid;
352 out->st_gid = in->st_gid;
353 out->st_rdev = in->st_rdev;
354 out->st_size = in->st_size;
355 out->st_blksize = in->st_blksize;
356 out->st_blocks = in->st_blocks;
357 out->st_atime = in->st_atime;
358 out->st_mtime = in->st_mtime;
359 out->st_ctime = in->st_ctime;
360}
361# endif
362
363# if SANITIZER_LINUX && defined(__loongarch__)
364static void statx_to_stat(struct statx *in, struct stat *out) {
365 internal_memset(out, 0, sizeof(*out));
366 out->st_dev = makedev(in->stx_dev_major, in->stx_dev_minor);
367 out->st_ino = in->stx_ino;
368 out->st_mode = in->stx_mode;
369 out->st_nlink = in->stx_nlink;
370 out->st_uid = in->stx_uid;
371 out->st_gid = in->stx_gid;
372 out->st_rdev = makedev(in->stx_rdev_major, in->stx_rdev_minor);
373 out->st_size = in->stx_size;
374 out->st_blksize = in->stx_blksize;
375 out->st_blocks = in->stx_blocks;
376 out->st_atime = in->stx_atime.tv_sec;
377 out->st_atim.tv_nsec = in->stx_atime.tv_nsec;
378 out->st_mtime = in->stx_mtime.tv_sec;
379 out->st_mtim.tv_nsec = in->stx_mtime.tv_nsec;
380 out->st_ctime = in->stx_ctime.tv_sec;
381 out->st_ctim.tv_nsec = in->stx_ctime.tv_nsec;
382}
383# endif
384
385# if SANITIZER_MIPS64 || SANITIZER_SPARC64
386# if SANITIZER_MIPS64
387typedef struct kernel_stat kstat_t;
388# else
389typedef struct kernel_stat64 kstat_t;
390# endif
391// Undefine compatibility macros from <sys/stat.h>
392// so that they would not clash with the kernel_stat
393// st_[a|m|c]time fields
394# if !SANITIZER_GO
395# undef st_atime
396# undef st_mtime
397# undef st_ctime
398# endif
399# if defined(SANITIZER_ANDROID)
400// Bionic sys/stat.h defines additional macros
401// for compatibility with the old NDKs and
402// they clash with the kernel_stat structure
403// st_[a|m|c]time_nsec fields.
404# undef st_atime_nsec
405# undef st_mtime_nsec
406# undef st_ctime_nsec
407# endif
408static void kernel_stat_to_stat(kstat_t *in, struct stat *out) {
409 internal_memset(out, 0, sizeof(*out));
410 out->st_dev = in->st_dev;
411 out->st_ino = in->st_ino;
412 out->st_mode = in->st_mode;
413 out->st_nlink = in->st_nlink;
414 out->st_uid = in->st_uid;
415 out->st_gid = in->st_gid;
416 out->st_rdev = in->st_rdev;
417 out->st_size = in->st_size;
418 out->st_blksize = in->st_blksize;
419 out->st_blocks = in->st_blocks;
420# if defined(__USE_MISC) || defined(__USE_XOPEN2K8) || \
421 defined(SANITIZER_ANDROID)
422 out->st_atim.tv_sec = in->st_atime;
423 out->st_atim.tv_nsec = in->st_atime_nsec;
424 out->st_mtim.tv_sec = in->st_mtime;
425 out->st_mtim.tv_nsec = in->st_mtime_nsec;
426 out->st_ctim.tv_sec = in->st_ctime;
427 out->st_ctim.tv_nsec = in->st_ctime_nsec;
428# else
429 out->st_atime = in->st_atime;
430 out->st_atimensec = in->st_atime_nsec;
431 out->st_mtime = in->st_mtime;
432 out->st_mtimensec = in->st_mtime_nsec;
433 out->st_ctime = in->st_ctime;
434 out->st_atimensec = in->st_ctime_nsec;
435# endif
436}
437# endif
438
439uptr internal_stat(const char *path, void *buf) {
440# if SANITIZER_FREEBSD
441 return internal_syscall(SYSCALL(fstatat), AT_FDCWD, (uptr)path, (uptr)buf, 0);
442# elif SANITIZER_LINUX
443# if defined(__loongarch__)
444 struct statx bufx;
445 int res = internal_syscall(SYSCALL(statx), AT_FDCWD, (uptr)path,
446 AT_NO_AUTOMOUNT, STATX_BASIC_STATS, (uptr)&bufx);
447 statx_to_stat(&bufx, (struct stat *)buf);
448 return res;
449# elif ( \
450 SANITIZER_WORDSIZE == 64 || SANITIZER_X32 || \
451 (defined(__mips__) && defined(_ABIN32) && _MIPS_SIM == _ABIN32)) && \
452 !SANITIZER_SPARC
453 return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path, (uptr)buf,
454 0);
455# elif SANITIZER_SPARC64
456 kstat_t buf64;
457 int res = internal_syscall(SYSCALL(fstatat64), AT_FDCWD, (uptr)path,
458 (uptr)&buf64, 0);
459 kernel_stat_to_stat(&buf64, (struct stat *)buf);
460 return res;
461# else
462 struct stat64 buf64;
463 int res = internal_syscall(SYSCALL(fstatat64), AT_FDCWD, (uptr)path,
464 (uptr)&buf64, 0);
465 stat64_to_stat(&buf64, (struct stat *)buf);
466 return res;
467# endif
468# else
469 struct stat64 buf64;
470 int res = internal_syscall(SYSCALL(stat64), path, &buf64);
471 stat64_to_stat(&buf64, (struct stat *)buf);
472 return res;
473# endif
474}
475
476uptr internal_lstat(const char *path, void *buf) {
477# if SANITIZER_FREEBSD
478 return internal_syscall(SYSCALL(fstatat), AT_FDCWD, (uptr)path, (uptr)buf,
479 AT_SYMLINK_NOFOLLOW);
480# elif SANITIZER_LINUX
481# if defined(__loongarch__)
482 struct statx bufx;
483 int res = internal_syscall(SYSCALL(statx), AT_FDCWD, (uptr)path,
484 AT_SYMLINK_NOFOLLOW | AT_NO_AUTOMOUNT,
485 STATX_BASIC_STATS, (uptr)&bufx);
486 statx_to_stat(&bufx, (struct stat *)buf);
487 return res;
488# elif ( \
489 defined(_LP64) || SANITIZER_X32 || \
490 (defined(__mips__) && defined(_ABIN32) && _MIPS_SIM == _ABIN32)) && \
491 !SANITIZER_SPARC
492 return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path, (uptr)buf,
493 AT_SYMLINK_NOFOLLOW);
494# elif SANITIZER_SPARC64
495 kstat_t buf64;
496 int res = internal_syscall(SYSCALL(fstatat64), AT_FDCWD, (uptr)path,
497 (uptr)&buf64, AT_SYMLINK_NOFOLLOW);
498 kernel_stat_to_stat(&buf64, (struct stat *)buf);
499 return res;
500# else
501 struct stat64 buf64;
502 int res = internal_syscall(SYSCALL(fstatat64), AT_FDCWD, (uptr)path,
503 (uptr)&buf64, AT_SYMLINK_NOFOLLOW);
504 stat64_to_stat(&buf64, (struct stat *)buf);
505 return res;
506# endif
507# else
508 struct stat64 buf64;
509 int res = internal_syscall(SYSCALL(lstat64), path, &buf64);
510 stat64_to_stat(&buf64, (struct stat *)buf);
511 return res;
512# endif
513}
514
515uptr internal_fstat(fd_t fd, void *buf) {
516# if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
517# if SANITIZER_MIPS64
518 // For mips64, fstat syscall fills buffer in the format of kernel_stat
519 kstat_t kbuf;
520 int res = internal_syscall(SYSCALL(fstat), fd, &kbuf);
521 kernel_stat_to_stat(&kbuf, (struct stat *)buf);
522 return res;
523# elif SANITIZER_LINUX && SANITIZER_SPARC64
524 // For sparc64, fstat64 syscall fills buffer in the format of kernel_stat64
525 kstat_t kbuf;
526 int res = internal_syscall(SYSCALL(fstat64), fd, &kbuf);
527 kernel_stat_to_stat(&kbuf, (struct stat *)buf);
528 return res;
529# elif SANITIZER_LINUX && defined(__loongarch__)
530 struct statx bufx;
531 int res = internal_syscall(SYSCALL(statx), fd, "", AT_EMPTY_PATH,
532 STATX_BASIC_STATS, (uptr)&bufx);
533 statx_to_stat(&bufx, (struct stat *)buf);
534 return res;
535# else
536 return internal_syscall(SYSCALL(fstat), fd, (uptr)buf);
537# endif
538# else
539 struct stat64 buf64;
540 int res = internal_syscall(SYSCALL(fstat64), fd, &buf64);
541 stat64_to_stat(&buf64, (struct stat *)buf);
542 return res;
543# endif
544}
545
546uptr internal_filesize(fd_t fd) {
547 struct stat st;
548 if (internal_fstat(fd, &st))
549 return -1;
550 return (uptr)st.st_size;
551}
552
553uptr internal_dup(int oldfd) { return internal_syscall(SYSCALL(dup), oldfd); }
554
555uptr internal_dup2(int oldfd, int newfd) {
556# if SANITIZER_LINUX
557 return internal_syscall(SYSCALL(dup3), oldfd, newfd, 0);
558# else
559 return internal_syscall(SYSCALL(dup2), oldfd, newfd);
560# endif
561}
562
563uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
564# if SANITIZER_LINUX
565 return internal_syscall(SYSCALL(readlinkat), AT_FDCWD, (uptr)path, (uptr)buf,
566 bufsize);
567# else
568 return internal_syscall(SYSCALL(readlink), (uptr)path, (uptr)buf, bufsize);
569# endif
570}
571
572uptr internal_unlink(const char *path) {
573# if SANITIZER_LINUX
574 return internal_syscall(SYSCALL(unlinkat), AT_FDCWD, (uptr)path, 0);
575# else
576 return internal_syscall(SYSCALL(unlink), (uptr)path);
577# endif
578}
579
580uptr internal_rename(const char *oldpath, const char *newpath) {
581# if (defined(__riscv) || defined(__loongarch__)) && defined(__linux__)
582 return internal_syscall(SYSCALL(renameat2), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
583 (uptr)newpath, 0);
584# elif SANITIZER_LINUX
585 return internal_syscall(SYSCALL(renameat), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
586 (uptr)newpath);
587# else
588 return internal_syscall(SYSCALL(rename), (uptr)oldpath, (uptr)newpath);
589# endif
590}
591
592uptr internal_sched_yield() { return internal_syscall(SYSCALL(sched_yield)); }
593
594void internal_usleep(u64 useconds) {
595 struct timespec ts;
596 ts.tv_sec = useconds / 1000000;
597 ts.tv_nsec = (useconds % 1000000) * 1000;
598 internal_syscall(SYSCALL(nanosleep), &ts, &ts);
599}
600
601uptr internal_execve(const char *filename, char *const argv[],
602 char *const envp[]) {
603 return internal_syscall(SYSCALL(execve), (uptr)filename, (uptr)argv,
604 (uptr)envp);
605}
606# endif // !SANITIZER_SOLARIS && !SANITIZER_NETBSD && !SANITIZER_HAIKU
607
608# if !SANITIZER_NETBSD && !SANITIZER_HAIKU
609void internal__exit(int exitcode) {
610# if SANITIZER_FREEBSD || SANITIZER_SOLARIS
611 internal_syscall(SYSCALL(exit), exitcode);
612# else
613 internal_syscall(SYSCALL(exit_group), exitcode);
614# endif
615 Die(); // Unreachable.
616}
617# endif // !SANITIZER_NETBSD && !SANITIZER_HAIKU
618
619// ----------------- sanitizer_common.h
620bool FileExists(const char *filename) {
621 if (ShouldMockFailureToOpen(filename))
622 return false;
623 struct stat st;
624 if (internal_stat(filename, &st))
625 return false;
626 // Sanity check: filename is a regular file.
627 return S_ISREG(st.st_mode);
628}
629
630bool DirExists(const char *path) {
631 struct stat st;
632 if (internal_stat(path, &st))
633 return false;
634 return S_ISDIR(st.st_mode);
635}
636
637# if !SANITIZER_NETBSD
638tid_t GetTid() {
639# if SANITIZER_FREEBSD
640 long Tid;
641 thr_self(&Tid);
642 return Tid;
643# elif SANITIZER_SOLARIS
644 return thr_self();
645# elif SANITIZER_HAIKU
646 return find_thread(NULL);
647# else
648 return internal_syscall(SYSCALL(gettid));
649# endif
650}
651
652int TgKill(pid_t pid, tid_t tid, int sig) {
653# if SANITIZER_LINUX
654 return internal_syscall(SYSCALL(tgkill), pid, tid, sig);
655# elif SANITIZER_FREEBSD
656 return internal_syscall(SYSCALL(thr_kill2), pid, tid, sig);
657# elif SANITIZER_SOLARIS
658 (void)pid;
659 errno = thr_kill(tid, sig);
660 // TgKill is expected to return -1 on error, not an errno.
661 return errno != 0 ? -1 : 0;
662# elif SANITIZER_HAIKU
663 return kill_thread(tid);
664# endif
665}
666# endif
667
668# if SANITIZER_GLIBC
669u64 NanoTime() {
670 kernel_timeval tv;
671 internal_memset(&tv, 0, sizeof(tv));
672 internal_syscall(SYSCALL(gettimeofday), &tv, 0);
673 return (u64)tv.tv_sec * 1000 * 1000 * 1000 + tv.tv_usec * 1000;
674}
675// Used by real_clock_gettime.
676uptr internal_clock_gettime(__sanitizer_clockid_t clk_id, void *tp) {
677 return internal_syscall(SYSCALL(clock_gettime), clk_id, tp);
678}
679# elif !SANITIZER_SOLARIS && !SANITIZER_NETBSD
680u64 NanoTime() {
681 struct timespec ts;
682 clock_gettime(CLOCK_REALTIME, &ts);
683 return (u64)ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec;
684}
685# endif
686
687// Like getenv, but reads env directly from /proc (on Linux) or parses the
688// 'environ' array (on some others) and does not use libc. This function
689// should be called first inside __asan_init.
690const char *GetEnv(const char *name) {
691# if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_SOLARIS || \
692 SANITIZER_HAIKU
693 if (::environ != 0) {
694 uptr NameLen = internal_strlen(name);
695 for (char **Env = ::environ; *Env != 0; Env++) {
696 if (internal_strncmp(*Env, name, NameLen) == 0 && (*Env)[NameLen] == '=')
697 return (*Env) + NameLen + 1;
698 }
699 }
700 return 0; // Not found.
701# elif SANITIZER_LINUX
702 static char *environ;
703 static uptr len;
704 static bool inited;
705 if (!inited) {
706 inited = true;
707 uptr environ_size;
708 if (!ReadFileToBuffer("/proc/self/environ", &environ, &environ_size, &len))
709 environ = nullptr;
710 }
711 if (!environ || len == 0)
712 return nullptr;
713 uptr namelen = internal_strlen(name);
714 const char *p = environ;
715 while (*p != '\0') { // will happen at the \0\0 that terminates the buffer
716 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
717 const char *endp = (char *)internal_memchr(p, '\0', len - (p - environ));
718 if (!endp) // this entry isn't NUL terminated
719 return nullptr;
720 else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') // Match.
721 return p + namelen + 1; // point after =
722 p = endp + 1;
723 }
724 return nullptr; // Not found.
725# else
726# error "Unsupported platform"
727# endif
728}
729
730# if !SANITIZER_HAIKU && !SANITIZER_FREEBSD && !SANITIZER_NETBSD && \
731 !SANITIZER_GO
732extern "C" {
733SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
734}
735# endif
736
737# if !SANITIZER_HAIKU && !SANITIZER_FREEBSD && !SANITIZER_NETBSD
738static void ReadNullSepFileToArray(const char *path, char ***arr,
739 int arr_size) {
740 char *buff;
741 uptr buff_size;
742 uptr buff_len;
743 *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
744 if (!ReadFileToBuffer(path, &buff, &buff_size, &buff_len, 1024 * 1024)) {
745 (*arr)[0] = nullptr;
746 return;
747 }
748 (*arr)[0] = buff;
749 int count, i;
750 for (count = 1, i = 1;; i++) {
751 if (buff[i] == 0) {
752 if (buff[i + 1] == 0)
753 break;
754 (*arr)[count] = &buff[i + 1];
755 CHECK_LE(count, arr_size - 1); // FIXME: make this more flexible.
756 count++;
757 }
758 }
759 (*arr)[count] = nullptr;
760}
761# endif
762
763static void GetArgsAndEnv(char ***argv, char ***envp) {
764# if SANITIZER_HAIKU
765 *argv = __libc_argv;
766 *envp = environ;
767# elif SANITIZER_FREEBSD
768 // On FreeBSD, retrieving the argument and environment arrays is done via the
769 // kern.ps_strings sysctl, which returns a pointer to a structure containing
770 // this information. See also <sys/exec.h>.
771 ps_strings *pss;
772 uptr sz = sizeof(pss);
773 if (internal_sysctlbyname("kern.ps_strings", &pss, &sz, NULL, 0) == -1) {
774 Printf("sysctl kern.ps_strings failed\n");
775 Die();
776 }
777 *argv = pss->ps_argvstr;
778 *envp = pss->ps_envstr;
779# elif SANITIZER_NETBSD
780 *argv = __ps_strings->ps_argvstr;
781 *envp = __ps_strings->ps_envstr;
782# else // SANITIZER_FREEBSD
783# if !SANITIZER_GO
784 if (&__libc_stack_end) {
785 uptr *stack_end = (uptr *)__libc_stack_end;
786 // Linux/sparc64 needs an adjustment, cf. glibc
787 // sysdeps/sparc/sparc{32,64}/dl-machine.h (DL_STACK_END).
788# if SANITIZER_LINUX && defined(__sparc__)
789 stack_end = &stack_end[16];
790# endif
791 // Normally argc can be obtained from *stack_end, however, on ARM glibc's
792 // _start clobbers it:
793 // https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/arm/start.S;hb=refs/heads/release/2.31/master#l75
794 // Do not special-case ARM and infer argc from argv everywhere.
795 int argc = 0;
796 while (stack_end[argc + 1]) argc++;
797 *argv = (char **)(stack_end + 1);
798 *envp = (char **)(stack_end + argc + 2);
799 } else {
800# endif // !SANITIZER_GO
801 static const int kMaxArgv = 2000, kMaxEnvp = 2000;
802 ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
803 ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
804# if !SANITIZER_GO
805 }
806# endif // !SANITIZER_GO
807# endif // SANITIZER_HAIKU
808}
809
810char **GetArgv() {
811 char **argv, **envp;
812 GetArgsAndEnv(&argv, &envp);
813 return argv;
814}
815
816char **GetEnviron() {
817 char **argv, **envp;
818 GetArgsAndEnv(&argv, &envp);
819 return envp;
820}
821
822# if !SANITIZER_SOLARIS
823void FutexWait(atomic_uint32_t *p, u32 cmp) {
824# if SANITIZER_FREEBSD
825 _umtx_op(p, UMTX_OP_WAIT_UINT, cmp, 0, 0);
826# elif SANITIZER_NETBSD || SANITIZER_HAIKU
827 sched_yield(); /* No userspace futex-like synchronization */
828# else
829 internal_syscall(SYSCALL(futex), (uptr)p, FUTEX_WAIT_PRIVATE, cmp, 0, 0, 0);
830# endif
831}
832
833void FutexWake(atomic_uint32_t *p, u32 count) {
834# if SANITIZER_FREEBSD
835 _umtx_op(p, UMTX_OP_WAKE, count, 0, 0);
836# elif SANITIZER_NETBSD || SANITIZER_HAIKU
837 /* No userspace futex-like synchronization */
838# else
839 internal_syscall(SYSCALL(futex), (uptr)p, FUTEX_WAKE_PRIVATE, count, 0, 0, 0);
840# endif
841}
842
843# endif // !SANITIZER_SOLARIS
844
845// ----------------- sanitizer_linux.h
846// The actual size of this structure is specified by d_reclen.
847// Note that getdents64 uses a different structure format. We only provide the
848// 32-bit syscall here.
849# if SANITIZER_NETBSD
850// Not used
851# else
852struct linux_dirent {
853# if SANITIZER_X32 || SANITIZER_LINUX
854 u64 d_ino;
855 u64 d_off;
856# else
857 unsigned long d_ino;
858 unsigned long d_off;
859# endif
860 unsigned short d_reclen;
861# if SANITIZER_LINUX
862 unsigned char d_type;
863# endif
864 char d_name[256];
865};
866# endif
867
868# if !SANITIZER_SOLARIS && !SANITIZER_NETBSD && !SANITIZER_HAIKU
869// Syscall wrappers.
870uptr internal_ptrace(int request, int pid, void *addr, void *data) {
871 return internal_syscall(SYSCALL(ptrace), request, pid, (uptr)addr,
872 (uptr)data);
873}
874
875uptr internal_waitpid(int pid, int *status, int options) {
876 return internal_syscall(SYSCALL(wait4), pid, (uptr)status, options,
877 0 /* rusage */);
878}
879
880uptr internal_getpid() { return internal_syscall(SYSCALL(getpid)); }
881
882uptr internal_getppid() { return internal_syscall(SYSCALL(getppid)); }
883
884int internal_dlinfo(void *handle, int request, void *p) {
885# if SANITIZER_FREEBSD
886 return dlinfo(handle, request, p);
887# else
888 UNIMPLEMENTED();
889# endif
890}
891
892uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) {
893# if SANITIZER_FREEBSD
894 return internal_syscall(SYSCALL(getdirentries), fd, (uptr)dirp, count, NULL);
895# elif SANITIZER_LINUX
896 return internal_syscall(SYSCALL(getdents64), fd, (uptr)dirp, count);
897# else
898 return internal_syscall(SYSCALL(getdents), fd, (uptr)dirp, count);
899# endif
900}
901
902uptr internal_lseek(fd_t fd, OFF_T offset, int whence) {
903 return internal_syscall(SYSCALL(lseek), fd, offset, whence);
904}
905
906# if SANITIZER_LINUX
907uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
908 return internal_syscall(SYSCALL(prctl), option, arg2, arg3, arg4, arg5);
909}
910# if defined(__x86_64__)
911# include <asm/unistd_64.h>
912// Currently internal_arch_prctl() is only needed on x86_64.
913uptr internal_arch_prctl(int option, uptr arg2) {
914 return internal_syscall(__NR_arch_prctl, option, arg2);
915}
916# endif
917# endif
918
919uptr internal_sigaltstack(const void *ss, void *oss) {
920 return internal_syscall(SYSCALL(sigaltstack), (uptr)ss, (uptr)oss);
921}
922
923extern "C" pid_t __fork(void);
924
925int internal_fork() {
926# if SANITIZER_LINUX
927# if SANITIZER_S390
928 return internal_syscall(SYSCALL(clone), 0, SIGCHLD);
929# elif SANITIZER_SPARC
930 // The clone syscall interface on SPARC differs massively from the rest,
931 // so fall back to __fork.
932 return __fork();
933# else
934 return internal_syscall(SYSCALL(clone), SIGCHLD, 0);
935# endif
936# else
937 return internal_syscall(SYSCALL(fork));
938# endif
939}
940
941# if SANITIZER_FREEBSD
942int internal_sigaction(int signum, const void *act, void *oldact) {
943 /* zig patch: use direct syscall for freebsd mmap */
944 return internal_syscall(SYSCALL(sigaction), signum, (uptr)act, (uptr)oldact);
945}
946
947int internal_sysctl(const int *name, unsigned int namelen, void *oldp,
948 uptr *oldlenp, const void *newp, uptr newlen) {
949 return internal_syscall(SYSCALL(__sysctl), name, namelen, oldp,
950 (size_t *)oldlenp, newp, (size_t)newlen);
951}
952
953int internal_sysctlbyname(const char *sname, void *oldp, uptr *oldlenp,
954 const void *newp, uptr newlen) {
955 // Note: this function can be called during startup, so we need to avoid
956 // calling any interceptable functions. On FreeBSD >= 1300045 sysctlbyname()
957 // is a real syscall, but for older versions it calls sysctlnametomib()
958 // followed by sysctl(). To avoid calling the intercepted version and
959 // asserting if this happens during startup, call the real sysctlnametomib()
960 // followed by internal_sysctl() if the syscall is not available.
961# ifdef SYS___sysctlbyname
962 return internal_syscall(SYSCALL(__sysctlbyname), sname,
963 internal_strlen(sname), oldp, (size_t *)oldlenp, newp,
964 (size_t)newlen);
965# else
966 static decltype(sysctlnametomib) *real_sysctlnametomib = nullptr;
967 if (!real_sysctlnametomib)
968 real_sysctlnametomib =
969 (decltype(sysctlnametomib) *)dlsym(RTLD_NEXT, "sysctlnametomib");
970 CHECK(real_sysctlnametomib);
971
972 int oid[CTL_MAXNAME];
973 size_t len = CTL_MAXNAME;
974 if (real_sysctlnametomib(sname, oid, &len) == -1)
975 return (-1);
976 return internal_sysctl(oid, len, oldp, oldlenp, newp, newlen);
977# endif
978}
979# endif
980
981# if SANITIZER_LINUX
982# define SA_RESTORER 0x04000000
983// Doesn't set sa_restorer if the caller did not set it, so use with caution
984//(see below).
985int internal_sigaction_norestorer(int signum, const void *act, void *oldact) {
986 __sanitizer_kernel_sigaction_t k_act, k_oldact;
987 internal_memset(&k_act, 0, sizeof(__sanitizer_kernel_sigaction_t));
988 internal_memset(&k_oldact, 0, sizeof(__sanitizer_kernel_sigaction_t));
989 const __sanitizer_sigaction *u_act = (const __sanitizer_sigaction *)act;
990 __sanitizer_sigaction *u_oldact = (__sanitizer_sigaction *)oldact;
991 if (u_act) {
992 k_act.handler = u_act->handler;
993 k_act.sigaction = u_act->sigaction;
994 internal_memcpy(&k_act.sa_mask, &u_act->sa_mask,
995 sizeof(__sanitizer_kernel_sigset_t));
996 // Without SA_RESTORER kernel ignores the calls (probably returns EINVAL).
997 k_act.sa_flags = u_act->sa_flags | SA_RESTORER;
998 // FIXME: most often sa_restorer is unset, however the kernel requires it
999 // to point to a valid signal restorer that calls the rt_sigreturn syscall.
1000 // If sa_restorer passed to the kernel is NULL, the program may crash upon
1001 // signal delivery or fail to unwind the stack in the signal handler.
1002 // libc implementation of sigaction() passes its own restorer to
1003 // rt_sigaction, so we need to do the same (we'll need to reimplement the
1004 // restorers; for x86_64 the restorer address can be obtained from
1005 // oldact->sa_restorer upon a call to sigaction(xxx, NULL, oldact).
1006# if !SANITIZER_ANDROID || !SANITIZER_MIPS32
1007 k_act.sa_restorer = u_act->sa_restorer;
1008# endif
1009 }
1010
1011 uptr result = internal_syscall(SYSCALL(rt_sigaction), (uptr)signum,
1012 (uptr)(u_act ? &k_act : nullptr),
1013 (uptr)(u_oldact ? &k_oldact : nullptr),
1014 (uptr)sizeof(__sanitizer_kernel_sigset_t));
1015
1016 if ((result == 0) && u_oldact) {
1017 u_oldact->handler = k_oldact.handler;
1018 u_oldact->sigaction = k_oldact.sigaction;
1019 internal_memcpy(&u_oldact->sa_mask, &k_oldact.sa_mask,
1020 sizeof(__sanitizer_kernel_sigset_t));
1021 u_oldact->sa_flags = k_oldact.sa_flags;
1022# if !SANITIZER_ANDROID || !SANITIZER_MIPS32
1023 u_oldact->sa_restorer = k_oldact.sa_restorer;
1024# endif
1025 }
1026 return result;
1027}
1028# endif // SANITIZER_LINUX
1029
1030uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
1031 __sanitizer_sigset_t *oldset) {
1032# if SANITIZER_FREEBSD
1033 return internal_syscall(SYSCALL(sigprocmask), how, set, oldset);
1034# else
1035 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
1036 __sanitizer_kernel_sigset_t *k_oldset = (__sanitizer_kernel_sigset_t *)oldset;
1037 return internal_syscall(SYSCALL(rt_sigprocmask), (uptr)how, (uptr)k_set,
1038 (uptr)k_oldset, sizeof(__sanitizer_kernel_sigset_t));
1039# endif
1040}
1041
1042void internal_sigfillset(__sanitizer_sigset_t *set) {
1043 internal_memset(set, 0xff, sizeof(*set));
1044}
1045
1046void internal_sigemptyset(__sanitizer_sigset_t *set) {
1047 internal_memset(set, 0, sizeof(*set));
1048}
1049
1050# if SANITIZER_LINUX
1051void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
1052 signum -= 1;
1053 CHECK_GE(signum, 0);
1054 CHECK_LT(signum, sizeof(*set) * 8);
1055 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
1056 const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
1057 const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
1058 k_set->sig[idx] &= ~((uptr)1 << bit);
1059}
1060
1061bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
1062 signum -= 1;
1063 CHECK_GE(signum, 0);
1064 CHECK_LT(signum, sizeof(*set) * 8);
1065 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
1066 const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
1067 const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
1068 return k_set->sig[idx] & ((uptr)1 << bit);
1069}
1070# elif SANITIZER_FREEBSD
1071uptr internal_procctl(int type, int id, int cmd, void *data) {
1072 return internal_syscall(SYSCALL(procctl), type, id, cmd, data);
1073}
1074
1075void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
1076 sigset_t *rset = reinterpret_cast<sigset_t *>(set);
1077 sigdelset(rset, signum);
1078}
1079
1080bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
1081 sigset_t *rset = reinterpret_cast<sigset_t *>(set);
1082 return sigismember(rset, signum);
1083}
1084# endif
1085# endif // !SANITIZER_SOLARIS
1086
1087# if !SANITIZER_NETBSD && !SANITIZER_HAIKU
1088// ThreadLister implementation.
1089ThreadLister::ThreadLister(pid_t pid) : buffer_(4096) {
1090 task_path_.AppendF("/proc/%d/task", pid);
1091}
1092
1093ThreadLister::Result ThreadLister::ListThreads(
1094 InternalMmapVector<tid_t> *threads) {
1095 int descriptor = internal_open(task_path_.data(), O_RDONLY | O_DIRECTORY);
1096 if (internal_iserror(descriptor)) {
1097 Report("Can't open %s for reading.\n", task_path_.data());
1098 return Error;
1099 }
1100 auto cleanup = at_scope_exit([&] { internal_close(descriptor); });
1101 threads->clear();
1102
1103 Result result = Ok;
1104 for (bool first_read = true;; first_read = false) {
1105 CHECK_GE(buffer_.size(), 4096);
1106 uptr read = internal_getdents(
1107 descriptor, (struct linux_dirent *)buffer_.data(), buffer_.size());
1108 if (!read)
1109 return result;
1110 if (internal_iserror(read)) {
1111 Report("Can't read directory entries from %s.\n", task_path_.data());
1112 return Error;
1113 }
1114
1115 for (uptr begin = (uptr)buffer_.data(), end = begin + read; begin < end;) {
1116 struct linux_dirent *entry = (struct linux_dirent *)begin;
1117 begin += entry->d_reclen;
1118 if (entry->d_ino == 1) {
1119 // Inode 1 is for bad blocks and also can be a reason for early return.
1120 // Should be emitted if kernel tried to output terminating thread.
1121 // See proc_task_readdir implementation in Linux.
1122 result = Incomplete;
1123 }
1124 if (entry->d_ino && *entry->d_name >= '0' && *entry->d_name <= '9')
1125 threads->push_back(internal_atoll(entry->d_name));
1126 }
1127
1128 // Now we are going to detect short-read or early EOF. In such cases Linux
1129 // can return inconsistent list with missing alive threads.
1130 // Code will just remember that the list can be incomplete but it will
1131 // continue reads to return as much as possible.
1132 if (!first_read) {
1133 // The first one was a short-read by definition.
1134 result = Incomplete;
1135 } else if (read > buffer_.size() - 1024) {
1136 // Read was close to the buffer size. So double the size and assume the
1137 // worst.
1138 buffer_.resize(buffer_.size() * 2);
1139 result = Incomplete;
1140 } else if (!threads->empty() && !IsAlive(threads->back())) {
1141 // Maybe Linux early returned from read on terminated thread (!pid_alive)
1142 // and failed to restore read position.
1143 // See next_tid and proc_task_instantiate in Linux.
1144 result = Incomplete;
1145 }
1146 }
1147}
1148
1149const char *ThreadLister::LoadStatus(tid_t tid) {
1150 status_path_.clear();
1151 status_path_.AppendF("%s/%llu/status", task_path_.data(), tid);
1152 auto cleanup = at_scope_exit([&] {
1153 // Resize back to capacity if it is downsized by `ReadFileToVector`.
1154 buffer_.resize(buffer_.capacity());
1155 });
1156 if (!ReadFileToVector(status_path_.data(), &buffer_) || buffer_.empty())
1157 return nullptr;
1158 buffer_.push_back('\0');
1159 return buffer_.data();
1160}
1161
1162bool ThreadLister::IsAlive(tid_t tid) {
1163 // /proc/%d/task/%d/status uses same call to detect alive threads as
1164 // proc_task_readdir. See task_state implementation in Linux.
1165 static const char kPrefix[] = "\nPPid:";
1166 const char *status = LoadStatus(tid);
1167 if (!status)
1168 return false;
1169 const char *field = internal_strstr(status, kPrefix);
1170 if (!field)
1171 return false;
1172 field += internal_strlen(kPrefix);
1173 return (int)internal_atoll(field) != 0;
1174}
1175
1176# endif
1177
1178# if SANITIZER_WORDSIZE == 32
1179// Take care of unusable kernel area in top gigabyte.
1180static uptr GetKernelAreaSize() {
1181# if SANITIZER_LINUX && !SANITIZER_X32
1182 const uptr gbyte = 1UL << 30;
1183
1184 // Firstly check if there are writable segments
1185 // mapped to top gigabyte (e.g. stack).
1186 MemoryMappingLayout proc_maps(/*cache_enabled*/ true);
1187 if (proc_maps.Error())
1188 return 0;
1189 MemoryMappedSegment segment;
1190 while (proc_maps.Next(&segment)) {
1191 if ((segment.end >= 3 * gbyte) && segment.IsWritable())
1192 return 0;
1193 }
1194
1195# if !SANITIZER_ANDROID
1196 // Even if nothing is mapped, top Gb may still be accessible
1197 // if we are running on 64-bit kernel.
1198 // Uname may report misleading results if personality type
1199 // is modified (e.g. under schroot) so check this as well.
1200 struct utsname uname_info;
1201 int pers = personality(0xffffffffUL);
1202 if (!(pers & PER_MASK) && internal_uname(&uname_info) == 0 &&
1203 internal_strstr(uname_info.machine, "64"))
1204 return 0;
1205# endif // SANITIZER_ANDROID
1206
1207 // Top gigabyte is reserved for kernel.
1208 return gbyte;
1209# else
1210 return 0;
1211# endif // SANITIZER_LINUX && !SANITIZER_X32
1212}
1213# endif // SANITIZER_WORDSIZE == 32
1214
1215uptr GetMaxVirtualAddress() {
1216# if SANITIZER_NETBSD && defined(__x86_64__)
1217 return 0x7f7ffffff000ULL; // (0x00007f8000000000 - PAGE_SIZE)
1218# elif SANITIZER_WORDSIZE == 64
1219# if defined(__powerpc64__) || defined(__aarch64__) || \
1220 defined(__loongarch__) || SANITIZER_RISCV64
1221 // On PowerPC64 we have two different address space layouts: 44- and 46-bit.
1222 // We somehow need to figure out which one we are using now and choose
1223 // one of 0x00000fffffffffffUL and 0x00003fffffffffffUL.
1224 // Note that with 'ulimit -s unlimited' the stack is moved away from the top
1225 // of the address space, so simply checking the stack address is not enough.
1226 // This should (does) work for both PowerPC64 Endian modes.
1227 // Similarly, aarch64 has multiple address space layouts: 39, 42 and 47-bit.
1228 // loongarch64 also has multiple address space layouts: default is 47-bit.
1229 // RISC-V 64 also has multiple address space layouts: 39, 48 and 57-bit.
1230 return (1ULL << (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1)) - 1;
1231# elif SANITIZER_MIPS64
1232 return (1ULL << 40) - 1; // 0x000000ffffffffffUL;
1233# elif defined(__s390x__)
1234 return (1ULL << 53) - 1; // 0x001fffffffffffffUL;
1235# elif defined(__sparc__)
1236 return ~(uptr)0;
1237# else
1238 return (1ULL << 47) - 1; // 0x00007fffffffffffUL;
1239# endif
1240# else // SANITIZER_WORDSIZE == 32
1241# if defined(__s390__)
1242 return (1ULL << 31) - 1; // 0x7fffffff;
1243# else
1244 return (1ULL << 32) - 1; // 0xffffffff;
1245# endif
1246# endif // SANITIZER_WORDSIZE
1247}
1248
1249uptr GetMaxUserVirtualAddress() {
1250 uptr addr = GetMaxVirtualAddress();
1251# if SANITIZER_WORDSIZE == 32 && !defined(__s390__)
1252 if (!common_flags()->full_address_space)
1253 addr -= GetKernelAreaSize();
1254 CHECK_LT(reinterpret_cast<uptr>(&addr), addr);
1255# endif
1256 return addr;
1257}
1258
1259# if !SANITIZER_ANDROID || defined(__aarch64__)
1260uptr GetPageSize() {
1261# if SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__)) && \
1262 defined(EXEC_PAGESIZE)
1263 return EXEC_PAGESIZE;
1264# elif SANITIZER_FREEBSD || SANITIZER_NETBSD
1265 // Use sysctl as sysconf can trigger interceptors internally.
1266 int pz = 0;
1267 uptr pzl = sizeof(pz);
1268 int mib[2] = {CTL_HW, HW_PAGESIZE};
1269 int rv = internal_sysctl(mib, 2, &pz, &pzl, nullptr, 0);
1270 CHECK_EQ(rv, 0);
1271 return (uptr)pz;
1272# elif SANITIZER_USE_GETAUXVAL
1273# if SANITIZER_ANDROID && __ANDROID_API__ < 35
1274 // The 16 KB page size was introduced in Android 15 (API level 35), while
1275 // earlier versions of Android always used a 4 KB page size.
1276 // We are checking the weak definition of `strerrorname_np` (introduced in API
1277 // level 35) because some earlier API levels crashed when
1278 // `getauxval(AT_PAGESZ)` was called from the `.preinit_array`.
1279 if (!strerrorname_np)
1280 return 4096;
1281# endif
1282
1283 return getauxval(AT_PAGESZ);
1284# else
1285 return sysconf(_SC_PAGESIZE); // EXEC_PAGESIZE may not be trustworthy.
1286# endif
1287}
1288# endif
1289
1290uptr ReadBinaryName(/*out*/ char *buf, uptr buf_len) {
1291# if SANITIZER_HAIKU
1292 int cookie = 0;
1293 image_info info;
1294 const char *argv0 = "<UNKNOWN>";
1295 while (get_next_image_info(B_CURRENT_TEAM, &cookie, &info) == B_OK) {
1296 if (info.type != B_APP_IMAGE)
1297 continue;
1298 argv0 = info.name;
1299 break;
1300 }
1301 internal_strncpy(buf, argv0, buf_len);
1302 return internal_strlen(buf);
1303# elif SANITIZER_SOLARIS
1304 const char *default_module_name = getexecname();
1305 CHECK_NE(default_module_name, NULL);
1306 return internal_snprintf(buf, buf_len, "%s", default_module_name);
1307# else
1308# if SANITIZER_FREEBSD || SANITIZER_NETBSD
1309# if SANITIZER_FREEBSD
1310 const int Mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
1311# else
1312 const int Mib[4] = {CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME};
1313# endif
1314 const char *default_module_name = "kern.proc.pathname";
1315 uptr Size = buf_len;
1316 bool IsErr =
1317 (internal_sysctl(Mib, ARRAY_SIZE(Mib), buf, &Size, NULL, 0) != 0);
1318 int readlink_error = IsErr ? errno : 0;
1319 uptr module_name_len = Size;
1320# else
1321 const char *default_module_name = "/proc/self/exe";
1322 uptr module_name_len = internal_readlink(default_module_name, buf, buf_len);
1323 int readlink_error;
1324 bool IsErr = internal_iserror(module_name_len, &readlink_error);
1325# endif
1326 if (IsErr) {
1327 // We can't read binary name for some reason, assume it's unknown.
1328 Report(
1329 "WARNING: reading executable name failed with errno %d, "
1330 "some stack frames may not be symbolized\n",
1331 readlink_error);
1332 module_name_len =
1333 internal_snprintf(buf, buf_len, "%s", default_module_name);
1334 CHECK_LT(module_name_len, buf_len);
1335 }
1336 return module_name_len;
1337# endif
1338}
1339
1340uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len) {
1341# if SANITIZER_LINUX
1342 char *tmpbuf;
1343 uptr tmpsize;
1344 uptr tmplen;
1345 if (ReadFileToBuffer("/proc/self/cmdline", &tmpbuf, &tmpsize, &tmplen,
1346 1024 * 1024)) {
1347 internal_strncpy(buf, tmpbuf, buf_len);
1348 UnmapOrDie(tmpbuf, tmpsize);
1349 return internal_strlen(buf);
1350 }
1351# endif
1352 return ReadBinaryName(buf, buf_len);
1353}
1354
1355// Match full names of the form /path/to/base_name{-,.}*
1356bool LibraryNameIs(const char *full_name, const char *base_name) {
1357 const char *name = full_name;
1358 // Strip path.
1359 while (*name != '\0') name++;
1360 while (name > full_name && *name != '/') name--;
1361 if (*name == '/')
1362 name++;
1363 uptr base_name_length = internal_strlen(base_name);
1364 if (internal_strncmp(name, base_name, base_name_length))
1365 return false;
1366 return (name[base_name_length] == '-' || name[base_name_length] == '.');
1367}
1368
1369# if !SANITIZER_ANDROID && !SANITIZER_HAIKU
1370// Call cb for each region mapped by map.
1371void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr)) {
1372 CHECK_NE(map, nullptr);
1373# if !SANITIZER_FREEBSD && !SANITIZER_HAIKU
1374 typedef ElfW(Phdr) Elf_Phdr;
1375 typedef ElfW(Ehdr) Elf_Ehdr;
1376# endif // !SANITIZER_FREEBSD
1377 char *base = (char *)map->l_addr;
1378 Elf_Ehdr *ehdr = (Elf_Ehdr *)base;
1379 char *phdrs = base + ehdr->e_phoff;
1380 char *phdrs_end = phdrs + ehdr->e_phnum * ehdr->e_phentsize;
1381
1382 // Find the segment with the minimum base so we can "relocate" the p_vaddr
1383 // fields. Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
1384 // objects have a non-zero base.
1385 uptr preferred_base = (uptr)-1;
1386 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
1387 Elf_Phdr *phdr = (Elf_Phdr *)iter;
1388 if (phdr->p_type == PT_LOAD && preferred_base > (uptr)phdr->p_vaddr)
1389 preferred_base = (uptr)phdr->p_vaddr;
1390 }
1391
1392 // Compute the delta from the real base to get a relocation delta.
1393 sptr delta = (uptr)base - preferred_base;
1394 // Now we can figure out what the loader really mapped.
1395 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
1396 Elf_Phdr *phdr = (Elf_Phdr *)iter;
1397 if (phdr->p_type == PT_LOAD) {
1398 uptr seg_start = phdr->p_vaddr + delta;
1399 uptr seg_end = seg_start + phdr->p_memsz;
1400 // None of these values are aligned. We consider the ragged edges of the
1401 // load command as defined, since they are mapped from the file.
1402 seg_start = RoundDownTo(seg_start, GetPageSizeCached());
1403 seg_end = RoundUpTo(seg_end, GetPageSizeCached());
1404 cb((void *)seg_start, seg_end - seg_start);
1405 }
1406 }
1407}
1408# endif
1409
1410# if SANITIZER_LINUX
1411# if defined(__x86_64__)
1412// We cannot use glibc's clone wrapper, because it messes with the child
1413// task's TLS. It writes the PID and TID of the child task to its thread
1414// descriptor, but in our case the child task shares the thread descriptor with
1415// the parent (because we don't know how to allocate a new thread
1416// descriptor to keep glibc happy). So the stock version of clone(), when
1417// used with CLONE_VM, would end up corrupting the parent's thread descriptor.
1418uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1419 int *parent_tidptr, void *newtls, int *child_tidptr) {
1420 long long res;
1421 if (!fn || !child_stack)
1422 return -EINVAL;
1423 CHECK_EQ(0, (uptr)child_stack % 16);
1424 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1425 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1426 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1427 register void *r8 __asm__("r8") = newtls;
1428 register int *r10 __asm__("r10") = child_tidptr;
1429 __asm__ __volatile__(
1430 /* %rax = syscall(%rax = SYSCALL(clone),
1431 * %rdi = flags,
1432 * %rsi = child_stack,
1433 * %rdx = parent_tidptr,
1434 * %r8 = new_tls,
1435 * %r10 = child_tidptr)
1436 */
1437 "syscall\n"
1438
1439 /* if (%rax != 0)
1440 * return;
1441 */
1442 "testq %%rax,%%rax\n"
1443 "jnz 1f\n"
1444
1445 /* In the child. Terminate unwind chain. */
1446 // XXX: We should also terminate the CFI unwind chain
1447 // here. Unfortunately clang 3.2 doesn't support the
1448 // necessary CFI directives, so we skip that part.
1449 "xorq %%rbp,%%rbp\n"
1450
1451 /* Call "fn(arg)". */
1452 "popq %%rax\n"
1453 "popq %%rdi\n"
1454 "call *%%rax\n"
1455
1456 /* Call _exit(%rax). */
1457 "movq %%rax,%%rdi\n"
1458 "movq %2,%%rax\n"
1459 "syscall\n"
1460
1461 /* Return to parent. */
1462 "1:\n"
1463 : "=a"(res)
1464 : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)), "S"(child_stack), "D"(flags),
1465 "d"(parent_tidptr), "r"(r8), "r"(r10)
1466 : "memory", "r11", "rcx");
1467 return res;
1468}
1469# elif defined(__mips__)
1470uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1471 int *parent_tidptr, void *newtls, int *child_tidptr) {
1472 long long res;
1473 if (!fn || !child_stack)
1474 return -EINVAL;
1475 CHECK_EQ(0, (uptr)child_stack % 16);
1476 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1477 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1478 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1479 register void *a3 __asm__("$7") = newtls;
1480 register int *a4 __asm__("$8") = child_tidptr;
1481 // We don't have proper CFI directives here because it requires alot of code
1482 // for very marginal benefits.
1483 __asm__ __volatile__(
1484 /* $v0 = syscall($v0 = __NR_clone,
1485 * $a0 = flags,
1486 * $a1 = child_stack,
1487 * $a2 = parent_tidptr,
1488 * $a3 = new_tls,
1489 * $a4 = child_tidptr)
1490 */
1491 ".cprestore 16;\n"
1492 "move $4,%1;\n"
1493 "move $5,%2;\n"
1494 "move $6,%3;\n"
1495 "move $7,%4;\n"
1496 /* Store the fifth argument on stack
1497 * if we are using 32-bit abi.
1498 */
1499# if SANITIZER_WORDSIZE == 32
1500 "lw %5,16($29);\n"
1501# else
1502 "move $8,%5;\n"
1503# endif
1504 "li $2,%6;\n"
1505 "syscall;\n"
1506
1507 /* if ($v0 != 0)
1508 * return;
1509 */
1510 "bnez $2,1f;\n"
1511
1512 /* Call "fn(arg)". */
1513# if SANITIZER_WORDSIZE == 32
1514# ifdef __BIG_ENDIAN__
1515 "lw $25,4($29);\n"
1516 "lw $4,12($29);\n"
1517# else
1518 "lw $25,0($29);\n"
1519 "lw $4,8($29);\n"
1520# endif
1521# else
1522 "ld $25,0($29);\n"
1523 "ld $4,8($29);\n"
1524# endif
1525 "jal $25;\n"
1526
1527 /* Call _exit($v0). */
1528 "move $4,$2;\n"
1529 "li $2,%7;\n"
1530 "syscall;\n"
1531
1532 /* Return to parent. */
1533 "1:\n"
1534 : "=r"(res)
1535 : "r"(flags), "r"(child_stack), "r"(parent_tidptr), "r"(a3), "r"(a4),
1536 "i"(__NR_clone), "i"(__NR_exit)
1537 : "memory", "$29");
1538 return res;
1539}
1540# elif SANITIZER_RISCV64
1541uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1542 int *parent_tidptr, void *newtls, int *child_tidptr) {
1543 if (!fn || !child_stack)
1544 return -EINVAL;
1545
1546 CHECK_EQ(0, (uptr)child_stack % 16);
1547
1548 register int res __asm__("a0");
1549 register int __flags __asm__("a0") = flags;
1550 register void *__stack __asm__("a1") = child_stack;
1551 register int *__ptid __asm__("a2") = parent_tidptr;
1552 register void *__tls __asm__("a3") = newtls;
1553 register int *__ctid __asm__("a4") = child_tidptr;
1554 register int (*__fn)(void *) __asm__("a5") = fn;
1555 register void *__arg __asm__("a6") = arg;
1556 register int nr_clone __asm__("a7") = __NR_clone;
1557
1558 __asm__ __volatile__(
1559 "ecall\n"
1560
1561 /* if (a0 != 0)
1562 * return a0;
1563 */
1564 "bnez a0, 1f\n"
1565
1566 // In the child, now. Call "fn(arg)".
1567 "mv a0, a6\n"
1568 "jalr a5\n"
1569
1570 // Call _exit(a0).
1571 "addi a7, zero, %9\n"
1572 "ecall\n"
1573 "1:\n"
1574
1575 : "=r"(res)
1576 : "0"(__flags), "r"(__stack), "r"(__ptid), "r"(__tls), "r"(__ctid),
1577 "r"(__fn), "r"(__arg), "r"(nr_clone), "i"(__NR_exit)
1578 : "memory");
1579 return res;
1580}
1581# elif defined(__aarch64__)
1582uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1583 int *parent_tidptr, void *newtls, int *child_tidptr) {
1584 register long long res __asm__("x0");
1585 if (!fn || !child_stack)
1586 return -EINVAL;
1587 CHECK_EQ(0, (uptr)child_stack % 16);
1588 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1589 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1590 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1591
1592 register int (*__fn)(void *) __asm__("x0") = fn;
1593 register void *__stack __asm__("x1") = child_stack;
1594 register int __flags __asm__("x2") = flags;
1595 register void *__arg __asm__("x3") = arg;
1596 register int *__ptid __asm__("x4") = parent_tidptr;
1597 register void *__tls __asm__("x5") = newtls;
1598 register int *__ctid __asm__("x6") = child_tidptr;
1599
1600 __asm__ __volatile__(
1601 "mov x0,x2\n" /* flags */
1602 "mov x2,x4\n" /* ptid */
1603 "mov x3,x5\n" /* tls */
1604 "mov x4,x6\n" /* ctid */
1605 "mov x8,%9\n" /* clone */
1606
1607 "svc 0x0\n"
1608
1609 /* if (%r0 != 0)
1610 * return %r0;
1611 */
1612 "cmp x0, #0\n"
1613 "bne 1f\n"
1614
1615 /* In the child, now. Call "fn(arg)". */
1616 "ldp x1, x0, [sp], #16\n"
1617 "blr x1\n"
1618
1619 /* Call _exit(%r0). */
1620 "mov x8, %10\n"
1621 "svc 0x0\n"
1622 "1:\n"
1623
1624 : "=r"(res)
1625 : "i"(-EINVAL), "r"(__fn), "r"(__stack), "r"(__flags), "r"(__arg),
1626 "r"(__ptid), "r"(__tls), "r"(__ctid), "i"(__NR_clone), "i"(__NR_exit)
1627 : "x30", "memory");
1628 return res;
1629}
1630# elif SANITIZER_LOONGARCH64
1631uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1632 int *parent_tidptr, void *newtls, int *child_tidptr) {
1633 if (!fn || !child_stack)
1634 return -EINVAL;
1635
1636 CHECK_EQ(0, (uptr)child_stack % 16);
1637
1638 register int res __asm__("$a0");
1639 register int __flags __asm__("$a0") = flags;
1640 register void *__stack __asm__("$a1") = child_stack;
1641 register int *__ptid __asm__("$a2") = parent_tidptr;
1642 register int *__ctid __asm__("$a3") = child_tidptr;
1643 register void *__tls __asm__("$a4") = newtls;
1644 register int (*__fn)(void *) __asm__("$a5") = fn;
1645 register void *__arg __asm__("$a6") = arg;
1646 register int nr_clone __asm__("$a7") = __NR_clone;
1647
1648 __asm__ __volatile__(
1649 "syscall 0\n"
1650
1651 // if ($a0 != 0)
1652 // return $a0;
1653 "bnez $a0, 1f\n"
1654
1655 // In the child, now. Call "fn(arg)".
1656 "move $a0, $a6\n"
1657 "jirl $ra, $a5, 0\n"
1658
1659 // Call _exit($a0).
1660 "addi.d $a7, $zero, %9\n"
1661 "syscall 0\n"
1662
1663 "1:\n"
1664
1665 : "=r"(res)
1666 : "0"(__flags), "r"(__stack), "r"(__ptid), "r"(__ctid), "r"(__tls),
1667 "r"(__fn), "r"(__arg), "r"(nr_clone), "i"(__NR_exit)
1668 : "memory", "$t0", "$t1", "$t2", "$t3", "$t4", "$t5", "$t6", "$t7",
1669 "$t8");
1670 return res;
1671}
1672# elif defined(__powerpc64__)
1673uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1674 int *parent_tidptr, void *newtls, int *child_tidptr) {
1675 long long res;
1676// Stack frame structure.
1677# if SANITIZER_PPC64V1
1678 // Back chain == 0 (SP + 112)
1679 // Frame (112 bytes):
1680 // Parameter save area (SP + 48), 8 doublewords
1681 // TOC save area (SP + 40)
1682 // Link editor doubleword (SP + 32)
1683 // Compiler doubleword (SP + 24)
1684 // LR save area (SP + 16)
1685 // CR save area (SP + 8)
1686 // Back chain (SP + 0)
1687# define FRAME_SIZE 112
1688# define FRAME_TOC_SAVE_OFFSET 40
1689# elif SANITIZER_PPC64V2
1690 // Back chain == 0 (SP + 32)
1691 // Frame (32 bytes):
1692 // TOC save area (SP + 24)
1693 // LR save area (SP + 16)
1694 // CR save area (SP + 8)
1695 // Back chain (SP + 0)
1696# define FRAME_SIZE 32
1697# define FRAME_TOC_SAVE_OFFSET 24
1698# else
1699# error "Unsupported PPC64 ABI"
1700# endif
1701 if (!fn || !child_stack)
1702 return -EINVAL;
1703 CHECK_EQ(0, (uptr)child_stack % 16);
1704
1705 register int (*__fn)(void *) __asm__("r3") = fn;
1706 register void *__cstack __asm__("r4") = child_stack;
1707 register int __flags __asm__("r5") = flags;
1708 register void *__arg __asm__("r6") = arg;
1709 register int *__ptidptr __asm__("r7") = parent_tidptr;
1710 register void *__newtls __asm__("r8") = newtls;
1711 register int *__ctidptr __asm__("r9") = child_tidptr;
1712
1713 __asm__ __volatile__(
1714 /* fn and arg are saved across the syscall */
1715 "mr 28, %5\n\t"
1716 "mr 27, %8\n\t"
1717
1718 /* syscall
1719 r0 == __NR_clone
1720 r3 == flags
1721 r4 == child_stack
1722 r5 == parent_tidptr
1723 r6 == newtls
1724 r7 == child_tidptr */
1725 "mr 3, %7\n\t"
1726 "mr 5, %9\n\t"
1727 "mr 6, %10\n\t"
1728 "mr 7, %11\n\t"
1729 "li 0, %3\n\t"
1730 "sc\n\t"
1731
1732 /* Test if syscall was successful */
1733 "cmpdi cr1, 3, 0\n\t"
1734 "crandc cr1*4+eq, cr1*4+eq, cr0*4+so\n\t"
1735 "bne- cr1, 1f\n\t"
1736
1737 /* Set up stack frame */
1738 "li 29, 0\n\t"
1739 "stdu 29, -8(1)\n\t"
1740 "stdu 1, -%12(1)\n\t"
1741 /* Do the function call */
1742 "std 2, %13(1)\n\t"
1743# if SANITIZER_PPC64V1
1744 "ld 0, 0(28)\n\t"
1745 "ld 2, 8(28)\n\t"
1746 "mtctr 0\n\t"
1747# elif SANITIZER_PPC64V2
1748 "mr 12, 28\n\t"
1749 "mtctr 12\n\t"
1750# else
1751# error "Unsupported PPC64 ABI"
1752# endif
1753 "mr 3, 27\n\t"
1754 "bctrl\n\t"
1755 "ld 2, %13(1)\n\t"
1756
1757 /* Call _exit(r3) */
1758 "li 0, %4\n\t"
1759 "sc\n\t"
1760
1761 /* Return to parent */
1762 "1:\n\t"
1763 "mr %0, 3\n\t"
1764 : "=r"(res)
1765 : "0"(-1), "i"(EINVAL), "i"(__NR_clone), "i"(__NR_exit), "r"(__fn),
1766 "r"(__cstack), "r"(__flags), "r"(__arg), "r"(__ptidptr), "r"(__newtls),
1767 "r"(__ctidptr), "i"(FRAME_SIZE), "i"(FRAME_TOC_SAVE_OFFSET)
1768 : "cr0", "cr1", "memory", "ctr", "r0", "r27", "r28", "r29");
1769 return res;
1770}
1771# elif defined(__i386__)
1772uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1773 int *parent_tidptr, void *newtls, int *child_tidptr) {
1774 int res;
1775 if (!fn || !child_stack)
1776 return -EINVAL;
1777 CHECK_EQ(0, (uptr)child_stack % 16);
1778 child_stack = (char *)child_stack - 7 * sizeof(unsigned int);
1779 ((unsigned int *)child_stack)[0] = (uptr)flags;
1780 ((unsigned int *)child_stack)[1] = (uptr)0;
1781 ((unsigned int *)child_stack)[2] = (uptr)fn;
1782 ((unsigned int *)child_stack)[3] = (uptr)arg;
1783 __asm__ __volatile__(
1784 /* %eax = syscall(%eax = SYSCALL(clone),
1785 * %ebx = flags,
1786 * %ecx = child_stack,
1787 * %edx = parent_tidptr,
1788 * %esi = new_tls,
1789 * %edi = child_tidptr)
1790 */
1791
1792 /* Obtain flags */
1793 "movl (%%ecx), %%ebx\n"
1794 /* Do the system call */
1795 "pushl %%ebx\n"
1796 "pushl %%esi\n"
1797 "pushl %%edi\n"
1798 /* Remember the flag value. */
1799 "movl %%ebx, (%%ecx)\n"
1800 "int $0x80\n"
1801 "popl %%edi\n"
1802 "popl %%esi\n"
1803 "popl %%ebx\n"
1804
1805 /* if (%eax != 0)
1806 * return;
1807 */
1808
1809 "test %%eax,%%eax\n"
1810 "jnz 1f\n"
1811
1812 /* terminate the stack frame */
1813 "xorl %%ebp,%%ebp\n"
1814 /* Call FN. */
1815 "call *%%ebx\n"
1816# ifdef PIC
1817 "call here\n"
1818 "here:\n"
1819 "popl %%ebx\n"
1820 "addl $_GLOBAL_OFFSET_TABLE_+[.-here], %%ebx\n"
1821# endif
1822 /* Call exit */
1823 "movl %%eax, %%ebx\n"
1824 "movl %2, %%eax\n"
1825 "int $0x80\n"
1826 "1:\n"
1827 : "=a"(res)
1828 : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)), "c"(child_stack),
1829 "d"(parent_tidptr), "S"(newtls), "D"(child_tidptr)
1830 : "memory");
1831 return res;
1832}
1833# elif defined(__arm__)
1834uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1835 int *parent_tidptr, void *newtls, int *child_tidptr) {
1836 unsigned int res;
1837 if (!fn || !child_stack)
1838 return -EINVAL;
1839 child_stack = (char *)child_stack - 2 * sizeof(unsigned int);
1840 ((unsigned int *)child_stack)[0] = (uptr)fn;
1841 ((unsigned int *)child_stack)[1] = (uptr)arg;
1842 register int r0 __asm__("r0") = flags;
1843 register void *r1 __asm__("r1") = child_stack;
1844 register int *r2 __asm__("r2") = parent_tidptr;
1845 register void *r3 __asm__("r3") = newtls;
1846 register int *r4 __asm__("r4") = child_tidptr;
1847 register int r7 __asm__("r7") = __NR_clone;
1848
1849# if __ARM_ARCH > 4 || defined(__ARM_ARCH_4T__)
1850# define ARCH_HAS_BX
1851# endif
1852# if __ARM_ARCH > 4
1853# define ARCH_HAS_BLX
1854# endif
1855
1856# ifdef ARCH_HAS_BX
1857# ifdef ARCH_HAS_BLX
1858# define BLX(R) "blx " #R "\n"
1859# else
1860# define BLX(R) "mov lr, pc; bx " #R "\n"
1861# endif
1862# else
1863# define BLX(R) "mov lr, pc; mov pc," #R "\n"
1864# endif
1865
1866 __asm__ __volatile__(
1867 /* %r0 = syscall(%r7 = SYSCALL(clone),
1868 * %r0 = flags,
1869 * %r1 = child_stack,
1870 * %r2 = parent_tidptr,
1871 * %r3 = new_tls,
1872 * %r4 = child_tidptr)
1873 */
1874
1875 /* Do the system call */
1876 "swi 0x0\n"
1877
1878 /* if (%r0 != 0)
1879 * return %r0;
1880 */
1881 "cmp r0, #0\n"
1882 "bne 1f\n"
1883
1884 /* In the child, now. Call "fn(arg)". */
1885 "ldr r0, [sp, #4]\n"
1886 "ldr ip, [sp], #8\n" BLX(ip)
1887 /* Call _exit(%r0). */
1888 "mov r7, %7\n"
1889 "swi 0x0\n"
1890 "1:\n"
1891 "mov %0, r0\n"
1892 : "=r"(res)
1893 : "r"(r0), "r"(r1), "r"(r2), "r"(r3), "r"(r4), "r"(r7), "i"(__NR_exit)
1894 : "memory");
1895 return res;
1896}
1897# endif
1898# endif // SANITIZER_LINUX
1899
1900# if SANITIZER_LINUX
1901int internal_uname(struct utsname *buf) {
1902 return internal_syscall(SYSCALL(uname), buf);
1903}
1904# endif
1905
1906static HandleSignalMode GetHandleSignalModeImpl(int signum) {
1907 switch (signum) {
1908 case SIGABRT:
1909 return common_flags()->handle_abort;
1910 case SIGILL:
1911 return common_flags()->handle_sigill;
1912 case SIGTRAP:
1913 return common_flags()->handle_sigtrap;
1914 case SIGFPE:
1915 return common_flags()->handle_sigfpe;
1916 case SIGSEGV:
1917 return common_flags()->handle_segv;
1918 case SIGBUS:
1919 return common_flags()->handle_sigbus;
1920 }
1921 return kHandleSignalNo;
1922}
1923
1924HandleSignalMode GetHandleSignalMode(int signum) {
1925 HandleSignalMode result = GetHandleSignalModeImpl(signum);
1926 if (result == kHandleSignalYes && !common_flags()->allow_user_segv_handler)
1927 return kHandleSignalExclusive;
1928 return result;
1929}
1930
1931# if !SANITIZER_GO
1932void *internal_start_thread(void *(*func)(void *arg), void *arg) {
1933 if (&internal_pthread_create == 0)
1934 return nullptr;
1935 // Start the thread with signals blocked, otherwise it can steal user signals.
1936 ScopedBlockSignals block(nullptr);
1937 void *th;
1938 internal_pthread_create(&th, nullptr, func, arg);
1939 return th;
1940}
1941
1942void internal_join_thread(void *th) {
1943 if (&internal_pthread_join)
1944 internal_pthread_join(th, nullptr);
1945}
1946# else
1947void *internal_start_thread(void *(*func)(void *), void *arg) { return 0; }
1948
1949void internal_join_thread(void *th) {}
1950# endif
1951
1952# if SANITIZER_LINUX && defined(__aarch64__)
1953// Android headers in the older NDK releases miss this definition.
1954struct __sanitizer_esr_context {
1955 struct _aarch64_ctx head;
1956 uint64_t esr;
1957};
1958
1959static bool Aarch64GetESR(ucontext_t *ucontext, u64 *esr) {
1960 static const u32 kEsrMagic = 0x45535201;
1961 u8 *aux = reinterpret_cast<u8 *>(ucontext->uc_mcontext.__reserved);
1962 while (true) {
1963 _aarch64_ctx *ctx = (_aarch64_ctx *)aux;
1964 if (ctx->size == 0)
1965 break;
1966 if (ctx->magic == kEsrMagic) {
1967 *esr = ((__sanitizer_esr_context *)ctx)->esr;
1968 return true;
1969 }
1970 aux += ctx->size;
1971 }
1972 return false;
1973}
1974# elif SANITIZER_FREEBSD && defined(__aarch64__)
1975// FreeBSD doesn't provide ESR in the ucontext.
1976static bool Aarch64GetESR(ucontext_t *ucontext, u64 *esr) { return false; }
1977# endif
1978
1979using Context = ucontext_t;
1980
1981SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
1982 Context *ucontext = (Context *)context;
1983# if defined(__x86_64__) || defined(__i386__)
1984# if !SANITIZER_HAIKU
1985 static const uptr PF_WRITE = 1U << 1;
1986# endif
1987# if SANITIZER_FREEBSD
1988 uptr err = ucontext->uc_mcontext.mc_err;
1989# elif SANITIZER_NETBSD
1990 uptr err = ucontext->uc_mcontext.__gregs[_REG_ERR];
1991# elif SANITIZER_HAIKU
1992 uptr err = ucontext->uc_mcontext.r13;
1993# elif SANITIZER_SOLARIS && defined(__i386__)
1994 const int Err = 13;
1995 uptr err = ucontext->uc_mcontext.gregs[Err];
1996# else
1997 uptr err = ucontext->uc_mcontext.gregs[REG_ERR];
1998# endif // SANITIZER_FREEBSD
1999 return err & PF_WRITE ? Write : Read;
2000# elif defined(__mips__)
2001 uint32_t *exception_source;
2002 uint32_t faulty_instruction;
2003 uint32_t op_code;
2004
2005 exception_source = (uint32_t *)ucontext->uc_mcontext.pc;
2006 faulty_instruction = (uint32_t)(*exception_source);
2007
2008 op_code = (faulty_instruction >> 26) & 0x3f;
2009
2010 // FIXME: Add support for FPU, microMIPS, DSP, MSA memory instructions.
2011 switch (op_code) {
2012 case 0x28: // sb
2013 case 0x29: // sh
2014 case 0x2b: // sw
2015 case 0x3f: // sd
2016# if __mips_isa_rev < 6
2017 case 0x2c: // sdl
2018 case 0x2d: // sdr
2019 case 0x2a: // swl
2020 case 0x2e: // swr
2021# endif
2022 return SignalContext::Write;
2023
2024 case 0x20: // lb
2025 case 0x24: // lbu
2026 case 0x21: // lh
2027 case 0x25: // lhu
2028 case 0x23: // lw
2029 case 0x27: // lwu
2030 case 0x37: // ld
2031# if __mips_isa_rev < 6
2032 case 0x1a: // ldl
2033 case 0x1b: // ldr
2034 case 0x22: // lwl
2035 case 0x26: // lwr
2036# endif
2037 return SignalContext::Read;
2038# if __mips_isa_rev == 6
2039 case 0x3b: // pcrel
2040 op_code = (faulty_instruction >> 19) & 0x3;
2041 switch (op_code) {
2042 case 0x1: // lwpc
2043 case 0x2: // lwupc
2044 return SignalContext::Read;
2045 }
2046# endif
2047 }
2048 return SignalContext::Unknown;
2049# elif defined(__arm__)
2050 static const uptr FSR_WRITE = 1U << 11;
2051 uptr fsr = ucontext->uc_mcontext.error_code;
2052 return fsr & FSR_WRITE ? Write : Read;
2053# elif defined(__aarch64__)
2054 static const u64 ESR_ELx_WNR = 1U << 6;
2055 u64 esr;
2056 if (!Aarch64GetESR(ucontext, &esr))
2057 return Unknown;
2058 return esr & ESR_ELx_WNR ? Write : Read;
2059# elif defined(__loongarch__)
2060 // In the musl environment, the Linux kernel uapi sigcontext.h is not
2061 // included in signal.h. To avoid missing the SC_ADDRERR_{RD,WR} macros,
2062 // copy them here. The LoongArch Linux kernel uapi is already stable,
2063 // so there's no need to worry about the value changing.
2064# ifndef SC_ADDRERR_RD
2065 // Address error was due to memory load
2066# define SC_ADDRERR_RD (1 << 30)
2067# endif
2068# ifndef SC_ADDRERR_WR
2069 // Address error was due to memory store
2070# define SC_ADDRERR_WR (1 << 31)
2071# endif
2072 u32 flags = ucontext->uc_mcontext.__flags;
2073 if (flags & SC_ADDRERR_RD)
2074 return SignalContext::Read;
2075 if (flags & SC_ADDRERR_WR)
2076 return SignalContext::Write;
2077 return SignalContext::Unknown;
2078# elif defined(__sparc__)
2079 // Decode the instruction to determine the access type.
2080 // From OpenSolaris $SRC/uts/sun4/os/trap.c (get_accesstype).
2081# if SANITIZER_SOLARIS
2082 uptr pc = ucontext->uc_mcontext.gregs[REG_PC];
2083# else
2084 // Historical BSDism here.
2085 struct sigcontext *scontext = (struct sigcontext *)context;
2086# if defined(__arch64__)
2087 uptr pc = scontext->sigc_regs.tpc;
2088# else
2089 uptr pc = scontext->si_regs.pc;
2090# endif
2091# endif
2092 u32 instr = *(u32 *)pc;
2093 return (instr >> 21) & 1 ? Write : Read;
2094# elif defined(__riscv)
2095# if SANITIZER_FREEBSD
2096 unsigned long pc = ucontext->uc_mcontext.mc_gpregs.gp_sepc;
2097# else
2098 unsigned long pc = ucontext->uc_mcontext.__gregs[REG_PC];
2099# endif
2100 unsigned faulty_instruction = *(uint16_t *)pc;
2101
2102# if defined(__riscv_compressed)
2103 if ((faulty_instruction & 0x3) != 0x3) { // it's a compressed instruction
2104 // set op_bits to the instruction bits [1, 0, 15, 14, 13]
2105 unsigned op_bits =
2106 ((faulty_instruction & 0x3) << 3) | (faulty_instruction >> 13);
2107 unsigned rd = faulty_instruction & 0xF80; // bits 7-11, inclusive
2108 switch (op_bits) {
2109 case 0b10'010: // c.lwsp (rd != x0)
2110# if __riscv_xlen == 64
2111 case 0b10'011: // c.ldsp (rd != x0)
2112# endif
2113 return rd ? SignalContext::Read : SignalContext::Unknown;
2114 case 0b00'010: // c.lw
2115# if __riscv_flen >= 32 && __riscv_xlen == 32
2116 case 0b10'011: // c.flwsp
2117# endif
2118# if __riscv_flen >= 32 || __riscv_xlen == 64
2119 case 0b00'011: // c.flw / c.ld
2120# endif
2121# if __riscv_flen == 64
2122 case 0b00'001: // c.fld
2123 case 0b10'001: // c.fldsp
2124# endif
2125 return SignalContext::Read;
2126 case 0b00'110: // c.sw
2127 case 0b10'110: // c.swsp
2128# if __riscv_flen >= 32 || __riscv_xlen == 64
2129 case 0b00'111: // c.fsw / c.sd
2130 case 0b10'111: // c.fswsp / c.sdsp
2131# endif
2132# if __riscv_flen == 64
2133 case 0b00'101: // c.fsd
2134 case 0b10'101: // c.fsdsp
2135# endif
2136 return SignalContext::Write;
2137 default:
2138 return SignalContext::Unknown;
2139 }
2140 }
2141# endif
2142
2143 unsigned opcode = faulty_instruction & 0x7f; // lower 7 bits
2144 unsigned funct3 = (faulty_instruction >> 12) & 0x7; // bits 12-14, inclusive
2145 switch (opcode) {
2146 case 0b0000011: // loads
2147 switch (funct3) {
2148 case 0b000: // lb
2149 case 0b001: // lh
2150 case 0b010: // lw
2151# if __riscv_xlen == 64
2152 case 0b011: // ld
2153# endif
2154 case 0b100: // lbu
2155 case 0b101: // lhu
2156 return SignalContext::Read;
2157 default:
2158 return SignalContext::Unknown;
2159 }
2160 case 0b0100011: // stores
2161 switch (funct3) {
2162 case 0b000: // sb
2163 case 0b001: // sh
2164 case 0b010: // sw
2165# if __riscv_xlen == 64
2166 case 0b011: // sd
2167# endif
2168 return SignalContext::Write;
2169 default:
2170 return SignalContext::Unknown;
2171 }
2172# if __riscv_flen >= 32
2173 case 0b0000111: // floating-point loads
2174 switch (funct3) {
2175 case 0b010: // flw
2176# if __riscv_flen == 64
2177 case 0b011: // fld
2178# endif
2179 return SignalContext::Read;
2180 default:
2181 return SignalContext::Unknown;
2182 }
2183 case 0b0100111: // floating-point stores
2184 switch (funct3) {
2185 case 0b010: // fsw
2186# if __riscv_flen == 64
2187 case 0b011: // fsd
2188# endif
2189 return SignalContext::Write;
2190 default:
2191 return SignalContext::Unknown;
2192 }
2193# endif
2194 default:
2195 return SignalContext::Unknown;
2196 }
2197# else
2198 (void)ucontext;
2199 return Unknown; // FIXME: Implement.
2200# endif
2201}
2202
2203bool SignalContext::IsTrueFaultingAddress() const {
2204 auto si = static_cast<const siginfo_t *>(siginfo);
2205 // SIGSEGV signals without a true fault address have si_code set to 128.
2206 return si->si_signo == SIGSEGV && si->si_code != 128;
2207}
2208
2209UNUSED
2210static const char *RegNumToRegName(int reg) {
2211 switch (reg) {
2212# if SANITIZER_LINUX && SANITIZER_GLIBC || SANITIZER_NETBSD
2213# if defined(__x86_64__)
2214# if SANITIZER_NETBSD
2215# define REG_RAX _REG_RAX
2216# define REG_RBX _REG_RBX
2217# define REG_RCX _REG_RCX
2218# define REG_RDX _REG_RDX
2219# define REG_RDI _REG_RDI
2220# define REG_RSI _REG_RSI
2221# define REG_RBP _REG_RBP
2222# define REG_RSP _REG_RSP
2223# define REG_R8 _REG_R8
2224# define REG_R9 _REG_R9
2225# define REG_R10 _REG_R10
2226# define REG_R11 _REG_R11
2227# define REG_R12 _REG_R12
2228# define REG_R13 _REG_R13
2229# define REG_R14 _REG_R14
2230# define REG_R15 _REG_R15
2231# endif
2232 case REG_RAX:
2233 return "rax";
2234 case REG_RBX:
2235 return "rbx";
2236 case REG_RCX:
2237 return "rcx";
2238 case REG_RDX:
2239 return "rdx";
2240 case REG_RDI:
2241 return "rdi";
2242 case REG_RSI:
2243 return "rsi";
2244 case REG_RBP:
2245 return "rbp";
2246 case REG_RSP:
2247 return "rsp";
2248 case REG_R8:
2249 return "r8";
2250 case REG_R9:
2251 return "r9";
2252 case REG_R10:
2253 return "r10";
2254 case REG_R11:
2255 return "r11";
2256 case REG_R12:
2257 return "r12";
2258 case REG_R13:
2259 return "r13";
2260 case REG_R14:
2261 return "r14";
2262 case REG_R15:
2263 return "r15";
2264# elif defined(__i386__)
2265# if SANITIZER_NETBSD
2266# define REG_EAX _REG_EAX
2267# define REG_EBX _REG_EBX
2268# define REG_ECX _REG_ECX
2269# define REG_EDX _REG_EDX
2270# define REG_EDI _REG_EDI
2271# define REG_ESI _REG_ESI
2272# define REG_EBP _REG_EBP
2273# define REG_ESP _REG_ESP
2274# endif
2275 case REG_EAX:
2276 return "eax";
2277 case REG_EBX:
2278 return "ebx";
2279 case REG_ECX:
2280 return "ecx";
2281 case REG_EDX:
2282 return "edx";
2283 case REG_EDI:
2284 return "edi";
2285 case REG_ESI:
2286 return "esi";
2287 case REG_EBP:
2288 return "ebp";
2289 case REG_ESP:
2290 return "esp";
2291# elif defined(__arm__)
2292# ifdef MAKE_CASE
2293# undef MAKE_CASE
2294# endif
2295# define REG_STR(reg) #reg
2296# define MAKE_CASE(N) \
2297 case REG_R##N: \
2298 return REG_STR(r##N)
2299 MAKE_CASE(0);
2300 MAKE_CASE(1);
2301 MAKE_CASE(2);
2302 MAKE_CASE(3);
2303 MAKE_CASE(4);
2304 MAKE_CASE(5);
2305 MAKE_CASE(6);
2306 MAKE_CASE(7);
2307 MAKE_CASE(8);
2308 MAKE_CASE(9);
2309 MAKE_CASE(10);
2310 MAKE_CASE(11);
2311 MAKE_CASE(12);
2312 case REG_R13:
2313 return "sp";
2314 case REG_R14:
2315 return "lr";
2316 case REG_R15:
2317 return "pc";
2318# elif defined(__aarch64__)
2319# define REG_STR(reg) #reg
2320# define MAKE_CASE(N) \
2321 case N: \
2322 return REG_STR(x##N)
2323 MAKE_CASE(0);
2324 MAKE_CASE(1);
2325 MAKE_CASE(2);
2326 MAKE_CASE(3);
2327 MAKE_CASE(4);
2328 MAKE_CASE(5);
2329 MAKE_CASE(6);
2330 MAKE_CASE(7);
2331 MAKE_CASE(8);
2332 MAKE_CASE(9);
2333 MAKE_CASE(10);
2334 MAKE_CASE(11);
2335 MAKE_CASE(12);
2336 MAKE_CASE(13);
2337 MAKE_CASE(14);
2338 MAKE_CASE(15);
2339 MAKE_CASE(16);
2340 MAKE_CASE(17);
2341 MAKE_CASE(18);
2342 MAKE_CASE(19);
2343 MAKE_CASE(20);
2344 MAKE_CASE(21);
2345 MAKE_CASE(22);
2346 MAKE_CASE(23);
2347 MAKE_CASE(24);
2348 MAKE_CASE(25);
2349 MAKE_CASE(26);
2350 MAKE_CASE(27);
2351 MAKE_CASE(28);
2352 case 29:
2353 return "fp";
2354 case 30:
2355 return "lr";
2356 case 31:
2357 return "sp";
2358# endif
2359# endif // SANITIZER_LINUX && SANITIZER_GLIBC
2360 default:
2361 return NULL;
2362 }
2363 return NULL;
2364}
2365
2366# if ((SANITIZER_LINUX && SANITIZER_GLIBC) || SANITIZER_NETBSD) && \
2367 (defined(__arm__) || defined(__aarch64__))
2368static uptr GetArmRegister(ucontext_t *ctx, int RegNum) {
2369 switch (RegNum) {
2370# if defined(__arm__) && !SANITIZER_NETBSD
2371# ifdef MAKE_CASE
2372# undef MAKE_CASE
2373# endif
2374# define MAKE_CASE(N) \
2375 case REG_R##N: \
2376 return ctx->uc_mcontext.arm_r##N
2377 MAKE_CASE(0);
2378 MAKE_CASE(1);
2379 MAKE_CASE(2);
2380 MAKE_CASE(3);
2381 MAKE_CASE(4);
2382 MAKE_CASE(5);
2383 MAKE_CASE(6);
2384 MAKE_CASE(7);
2385 MAKE_CASE(8);
2386 MAKE_CASE(9);
2387 MAKE_CASE(10);
2388 case REG_R11:
2389 return ctx->uc_mcontext.arm_fp;
2390 case REG_R12:
2391 return ctx->uc_mcontext.arm_ip;
2392 case REG_R13:
2393 return ctx->uc_mcontext.arm_sp;
2394 case REG_R14:
2395 return ctx->uc_mcontext.arm_lr;
2396 case REG_R15:
2397 return ctx->uc_mcontext.arm_pc;
2398# elif defined(__aarch64__)
2399# if SANITIZER_LINUX
2400 case 0 ... 30:
2401 return ctx->uc_mcontext.regs[RegNum];
2402 case 31:
2403 return ctx->uc_mcontext.sp;
2404# elif SANITIZER_NETBSD
2405 case 0 ... 31:
2406 return ctx->uc_mcontext.__gregs[RegNum];
2407# endif
2408# endif
2409 default:
2410 return 0;
2411 }
2412 return 0;
2413}
2414# endif // SANITIZER_LINUX && SANITIZER_GLIBC && (defined(__arm__) ||
2415 // defined(__aarch64__))
2416
2417UNUSED
2418static void DumpSingleReg(ucontext_t *ctx, int RegNum) {
2419 const char *RegName = RegNumToRegName(RegNum);
2420# if SANITIZER_LINUX && SANITIZER_GLIBC || SANITIZER_NETBSD
2421# if defined(__x86_64__)
2422 Printf("%s%s = 0x%016llx ", internal_strlen(RegName) == 2 ? " " : "",
2423 RegName,
2424# if SANITIZER_LINUX
2425 ctx->uc_mcontext.gregs[RegNum]
2426# elif SANITIZER_NETBSD
2427 ctx->uc_mcontext.__gregs[RegNum]
2428# endif
2429 );
2430# elif defined(__i386__)
2431 Printf("%s = 0x%08x ", RegName,
2432# if SANITIZER_LINUX
2433 ctx->uc_mcontext.gregs[RegNum]
2434# elif SANITIZER_NETBSD
2435 ctx->uc_mcontext.__gregs[RegNum]
2436# endif
2437 );
2438# elif defined(__arm__)
2439 Printf("%s%s = 0x%08zx ", internal_strlen(RegName) == 2 ? " " : "", RegName,
2440 GetArmRegister(ctx, RegNum));
2441# elif defined(__aarch64__)
2442 Printf("%s%s = 0x%016zx ", internal_strlen(RegName) == 2 ? " " : "", RegName,
2443 GetArmRegister(ctx, RegNum));
2444# else
2445 (void)RegName;
2446# endif
2447# else
2448 (void)RegName;
2449# endif
2450}
2451
2452void SignalContext::DumpAllRegisters(void *context) {
2453 ucontext_t *ucontext = (ucontext_t *)context;
2454# if SANITIZER_LINUX && SANITIZER_GLIBC || SANITIZER_NETBSD
2455# if defined(__x86_64__)
2456 Report("Register values:\n");
2457 DumpSingleReg(ucontext, REG_RAX);
2458 DumpSingleReg(ucontext, REG_RBX);
2459 DumpSingleReg(ucontext, REG_RCX);
2460 DumpSingleReg(ucontext, REG_RDX);
2461 Printf("\n");
2462 DumpSingleReg(ucontext, REG_RDI);
2463 DumpSingleReg(ucontext, REG_RSI);
2464 DumpSingleReg(ucontext, REG_RBP);
2465 DumpSingleReg(ucontext, REG_RSP);
2466 Printf("\n");
2467 DumpSingleReg(ucontext, REG_R8);
2468 DumpSingleReg(ucontext, REG_R9);
2469 DumpSingleReg(ucontext, REG_R10);
2470 DumpSingleReg(ucontext, REG_R11);
2471 Printf("\n");
2472 DumpSingleReg(ucontext, REG_R12);
2473 DumpSingleReg(ucontext, REG_R13);
2474 DumpSingleReg(ucontext, REG_R14);
2475 DumpSingleReg(ucontext, REG_R15);
2476 Printf("\n");
2477# elif defined(__i386__)
2478 // Duplication of this report print is caused by partial support
2479 // of register values dumping. In case of unsupported yet architecture let's
2480 // avoid printing 'Register values:' without actual values in the following
2481 // output.
2482 Report("Register values:\n");
2483 DumpSingleReg(ucontext, REG_EAX);
2484 DumpSingleReg(ucontext, REG_EBX);
2485 DumpSingleReg(ucontext, REG_ECX);
2486 DumpSingleReg(ucontext, REG_EDX);
2487 Printf("\n");
2488 DumpSingleReg(ucontext, REG_EDI);
2489 DumpSingleReg(ucontext, REG_ESI);
2490 DumpSingleReg(ucontext, REG_EBP);
2491 DumpSingleReg(ucontext, REG_ESP);
2492 Printf("\n");
2493# elif defined(__arm__) && !SANITIZER_NETBSD
2494 Report("Register values:\n");
2495 DumpSingleReg(ucontext, REG_R0);
2496 DumpSingleReg(ucontext, REG_R1);
2497 DumpSingleReg(ucontext, REG_R2);
2498 DumpSingleReg(ucontext, REG_R3);
2499 Printf("\n");
2500 DumpSingleReg(ucontext, REG_R4);
2501 DumpSingleReg(ucontext, REG_R5);
2502 DumpSingleReg(ucontext, REG_R6);
2503 DumpSingleReg(ucontext, REG_R7);
2504 Printf("\n");
2505 DumpSingleReg(ucontext, REG_R8);
2506 DumpSingleReg(ucontext, REG_R9);
2507 DumpSingleReg(ucontext, REG_R10);
2508 DumpSingleReg(ucontext, REG_R11);
2509 Printf("\n");
2510 DumpSingleReg(ucontext, REG_R12);
2511 DumpSingleReg(ucontext, REG_R13);
2512 DumpSingleReg(ucontext, REG_R14);
2513 DumpSingleReg(ucontext, REG_R15);
2514 Printf("\n");
2515# elif defined(__aarch64__)
2516 Report("Register values:\n");
2517 for (int i = 0; i <= 31; ++i) {
2518 DumpSingleReg(ucontext, i);
2519 if (i % 4 == 3)
2520 Printf("\n");
2521 }
2522# else
2523 (void)ucontext;
2524# endif
2525# elif SANITIZER_FREEBSD
2526# if defined(__x86_64__)
2527 Report("Register values:\n");
2528 Printf("rax = 0x%016lx ", ucontext->uc_mcontext.mc_rax);
2529 Printf("rbx = 0x%016lx ", ucontext->uc_mcontext.mc_rbx);
2530 Printf("rcx = 0x%016lx ", ucontext->uc_mcontext.mc_rcx);
2531 Printf("rdx = 0x%016lx ", ucontext->uc_mcontext.mc_rdx);
2532 Printf("\n");
2533 Printf("rdi = 0x%016lx ", ucontext->uc_mcontext.mc_rdi);
2534 Printf("rsi = 0x%016lx ", ucontext->uc_mcontext.mc_rsi);
2535 Printf("rbp = 0x%016lx ", ucontext->uc_mcontext.mc_rbp);
2536 Printf("rsp = 0x%016lx ", ucontext->uc_mcontext.mc_rsp);
2537 Printf("\n");
2538 Printf(" r8 = 0x%016lx ", ucontext->uc_mcontext.mc_r8);
2539 Printf(" r9 = 0x%016lx ", ucontext->uc_mcontext.mc_r9);
2540 Printf("r10 = 0x%016lx ", ucontext->uc_mcontext.mc_r10);
2541 Printf("r11 = 0x%016lx ", ucontext->uc_mcontext.mc_r11);
2542 Printf("\n");
2543 Printf("r12 = 0x%016lx ", ucontext->uc_mcontext.mc_r12);
2544 Printf("r13 = 0x%016lx ", ucontext->uc_mcontext.mc_r13);
2545 Printf("r14 = 0x%016lx ", ucontext->uc_mcontext.mc_r14);
2546 Printf("r15 = 0x%016lx ", ucontext->uc_mcontext.mc_r15);
2547 Printf("\n");
2548# elif defined(__i386__)
2549 Report("Register values:\n");
2550 Printf("eax = 0x%08x ", ucontext->uc_mcontext.mc_eax);
2551 Printf("ebx = 0x%08x ", ucontext->uc_mcontext.mc_ebx);
2552 Printf("ecx = 0x%08x ", ucontext->uc_mcontext.mc_ecx);
2553 Printf("edx = 0x%08x ", ucontext->uc_mcontext.mc_edx);
2554 Printf("\n");
2555 Printf("edi = 0x%08x ", ucontext->uc_mcontext.mc_edi);
2556 Printf("esi = 0x%08x ", ucontext->uc_mcontext.mc_esi);
2557 Printf("ebp = 0x%08x ", ucontext->uc_mcontext.mc_ebp);
2558 Printf("esp = 0x%08x ", ucontext->uc_mcontext.mc_esp);
2559 Printf("\n");
2560# else
2561 (void)ucontext;
2562# endif
2563# else
2564 (void)ucontext;
2565# endif
2566 // FIXME: Implement this for other OSes and architectures.
2567}
2568
2569static void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
2570# if SANITIZER_NETBSD
2571 // This covers all NetBSD architectures
2572 ucontext_t *ucontext = (ucontext_t *)context;
2573 *pc = _UC_MACHINE_PC(ucontext);
2574 *bp = _UC_MACHINE_FP(ucontext);
2575 *sp = _UC_MACHINE_SP(ucontext);
2576# elif defined(__arm__)
2577 ucontext_t *ucontext = (ucontext_t *)context;
2578 *pc = ucontext->uc_mcontext.arm_pc;
2579 *bp = ucontext->uc_mcontext.arm_fp;
2580 *sp = ucontext->uc_mcontext.arm_sp;
2581# elif defined(__aarch64__)
2582# if SANITIZER_FREEBSD
2583 ucontext_t *ucontext = (ucontext_t *)context;
2584 *pc = ucontext->uc_mcontext.mc_gpregs.gp_elr;
2585 *bp = ucontext->uc_mcontext.mc_gpregs.gp_x[29];
2586 *sp = ucontext->uc_mcontext.mc_gpregs.gp_sp;
2587# else
2588 ucontext_t *ucontext = (ucontext_t *)context;
2589 *pc = ucontext->uc_mcontext.pc;
2590 *bp = ucontext->uc_mcontext.regs[29];
2591 *sp = ucontext->uc_mcontext.sp;
2592# endif
2593# elif defined(__hppa__)
2594 ucontext_t *ucontext = (ucontext_t *)context;
2595 *pc = ucontext->uc_mcontext.sc_iaoq[0];
2596 /* GCC uses %r3 whenever a frame pointer is needed. */
2597 *bp = ucontext->uc_mcontext.sc_gr[3];
2598 *sp = ucontext->uc_mcontext.sc_gr[30];
2599# elif defined(__x86_64__)
2600# if SANITIZER_FREEBSD
2601 ucontext_t *ucontext = (ucontext_t *)context;
2602 *pc = ucontext->uc_mcontext.mc_rip;
2603 *bp = ucontext->uc_mcontext.mc_rbp;
2604 *sp = ucontext->uc_mcontext.mc_rsp;
2605# elif SANITIZER_HAIKU
2606 ucontext_t *ucontext = (ucontext_t *)context;
2607 *pc = ucontext->uc_mcontext.rip;
2608 *bp = ucontext->uc_mcontext.rbp;
2609 *sp = ucontext->uc_mcontext.rsp;
2610# else
2611 ucontext_t *ucontext = (ucontext_t *)context;
2612 *pc = ucontext->uc_mcontext.gregs[REG_RIP];
2613 *bp = ucontext->uc_mcontext.gregs[REG_RBP];
2614 *sp = ucontext->uc_mcontext.gregs[REG_RSP];
2615# endif
2616# elif defined(__i386__)
2617# if SANITIZER_FREEBSD
2618 ucontext_t *ucontext = (ucontext_t *)context;
2619 *pc = ucontext->uc_mcontext.mc_eip;
2620 *bp = ucontext->uc_mcontext.mc_ebp;
2621 *sp = ucontext->uc_mcontext.mc_esp;
2622# else
2623 ucontext_t *ucontext = (ucontext_t *)context;
2624# if SANITIZER_SOLARIS
2625 /* Use the numeric values: the symbolic ones are undefined by llvm
2626 include/llvm/Support/Solaris.h. */
2627# ifndef REG_EIP
2628# define REG_EIP 14 // REG_PC
2629# endif
2630# ifndef REG_EBP
2631# define REG_EBP 6 // REG_FP
2632# endif
2633# ifndef REG_UESP
2634# define REG_UESP 17 // REG_SP
2635# endif
2636# endif
2637 *pc = ucontext->uc_mcontext.gregs[REG_EIP];
2638 *bp = ucontext->uc_mcontext.gregs[REG_EBP];
2639 *sp = ucontext->uc_mcontext.gregs[REG_UESP];
2640# endif
2641# elif defined(__powerpc__) || defined(__powerpc64__)
2642# if SANITIZER_FREEBSD
2643 ucontext_t *ucontext = (ucontext_t *)context;
2644 *pc = ucontext->uc_mcontext.mc_srr0;
2645 *sp = ucontext->uc_mcontext.mc_frame[1];
2646 *bp = ucontext->uc_mcontext.mc_frame[31];
2647# else
2648 ucontext_t *ucontext = (ucontext_t *)context;
2649 *pc = ucontext->uc_mcontext.regs->nip;
2650 *sp = ucontext->uc_mcontext.regs->gpr[PT_R1];
2651 // The powerpc{,64}-linux ABIs do not specify r31 as the frame
2652 // pointer, but GCC always uses r31 when we need a frame pointer.
2653 *bp = ucontext->uc_mcontext.regs->gpr[PT_R31];
2654# endif
2655# elif defined(__sparc__)
2656# if defined(__arch64__) || defined(__sparcv9)
2657# define STACK_BIAS 2047
2658# else
2659# define STACK_BIAS 0
2660# endif
2661# if SANITIZER_SOLARIS
2662 ucontext_t *ucontext = (ucontext_t *)context;
2663 *pc = ucontext->uc_mcontext.gregs[REG_PC];
2664 *sp = ucontext->uc_mcontext.gregs[REG_SP] + STACK_BIAS;
2665 // Avoid SEGV when dereferencing sp on stack overflow with non-faulting load.
2666 // This requires a SPARC V9 CPU. Cannot use #ASI_PNF here: only supported
2667 // since clang-19.
2668# if defined(__sparcv9)
2669 asm("ldxa [%[fp]] 0x82, %[bp]"
2670# else
2671 asm("lduwa [%[fp]] 0x82, %[bp]"
2672# endif
2673 : [bp] "=r"(*bp)
2674 : [fp] "r"(&((struct frame *)*sp)->fr_savfp));
2675 if (*bp)
2676 *bp += STACK_BIAS;
2677# else
2678 // Historical BSDism here.
2679 struct sigcontext *scontext = (struct sigcontext *)context;
2680# if defined(__arch64__)
2681 *pc = scontext->sigc_regs.tpc;
2682 *sp = scontext->sigc_regs.u_regs[14] + STACK_BIAS;
2683# else
2684 *pc = scontext->si_regs.pc;
2685 *sp = scontext->si_regs.u_regs[14];
2686# endif
2687 *bp = (uptr)((uhwptr *)*sp)[14] + STACK_BIAS;
2688# endif
2689# elif defined(__mips__)
2690 ucontext_t *ucontext = (ucontext_t *)context;
2691 *pc = ucontext->uc_mcontext.pc;
2692 *bp = ucontext->uc_mcontext.gregs[30];
2693 *sp = ucontext->uc_mcontext.gregs[29];
2694# elif defined(__s390__)
2695 ucontext_t *ucontext = (ucontext_t *)context;
2696# if defined(__s390x__)
2697 *pc = ucontext->uc_mcontext.psw.addr;
2698# else
2699 *pc = ucontext->uc_mcontext.psw.addr & 0x7fffffff;
2700# endif
2701 *bp = ucontext->uc_mcontext.gregs[11];
2702 *sp = ucontext->uc_mcontext.gregs[15];
2703# elif defined(__riscv)
2704 ucontext_t *ucontext = (ucontext_t *)context;
2705# if SANITIZER_FREEBSD
2706 *pc = ucontext->uc_mcontext.mc_gpregs.gp_sepc;
2707 *bp = ucontext->uc_mcontext.mc_gpregs.gp_s[0];
2708 *sp = ucontext->uc_mcontext.mc_gpregs.gp_sp;
2709# else
2710 *pc = ucontext->uc_mcontext.__gregs[REG_PC];
2711 *bp = ucontext->uc_mcontext.__gregs[REG_S0];
2712 *sp = ucontext->uc_mcontext.__gregs[REG_SP];
2713# endif
2714# elif defined(__hexagon__)
2715 ucontext_t *ucontext = (ucontext_t *)context;
2716 *pc = ucontext->uc_mcontext.pc;
2717 *bp = ucontext->uc_mcontext.r30;
2718 *sp = ucontext->uc_mcontext.r29;
2719# elif defined(__loongarch__)
2720 ucontext_t *ucontext = (ucontext_t *)context;
2721 *pc = ucontext->uc_mcontext.__pc;
2722 *bp = ucontext->uc_mcontext.__gregs[22];
2723 *sp = ucontext->uc_mcontext.__gregs[3];
2724# else
2725# error "Unsupported arch"
2726# endif
2727}
2728
2729void SignalContext::InitPcSpBp() { GetPcSpBp(context, &pc, &sp, &bp); }
2730
2731void InitializePlatformEarly() { InitTlsSize(); }
2732
2733void CheckASLR() {
2734# if SANITIZER_NETBSD
2735 int mib[3];
2736 int paxflags;
2737 uptr len = sizeof(paxflags);
2738
2739 mib[0] = CTL_PROC;
2740 mib[1] = internal_getpid();
2741 mib[2] = PROC_PID_PAXFLAGS;
2742
2743 if (UNLIKELY(internal_sysctl(mib, 3, &paxflags, &len, NULL, 0) == -1)) {
2744 Printf("sysctl failed\n");
2745 Die();
2746 }
2747
2748 if (UNLIKELY(paxflags & CTL_PROC_PAXFLAGS_ASLR)) {
2749 Printf(
2750 "This sanitizer is not compatible with enabled ASLR.\n"
2751 "To disable ASLR, please run \"paxctl +a %s\" and try again.\n",
2752 GetArgv()[0]);
2753 Die();
2754 }
2755# elif SANITIZER_FREEBSD
2756 int aslr_status;
2757 int r = internal_procctl(P_PID, 0, PROC_ASLR_STATUS, &aslr_status);
2758 if (UNLIKELY(r == -1)) {
2759 // We're making things less 'dramatic' here since
2760 // the cmd is not necessarily guaranteed to be here
2761 // just yet regarding FreeBSD release
2762 return;
2763 }
2764 if ((aslr_status & PROC_ASLR_ACTIVE) != 0) {
2765 VReport(1,
2766 "This sanitizer is not compatible with enabled ASLR "
2767 "and binaries compiled with PIE\n"
2768 "ASLR will be disabled and the program re-executed.\n");
2769 int aslr_ctl = PROC_ASLR_FORCE_DISABLE;
2770 CHECK_NE(internal_procctl(P_PID, 0, PROC_ASLR_CTL, &aslr_ctl), -1);
2771 ReExec();
2772 }
2773# elif SANITIZER_PPC64V2
2774 // Disable ASLR for Linux PPC64LE.
2775 int old_personality = personality(0xffffffff);
2776 if (old_personality != -1 && (old_personality & ADDR_NO_RANDOMIZE) == 0) {
2777 VReport(1,
2778 "WARNING: Program is being run with address space layout "
2779 "randomization (ASLR) enabled which prevents the thread and "
2780 "memory sanitizers from working on powerpc64le.\n"
2781 "ASLR will be disabled and the program re-executed.\n");
2782 CHECK_NE(personality(old_personality | ADDR_NO_RANDOMIZE), -1);
2783 ReExec();
2784 }
2785# else
2786 // Do nothing
2787# endif
2788}
2789
2790void CheckMPROTECT() {
2791# if SANITIZER_NETBSD
2792 int mib[3];
2793 int paxflags;
2794 uptr len = sizeof(paxflags);
2795
2796 mib[0] = CTL_PROC;
2797 mib[1] = internal_getpid();
2798 mib[2] = PROC_PID_PAXFLAGS;
2799
2800 if (UNLIKELY(internal_sysctl(mib, 3, &paxflags, &len, NULL, 0) == -1)) {
2801 Printf("sysctl failed\n");
2802 Die();
2803 }
2804
2805 if (UNLIKELY(paxflags & CTL_PROC_PAXFLAGS_MPROTECT)) {
2806 Printf("This sanitizer is not compatible with enabled MPROTECT\n");
2807 Die();
2808 }
2809# else
2810 // Do nothing
2811# endif
2812}
2813
2814void CheckNoDeepBind(const char *filename, int flag) {
2815# ifdef RTLD_DEEPBIND
2816 if (flag & RTLD_DEEPBIND) {
2817 Report(
2818 "You are trying to dlopen a %s shared library with RTLD_DEEPBIND flag"
2819 " which is incompatible with sanitizer runtime "
2820 "(see https://github.com/google/sanitizers/issues/611 for details"
2821 "). If you want to run %s library under sanitizers please remove "
2822 "RTLD_DEEPBIND from dlopen flags.\n",
2823 filename, filename);
2824 Die();
2825 }
2826# endif
2827}
2828
2829uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
2830 uptr *largest_gap_found,
2831 uptr *max_occupied_addr) {
2832 UNREACHABLE("FindAvailableMemoryRange is not available");
2833 return 0;
2834}
2835
2836bool GetRandom(void *buffer, uptr length, bool blocking) {
2837 if (!buffer || !length || length > 256)
2838 return false;
2839# if SANITIZER_USE_GETENTROPY
2840 uptr rnd = getentropy(buffer, length);
2841 int rverrno = 0;
2842 if (internal_iserror(rnd, &rverrno) && rverrno == EFAULT)
2843 return false;
2844 else if (rnd == 0)
2845 return true;
2846# endif // SANITIZER_USE_GETENTROPY
2847
2848# if SANITIZER_USE_GETRANDOM
2849 static atomic_uint8_t skip_getrandom_syscall;
2850 if (!atomic_load_relaxed(&skip_getrandom_syscall)) {
2851 // Up to 256 bytes, getrandom will not be interrupted.
2852 uptr res = internal_syscall(SYSCALL(getrandom), buffer, length,
2853 blocking ? 0 : GRND_NONBLOCK);
2854 int rverrno = 0;
2855 if (internal_iserror(res, &rverrno) && rverrno == ENOSYS)
2856 atomic_store_relaxed(&skip_getrandom_syscall, 1);
2857 else if (res == length)
2858 return true;
2859 }
2860# endif // SANITIZER_USE_GETRANDOM
2861 // Up to 256 bytes, a read off /dev/urandom will not be interrupted.
2862 // blocking is moot here, O_NONBLOCK has no effect when opening /dev/urandom.
2863 uptr fd = internal_open("/dev/urandom", O_RDONLY);
2864 if (internal_iserror(fd))
2865 return false;
2866 uptr res = internal_read(fd, buffer, length);
2867 if (internal_iserror(res))
2868 return false;
2869 internal_close(fd);
2870 return true;
2871}
2872
2873} // namespace __sanitizer
2874
2875#endif