Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name sanitizer_linux.cc -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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D HAVE_RPC_XDR_H=0 -D HAVE_TIRPC_RPC_XDR_H=0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/projects/compiler-rt/lib/sanitizer_common -I /build/llvm-toolchain-snapshot-8~svn350071/projects/compiler-rt/lib/sanitizer_common -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn350071/include -I /build/llvm-toolchain-snapshot-8~svn350071/projects/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/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.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++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/projects/compiler-rt/lib/sanitizer_common -fdebug-prefix-map=/build/llvm-toolchain-snapshot-8~svn350071=. -ferror-limit 19 -fmessage-length 0 -fvisibility hidden -fvisibility-inlines-hidden -fno-builtin -fno-rtti -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-12-27-042839-1215-1 -x c++ /build/llvm-toolchain-snapshot-8~svn350071/projects/compiler-rt/lib/sanitizer_common/sanitizer_linux.cc -faddrsig

/build/llvm-toolchain-snapshot-8~svn350071/projects/compiler-rt/lib/sanitizer_common/sanitizer_linux.cc

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

/build/llvm-toolchain-snapshot-8~svn350071/projects/compiler-rt/lib/sanitizer_common/sanitizer_syscall_linux_x86_64.inc

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