Bug Summary

File:compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp
Warning:line 472, column 10
The left operand of '&' is a garbage value

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name sanitizer_linux.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D HAVE_RPC_XDR_H=1 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I projects/compiler-rt/lib/sanitizer_common -I /build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common -I include -I /build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/include -I /build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/.. -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O3 -Wno-unused-command-line-argument -Wno-unknown-warning-option -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-unused-parameter -Wno-variadic-macros -Wno-format -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/build-llvm -ferror-limit 19 -fvisibility hidden -fvisibility-inlines-hidden -fno-builtin -fno-rtti -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-11-10-160236-22541-1 -x c++ /build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp

/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp

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_FREEBSD0 || SANITIZER_LINUX1 || SANITIZER_NETBSD0 || \
17 SANITIZER_SOLARIS0
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_LINUX1 && !SANITIZER_GO0
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.
37#if defined(__mips64)
38#include <asm/unistd.h>
39#include <sys/types.h>
40#define stat kernel_stat
41#if SANITIZER_GO0
42#undef st_atimest_atim.tv_sec
43#undef st_mtimest_mtim.tv_sec
44#undef st_ctimest_ctim.tv_sec
45#define st_atimest_atim.tv_sec st_atim
46#define st_mtimest_mtim.tv_sec st_mtim
47#define st_ctimest_ctim.tv_sec st_ctim
48#endif
49#include <asm/stat.h>
50#undef stat
51#endif
52
53#include <dlfcn.h>
54#include <errno(*__errno_location ()).h>
55#include <fcntl.h>
56#include <link.h>
57#include <pthread.h>
58#include <sched.h>
59#include <signal.h>
60#include <sys/mman.h>
61#include <sys/param.h>
62#if !SANITIZER_SOLARIS0
63#include <sys/ptrace.h>
64#endif
65#include <sys/resource.h>
66#include <sys/stat.h>
67#include <sys/syscall.h>
68#include <sys/time.h>
69#include <sys/types.h>
70#include <ucontext.h>
71#include <unistd.h>
72
73#if SANITIZER_LINUX1
74#include <sys/utsname.h>
75#endif
76
77#if SANITIZER_LINUX1 && !SANITIZER_ANDROID0
78#include <sys/personality.h>
79#endif
80
81#if SANITIZER_FREEBSD0
82#include <sys/exec.h>
83#include <sys/sysctl.h>
84#include <machine/atomic.h>
85extern "C" {
86// <sys/umtx.h> must be included after <errno.h> and <sys/types.h> on
87// FreeBSD 9.2 and 10.0.
88#include <sys/umtx.h>
89}
90#include <sys/thr.h>
91#endif // SANITIZER_FREEBSD
92
93#if SANITIZER_NETBSD0
94#include <limits.h> // For NAME_MAX
95#include <sys/sysctl.h>
96#include <sys/exec.h>
97extern struct ps_strings *__ps_strings;
98#endif // SANITIZER_NETBSD
99
100#if SANITIZER_SOLARIS0
101#include <stdlib.h>
102#include <thread.h>
103#define environ _environ
104#endif
105
106extern char **environ;
107
108#if SANITIZER_LINUX1
109// <linux/time.h>
110struct kernel_timeval {
111 long tv_sec;
112 long tv_usec;
113};
114
115// <linux/futex.h> is broken on some linux distributions.
116const int FUTEX_WAIT = 0;
117const int FUTEX_WAKE = 1;
118const int FUTEX_PRIVATE_FLAG = 128;
119const int FUTEX_WAIT_PRIVATE = FUTEX_WAIT | FUTEX_PRIVATE_FLAG;
120const int FUTEX_WAKE_PRIVATE = FUTEX_WAKE | FUTEX_PRIVATE_FLAG;
121#endif // SANITIZER_LINUX
122
123// Are we using 32-bit or 64-bit Linux syscalls?
124// x32 (which defines __x86_64__) has SANITIZER_WORDSIZE == 32
125// but it still needs to use 64-bit syscalls.
126#if SANITIZER_LINUX1 && (defined(__x86_64__1) || defined(__powerpc64__) || \
127 SANITIZER_WORDSIZE64 == 64)
128# define SANITIZER_LINUX_USES_64BIT_SYSCALLS1 1
129#else
130# define SANITIZER_LINUX_USES_64BIT_SYSCALLS1 0
131#endif
132
133// Note : FreeBSD had implemented both
134// Linux apis, available from
135// future 12.x version most likely
136#if SANITIZER_LINUX1 && defined(__NR_getrandom318)
137# if !defined(GRND_NONBLOCK1)
138# define GRND_NONBLOCK1 1
139# endif
140# define SANITIZER_USE_GETRANDOM1 1
141#else
142# define SANITIZER_USE_GETRANDOM1 0
143#endif // SANITIZER_LINUX && defined(__NR_getrandom)
144
145#if SANITIZER_FREEBSD0 && __FreeBSD_version >= 1200000
146# define SANITIZER_USE_GETENTROPY0 1
147#else
148# define SANITIZER_USE_GETENTROPY0 0
149#endif
150
151namespace __sanitizer {
152
153#if SANITIZER_LINUX1 && defined(__x86_64__1)
154#include "sanitizer_syscall_linux_x86_64.inc"
155#elif SANITIZER_LINUX1 && SANITIZER_RISCV640
156#include "sanitizer_syscall_linux_riscv64.inc"
157#elif SANITIZER_LINUX1 && defined(__aarch64__)
158#include "sanitizer_syscall_linux_aarch64.inc"
159#elif SANITIZER_LINUX1 && defined(__arm__)
160#include "sanitizer_syscall_linux_arm.inc"
161# elif SANITIZER_LINUX1 && defined(__hexagon__)
162# include "sanitizer_syscall_linux_hexagon.inc"
163# else
164# include "sanitizer_syscall_generic.inc"
165# endif
166
167// --------------- sanitizer_libc.h
168#if !SANITIZER_SOLARIS0 && !SANITIZER_NETBSD0
169#if !SANITIZER_S3900
170uptr internal_mmap(void *addr, uptr length, int prot, int flags, int fd,
171 u64 offset) {
172#if SANITIZER_FREEBSD0 || SANITIZER_LINUX_USES_64BIT_SYSCALLS1
173 return internal_syscall(SYSCALL(mmap)9, (uptr)addr, length, prot, flags, fd,
174 offset);
175#else
176 // mmap2 specifies file offset in 4096-byte units.
177 CHECK(IsAligned(offset, 4096))do { __sanitizer::u64 v1 = (__sanitizer::u64)((IsAligned(offset
, 4096))); __sanitizer::u64 v2 = (__sanitizer::u64)(0); if (__builtin_expect
(!!(!(v1 != v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 177, "(" "(IsAligned(offset, 4096))" ") " "!=" " (" "0" ")"
, v1, v2); } while (false)
;
178 return internal_syscall(SYSCALL(mmap2)__NR_mmap2, addr, length, prot, flags, fd,
179 offset / 4096);
180#endif
181}
182#endif // !SANITIZER_S390
183
184uptr internal_munmap(void *addr, uptr length) {
185 return internal_syscall(SYSCALL(munmap)11, (uptr)addr, length);
186}
187
188#if SANITIZER_LINUX1
189uptr internal_mremap(void *old_address, uptr old_size, uptr new_size, int flags,
190 void *new_address) {
191 return internal_syscall(SYSCALL(mremap)25, (uptr)old_address, old_size,
192 new_size, flags, (uptr)new_address);
193}
194#endif
195
196int internal_mprotect(void *addr, uptr length, int prot) {
197 return internal_syscall(SYSCALL(mprotect)10, (uptr)addr, length, prot);
198}
199
200int internal_madvise(uptr addr, uptr length, int advice) {
201 return internal_syscall(SYSCALL(madvise)28, addr, length, advice);
202}
203
204uptr internal_close(fd_t fd) {
205 return internal_syscall(SYSCALL(close)3, fd);
206}
207
208uptr internal_open(const char *filename, int flags) {
209#if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS0
210 return internal_syscall(SYSCALL(openat)257, AT_FDCWD-100, (uptr)filename, flags);
211#else
212 return internal_syscall(SYSCALL(open)2, (uptr)filename, flags);
213#endif
214}
215
216uptr internal_open(const char *filename, int flags, u32 mode) {
217#if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS0
218 return internal_syscall(SYSCALL(openat)257, AT_FDCWD-100, (uptr)filename, flags,
219 mode);
220#else
221 return internal_syscall(SYSCALL(open)2, (uptr)filename, flags, mode);
222#endif
223}
224
225uptr internal_read(fd_t fd, void *buf, uptr count) {
226 sptr res;
227 HANDLE_EINTR(res,{ int rverrno; do { res = ((sptr)internal_syscall(0, fd, (uptr
)buf, count)); } while (internal_iserror(res, &rverrno) &&
rverrno == 4); }
228 (sptr)internal_syscall(SYSCALL(read), fd, (uptr)buf, count)){ int rverrno; do { res = ((sptr)internal_syscall(0, fd, (uptr
)buf, count)); } while (internal_iserror(res, &rverrno) &&
rverrno == 4); }
;
229 return res;
230}
231
232uptr internal_write(fd_t fd, const void *buf, uptr count) {
233 sptr res;
234 HANDLE_EINTR(res,{ int rverrno; do { res = ((sptr)internal_syscall(1, fd, (uptr
)buf, count)); } while (internal_iserror(res, &rverrno) &&
rverrno == 4); }
235 (sptr)internal_syscall(SYSCALL(write), fd, (uptr)buf, count)){ int rverrno; do { res = ((sptr)internal_syscall(1, fd, (uptr
)buf, count)); } while (internal_iserror(res, &rverrno) &&
rverrno == 4); }
;
236 return res;
237}
238
239uptr internal_ftruncate(fd_t fd, uptr size) {
240 sptr res;
241 HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(ftruncate), fd,{ int rverrno; do { res = ((sptr)internal_syscall(77, fd, (OFF_T
)size)); } while (internal_iserror(res, &rverrno) &&
rverrno == 4); }
242 (OFF_T)size)){ int rverrno; do { res = ((sptr)internal_syscall(77, fd, (OFF_T
)size)); } while (internal_iserror(res, &rverrno) &&
rverrno == 4); }
;
243 return res;
244}
245
246#if !SANITIZER_LINUX_USES_64BIT_SYSCALLS1 && SANITIZER_LINUX1
247static void stat64_to_stat(struct stat64 *in, struct stat *out) {
248 internal_memset(out, 0, sizeof(*out));
249 out->st_dev = in->st_dev;
250 out->st_ino = in->st_ino;
251 out->st_mode = in->st_mode;
252 out->st_nlink = in->st_nlink;
253 out->st_uid = in->st_uid;
254 out->st_gid = in->st_gid;
255 out->st_rdev = in->st_rdev;
256 out->st_size = in->st_size;
257 out->st_blksize = in->st_blksize;
258 out->st_blocks = in->st_blocks;
259 out->st_atimest_atim.tv_sec = in->st_atimest_atim.tv_sec;
260 out->st_mtimest_mtim.tv_sec = in->st_mtimest_mtim.tv_sec;
261 out->st_ctimest_ctim.tv_sec = in->st_ctimest_ctim.tv_sec;
262}
263#endif
264
265#if defined(__mips64)
266// Undefine compatibility macros from <sys/stat.h>
267// so that they would not clash with the kernel_stat
268// st_[a|m|c]time fields
269#if !SANITIZER_GO0
270#undef st_atimest_atim.tv_sec
271#undef st_mtimest_mtim.tv_sec
272#undef st_ctimest_ctim.tv_sec
273#endif
274#if defined(SANITIZER_ANDROID0)
275// Bionic sys/stat.h defines additional macros
276// for compatibility with the old NDKs and
277// they clash with the kernel_stat structure
278// st_[a|m|c]time_nsec fields.
279#undef st_atime_nsec
280#undef st_mtime_nsec
281#undef st_ctime_nsec
282#endif
283static void kernel_stat_to_stat(struct kernel_stat *in, struct stat *out) {
284 internal_memset(out, 0, sizeof(*out));
285 out->st_dev = in->st_dev;
286 out->st_ino = in->st_ino;
287 out->st_mode = in->st_mode;
288 out->st_nlink = in->st_nlink;
289 out->st_uid = in->st_uid;
290 out->st_gid = in->st_gid;
291 out->st_rdev = in->st_rdev;
292 out->st_size = in->st_size;
293 out->st_blksize = in->st_blksize;
294 out->st_blocks = in->st_blocks;
295#if defined(__USE_MISC1) || \
296 defined(__USE_XOPEN2K81) || \
297 defined(SANITIZER_ANDROID0)
298 out->st_atim.tv_sec = in->st_atimest_atim.tv_sec;
299 out->st_atim.tv_nsec = in->st_atime_nsec;
300 out->st_mtim.tv_sec = in->st_mtimest_mtim.tv_sec;
301 out->st_mtim.tv_nsec = in->st_mtime_nsec;
302 out->st_ctim.tv_sec = in->st_ctimest_ctim.tv_sec;
303 out->st_ctim.tv_nsec = in->st_ctime_nsec;
304#else
305 out->st_atimest_atim.tv_sec = in->st_atimest_atim.tv_sec;
306 out->st_atimensec = in->st_atime_nsec;
307 out->st_mtimest_mtim.tv_sec = in->st_mtimest_mtim.tv_sec;
308 out->st_mtimensec = in->st_mtime_nsec;
309 out->st_ctimest_ctim.tv_sec = in->st_ctimest_ctim.tv_sec;
310 out->st_atimensec = in->st_ctime_nsec;
311#endif
312}
313#endif
314
315uptr internal_stat(const char *path, void *buf) {
316#if SANITIZER_FREEBSD0
317 return internal_syscall(SYSCALL(fstatat)__NR_fstatat, AT_FDCWD-100, (uptr)path, (uptr)buf, 0);
318#elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS0
319 return internal_syscall(SYSCALL(newfstatat)262, AT_FDCWD-100, (uptr)path, (uptr)buf,
320 0);
321#elif SANITIZER_LINUX_USES_64BIT_SYSCALLS1
322# if defined(__mips64)
323 // For mips64, stat syscall fills buffer in the format of kernel_stat
324 struct kernel_stat kbuf;
325 int res = internal_syscall(SYSCALL(stat)4, path, &kbuf);
326 kernel_stat_to_stat(&kbuf, (struct stat *)buf);
327 return res;
328# else
329 return internal_syscall(SYSCALL(stat)4, (uptr)path, (uptr)buf);
4
Calling 'internal_syscall<unsigned long, unsigned long>'
6
Returning from 'internal_syscall<unsigned long, unsigned long>'
7
Returning without writing to 'buf->st_mode'
330# endif
331#else
332 struct stat64 buf64;
333 int res = internal_syscall(SYSCALL(stat64)__NR_stat64, path, &buf64);
334 stat64_to_stat(&buf64, (struct stat *)buf);
335 return res;
336#endif
337}
338
339uptr internal_lstat(const char *path, void *buf) {
340#if SANITIZER_FREEBSD0
341 return internal_syscall(SYSCALL(fstatat)__NR_fstatat, AT_FDCWD-100, (uptr)path, (uptr)buf,
342 AT_SYMLINK_NOFOLLOW0x100);
343#elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS0
344 return internal_syscall(SYSCALL(newfstatat)262, AT_FDCWD-100, (uptr)path, (uptr)buf,
345 AT_SYMLINK_NOFOLLOW0x100);
346#elif SANITIZER_LINUX_USES_64BIT_SYSCALLS1
347# if SANITIZER_MIPS640
348 // For mips64, lstat syscall fills buffer in the format of kernel_stat
349 struct kernel_stat kbuf;
350 int res = internal_syscall(SYSCALL(lstat)6, path, &kbuf);
351 kernel_stat_to_stat(&kbuf, (struct stat *)buf);
352 return res;
353# else
354 return internal_syscall(SYSCALL(lstat)6, (uptr)path, (uptr)buf);
355# endif
356#else
357 struct stat64 buf64;
358 int res = internal_syscall(SYSCALL(lstat64)__NR_lstat64, path, &buf64);
359 stat64_to_stat(&buf64, (struct stat *)buf);
360 return res;
361#endif
362}
363
364uptr internal_fstat(fd_t fd, void *buf) {
365#if SANITIZER_FREEBSD0 || SANITIZER_LINUX_USES_64BIT_SYSCALLS1
366#if SANITIZER_MIPS640
367 // For mips64, fstat syscall fills buffer in the format of kernel_stat
368 struct kernel_stat kbuf;
369 int res = internal_syscall(SYSCALL(fstat)5, fd, &kbuf);
370 kernel_stat_to_stat(&kbuf, (struct stat *)buf);
371 return res;
372# else
373 return internal_syscall(SYSCALL(fstat)5, fd, (uptr)buf);
374# endif
375#else
376 struct stat64 buf64;
377 int res = internal_syscall(SYSCALL(fstat64)__NR_fstat64, fd, &buf64);
378 stat64_to_stat(&buf64, (struct stat *)buf);
379 return res;
380#endif
381}
382
383uptr internal_filesize(fd_t fd) {
384 struct stat st;
385 if (internal_fstat(fd, &st))
386 return -1;
387 return (uptr)st.st_size;
388}
389
390uptr internal_dup(int oldfd) {
391 return internal_syscall(SYSCALL(dup)32, oldfd);
392}
393
394uptr internal_dup2(int oldfd, int newfd) {
395#if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS0
396 return internal_syscall(SYSCALL(dup3)292, oldfd, newfd, 0);
397#else
398 return internal_syscall(SYSCALL(dup2)33, oldfd, newfd);
399#endif
400}
401
402uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
403#if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS0
404 return internal_syscall(SYSCALL(readlinkat)267, AT_FDCWD-100, (uptr)path, (uptr)buf,
405 bufsize);
406#else
407 return internal_syscall(SYSCALL(readlink)89, (uptr)path, (uptr)buf, bufsize);
408#endif
409}
410
411uptr internal_unlink(const char *path) {
412#if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS0
413 return internal_syscall(SYSCALL(unlinkat)263, AT_FDCWD-100, (uptr)path, 0);
414#else
415 return internal_syscall(SYSCALL(unlink)87, (uptr)path);
416#endif
417}
418
419uptr internal_rename(const char *oldpath, const char *newpath) {
420#if defined(__riscv) && defined(__linux__1)
421 return internal_syscall(SYSCALL(renameat2)316, AT_FDCWD-100, (uptr)oldpath, AT_FDCWD-100,
422 (uptr)newpath, 0);
423#elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS0
424 return internal_syscall(SYSCALL(renameat)264, AT_FDCWD-100, (uptr)oldpath, AT_FDCWD-100,
425 (uptr)newpath);
426#else
427 return internal_syscall(SYSCALL(rename)82, (uptr)oldpath, (uptr)newpath);
428#endif
429}
430
431uptr internal_sched_yield() {
432 return internal_syscall(SYSCALL(sched_yield)24);
433}
434
435void internal_usleep(u64 useconds) {
436 struct timespec ts;
437 ts.tv_sec = useconds / 1000000;
438 ts.tv_nsec = (useconds % 1000000) * 1000;
439 internal_syscall(SYSCALL(nanosleep)35, &ts, &ts);
440}
441
442uptr internal_execve(const char *filename, char *const argv[],
443 char *const envp[]) {
444 return internal_syscall(SYSCALL(execve)59, (uptr)filename, (uptr)argv,
445 (uptr)envp);
446}
447#endif // !SANITIZER_SOLARIS && !SANITIZER_NETBSD
448
449#if !SANITIZER_NETBSD0
450void internal__exit(int exitcode) {
451#if SANITIZER_FREEBSD0 || SANITIZER_SOLARIS0
452 internal_syscall(SYSCALL(exit)60, exitcode);
453#else
454 internal_syscall(SYSCALL(exit_group)231, exitcode);
455#endif
456 Die(); // Unreachable.
457}
458#endif // !SANITIZER_NETBSD
459
460// ----------------- sanitizer_common.h
461bool FileExists(const char *filename) {
462 if (ShouldMockFailureToOpen(filename))
1
Assuming the condition is false
2
Taking false branch
463 return false;
464 struct stat st;
465#if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS0
466 if (internal_syscall(SYSCALL(newfstatat)262, AT_FDCWD-100, filename, &st, 0))
467#else
468 if (internal_stat(filename, &st))
3
Calling 'internal_stat'
8
Returning from 'internal_stat'
9
Assuming the condition is false
10
Taking false branch
469#endif
470 return false;
471 // Sanity check: filename is a regular file.
472 return S_ISREG(st.st_mode)((((st.st_mode)) & 0170000) == (0100000));
11
The left operand of '&' is a garbage value
473}
474
475#if !SANITIZER_NETBSD0
476tid_t GetTid() {
477#if SANITIZER_FREEBSD0
478 long Tid;
479 thr_self(&Tid);
480 return Tid;
481#elif SANITIZER_SOLARIS0
482 return thr_self();
483#else
484 return internal_syscall(SYSCALL(gettid)186);
485#endif
486}
487
488int TgKill(pid_t pid, tid_t tid, int sig) {
489#if SANITIZER_LINUX1
490 return internal_syscall(SYSCALL(tgkill)234, pid, tid, sig);
491#elif SANITIZER_FREEBSD0
492 return internal_syscall(SYSCALL(thr_kill2)__NR_thr_kill2, pid, tid, sig);
493#elif SANITIZER_SOLARIS0
494 (void)pid;
495 return thr_kill(tid, sig);
496#endif
497}
498#endif
499
500#if SANITIZER_GLIBC1
501u64 NanoTime() {
502 kernel_timeval tv;
503 internal_memset(&tv, 0, sizeof(tv));
504 internal_syscall(SYSCALL(gettimeofday)96, &tv, 0);
505 return (u64)tv.tv_sec * 1000 * 1000 * 1000 + tv.tv_usec * 1000;
506}
507// Used by real_clock_gettime.
508uptr internal_clock_gettime(__sanitizer_clockid_t clk_id, void *tp) {
509 return internal_syscall(SYSCALL(clock_gettime)228, clk_id, tp);
510}
511#elif !SANITIZER_SOLARIS0 && !SANITIZER_NETBSD0
512u64 NanoTime() {
513 struct timespec ts;
514 clock_gettime(CLOCK_REALTIME0, &ts);
515 return (u64)ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec;
516}
517#endif
518
519// Like getenv, but reads env directly from /proc (on Linux) or parses the
520// 'environ' array (on some others) and does not use libc. This function
521// should be called first inside __asan_init.
522const char *GetEnv(const char *name) {
523#if SANITIZER_FREEBSD0 || SANITIZER_NETBSD0 || SANITIZER_SOLARIS0
524 if (::environ != 0) {
525 uptr NameLen = internal_strlen(name);
526 for (char **Env = ::environ; *Env != 0; Env++) {
527 if (internal_strncmp(*Env, name, NameLen) == 0 && (*Env)[NameLen] == '=')
528 return (*Env) + NameLen + 1;
529 }
530 }
531 return 0; // Not found.
532#elif SANITIZER_LINUX1
533 static char *environ;
534 static uptr len;
535 static bool inited;
536 if (!inited) {
537 inited = true;
538 uptr environ_size;
539 if (!ReadFileToBuffer("/proc/self/environ", &environ, &environ_size, &len))
540 environ = nullptr;
541 }
542 if (!environ || len == 0) return nullptr;
543 uptr namelen = internal_strlen(name);
544 const char *p = environ;
545 while (*p != '\0') { // will happen at the \0\0 that terminates the buffer
546 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
547 const char* endp =
548 (char*)internal_memchr(p, '\0', len - (p - environ));
549 if (!endp) // this entry isn't NUL terminated
550 return nullptr;
551 else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') // Match.
552 return p + namelen + 1; // point after =
553 p = endp + 1;
554 }
555 return nullptr; // Not found.
556#else
557#error "Unsupported platform"
558#endif
559}
560
561#if !SANITIZER_FREEBSD0 && !SANITIZER_NETBSD0 && !SANITIZER_GO0
562extern "C" {
563SANITIZER_WEAK_ATTRIBUTE__attribute__((weak)) extern void *__libc_stack_end;
564}
565#endif
566
567#if !SANITIZER_FREEBSD0 && !SANITIZER_NETBSD0
568static void ReadNullSepFileToArray(const char *path, char ***arr,
569 int arr_size) {
570 char *buff;
571 uptr buff_size;
572 uptr buff_len;
573 *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
574 if (!ReadFileToBuffer(path, &buff, &buff_size, &buff_len, 1024 * 1024)) {
575 (*arr)[0] = nullptr;
576 return;
577 }
578 (*arr)[0] = buff;
579 int count, i;
580 for (count = 1, i = 1; ; i++) {
581 if (buff[i] == 0) {
582 if (buff[i+1] == 0) break;
583 (*arr)[count] = &buff[i+1];
584 CHECK_LE(count, arr_size - 1)do { __sanitizer::u64 v1 = (__sanitizer::u64)((count)); __sanitizer
::u64 v2 = (__sanitizer::u64)((arr_size - 1)); if (__builtin_expect
(!!(!(v1 <= v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 584, "(" "(count)" ") " "<=" " (" "(arr_size - 1)" ")", v1
, v2); } while (false)
; // FIXME: make this more flexible.
585 count++;
586 }
587 }
588 (*arr)[count] = nullptr;
589}
590#endif
591
592static void GetArgsAndEnv(char ***argv, char ***envp) {
593#if SANITIZER_FREEBSD0
594 // On FreeBSD, retrieving the argument and environment arrays is done via the
595 // kern.ps_strings sysctl, which returns a pointer to a structure containing
596 // this information. See also <sys/exec.h>.
597 ps_strings *pss;
598 uptr sz = sizeof(pss);
599 if (internal_sysctlbyname("kern.ps_strings", &pss, &sz, NULL__null, 0) == -1) {
600 Printf("sysctl kern.ps_strings failed\n");
601 Die();
602 }
603 *argv = pss->ps_argvstr;
604 *envp = pss->ps_envstr;
605#elif SANITIZER_NETBSD0
606 *argv = __ps_strings->ps_argvstr;
607 *envp = __ps_strings->ps_envstr;
608#else // SANITIZER_FREEBSD
609#if !SANITIZER_GO0
610 if (&__libc_stack_end) {
611 uptr* stack_end = (uptr*)__libc_stack_end;
612 // Normally argc can be obtained from *stack_end, however, on ARM glibc's
613 // _start clobbers it:
614 // https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/arm/start.S;hb=refs/heads/release/2.31/master#l75
615 // Do not special-case ARM and infer argc from argv everywhere.
616 int argc = 0;
617 while (stack_end[argc + 1]) argc++;
618 *argv = (char**)(stack_end + 1);
619 *envp = (char**)(stack_end + argc + 2);
620 } else {
621#endif // !SANITIZER_GO
622 static const int kMaxArgv = 2000, kMaxEnvp = 2000;
623 ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
624 ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
625#if !SANITIZER_GO0
626 }
627#endif // !SANITIZER_GO
628#endif // SANITIZER_FREEBSD
629}
630
631char **GetArgv() {
632 char **argv, **envp;
633 GetArgsAndEnv(&argv, &envp);
634 return argv;
635}
636
637char **GetEnviron() {
638 char **argv, **envp;
639 GetArgsAndEnv(&argv, &envp);
640 return envp;
641}
642
643#if !SANITIZER_SOLARIS0
644void FutexWait(atomic_uint32_t *p, u32 cmp) {
645# if SANITIZER_FREEBSD0
646 _umtx_op(p, UMTX_OP_WAIT_UINT, cmp, 0, 0);
647# elif SANITIZER_NETBSD0
648 sched_yield(); /* No userspace futex-like synchronization */
649# else
650 internal_syscall(SYSCALL(futex)202, (uptr)p, FUTEX_WAIT_PRIVATE, cmp, 0, 0, 0);
651# endif
652}
653
654void FutexWake(atomic_uint32_t *p, u32 count) {
655# if SANITIZER_FREEBSD0
656 _umtx_op(p, UMTX_OP_WAKE, count, 0, 0);
657# elif SANITIZER_NETBSD0
658 /* No userspace futex-like synchronization */
659# else
660 internal_syscall(SYSCALL(futex)202, (uptr)p, FUTEX_WAKE_PRIVATE, count, 0, 0, 0);
661# endif
662}
663
664# endif // !SANITIZER_SOLARIS
665
666// ----------------- sanitizer_linux.h
667// The actual size of this structure is specified by d_reclen.
668// Note that getdents64 uses a different structure format. We only provide the
669// 32-bit syscall here.
670#if SANITIZER_NETBSD0
671// Not used
672#else
673struct linux_dirent {
674#if SANITIZER_X320 || defined(__aarch64__) || SANITIZER_RISCV640
675 u64 d_ino;
676 u64 d_off;
677#else
678 unsigned long d_ino;
679 unsigned long d_off;
680#endif
681 unsigned short d_reclen;
682#if defined(__aarch64__) || SANITIZER_RISCV640
683 unsigned char d_type;
684#endif
685 char d_name[256];
686};
687#endif
688
689#if !SANITIZER_SOLARIS0 && !SANITIZER_NETBSD0
690// Syscall wrappers.
691uptr internal_ptrace(int request, int pid, void *addr, void *data) {
692 return internal_syscall(SYSCALL(ptrace)101, request, pid, (uptr)addr,
693 (uptr)data);
694}
695
696uptr internal_waitpid(int pid, int *status, int options) {
697 return internal_syscall(SYSCALL(wait4)61, pid, (uptr)status, options,
698 0 /* rusage */);
699}
700
701uptr internal_getpid() {
702 return internal_syscall(SYSCALL(getpid)39);
703}
704
705uptr internal_getppid() {
706 return internal_syscall(SYSCALL(getppid)110);
707}
708
709int internal_dlinfo(void *handle, int request, void *p) {
710#if SANITIZER_FREEBSD0
711 return dlinfo(handle, request, p);
712#else
713 UNIMPLEMENTED()do { do { __sanitizer::u64 v1 = (__sanitizer::u64)((0 &&
"unimplemented")); __sanitizer::u64 v2 = (__sanitizer::u64)(
0); if (__builtin_expect(!!(!(v1 != v2)), 0)) __sanitizer::CheckFailed
("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 713, "(" "(0 && \"unimplemented\")" ") " "!=" " (" "0"
")", v1, v2); } while (false); Die(); } while (0)
;
714#endif
715}
716
717uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) {
718#if SANITIZER_FREEBSD0
719 return internal_syscall(SYSCALL(getdirentries)__NR_getdirentries, fd, (uptr)dirp, count, NULL__null);
720#elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS0
721 return internal_syscall(SYSCALL(getdents64)217, fd, (uptr)dirp, count);
722#else
723 return internal_syscall(SYSCALL(getdents)78, fd, (uptr)dirp, count);
724#endif
725}
726
727uptr internal_lseek(fd_t fd, OFF_T offset, int whence) {
728 return internal_syscall(SYSCALL(lseek)8, fd, offset, whence);
729}
730
731#if SANITIZER_LINUX1
732uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
733 return internal_syscall(SYSCALL(prctl)157, option, arg2, arg3, arg4, arg5);
734}
735#endif
736
737uptr internal_sigaltstack(const void *ss, void *oss) {
738 return internal_syscall(SYSCALL(sigaltstack)131, (uptr)ss, (uptr)oss);
739}
740
741int internal_fork() {
742#if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS0
743 return internal_syscall(SYSCALL(clone)56, SIGCHLD17, 0);
744#else
745 return internal_syscall(SYSCALL(fork)57);
746#endif
747}
748
749#if SANITIZER_FREEBSD0
750int internal_sysctl(const int *name, unsigned int namelen, void *oldp,
751 uptr *oldlenp, const void *newp, uptr newlen) {
752 return internal_syscall(SYSCALL(__sysctl)__NR___sysctl, name, namelen, oldp,
753 (size_t *)oldlenp, newp, (size_t)newlen);
754}
755
756int internal_sysctlbyname(const char *sname, void *oldp, uptr *oldlenp,
757 const void *newp, uptr newlen) {
758 // Note: this function can be called during startup, so we need to avoid
759 // calling any interceptable functions. On FreeBSD >= 1300045 sysctlbyname()
760 // is a real syscall, but for older versions it calls sysctlnametomib()
761 // followed by sysctl(). To avoid calling the intercepted version and
762 // asserting if this happens during startup, call the real sysctlnametomib()
763 // followed by internal_sysctl() if the syscall is not available.
764#ifdef SYS___sysctlbyname
765 return internal_syscall(SYSCALL(__sysctlbyname)__NR___sysctlbyname, sname,
766 internal_strlen(sname), oldp, (size_t *)oldlenp, newp,
767 (size_t)newlen);
768#else
769 static decltype(sysctlnametomib) *real_sysctlnametomib = nullptr;
770 if (!real_sysctlnametomib)
771 real_sysctlnametomib =
772 (decltype(sysctlnametomib) *)dlsym(RTLD_NEXT((void *) -1l), "sysctlnametomib");
773 CHECK(real_sysctlnametomib)do { __sanitizer::u64 v1 = (__sanitizer::u64)((real_sysctlnametomib
)); __sanitizer::u64 v2 = (__sanitizer::u64)(0); if (__builtin_expect
(!!(!(v1 != v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 773, "(" "(real_sysctlnametomib)" ") " "!=" " (" "0" ")", v1
, v2); } while (false)
;
774
775 int oid[CTL_MAXNAME];
776 size_t len = CTL_MAXNAME;
777 if (real_sysctlnametomib(sname, oid, &len) == -1)
778 return (-1);
779 return internal_sysctl(oid, len, oldp, oldlenp, newp, newlen);
780#endif
781}
782#endif
783
784#if SANITIZER_LINUX1
785#define SA_RESTORER0x04000000 0x04000000
786// Doesn't set sa_restorer if the caller did not set it, so use with caution
787//(see below).
788int internal_sigaction_norestorer(int signum, const void *act, void *oldact) {
789 __sanitizer_kernel_sigaction_t k_act, k_oldact;
790 internal_memset(&k_act, 0, sizeof(__sanitizer_kernel_sigaction_t));
791 internal_memset(&k_oldact, 0, sizeof(__sanitizer_kernel_sigaction_t));
792 const __sanitizer_sigaction *u_act = (const __sanitizer_sigaction *)act;
793 __sanitizer_sigaction *u_oldact = (__sanitizer_sigaction *)oldact;
794 if (u_act) {
795 k_act.handler = u_act->handler;
796 k_act.sigaction = u_act->sigaction;
797 internal_memcpy(&k_act.sa_mask, &u_act->sa_mask,
798 sizeof(__sanitizer_kernel_sigset_t));
799 // Without SA_RESTORER kernel ignores the calls (probably returns EINVAL).
800 k_act.sa_flags = u_act->sa_flags | SA_RESTORER0x04000000;
801 // FIXME: most often sa_restorer is unset, however the kernel requires it
802 // to point to a valid signal restorer that calls the rt_sigreturn syscall.
803 // If sa_restorer passed to the kernel is NULL, the program may crash upon
804 // signal delivery or fail to unwind the stack in the signal handler.
805 // libc implementation of sigaction() passes its own restorer to
806 // rt_sigaction, so we need to do the same (we'll need to reimplement the
807 // restorers; for x86_64 the restorer address can be obtained from
808 // oldact->sa_restorer upon a call to sigaction(xxx, NULL, oldact).
809#if !SANITIZER_ANDROID0 || !SANITIZER_MIPS320
810 k_act.sa_restorer = u_act->sa_restorer;
811#endif
812 }
813
814 uptr result = internal_syscall(SYSCALL(rt_sigaction)13, (uptr)signum,
815 (uptr)(u_act ? &k_act : nullptr),
816 (uptr)(u_oldact ? &k_oldact : nullptr),
817 (uptr)sizeof(__sanitizer_kernel_sigset_t));
818
819 if ((result == 0) && u_oldact) {
820 u_oldact->handler = k_oldact.handler;
821 u_oldact->sigaction = k_oldact.sigaction;
822 internal_memcpy(&u_oldact->sa_mask, &k_oldact.sa_mask,
823 sizeof(__sanitizer_kernel_sigset_t));
824 u_oldact->sa_flags = k_oldact.sa_flags;
825#if !SANITIZER_ANDROID0 || !SANITIZER_MIPS320
826 u_oldact->sa_restorer = k_oldact.sa_restorer;
827#endif
828 }
829 return result;
830}
831#endif // SANITIZER_LINUX
832
833uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
834 __sanitizer_sigset_t *oldset) {
835#if SANITIZER_FREEBSD0
836 return internal_syscall(SYSCALL(sigprocmask)__NR_sigprocmask, how, set, oldset);
837#else
838 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
839 __sanitizer_kernel_sigset_t *k_oldset = (__sanitizer_kernel_sigset_t *)oldset;
840 return internal_syscall(SYSCALL(rt_sigprocmask)14, (uptr)how, (uptr)k_set,
841 (uptr)k_oldset, sizeof(__sanitizer_kernel_sigset_t));
842#endif
843}
844
845void SetSigProcMask(__sanitizer_sigset_t *set, __sanitizer_sigset_t *old) {
846 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, set, old))do { __sanitizer::u64 v1 = (__sanitizer::u64)((0)); __sanitizer
::u64 v2 = (__sanitizer::u64)((internal_sigprocmask(2, set, old
))); if (__builtin_expect(!!(!(v1 == v2)), 0)) __sanitizer::CheckFailed
("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 846, "(" "(0)" ") " "==" " (" "(internal_sigprocmask(2, set, old))"
")", v1, v2); } while (false)
;
847}
848
849ScopedBlockSignals::ScopedBlockSignals(__sanitizer_sigset_t *copy) {
850 __sanitizer_sigset_t set;
851 internal_sigfillset(&set);
852# if SANITIZER_LINUX1 && !SANITIZER_ANDROID0
853 // Glibc uses SIGSETXID signal during setuid call. If this signal is blocked
854 // on any thread, setuid call hangs.
855 // See test/sanitizer_common/TestCases/Linux/setuid.c.
856 internal_sigdelset(&set, 33);
857# endif
858 SetSigProcMask(&set, &saved_);
859 if (copy)
860 internal_memcpy(copy, &saved_, sizeof(saved_));
861}
862
863ScopedBlockSignals::~ScopedBlockSignals() { SetSigProcMask(&saved_, nullptr); }
864
865void internal_sigfillset(__sanitizer_sigset_t *set) {
866 internal_memset(set, 0xff, sizeof(*set));
867}
868
869void internal_sigemptyset(__sanitizer_sigset_t *set) {
870 internal_memset(set, 0, sizeof(*set));
871}
872
873#if SANITIZER_LINUX1
874void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
875 signum -= 1;
876 CHECK_GE(signum, 0)do { __sanitizer::u64 v1 = (__sanitizer::u64)((signum)); __sanitizer
::u64 v2 = (__sanitizer::u64)((0)); if (__builtin_expect(!!(!
(v1 >= v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 876, "(" "(signum)" ") " ">=" " (" "(0)" ")", v1, v2); }
while (false)
;
877 CHECK_LT(signum, sizeof(*set) * 8)do { __sanitizer::u64 v1 = (__sanitizer::u64)((signum)); __sanitizer
::u64 v2 = (__sanitizer::u64)((sizeof(*set) * 8)); if (__builtin_expect
(!!(!(v1 < v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 877, "(" "(signum)" ") " "<" " (" "(sizeof(*set) * 8)" ")"
, v1, v2); } while (false)
;
878 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
879 const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
880 const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
881 k_set->sig[idx] &= ~((uptr)1 << bit);
882}
883
884bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
885 signum -= 1;
886 CHECK_GE(signum, 0)do { __sanitizer::u64 v1 = (__sanitizer::u64)((signum)); __sanitizer
::u64 v2 = (__sanitizer::u64)((0)); if (__builtin_expect(!!(!
(v1 >= v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 886, "(" "(signum)" ") " ">=" " (" "(0)" ")", v1, v2); }
while (false)
;
887 CHECK_LT(signum, sizeof(*set) * 8)do { __sanitizer::u64 v1 = (__sanitizer::u64)((signum)); __sanitizer
::u64 v2 = (__sanitizer::u64)((sizeof(*set) * 8)); if (__builtin_expect
(!!(!(v1 < v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 887, "(" "(signum)" ") " "<" " (" "(sizeof(*set) * 8)" ")"
, v1, v2); } while (false)
;
888 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
889 const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
890 const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
891 return k_set->sig[idx] & ((uptr)1 << bit);
892}
893#elif SANITIZER_FREEBSD0
894void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
895 sigset_t *rset = reinterpret_cast<sigset_t *>(set);
896 sigdelset(rset, signum);
897}
898
899bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
900 sigset_t *rset = reinterpret_cast<sigset_t *>(set);
901 return sigismember(rset, signum);
902}
903#endif
904#endif // !SANITIZER_SOLARIS
905
906#if !SANITIZER_NETBSD0
907// ThreadLister implementation.
908ThreadLister::ThreadLister(pid_t pid) : pid_(pid), buffer_(4096) {
909 char task_directory_path[80];
910 internal_snprintf(task_directory_path, sizeof(task_directory_path),
911 "/proc/%d/task/", pid);
912 descriptor_ = internal_open(task_directory_path, O_RDONLY00 | O_DIRECTORY0200000);
913 if (internal_iserror(descriptor_)) {
914 Report("Can't open /proc/%d/task for reading.\n", pid);
915 }
916}
917
918ThreadLister::Result ThreadLister::ListThreads(
919 InternalMmapVector<tid_t> *threads) {
920 if (internal_iserror(descriptor_))
921 return Error;
922 internal_lseek(descriptor_, 0, SEEK_SET0);
923 threads->clear();
924
925 Result result = Ok;
926 for (bool first_read = true;; first_read = false) {
927 // Resize to max capacity if it was downsized by IsAlive.
928 buffer_.resize(buffer_.capacity());
929 CHECK_GE(buffer_.size(), 4096)do { __sanitizer::u64 v1 = (__sanitizer::u64)((buffer_.size()
)); __sanitizer::u64 v2 = (__sanitizer::u64)((4096)); if (__builtin_expect
(!!(!(v1 >= v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 929, "(" "(buffer_.size())" ") " ">=" " (" "(4096)" ")",
v1, v2); } while (false)
;
930 uptr read = internal_getdents(
931 descriptor_, (struct linux_dirent *)buffer_.data(), buffer_.size());
932 if (!read)
933 return result;
934 if (internal_iserror(read)) {
935 Report("Can't read directory entries from /proc/%d/task.\n", pid_);
936 return Error;
937 }
938
939 for (uptr begin = (uptr)buffer_.data(), end = begin + read; begin < end;) {
940 struct linux_dirent *entry = (struct linux_dirent *)begin;
941 begin += entry->d_reclen;
942 if (entry->d_ino == 1) {
943 // Inode 1 is for bad blocks and also can be a reason for early return.
944 // Should be emitted if kernel tried to output terminating thread.
945 // See proc_task_readdir implementation in Linux.
946 result = Incomplete;
947 }
948 if (entry->d_ino && *entry->d_name >= '0' && *entry->d_name <= '9')
949 threads->push_back(internal_atoll(entry->d_name));
950 }
951
952 // Now we are going to detect short-read or early EOF. In such cases Linux
953 // can return inconsistent list with missing alive threads.
954 // Code will just remember that the list can be incomplete but it will
955 // continue reads to return as much as possible.
956 if (!first_read) {
957 // The first one was a short-read by definition.
958 result = Incomplete;
959 } else if (read > buffer_.size() - 1024) {
960 // Read was close to the buffer size. So double the size and assume the
961 // worst.
962 buffer_.resize(buffer_.size() * 2);
963 result = Incomplete;
964 } else if (!threads->empty() && !IsAlive(threads->back())) {
965 // Maybe Linux early returned from read on terminated thread (!pid_alive)
966 // and failed to restore read position.
967 // See next_tid and proc_task_instantiate in Linux.
968 result = Incomplete;
969 }
970 }
971}
972
973bool ThreadLister::IsAlive(int tid) {
974 // /proc/%d/task/%d/status uses same call to detect alive threads as
975 // proc_task_readdir. See task_state implementation in Linux.
976 char path[80];
977 internal_snprintf(path, sizeof(path), "/proc/%d/task/%d/status", pid_, tid);
978 if (!ReadFileToVector(path, &buffer_) || buffer_.empty())
979 return false;
980 buffer_.push_back(0);
981 static const char kPrefix[] = "\nPPid:";
982 const char *field = internal_strstr(buffer_.data(), kPrefix);
983 if (!field)
984 return false;
985 field += internal_strlen(kPrefix);
986 return (int)internal_atoll(field) != 0;
987}
988
989ThreadLister::~ThreadLister() {
990 if (!internal_iserror(descriptor_))
991 internal_close(descriptor_);
992}
993#endif
994
995#if SANITIZER_WORDSIZE64 == 32
996// Take care of unusable kernel area in top gigabyte.
997static uptr GetKernelAreaSize() {
998#if SANITIZER_LINUX1 && !SANITIZER_X320
999 const uptr gbyte = 1UL << 30;
1000
1001 // Firstly check if there are writable segments
1002 // mapped to top gigabyte (e.g. stack).
1003 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
1004 if (proc_maps.Error())
1005 return 0;
1006 MemoryMappedSegment segment;
1007 while (proc_maps.Next(&segment)) {
1008 if ((segment.end >= 3 * gbyte) && segment.IsWritable()) return 0;
1009 }
1010
1011#if !SANITIZER_ANDROID0
1012 // Even if nothing is mapped, top Gb may still be accessible
1013 // if we are running on 64-bit kernel.
1014 // Uname may report misleading results if personality type
1015 // is modified (e.g. under schroot) so check this as well.
1016 struct utsname uname_info;
1017 int pers = personality(0xffffffffUL);
1018 if (!(pers & PER_MASK) && internal_uname(&uname_info) == 0 &&
1019 internal_strstr(uname_info.machine, "64"))
1020 return 0;
1021#endif // SANITIZER_ANDROID
1022
1023 // Top gigabyte is reserved for kernel.
1024 return gbyte;
1025#else
1026 return 0;
1027#endif // SANITIZER_LINUX && !SANITIZER_X32
1028}
1029#endif // SANITIZER_WORDSIZE == 32
1030
1031uptr GetMaxVirtualAddress() {
1032#if SANITIZER_NETBSD0 && defined(__x86_64__1)
1033 return 0x7f7ffffff000ULL; // (0x00007f8000000000 - PAGE_SIZE)
1034#elif SANITIZER_WORDSIZE64 == 64
1035# if defined(__powerpc64__) || defined(__aarch64__)
1036 // On PowerPC64 we have two different address space layouts: 44- and 46-bit.
1037 // We somehow need to figure out which one we are using now and choose
1038 // one of 0x00000fffffffffffUL and 0x00003fffffffffffUL.
1039 // Note that with 'ulimit -s unlimited' the stack is moved away from the top
1040 // of the address space, so simply checking the stack address is not enough.
1041 // This should (does) work for both PowerPC64 Endian modes.
1042 // Similarly, aarch64 has multiple address space layouts: 39, 42 and 47-bit.
1043 return (1ULL << (MostSignificantSetBitIndex(GET_CURRENT_FRAME()(__sanitizer::uptr) __builtin_frame_address(0)) + 1)) - 1;
1044#elif SANITIZER_RISCV640
1045 return (1ULL << 38) - 1;
1046# elif defined(__mips64)
1047 return (1ULL << 40) - 1; // 0x000000ffffffffffUL;
1048# elif defined(__s390x__)
1049 return (1ULL << 53) - 1; // 0x001fffffffffffffUL;
1050#elif defined(__sparc__)
1051 return ~(uptr)0;
1052# else
1053 return (1ULL << 47) - 1; // 0x00007fffffffffffUL;
1054# endif
1055#else // SANITIZER_WORDSIZE == 32
1056# if defined(__s390__)
1057 return (1ULL << 31) - 1; // 0x7fffffff;
1058# else
1059 return (1ULL << 32) - 1; // 0xffffffff;
1060# endif
1061#endif // SANITIZER_WORDSIZE
1062}
1063
1064uptr GetMaxUserVirtualAddress() {
1065 uptr addr = GetMaxVirtualAddress();
1066#if SANITIZER_WORDSIZE64 == 32 && !defined(__s390__)
1067 if (!common_flags()->full_address_space)
1068 addr -= GetKernelAreaSize();
1069 CHECK_LT(reinterpret_cast<uptr>(&addr), addr)do { __sanitizer::u64 v1 = (__sanitizer::u64)((reinterpret_cast
<uptr>(&addr))); __sanitizer::u64 v2 = (__sanitizer
::u64)((addr)); if (__builtin_expect(!!(!(v1 < v2)), 0)) __sanitizer
::CheckFailed("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 1069, "(" "(reinterpret_cast<uptr>(&addr))" ") " "<"
" (" "(addr)" ")", v1, v2); } while (false)
;
1070#endif
1071 return addr;
1072}
1073
1074#if !SANITIZER_ANDROID0
1075uptr GetPageSize() {
1076#if SANITIZER_LINUX1 && (defined(__x86_64__1) || defined(__i386__)) && \
1077 defined(EXEC_PAGESIZE4096)
1078 return EXEC_PAGESIZE4096;
1079#elif SANITIZER_FREEBSD0 || SANITIZER_NETBSD0
1080// Use sysctl as sysconf can trigger interceptors internally.
1081 int pz = 0;
1082 uptr pzl = sizeof(pz);
1083 int mib[2] = {CTL_HW, HW_PAGESIZE};
1084 int rv = internal_sysctl(mib, 2, &pz, &pzl, nullptr, 0);
1085 CHECK_EQ(rv, 0)do { __sanitizer::u64 v1 = (__sanitizer::u64)((rv)); __sanitizer
::u64 v2 = (__sanitizer::u64)((0)); if (__builtin_expect(!!(!
(v1 == v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 1085, "(" "(rv)" ") " "==" " (" "(0)" ")", v1, v2); } while
(false)
;
1086 return (uptr)pz;
1087#elif SANITIZER_USE_GETAUXVAL1
1088 return getauxval(AT_PAGESZ6);
1089#else
1090 return sysconf(_SC_PAGESIZE_SC_PAGESIZE); // EXEC_PAGESIZE may not be trustworthy.
1091#endif
1092}
1093#endif // !SANITIZER_ANDROID
1094
1095uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
1096#if SANITIZER_SOLARIS0
1097 const char *default_module_name = getexecname();
1098 CHECK_NE(default_module_name, NULL)do { __sanitizer::u64 v1 = (__sanitizer::u64)((default_module_name
)); __sanitizer::u64 v2 = (__sanitizer::u64)((__null)); if (__builtin_expect
(!!(!(v1 != v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 1098, "(" "(default_module_name)" ") " "!=" " (" "(__null)"
")", v1, v2); } while (false)
;
1099 return internal_snprintf(buf, buf_len, "%s", default_module_name);
1100#else
1101#if SANITIZER_FREEBSD0 || SANITIZER_NETBSD0
1102#if SANITIZER_FREEBSD0
1103 const int Mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
1104#else
1105 const int Mib[4] = {CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME};
1106#endif
1107 const char *default_module_name = "kern.proc.pathname";
1108 uptr Size = buf_len;
1109 bool IsErr =
1110 (internal_sysctl(Mib, ARRAY_SIZE(Mib)(sizeof(Mib)/sizeof((Mib)[0])), buf, &Size, NULL__null, 0) != 0);
1111 int readlink_error = IsErr ? errno(*__errno_location ()) : 0;
1112 uptr module_name_len = Size;
1113#else
1114 const char *default_module_name = "/proc/self/exe";
1115 uptr module_name_len = internal_readlink(
1116 default_module_name, buf, buf_len);
1117 int readlink_error;
1118 bool IsErr = internal_iserror(module_name_len, &readlink_error);
1119#endif // SANITIZER_SOLARIS
1120 if (IsErr) {
1121 // We can't read binary name for some reason, assume it's unknown.
1122 Report("WARNING: reading executable name failed with errno %d, "
1123 "some stack frames may not be symbolized\n", readlink_error);
1124 module_name_len = internal_snprintf(buf, buf_len, "%s",
1125 default_module_name);
1126 CHECK_LT(module_name_len, buf_len)do { __sanitizer::u64 v1 = (__sanitizer::u64)((module_name_len
)); __sanitizer::u64 v2 = (__sanitizer::u64)((buf_len)); if (
__builtin_expect(!!(!(v1 < v2)), 0)) __sanitizer::CheckFailed
("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 1126, "(" "(module_name_len)" ") " "<" " (" "(buf_len)" ")"
, v1, v2); } while (false)
;
1127 }
1128 return module_name_len;
1129#endif
1130}
1131
1132uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len) {
1133#if SANITIZER_LINUX1
1134 char *tmpbuf;
1135 uptr tmpsize;
1136 uptr tmplen;
1137 if (ReadFileToBuffer("/proc/self/cmdline", &tmpbuf, &tmpsize, &tmplen,
1138 1024 * 1024)) {
1139 internal_strncpy(buf, tmpbuf, buf_len);
1140 UnmapOrDie(tmpbuf, tmpsize);
1141 return internal_strlen(buf);
1142 }
1143#endif
1144 return ReadBinaryName(buf, buf_len);
1145}
1146
1147// Match full names of the form /path/to/base_name{-,.}*
1148bool LibraryNameIs(const char *full_name, const char *base_name) {
1149 const char *name = full_name;
1150 // Strip path.
1151 while (*name != '\0') name++;
1152 while (name > full_name && *name != '/') name--;
1153 if (*name == '/') name++;
1154 uptr base_name_length = internal_strlen(base_name);
1155 if (internal_strncmp(name, base_name, base_name_length)) return false;
1156 return (name[base_name_length] == '-' || name[base_name_length] == '.');
1157}
1158
1159#if !SANITIZER_ANDROID0
1160// Call cb for each region mapped by map.
1161void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr)) {
1162 CHECK_NE(map, nullptr)do { __sanitizer::u64 v1 = (__sanitizer::u64)((map)); __sanitizer
::u64 v2 = (__sanitizer::u64)((nullptr)); if (__builtin_expect
(!!(!(v1 != v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 1162, "(" "(map)" ") " "!=" " (" "(nullptr)" ")", v1, v2); }
while (false)
;
1163#if !SANITIZER_FREEBSD0
1164 typedef ElfW(Phdr)Elf64_Phdr Elf_Phdr;
1165 typedef ElfW(Ehdr)Elf64_Ehdr Elf_Ehdr;
1166#endif // !SANITIZER_FREEBSD
1167 char *base = (char *)map->l_addr;
1168 Elf_Ehdr *ehdr = (Elf_Ehdr *)base;
1169 char *phdrs = base + ehdr->e_phoff;
1170 char *phdrs_end = phdrs + ehdr->e_phnum * ehdr->e_phentsize;
1171
1172 // Find the segment with the minimum base so we can "relocate" the p_vaddr
1173 // fields. Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
1174 // objects have a non-zero base.
1175 uptr preferred_base = (uptr)-1;
1176 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
1177 Elf_Phdr *phdr = (Elf_Phdr *)iter;
1178 if (phdr->p_type == PT_LOAD1 && preferred_base > (uptr)phdr->p_vaddr)
1179 preferred_base = (uptr)phdr->p_vaddr;
1180 }
1181
1182 // Compute the delta from the real base to get a relocation delta.
1183 sptr delta = (uptr)base - preferred_base;
1184 // Now we can figure out what the loader really mapped.
1185 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
1186 Elf_Phdr *phdr = (Elf_Phdr *)iter;
1187 if (phdr->p_type == PT_LOAD1) {
1188 uptr seg_start = phdr->p_vaddr + delta;
1189 uptr seg_end = seg_start + phdr->p_memsz;
1190 // None of these values are aligned. We consider the ragged edges of the
1191 // load command as defined, since they are mapped from the file.
1192 seg_start = RoundDownTo(seg_start, GetPageSizeCached());
1193 seg_end = RoundUpTo(seg_end, GetPageSizeCached());
1194 cb((void *)seg_start, seg_end - seg_start);
1195 }
1196 }
1197}
1198#endif
1199
1200#if SANITIZER_LINUX1
1201#if defined(__x86_64__1)
1202// We cannot use glibc's clone wrapper, because it messes with the child
1203// task's TLS. It writes the PID and TID of the child task to its thread
1204// descriptor, but in our case the child task shares the thread descriptor with
1205// the parent (because we don't know how to allocate a new thread
1206// descriptor to keep glibc happy). So the stock version of clone(), when
1207// used with CLONE_VM, would end up corrupting the parent's thread descriptor.
1208uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1209 int *parent_tidptr, void *newtls, int *child_tidptr) {
1210 long long res;
1211 if (!fn || !child_stack)
1212 return -EINVAL22;
1213 CHECK_EQ(0, (uptr)child_stack % 16)do { __sanitizer::u64 v1 = (__sanitizer::u64)((0)); __sanitizer
::u64 v2 = (__sanitizer::u64)(((uptr)child_stack % 16)); if (
__builtin_expect(!!(!(v1 == v2)), 0)) __sanitizer::CheckFailed
("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 1213, "(" "(0)" ") " "==" " (" "((uptr)child_stack % 16)" ")"
, v1, v2); } while (false)
;
1214 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1215 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1216 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1217 register void *r8 __asm__("r8") = newtls;
1218 register int *r10 __asm__("r10") = child_tidptr;
1219 __asm__ __volatile__(
1220 /* %rax = syscall(%rax = SYSCALL(clone),
1221 * %rdi = flags,
1222 * %rsi = child_stack,
1223 * %rdx = parent_tidptr,
1224 * %r8 = new_tls,
1225 * %r10 = child_tidptr)
1226 */
1227 "syscall\n"
1228
1229 /* if (%rax != 0)
1230 * return;
1231 */
1232 "testq %%rax,%%rax\n"
1233 "jnz 1f\n"
1234
1235 /* In the child. Terminate unwind chain. */
1236 // XXX: We should also terminate the CFI unwind chain
1237 // here. Unfortunately clang 3.2 doesn't support the
1238 // necessary CFI directives, so we skip that part.
1239 "xorq %%rbp,%%rbp\n"
1240
1241 /* Call "fn(arg)". */
1242 "popq %%rax\n"
1243 "popq %%rdi\n"
1244 "call *%%rax\n"
1245
1246 /* Call _exit(%rax). */
1247 "movq %%rax,%%rdi\n"
1248 "movq %2,%%rax\n"
1249 "syscall\n"
1250
1251 /* Return to parent. */
1252 "1:\n"
1253 : "=a" (res)
1254 : "a"(SYSCALL(clone)56), "i"(SYSCALL(exit)60),
1255 "S"(child_stack),
1256 "D"(flags),
1257 "d"(parent_tidptr),
1258 "r"(r8),
1259 "r"(r10)
1260 : "memory", "r11", "rcx");
1261 return res;
1262}
1263#elif defined(__mips__)
1264uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1265 int *parent_tidptr, void *newtls, int *child_tidptr) {
1266 long long res;
1267 if (!fn || !child_stack)
1268 return -EINVAL22;
1269 CHECK_EQ(0, (uptr)child_stack % 16)do { __sanitizer::u64 v1 = (__sanitizer::u64)((0)); __sanitizer
::u64 v2 = (__sanitizer::u64)(((uptr)child_stack % 16)); if (
__builtin_expect(!!(!(v1 == v2)), 0)) __sanitizer::CheckFailed
("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 1269, "(" "(0)" ") " "==" " (" "((uptr)child_stack % 16)" ")"
, v1, v2); } while (false)
;
1270 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1271 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1272 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1273 register void *a3 __asm__("$7") = newtls;
1274 register int *a4 __asm__("$8") = child_tidptr;
1275 // We don't have proper CFI directives here because it requires alot of code
1276 // for very marginal benefits.
1277 __asm__ __volatile__(
1278 /* $v0 = syscall($v0 = __NR_clone,
1279 * $a0 = flags,
1280 * $a1 = child_stack,
1281 * $a2 = parent_tidptr,
1282 * $a3 = new_tls,
1283 * $a4 = child_tidptr)
1284 */
1285 ".cprestore 16;\n"
1286 "move $4,%1;\n"
1287 "move $5,%2;\n"
1288 "move $6,%3;\n"
1289 "move $7,%4;\n"
1290 /* Store the fifth argument on stack
1291 * if we are using 32-bit abi.
1292 */
1293#if SANITIZER_WORDSIZE64 == 32
1294 "lw %5,16($29);\n"
1295#else
1296 "move $8,%5;\n"
1297#endif
1298 "li $2,%6;\n"
1299 "syscall;\n"
1300
1301 /* if ($v0 != 0)
1302 * return;
1303 */
1304 "bnez $2,1f;\n"
1305
1306 /* Call "fn(arg)". */
1307#if SANITIZER_WORDSIZE64 == 32
1308#ifdef __BIG_ENDIAN__
1309 "lw $25,4($29);\n"
1310 "lw $4,12($29);\n"
1311#else
1312 "lw $25,0($29);\n"
1313 "lw $4,8($29);\n"
1314#endif
1315#else
1316 "ld $25,0($29);\n"
1317 "ld $4,8($29);\n"
1318#endif
1319 "jal $25;\n"
1320
1321 /* Call _exit($v0). */
1322 "move $4,$2;\n"
1323 "li $2,%7;\n"
1324 "syscall;\n"
1325
1326 /* Return to parent. */
1327 "1:\n"
1328 : "=r" (res)
1329 : "r"(flags),
1330 "r"(child_stack),
1331 "r"(parent_tidptr),
1332 "r"(a3),
1333 "r"(a4),
1334 "i"(__NR_clone56),
1335 "i"(__NR_exit60)
1336 : "memory", "$29" );
1337 return res;
1338}
1339#elif SANITIZER_RISCV640
1340uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1341 int *parent_tidptr, void *newtls, int *child_tidptr) {
1342 if (!fn || !child_stack)
1343 return -EINVAL22;
1344
1345 CHECK_EQ(0, (uptr)child_stack % 16)do { __sanitizer::u64 v1 = (__sanitizer::u64)((0)); __sanitizer
::u64 v2 = (__sanitizer::u64)(((uptr)child_stack % 16)); if (
__builtin_expect(!!(!(v1 == v2)), 0)) __sanitizer::CheckFailed
("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 1345, "(" "(0)" ") " "==" " (" "((uptr)child_stack % 16)" ")"
, v1, v2); } while (false)
;
1346
1347 register int res __asm__("a0");
1348 register int __flags __asm__("a0") = flags;
1349 register void *__stack __asm__("a1") = child_stack;
1350 register int *__ptid __asm__("a2") = parent_tidptr;
1351 register void *__tls __asm__("a3") = newtls;
1352 register int *__ctid __asm__("a4") = child_tidptr;
1353 register int (*__fn)(void *) __asm__("a5") = fn;
1354 register void *__arg __asm__("a6") = arg;
1355 register int nr_clone __asm__("a7") = __NR_clone56;
1356
1357 __asm__ __volatile__(
1358 "ecall\n"
1359
1360 /* if (a0 != 0)
1361 * return a0;
1362 */
1363 "bnez a0, 1f\n"
1364
1365 // In the child, now. Call "fn(arg)".
1366 "mv a0, a6\n"
1367 "jalr a5\n"
1368
1369 // Call _exit(a0).
1370 "addi a7, zero, %9\n"
1371 "ecall\n"
1372 "1:\n"
1373
1374 : "=r"(res)
1375 : "0"(__flags), "r"(__stack), "r"(__ptid), "r"(__tls), "r"(__ctid),
1376 "r"(__fn), "r"(__arg), "r"(nr_clone), "i"(__NR_exit60)
1377 : "memory");
1378 return res;
1379}
1380#elif defined(__aarch64__)
1381uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1382 int *parent_tidptr, void *newtls, int *child_tidptr) {
1383 long long res;
1384 if (!fn || !child_stack)
1385 return -EINVAL22;
1386 CHECK_EQ(0, (uptr)child_stack % 16)do { __sanitizer::u64 v1 = (__sanitizer::u64)((0)); __sanitizer
::u64 v2 = (__sanitizer::u64)(((uptr)child_stack % 16)); if (
__builtin_expect(!!(!(v1 == v2)), 0)) __sanitizer::CheckFailed
("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 1386, "(" "(0)" ") " "==" " (" "((uptr)child_stack % 16)" ")"
, v1, v2); } while (false)
;
1387 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1388 ((unsigned long long *)child_stack)[0] = (uptr)fn;
1389 ((unsigned long long *)child_stack)[1] = (uptr)arg;
1390
1391 register int (*__fn)(void *) __asm__("x0") = fn;
1392 register void *__stack __asm__("x1") = child_stack;
1393 register int __flags __asm__("x2") = flags;
1394 register void *__arg __asm__("x3") = arg;
1395 register int *__ptid __asm__("x4") = parent_tidptr;
1396 register void *__tls __asm__("x5") = newtls;
1397 register int *__ctid __asm__("x6") = child_tidptr;
1398
1399 __asm__ __volatile__(
1400 "mov x0,x2\n" /* flags */
1401 "mov x2,x4\n" /* ptid */
1402 "mov x3,x5\n" /* tls */
1403 "mov x4,x6\n" /* ctid */
1404 "mov x8,%9\n" /* clone */
1405
1406 "svc 0x0\n"
1407
1408 /* if (%r0 != 0)
1409 * return %r0;
1410 */
1411 "cmp x0, #0\n"
1412 "bne 1f\n"
1413
1414 /* In the child, now. Call "fn(arg)". */
1415 "ldp x1, x0, [sp], #16\n"
1416 "blr x1\n"
1417
1418 /* Call _exit(%r0). */
1419 "mov x8, %10\n"
1420 "svc 0x0\n"
1421 "1:\n"
1422
1423 : "=r" (res)
1424 : "i"(-EINVAL22),
1425 "r"(__fn), "r"(__stack), "r"(__flags), "r"(__arg),
1426 "r"(__ptid), "r"(__tls), "r"(__ctid),
1427 "i"(__NR_clone56), "i"(__NR_exit60)
1428 : "x30", "memory");
1429 return res;
1430}
1431#elif defined(__powerpc64__)
1432uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1433 int *parent_tidptr, void *newtls, int *child_tidptr) {
1434 long long res;
1435// Stack frame structure.
1436#if SANITIZER_PPC64V10
1437// Back chain == 0 (SP + 112)
1438// Frame (112 bytes):
1439// Parameter save area (SP + 48), 8 doublewords
1440// TOC save area (SP + 40)
1441// Link editor doubleword (SP + 32)
1442// Compiler doubleword (SP + 24)
1443// LR save area (SP + 16)
1444// CR save area (SP + 8)
1445// Back chain (SP + 0)
1446# define FRAME_SIZE 112
1447# define FRAME_TOC_SAVE_OFFSET 40
1448#elif SANITIZER_PPC64V20
1449// Back chain == 0 (SP + 32)
1450// Frame (32 bytes):
1451// TOC save area (SP + 24)
1452// LR save area (SP + 16)
1453// CR save area (SP + 8)
1454// Back chain (SP + 0)
1455# define FRAME_SIZE 32
1456# define FRAME_TOC_SAVE_OFFSET 24
1457#else
1458# error "Unsupported PPC64 ABI"
1459#endif
1460 if (!fn || !child_stack)
1461 return -EINVAL22;
1462 CHECK_EQ(0, (uptr)child_stack % 16)do { __sanitizer::u64 v1 = (__sanitizer::u64)((0)); __sanitizer
::u64 v2 = (__sanitizer::u64)(((uptr)child_stack % 16)); if (
__builtin_expect(!!(!(v1 == v2)), 0)) __sanitizer::CheckFailed
("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 1462, "(" "(0)" ") " "==" " (" "((uptr)child_stack % 16)" ")"
, v1, v2); } while (false)
;
1463
1464 register int (*__fn)(void *) __asm__("r3") = fn;
1465 register void *__cstack __asm__("r4") = child_stack;
1466 register int __flags __asm__("r5") = flags;
1467 register void *__arg __asm__("r6") = arg;
1468 register int *__ptidptr __asm__("r7") = parent_tidptr;
1469 register void *__newtls __asm__("r8") = newtls;
1470 register int *__ctidptr __asm__("r9") = child_tidptr;
1471
1472 __asm__ __volatile__(
1473 /* fn and arg are saved across the syscall */
1474 "mr 28, %5\n\t"
1475 "mr 27, %8\n\t"
1476
1477 /* syscall
1478 r0 == __NR_clone
1479 r3 == flags
1480 r4 == child_stack
1481 r5 == parent_tidptr
1482 r6 == newtls
1483 r7 == child_tidptr */
1484 "mr 3, %7\n\t"
1485 "mr 5, %9\n\t"
1486 "mr 6, %10\n\t"
1487 "mr 7, %11\n\t"
1488 "li 0, %3\n\t"
1489 "sc\n\t"
1490
1491 /* Test if syscall was successful */
1492 "cmpdi cr1, 3, 0\n\t"
1493 "crandc cr1*4+eq, cr1*4+eq, cr0*4+so\n\t"
1494 "bne- cr1, 1f\n\t"
1495
1496 /* Set up stack frame */
1497 "li 29, 0\n\t"
1498 "stdu 29, -8(1)\n\t"
1499 "stdu 1, -%12(1)\n\t"
1500 /* Do the function call */
1501 "std 2, %13(1)\n\t"
1502#if SANITIZER_PPC64V10
1503 "ld 0, 0(28)\n\t"
1504 "ld 2, 8(28)\n\t"
1505 "mtctr 0\n\t"
1506#elif SANITIZER_PPC64V20
1507 "mr 12, 28\n\t"
1508 "mtctr 12\n\t"
1509#else
1510# error "Unsupported PPC64 ABI"
1511#endif
1512 "mr 3, 27\n\t"
1513 "bctrl\n\t"
1514 "ld 2, %13(1)\n\t"
1515
1516 /* Call _exit(r3) */
1517 "li 0, %4\n\t"
1518 "sc\n\t"
1519
1520 /* Return to parent */
1521 "1:\n\t"
1522 "mr %0, 3\n\t"
1523 : "=r" (res)
1524 : "0" (-1),
1525 "i" (EINVAL22),
1526 "i" (__NR_clone56),
1527 "i" (__NR_exit60),
1528 "r" (__fn),
1529 "r" (__cstack),
1530 "r" (__flags),
1531 "r" (__arg),
1532 "r" (__ptidptr),
1533 "r" (__newtls),
1534 "r" (__ctidptr),
1535 "i" (FRAME_SIZE),
1536 "i" (FRAME_TOC_SAVE_OFFSET)
1537 : "cr0", "cr1", "memory", "ctr", "r0", "r27", "r28", "r29");
1538 return res;
1539}
1540#elif defined(__i386__)
1541uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1542 int *parent_tidptr, void *newtls, int *child_tidptr) {
1543 int res;
1544 if (!fn || !child_stack)
1545 return -EINVAL22;
1546 CHECK_EQ(0, (uptr)child_stack % 16)do { __sanitizer::u64 v1 = (__sanitizer::u64)((0)); __sanitizer
::u64 v2 = (__sanitizer::u64)(((uptr)child_stack % 16)); if (
__builtin_expect(!!(!(v1 == v2)), 0)) __sanitizer::CheckFailed
("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 1546, "(" "(0)" ") " "==" " (" "((uptr)child_stack % 16)" ")"
, v1, v2); } while (false)
;
1547 child_stack = (char *)child_stack - 7 * sizeof(unsigned int);
1548 ((unsigned int *)child_stack)[0] = (uptr)flags;
1549 ((unsigned int *)child_stack)[1] = (uptr)0;
1550 ((unsigned int *)child_stack)[2] = (uptr)fn;
1551 ((unsigned int *)child_stack)[3] = (uptr)arg;
1552 __asm__ __volatile__(
1553 /* %eax = syscall(%eax = SYSCALL(clone),
1554 * %ebx = flags,
1555 * %ecx = child_stack,
1556 * %edx = parent_tidptr,
1557 * %esi = new_tls,
1558 * %edi = child_tidptr)
1559 */
1560
1561 /* Obtain flags */
1562 "movl (%%ecx), %%ebx\n"
1563 /* Do the system call */
1564 "pushl %%ebx\n"
1565 "pushl %%esi\n"
1566 "pushl %%edi\n"
1567 /* Remember the flag value. */
1568 "movl %%ebx, (%%ecx)\n"
1569 "int $0x80\n"
1570 "popl %%edi\n"
1571 "popl %%esi\n"
1572 "popl %%ebx\n"
1573
1574 /* if (%eax != 0)
1575 * return;
1576 */
1577
1578 "test %%eax,%%eax\n"
1579 "jnz 1f\n"
1580
1581 /* terminate the stack frame */
1582 "xorl %%ebp,%%ebp\n"
1583 /* Call FN. */
1584 "call *%%ebx\n"
1585#ifdef PIC
1586 "call here\n"
1587 "here:\n"
1588 "popl %%ebx\n"
1589 "addl $_GLOBAL_OFFSET_TABLE_+[.-here], %%ebx\n"
1590#endif
1591 /* Call exit */
1592 "movl %%eax, %%ebx\n"
1593 "movl %2, %%eax\n"
1594 "int $0x80\n"
1595 "1:\n"
1596 : "=a" (res)
1597 : "a"(SYSCALL(clone)56), "i"(SYSCALL(exit)60),
1598 "c"(child_stack),
1599 "d"(parent_tidptr),
1600 "S"(newtls),
1601 "D"(child_tidptr)
1602 : "memory");
1603 return res;
1604}
1605#elif defined(__arm__)
1606uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1607 int *parent_tidptr, void *newtls, int *child_tidptr) {
1608 unsigned int res;
1609 if (!fn || !child_stack)
1610 return -EINVAL22;
1611 child_stack = (char *)child_stack - 2 * sizeof(unsigned int);
1612 ((unsigned int *)child_stack)[0] = (uptr)fn;
1613 ((unsigned int *)child_stack)[1] = (uptr)arg;
1614 register int r0 __asm__("r0") = flags;
1615 register void *r1 __asm__("r1") = child_stack;
1616 register int *r2 __asm__("r2") = parent_tidptr;
1617 register void *r3 __asm__("r3") = newtls;
1618 register int *r4 __asm__("r4") = child_tidptr;
1619 register int r7 __asm__("r7") = __NR_clone56;
1620
1621#if __ARM_ARCH > 4 || defined (__ARM_ARCH_4T__)
1622# define ARCH_HAS_BX
1623#endif
1624#if __ARM_ARCH > 4
1625# define ARCH_HAS_BLX
1626#endif
1627
1628#ifdef ARCH_HAS_BX
1629# ifdef ARCH_HAS_BLX
1630# define BLX(R) "blx " #R "\n"
1631# else
1632# define BLX(R) "mov lr, pc; bx " #R "\n"
1633# endif
1634#else
1635# define BLX(R) "mov lr, pc; mov pc," #R "\n"
1636#endif
1637
1638 __asm__ __volatile__(
1639 /* %r0 = syscall(%r7 = SYSCALL(clone),
1640 * %r0 = flags,
1641 * %r1 = child_stack,
1642 * %r2 = parent_tidptr,
1643 * %r3 = new_tls,
1644 * %r4 = child_tidptr)
1645 */
1646
1647 /* Do the system call */
1648 "swi 0x0\n"
1649
1650 /* if (%r0 != 0)
1651 * return %r0;
1652 */
1653 "cmp r0, #0\n"
1654 "bne 1f\n"
1655
1656 /* In the child, now. Call "fn(arg)". */
1657 "ldr r0, [sp, #4]\n"
1658 "ldr ip, [sp], #8\n"
1659 BLX(ip)
1660 /* Call _exit(%r0). */
1661 "mov r7, %7\n"
1662 "swi 0x0\n"
1663 "1:\n"
1664 "mov %0, r0\n"
1665 : "=r"(res)
1666 : "r"(r0), "r"(r1), "r"(r2), "r"(r3), "r"(r4), "r"(r7),
1667 "i"(__NR_exit60)
1668 : "memory");
1669 return res;
1670}
1671#endif
1672#endif // SANITIZER_LINUX
1673
1674#if SANITIZER_LINUX1
1675int internal_uname(struct utsname *buf) {
1676 return internal_syscall(SYSCALL(uname)63, buf);
1677}
1678#endif
1679
1680#if SANITIZER_ANDROID0
1681#if __ANDROID_API__ < 21
1682extern "C" __attribute__((weak)) int dl_iterate_phdr(
1683 int (*)(struct dl_phdr_info *, size_t, void *), void *);
1684#endif
1685
1686static int dl_iterate_phdr_test_cb(struct dl_phdr_info *info, size_t size,
1687 void *data) {
1688 // Any name starting with "lib" indicates a bug in L where library base names
1689 // are returned instead of paths.
1690 if (info->dlpi_name && info->dlpi_name[0] == 'l' &&
1691 info->dlpi_name[1] == 'i' && info->dlpi_name[2] == 'b') {
1692 *(bool *)data = true;
1693 return 1;
1694 }
1695 return 0;
1696}
1697
1698static atomic_uint32_t android_api_level;
1699
1700static AndroidApiLevel AndroidDetectApiLevelStatic() {
1701#if __ANDROID_API__ <= 19
1702 return ANDROID_KITKAT;
1703#elif __ANDROID_API__ <= 22
1704 return ANDROID_LOLLIPOP_MR1;
1705#else
1706 return ANDROID_POST_LOLLIPOP;
1707#endif
1708}
1709
1710static AndroidApiLevel AndroidDetectApiLevel() {
1711 if (!&dl_iterate_phdr)
1712 return ANDROID_KITKAT; // K or lower
1713 bool base_name_seen = false;
1714 dl_iterate_phdr(dl_iterate_phdr_test_cb, &base_name_seen);
1715 if (base_name_seen)
1716 return ANDROID_LOLLIPOP_MR1; // L MR1
1717 return ANDROID_POST_LOLLIPOP; // post-L
1718 // Plain L (API level 21) is completely broken wrt ASan and not very
1719 // interesting to detect.
1720}
1721
1722extern "C" __attribute__((weak)) void* _DYNAMIC;
1723
1724AndroidApiLevel AndroidGetApiLevel() {
1725 AndroidApiLevel level =
1726 (AndroidApiLevel)atomic_load(&android_api_level, memory_order_relaxed);
1727 if (level) return level;
1728 level = &_DYNAMIC == nullptr ? AndroidDetectApiLevelStatic()
1729 : AndroidDetectApiLevel();
1730 atomic_store(&android_api_level, level, memory_order_relaxed);
1731 return level;
1732}
1733
1734#endif
1735
1736static HandleSignalMode GetHandleSignalModeImpl(int signum) {
1737 switch (signum) {
1738 case SIGABRT6:
1739 return common_flags()->handle_abort;
1740 case SIGILL4:
1741 return common_flags()->handle_sigill;
1742 case SIGTRAP5:
1743 return common_flags()->handle_sigtrap;
1744 case SIGFPE8:
1745 return common_flags()->handle_sigfpe;
1746 case SIGSEGV11:
1747 return common_flags()->handle_segv;
1748 case SIGBUS7:
1749 return common_flags()->handle_sigbus;
1750 }
1751 return kHandleSignalNo;
1752}
1753
1754HandleSignalMode GetHandleSignalMode(int signum) {
1755 HandleSignalMode result = GetHandleSignalModeImpl(signum);
1756 if (result == kHandleSignalYes && !common_flags()->allow_user_segv_handler)
1757 return kHandleSignalExclusive;
1758 return result;
1759}
1760
1761#if !SANITIZER_GO0
1762void *internal_start_thread(void *(*func)(void *arg), void *arg) {
1763 // Start the thread with signals blocked, otherwise it can steal user signals.
1764 ScopedBlockSignals block(nullptr);
1765 void *th;
1766 real_pthread_create(&th, nullptr, func, arg);
1767 return th;
1768}
1769
1770void internal_join_thread(void *th) {
1771 real_pthread_join(th, nullptr);
1772}
1773#else
1774void *internal_start_thread(void *(*func)(void *), void *arg) { return 0; }
1775
1776void internal_join_thread(void *th) {}
1777#endif
1778
1779#if defined(__aarch64__)
1780// Android headers in the older NDK releases miss this definition.
1781struct __sanitizer_esr_context {
1782 struct _aarch64_ctx head;
1783 uint64_t esr;
1784};
1785
1786static bool Aarch64GetESR(ucontext_t *ucontext, u64 *esr) {
1787 static const u32 kEsrMagic = 0x45535201;
1788 u8 *aux = reinterpret_cast<u8 *>(ucontext->uc_mcontext.__reserved);
1789 while (true) {
1790 _aarch64_ctx *ctx = (_aarch64_ctx *)aux;
1791 if (ctx->size == 0) break;
1792 if (ctx->magic == kEsrMagic) {
1793 *esr = ((__sanitizer_esr_context *)ctx)->esr;
1794 return true;
1795 }
1796 aux += ctx->size;
1797 }
1798 return false;
1799}
1800#endif
1801
1802using Context = ucontext_t;
1803
1804SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
1805 Context *ucontext = (Context *)context;
1806#if defined(__x86_64__1) || defined(__i386__)
1807 static const uptr PF_WRITE = 1U << 1;
1808#if SANITIZER_FREEBSD0
1809 uptr err = ucontext->uc_mcontext.mc_err;
1810#elif SANITIZER_NETBSD0
1811 uptr err = ucontext->uc_mcontext.__gregs[_REG_ERR];
1812#elif SANITIZER_SOLARIS0 && defined(__i386__)
1813 const int Err = 13;
1814 uptr err = ucontext->uc_mcontext.gregs[Err];
1815#else
1816 uptr err = ucontext->uc_mcontext.gregs[REG_ERRREG_ERR];
1817#endif // SANITIZER_FREEBSD
1818 return err & PF_WRITE ? WRITE : READ;
1819#elif defined(__mips__)
1820 uint32_t *exception_source;
1821 uint32_t faulty_instruction;
1822 uint32_t op_code;
1823
1824 exception_source = (uint32_t *)ucontext->uc_mcontext.pc;
1825 faulty_instruction = (uint32_t)(*exception_source);
1826
1827 op_code = (faulty_instruction >> 26) & 0x3f;
1828
1829 // FIXME: Add support for FPU, microMIPS, DSP, MSA memory instructions.
1830 switch (op_code) {
1831 case 0x28: // sb
1832 case 0x29: // sh
1833 case 0x2b: // sw
1834 case 0x3f: // sd
1835#if __mips_isa_rev < 6
1836 case 0x2c: // sdl
1837 case 0x2d: // sdr
1838 case 0x2a: // swl
1839 case 0x2e: // swr
1840#endif
1841 return SignalContext::WRITE;
1842
1843 case 0x20: // lb
1844 case 0x24: // lbu
1845 case 0x21: // lh
1846 case 0x25: // lhu
1847 case 0x23: // lw
1848 case 0x27: // lwu
1849 case 0x37: // ld
1850#if __mips_isa_rev < 6
1851 case 0x1a: // ldl
1852 case 0x1b: // ldr
1853 case 0x22: // lwl
1854 case 0x26: // lwr
1855#endif
1856 return SignalContext::READ;
1857#if __mips_isa_rev == 6
1858 case 0x3b: // pcrel
1859 op_code = (faulty_instruction >> 19) & 0x3;
1860 switch (op_code) {
1861 case 0x1: // lwpc
1862 case 0x2: // lwupc
1863 return SignalContext::READ;
1864 }
1865#endif
1866 }
1867 return SignalContext::UNKNOWN;
1868#elif defined(__arm__)
1869 static const uptr FSR_WRITE = 1U << 11;
1870 uptr fsr = ucontext->uc_mcontext.error_code;
1871 return fsr & FSR_WRITE ? WRITE : READ;
1872#elif defined(__aarch64__)
1873 static const u64 ESR_ELx_WNR = 1U << 6;
1874 u64 esr;
1875 if (!Aarch64GetESR(ucontext, &esr)) return UNKNOWN;
1876 return esr & ESR_ELx_WNR ? WRITE : READ;
1877#elif defined(__sparc__)
1878 // Decode the instruction to determine the access type.
1879 // From OpenSolaris $SRC/uts/sun4/os/trap.c (get_accesstype).
1880#if SANITIZER_SOLARIS0
1881 uptr pc = ucontext->uc_mcontext.gregs[REG_PC];
1882#else
1883 // Historical BSDism here.
1884 struct sigcontext *scontext = (struct sigcontext *)context;
1885#if defined(__arch64__)
1886 uptr pc = scontext->sigc_regs.tpc;
1887#else
1888 uptr pc = scontext->si_regs.pc;
1889#endif
1890#endif
1891 u32 instr = *(u32 *)pc;
1892 return (instr >> 21) & 1 ? WRITE: READ;
1893#elif defined(__riscv)
1894#if SANITIZER_FREEBSD0
1895 unsigned long pc = ucontext->uc_mcontext.mc_gpregs.gp_sepc;
1896#else
1897 unsigned long pc = ucontext->uc_mcontext.__gregs[REG_PC];
1898#endif
1899 unsigned faulty_instruction = *(uint16_t *)pc;
1900
1901#if defined(__riscv_compressed)
1902 if ((faulty_instruction & 0x3) != 0x3) { // it's a compressed instruction
1903 // set op_bits to the instruction bits [1, 0, 15, 14, 13]
1904 unsigned op_bits =
1905 ((faulty_instruction & 0x3) << 3) | (faulty_instruction >> 13);
1906 unsigned rd = faulty_instruction & 0xF80; // bits 7-11, inclusive
1907 switch (op_bits) {
1908 case 0b10'010: // c.lwsp (rd != x0)
1909#if __riscv_xlen == 64
1910 case 0b10'011: // c.ldsp (rd != x0)
1911#endif
1912 return rd ? SignalContext::READ : SignalContext::UNKNOWN;
1913 case 0b00'010: // c.lw
1914#if __riscv_flen >= 32 && __riscv_xlen == 32
1915 case 0b10'011: // c.flwsp
1916#endif
1917#if __riscv_flen >= 32 || __riscv_xlen == 64
1918 case 0b00'011: // c.flw / c.ld
1919#endif
1920#if __riscv_flen == 64
1921 case 0b00'001: // c.fld
1922 case 0b10'001: // c.fldsp
1923#endif
1924 return SignalContext::READ;
1925 case 0b00'110: // c.sw
1926 case 0b10'110: // c.swsp
1927#if __riscv_flen >= 32 || __riscv_xlen == 64
1928 case 0b00'111: // c.fsw / c.sd
1929 case 0b10'111: // c.fswsp / c.sdsp
1930#endif
1931#if __riscv_flen == 64
1932 case 0b00'101: // c.fsd
1933 case 0b10'101: // c.fsdsp
1934#endif
1935 return SignalContext::WRITE;
1936 default:
1937 return SignalContext::UNKNOWN;
1938 }
1939 }
1940#endif
1941
1942 unsigned opcode = faulty_instruction & 0x7f; // lower 7 bits
1943 unsigned funct3 = (faulty_instruction >> 12) & 0x7; // bits 12-14, inclusive
1944 switch (opcode) {
1945 case 0b0000011: // loads
1946 switch (funct3) {
1947 case 0b000: // lb
1948 case 0b001: // lh
1949 case 0b010: // lw
1950#if __riscv_xlen == 64
1951 case 0b011: // ld
1952#endif
1953 case 0b100: // lbu
1954 case 0b101: // lhu
1955 return SignalContext::READ;
1956 default:
1957 return SignalContext::UNKNOWN;
1958 }
1959 case 0b0100011: // stores
1960 switch (funct3) {
1961 case 0b000: // sb
1962 case 0b001: // sh
1963 case 0b010: // sw
1964#if __riscv_xlen == 64
1965 case 0b011: // sd
1966#endif
1967 return SignalContext::WRITE;
1968 default:
1969 return SignalContext::UNKNOWN;
1970 }
1971#if __riscv_flen >= 32
1972 case 0b0000111: // floating-point loads
1973 switch (funct3) {
1974 case 0b010: // flw
1975#if __riscv_flen == 64
1976 case 0b011: // fld
1977#endif
1978 return SignalContext::READ;
1979 default:
1980 return SignalContext::UNKNOWN;
1981 }
1982 case 0b0100111: // floating-point stores
1983 switch (funct3) {
1984 case 0b010: // fsw
1985#if __riscv_flen == 64
1986 case 0b011: // fsd
1987#endif
1988 return SignalContext::WRITE;
1989 default:
1990 return SignalContext::UNKNOWN;
1991 }
1992#endif
1993 default:
1994 return SignalContext::UNKNOWN;
1995 }
1996#else
1997 (void)ucontext;
1998 return UNKNOWN; // FIXME: Implement.
1999#endif
2000}
2001
2002bool SignalContext::IsTrueFaultingAddress() const {
2003 auto si = static_cast<const siginfo_t *>(siginfo);
2004 // SIGSEGV signals without a true fault address have si_code set to 128.
2005 return si->si_signo == SIGSEGV11 && si->si_code != 128;
2006}
2007
2008void SignalContext::DumpAllRegisters(void *context) {
2009 // FIXME: Implement this.
2010}
2011
2012static void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
2013#if SANITIZER_NETBSD0
2014 // This covers all NetBSD architectures
2015 ucontext_t *ucontext = (ucontext_t *)context;
2016 *pc = _UC_MACHINE_PC(ucontext);
2017 *bp = _UC_MACHINE_FP(ucontext);
2018 *sp = _UC_MACHINE_SP(ucontext);
2019#elif defined(__arm__)
2020 ucontext_t *ucontext = (ucontext_t*)context;
2021 *pc = ucontext->uc_mcontext.arm_pc;
2022 *bp = ucontext->uc_mcontext.arm_fp;
2023 *sp = ucontext->uc_mcontext.arm_sp;
2024#elif defined(__aarch64__)
2025 ucontext_t *ucontext = (ucontext_t*)context;
2026 *pc = ucontext->uc_mcontext.pc;
2027 *bp = ucontext->uc_mcontext.regs[29];
2028 *sp = ucontext->uc_mcontext.sp;
2029#elif defined(__hppa__)
2030 ucontext_t *ucontext = (ucontext_t*)context;
2031 *pc = ucontext->uc_mcontext.sc_iaoq[0];
2032 /* GCC uses %r3 whenever a frame pointer is needed. */
2033 *bp = ucontext->uc_mcontext.sc_gr[3];
2034 *sp = ucontext->uc_mcontext.sc_gr[30];
2035#elif defined(__x86_64__1)
2036# if SANITIZER_FREEBSD0
2037 ucontext_t *ucontext = (ucontext_t*)context;
2038 *pc = ucontext->uc_mcontext.mc_rip;
2039 *bp = ucontext->uc_mcontext.mc_rbp;
2040 *sp = ucontext->uc_mcontext.mc_rsp;
2041# else
2042 ucontext_t *ucontext = (ucontext_t*)context;
2043 *pc = ucontext->uc_mcontext.gregs[REG_RIPREG_RIP];
2044 *bp = ucontext->uc_mcontext.gregs[REG_RBPREG_RBP];
2045 *sp = ucontext->uc_mcontext.gregs[REG_RSPREG_RSP];
2046# endif
2047#elif defined(__i386__)
2048# if SANITIZER_FREEBSD0
2049 ucontext_t *ucontext = (ucontext_t*)context;
2050 *pc = ucontext->uc_mcontext.mc_eip;
2051 *bp = ucontext->uc_mcontext.mc_ebp;
2052 *sp = ucontext->uc_mcontext.mc_esp;
2053# else
2054 ucontext_t *ucontext = (ucontext_t*)context;
2055# if SANITIZER_SOLARIS0
2056 /* Use the numeric values: the symbolic ones are undefined by llvm
2057 include/llvm/Support/Solaris.h. */
2058# ifndef REG_EIP
2059# define REG_EIP 14 // REG_PC
2060# endif
2061# ifndef REG_EBP
2062# define REG_EBP 6 // REG_FP
2063# endif
2064# ifndef REG_UESP
2065# define REG_UESP 17 // REG_SP
2066# endif
2067# endif
2068 *pc = ucontext->uc_mcontext.gregs[REG_EIP];
2069 *bp = ucontext->uc_mcontext.gregs[REG_EBP];
2070 *sp = ucontext->uc_mcontext.gregs[REG_UESP];
2071# endif
2072#elif defined(__powerpc__) || defined(__powerpc64__)
2073 ucontext_t *ucontext = (ucontext_t*)context;
2074 *pc = ucontext->uc_mcontext.regs->nip;
2075 *sp = ucontext->uc_mcontext.regs->gpr[PT_R1];
2076 // The powerpc{,64}-linux ABIs do not specify r31 as the frame
2077 // pointer, but GCC always uses r31 when we need a frame pointer.
2078 *bp = ucontext->uc_mcontext.regs->gpr[PT_R31];
2079#elif defined(__sparc__)
2080#if defined(__arch64__) || defined(__sparcv9)
2081#define STACK_BIAS 2047
2082#else
2083#define STACK_BIAS 0
2084# endif
2085# if SANITIZER_SOLARIS0
2086 ucontext_t *ucontext = (ucontext_t *)context;
2087 *pc = ucontext->uc_mcontext.gregs[REG_PC];
2088 *sp = ucontext->uc_mcontext.gregs[REG_O6] + STACK_BIAS;
2089#else
2090 // Historical BSDism here.
2091 struct sigcontext *scontext = (struct sigcontext *)context;
2092#if defined(__arch64__)
2093 *pc = scontext->sigc_regs.tpc;
2094 *sp = scontext->sigc_regs.u_regs[14] + STACK_BIAS;
2095#else
2096 *pc = scontext->si_regs.pc;
2097 *sp = scontext->si_regs.u_regs[14];
2098#endif
2099# endif
2100 *bp = (uptr)((uhwptr *)*sp)[14] + STACK_BIAS;
2101#elif defined(__mips__)
2102 ucontext_t *ucontext = (ucontext_t*)context;
2103 *pc = ucontext->uc_mcontext.pc;
2104 *bp = ucontext->uc_mcontext.gregs[30];
2105 *sp = ucontext->uc_mcontext.gregs[29];
2106#elif defined(__s390__)
2107 ucontext_t *ucontext = (ucontext_t*)context;
2108# if defined(__s390x__)
2109 *pc = ucontext->uc_mcontext.psw.addr;
2110# else
2111 *pc = ucontext->uc_mcontext.psw.addr & 0x7fffffff;
2112# endif
2113 *bp = ucontext->uc_mcontext.gregs[11];
2114 *sp = ucontext->uc_mcontext.gregs[15];
2115#elif defined(__riscv)
2116 ucontext_t *ucontext = (ucontext_t*)context;
2117# if SANITIZER_FREEBSD0
2118 *pc = ucontext->uc_mcontext.mc_gpregs.gp_sepc;
2119 *bp = ucontext->uc_mcontext.mc_gpregs.gp_s[0];
2120 *sp = ucontext->uc_mcontext.mc_gpregs.gp_sp;
2121# else
2122 *pc = ucontext->uc_mcontext.__gregs[REG_PC];
2123 *bp = ucontext->uc_mcontext.__gregs[REG_S0];
2124 *sp = ucontext->uc_mcontext.__gregs[REG_SP];
2125# endif
2126# elif defined(__hexagon__)
2127 ucontext_t *ucontext = (ucontext_t *)context;
2128 *pc = ucontext->uc_mcontext.pc;
2129 *bp = ucontext->uc_mcontext.r30;
2130 *sp = ucontext->uc_mcontext.r29;
2131# else
2132# error "Unsupported arch"
2133# endif
2134}
2135
2136void SignalContext::InitPcSpBp() { GetPcSpBp(context, &pc, &sp, &bp); }
2137
2138void InitializePlatformEarly() {
2139 // Do nothing.
2140}
2141
2142void MaybeReexec() {
2143 // No need to re-exec on Linux.
2144}
2145
2146void CheckASLR() {
2147#if SANITIZER_NETBSD0
2148 int mib[3];
2149 int paxflags;
2150 uptr len = sizeof(paxflags);
2151
2152 mib[0] = CTL_PROC;
2153 mib[1] = internal_getpid();
2154 mib[2] = PROC_PID_PAXFLAGS;
2155
2156 if (UNLIKELY(internal_sysctl(mib, 3, &paxflags, &len, NULL, 0) == -1)__builtin_expect(!!(internal_sysctl(mib, 3, &paxflags, &
len, __null, 0) == -1), 0)
) {
2157 Printf("sysctl failed\n");
2158 Die();
2159 }
2160
2161 if (UNLIKELY(paxflags & CTL_PROC_PAXFLAGS_ASLR)__builtin_expect(!!(paxflags & CTL_PROC_PAXFLAGS_ASLR), 0
)
) {
2162 Printf("This sanitizer is not compatible with enabled ASLR.\n"
2163 "To disable ASLR, please run \"paxctl +a %s\" and try again.\n",
2164 GetArgv()[0]);
2165 Die();
2166 }
2167#elif SANITIZER_PPC64V20
2168 // Disable ASLR for Linux PPC64LE.
2169 int old_personality = personality(0xffffffff);
2170 if (old_personality != -1 && (old_personality & ADDR_NO_RANDOMIZE) == 0) {
2171 VReport(1, "WARNING: Program is being run with address space layout "do { if ((uptr)Verbosity() >= (1)) Report("WARNING: Program is being run with address space layout "
"randomization (ASLR) enabled which prevents the thread and "
"memory sanitizers from working on powerpc64le.\n" "ASLR will be disabled and the program re-executed.\n"
); } while (0)
2172 "randomization (ASLR) enabled which prevents the thread and "do { if ((uptr)Verbosity() >= (1)) Report("WARNING: Program is being run with address space layout "
"randomization (ASLR) enabled which prevents the thread and "
"memory sanitizers from working on powerpc64le.\n" "ASLR will be disabled and the program re-executed.\n"
); } while (0)
2173 "memory sanitizers from working on powerpc64le.\n"do { if ((uptr)Verbosity() >= (1)) Report("WARNING: Program is being run with address space layout "
"randomization (ASLR) enabled which prevents the thread and "
"memory sanitizers from working on powerpc64le.\n" "ASLR will be disabled and the program re-executed.\n"
); } while (0)
2174 "ASLR will be disabled and the program re-executed.\n")do { if ((uptr)Verbosity() >= (1)) Report("WARNING: Program is being run with address space layout "
"randomization (ASLR) enabled which prevents the thread and "
"memory sanitizers from working on powerpc64le.\n" "ASLR will be disabled and the program re-executed.\n"
); } while (0)
;
2175 CHECK_NE(personality(old_personality | ADDR_NO_RANDOMIZE), -1)do { __sanitizer::u64 v1 = (__sanitizer::u64)((personality(old_personality
| ADDR_NO_RANDOMIZE))); __sanitizer::u64 v2 = (__sanitizer::
u64)((-1)); if (__builtin_expect(!!(!(v1 != v2)), 0)) __sanitizer
::CheckFailed("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 2175, "(" "(personality(old_personality | ADDR_NO_RANDOMIZE))"
") " "!=" " (" "(-1)" ")", v1, v2); } while (false)
;
2176 ReExec();
2177 }
2178#elif SANITIZER_FREEBSD0
2179 int aslr_pie;
2180 uptr len = sizeof(aslr_pie);
2181#if SANITIZER_WORDSIZE64 == 64
2182 if (UNLIKELY(internal_sysctlbyname("kern.elf64.aslr.pie_enable",__builtin_expect(!!(internal_sysctlbyname("kern.elf64.aslr.pie_enable"
, &aslr_pie, &len, __null, 0) == -1), 0)
2183 &aslr_pie, &len, NULL, 0) == -1)__builtin_expect(!!(internal_sysctlbyname("kern.elf64.aslr.pie_enable"
, &aslr_pie, &len, __null, 0) == -1), 0)
) {
2184 // We're making things less 'dramatic' here since
2185 // the OID is not necessarily guaranteed to be here
2186 // just yet regarding FreeBSD release
2187 return;
2188 }
2189
2190 if (aslr_pie > 0) {
2191 Printf("This sanitizer is not compatible with enabled ASLR "
2192 "and binaries compiled with PIE\n");
2193 Die();
2194 }
2195#endif
2196 // there might be 32 bits compat for 64 bits
2197 if (UNLIKELY(internal_sysctlbyname("kern.elf32.aslr.pie_enable",__builtin_expect(!!(internal_sysctlbyname("kern.elf32.aslr.pie_enable"
, &aslr_pie, &len, __null, 0) == -1), 0)
2198 &aslr_pie, &len, NULL, 0) == -1)__builtin_expect(!!(internal_sysctlbyname("kern.elf32.aslr.pie_enable"
, &aslr_pie, &len, __null, 0) == -1), 0)
) {
2199 return;
2200 }
2201
2202 if (aslr_pie > 0) {
2203 Printf("This sanitizer is not compatible with enabled ASLR "
2204 "and binaries compiled with PIE\n");
2205 Die();
2206 }
2207#else
2208 // Do nothing
2209#endif
2210}
2211
2212void CheckMPROTECT() {
2213#if SANITIZER_NETBSD0
2214 int mib[3];
2215 int paxflags;
2216 uptr len = sizeof(paxflags);
2217
2218 mib[0] = CTL_PROC;
2219 mib[1] = internal_getpid();
2220 mib[2] = PROC_PID_PAXFLAGS;
2221
2222 if (UNLIKELY(internal_sysctl(mib, 3, &paxflags, &len, NULL, 0) == -1)__builtin_expect(!!(internal_sysctl(mib, 3, &paxflags, &
len, __null, 0) == -1), 0)
) {
2223 Printf("sysctl failed\n");
2224 Die();
2225 }
2226
2227 if (UNLIKELY(paxflags & CTL_PROC_PAXFLAGS_MPROTECT)__builtin_expect(!!(paxflags & CTL_PROC_PAXFLAGS_MPROTECT
), 0)
) {
2228 Printf("This sanitizer is not compatible with enabled MPROTECT\n");
2229 Die();
2230 }
2231#else
2232 // Do nothing
2233#endif
2234}
2235
2236void CheckNoDeepBind(const char *filename, int flag) {
2237#ifdef RTLD_DEEPBIND0x00008
2238 if (flag & RTLD_DEEPBIND0x00008) {
2239 Report(
2240 "You are trying to dlopen a %s shared library with RTLD_DEEPBIND flag"
2241 " which is incompatible with sanitizer runtime "
2242 "(see https://github.com/google/sanitizers/issues/611 for details"
2243 "). If you want to run %s library under sanitizers please remove "
2244 "RTLD_DEEPBIND from dlopen flags.\n",
2245 filename, filename);
2246 Die();
2247 }
2248#endif
2249}
2250
2251uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
2252 uptr *largest_gap_found,
2253 uptr *max_occupied_addr) {
2254 UNREACHABLE("FindAvailableMemoryRange is not available")do { do { __sanitizer::u64 v1 = (__sanitizer::u64)((0 &&
"FindAvailableMemoryRange is not available")); __sanitizer::
u64 v2 = (__sanitizer::u64)(0); if (__builtin_expect(!!(!(v1 !=
v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp"
, 2254, "(" "(0 && \"FindAvailableMemoryRange is not available\")"
") " "!=" " (" "0" ")", v1, v2); } while (false); Die(); } while
(0)
;
2255 return 0;
2256}
2257
2258bool GetRandom(void *buffer, uptr length, bool blocking) {
2259 if (!buffer || !length || length > 256)
2260 return false;
2261#if SANITIZER_USE_GETENTROPY0
2262 uptr rnd = getentropy(buffer, length);
2263 int rverrno = 0;
2264 if (internal_iserror(rnd, &rverrno) && rverrno == EFAULT14)
2265 return false;
2266 else if (rnd == 0)
2267 return true;
2268#endif // SANITIZER_USE_GETENTROPY
2269
2270#if SANITIZER_USE_GETRANDOM1
2271 static atomic_uint8_t skip_getrandom_syscall;
2272 if (!atomic_load_relaxed(&skip_getrandom_syscall)) {
2273 // Up to 256 bytes, getrandom will not be interrupted.
2274 uptr res = internal_syscall(SYSCALL(getrandom)318, buffer, length,
2275 blocking ? 0 : GRND_NONBLOCK1);
2276 int rverrno = 0;
2277 if (internal_iserror(res, &rverrno) && rverrno == ENOSYS38)
2278 atomic_store_relaxed(&skip_getrandom_syscall, 1);
2279 else if (res == length)
2280 return true;
2281 }
2282#endif // SANITIZER_USE_GETRANDOM
2283 // Up to 256 bytes, a read off /dev/urandom will not be interrupted.
2284 // blocking is moot here, O_NONBLOCK has no effect when opening /dev/urandom.
2285 uptr fd = internal_open("/dev/urandom", O_RDONLY00);
2286 if (internal_iserror(fd))
2287 return false;
2288 uptr res = internal_read(fd, buffer, length);
2289 if (internal_iserror(res))
2290 return false;
2291 internal_close(fd);
2292 return true;
2293}
2294
2295} // namespace __sanitizer
2296
2297#endif

/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/compiler-rt/lib/sanitizer_common/sanitizer_syscall_linux_x86_64.inc

1//===-- sanitizer_syscall_linux_x86_64.inc ----------------------*- C++ -*-===//
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// Implementations of internal_syscall and internal_iserror for Linux/x86_64.
10//
11//===----------------------------------------------------------------------===//
12
13#define SYSCALL(name)__NR_name __NR_ ## name
14
15static uptr internal_syscall(u64 nr) {
16 u64 retval;
17 asm volatile("syscall" : "=a"(retval) : "a"(nr) : "rcx", "r11",
18 "memory", "cc");
19 return retval;
20}
21
22template <typename T1>
23static uptr internal_syscall(u64 nr, T1 arg1) {
24 u64 retval;
25 asm volatile("syscall" : "=a"(retval) : "a"(nr), "D"((u64)arg1) :
26 "rcx", "r11", "memory", "cc");
27 return retval;
28}
29
30template <typename T1, typename T2>
31static uptr internal_syscall(u64 nr, T1 arg1, T2 arg2) {
32 u64 retval;
33 asm volatile("syscall" : "=a"(retval) : "a"(nr), "D"((u64)arg1),
34 "S"((u64)arg2) : "rcx", "r11", "memory", "cc");
35 return retval;
5
Returning without writing to 'arg2->st_mode'
36}
37
38template <typename T1, typename T2, typename T3>
39static uptr internal_syscall(u64 nr, T1 arg1, T2 arg2, T3 arg3) {
40 u64 retval;
41 asm volatile("syscall" : "=a"(retval) : "a"(nr), "D"((u64)arg1),
42 "S"((u64)arg2), "d"((u64)arg3) : "rcx", "r11", "memory", "cc");
43 return retval;
44}
45
46template <typename T1, typename T2, typename T3, typename T4>
47static uptr internal_syscall(u64 nr, T1 arg1, T2 arg2, T3 arg3, T4 arg4) {
48 u64 retval;
49 asm volatile("mov %5, %%r10;"
50 "syscall" : "=a"(retval) : "a"(nr), "D"((u64)arg1),
51 "S"((u64)arg2), "d"((u64)arg3), "r"((u64)arg4) :
52 "rcx", "r11", "r10", "memory", "cc");
53 return retval;
54}
55
56template <typename T1, typename T2, typename T3, typename T4, typename T5>
57static uptr internal_syscall(u64 nr, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
58 T5 arg5) {
59 u64 retval;
60 asm volatile("mov %5, %%r10;"
61 "mov %6, %%r8;"
62 "syscall" : "=a"(retval) : "a"(nr), "D"((u64)arg1),
63 "S"((u64)arg2), "d"((u64)arg3), "r"((u64)arg4), "r"((u64)arg5) :
64 "rcx", "r11", "r10", "r8", "memory", "cc");
65 return retval;
66}
67
68template <typename T1, typename T2, typename T3, typename T4, typename T5,
69 typename T6>
70static uptr internal_syscall(u64 nr, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
71 T5 arg5, T6 arg6) {
72 u64 retval;
73 asm volatile("mov %5, %%r10;"
74 "mov %6, %%r8;"
75 "mov %7, %%r9;"
76 "syscall" : "=a"(retval) : "a"(nr), "D"((u64)arg1),
77 "S"((u64)arg2), "d"((u64)arg3), "r"((u64)arg4), "r"((u64)arg5),
78 "r"((u64)arg6) : "rcx", "r11", "r10", "r8", "r9",
79 "memory", "cc");
80 return retval;
81}
82
83bool internal_iserror(uptr retval, int *rverrno) {
84 if (retval >= (uptr)-4095) {
85 if (rverrno)
86 *rverrno = -retval;
87 return true;
88 }
89 return false;
90}