Bug Summary

File:compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp
Warning:line 378, column 3
Undefined or garbage value returned to caller

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -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 -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.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 /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/projects/compiler-rt/lib/sanitizer_common -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/compiler-rt/lib/sanitizer_common -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/compiler-rt/lib/sanitizer_common/.. -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O3 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -Wno-unused-parameter -Wno-variadic-macros -Wno-non-virtual-dtor -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/projects/compiler-rt/lib/sanitizer_common -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b=. -ferror-limit 19 -fvisibility hidden -fvisibility-inlines-hidden -fno-builtin -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-09-17-195756-12974-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp

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

/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/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;
3
Returning without writing to 'arg2->st_size'
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}