Bug Summary

File:projects/compiler-rt/lib/sanitizer_common/sanitizer_linux.cc
Warning:line 379, 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-9/lib/clang/9.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-9~svn362543/build-llvm/projects/compiler-rt/lib/sanitizer_common -I /build/llvm-toolchain-snapshot-9~svn362543/projects/compiler-rt/lib/sanitizer_common -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn362543/include -I /build/llvm-toolchain-snapshot-9~svn362543/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/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.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-9~svn362543/build-llvm/projects/compiler-rt/lib/sanitizer_common -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn362543=. -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-2019-06-05-060531-1271-1 -x c++ /build/llvm-toolchain-snapshot-9~svn362543/projects/compiler-rt/lib/sanitizer_common/sanitizer_linux.cc -faddrsig

/build/llvm-toolchain-snapshot-9~svn362543/projects/compiler-rt/lib/sanitizer_common/sanitizer_linux.cc

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

/build/llvm-toolchain-snapshot-9~svn362543/projects/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}