Clean up some minor white space issues in trans-decl.c and trans-expr.c
[official-gcc.git] / libsanitizer / sanitizer_common / sanitizer_linux.cc
blob2cefa20a5f0832308d6bf8c41126e894181f7164
1 //===-- sanitizer_linux.cc ------------------------------------------------===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This file is shared between AddressSanitizer and ThreadSanitizer
9 // run-time libraries and implements linux-specific functions from
10 // sanitizer_libc.h.
11 //===----------------------------------------------------------------------===//
13 #include "sanitizer_platform.h"
15 #if SANITIZER_FREEBSD || SANITIZER_LINUX
17 #include "sanitizer_common.h"
18 #include "sanitizer_flags.h"
19 #include "sanitizer_internal_defs.h"
20 #include "sanitizer_libc.h"
21 #include "sanitizer_linux.h"
22 #include "sanitizer_mutex.h"
23 #include "sanitizer_placement_new.h"
24 #include "sanitizer_procmaps.h"
25 #include "sanitizer_stacktrace.h"
26 #include "sanitizer_symbolizer.h"
28 #if !SANITIZER_FREEBSD
29 #include <asm/param.h>
30 #endif
32 // For mips64, syscall(__NR_stat) fills the buffer in the 'struct kernel_stat'
33 // format. Struct kernel_stat is defined as 'struct stat' in asm/stat.h. To
34 // access stat from asm/stat.h, without conflicting with definition in
35 // sys/stat.h, we use this trick.
36 #if defined(__mips64)
37 #include <asm/unistd.h>
38 #include <sys/types.h>
39 #define stat kernel_stat
40 #include <asm/stat.h>
41 #undef stat
42 #endif
44 #include <dlfcn.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <link.h>
48 #include <pthread.h>
49 #include <sched.h>
50 #include <sys/mman.h>
51 #include <sys/ptrace.h>
52 #include <sys/resource.h>
53 #include <sys/stat.h>
54 #include <sys/syscall.h>
55 #include <sys/time.h>
56 #include <sys/types.h>
57 #include <ucontext.h>
58 #include <unistd.h>
60 #if SANITIZER_FREEBSD
61 #include <sys/sysctl.h>
62 #include <machine/atomic.h>
63 extern "C" {
64 // <sys/umtx.h> must be included after <errno.h> and <sys/types.h> on
65 // FreeBSD 9.2 and 10.0.
66 #include <sys/umtx.h>
68 extern char **environ; // provided by crt1
69 #endif // SANITIZER_FREEBSD
71 #if !SANITIZER_ANDROID
72 #include <sys/signal.h>
73 #endif
75 #if SANITIZER_LINUX
76 // <linux/time.h>
77 struct kernel_timeval {
78 long tv_sec;
79 long tv_usec;
82 // <linux/futex.h> is broken on some linux distributions.
83 const int FUTEX_WAIT = 0;
84 const int FUTEX_WAKE = 1;
85 #endif // SANITIZER_LINUX
87 // Are we using 32-bit or 64-bit Linux syscalls?
88 // x32 (which defines __x86_64__) has SANITIZER_WORDSIZE == 32
89 // but it still needs to use 64-bit syscalls.
90 #if SANITIZER_LINUX && (defined(__x86_64__) || SANITIZER_WORDSIZE == 64)
91 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 1
92 #else
93 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 0
94 #endif
96 namespace __sanitizer {
98 #if SANITIZER_LINUX && defined(__x86_64__)
99 #include "sanitizer_syscall_linux_x86_64.inc"
100 #elif SANITIZER_LINUX && defined(__aarch64__)
101 #include "sanitizer_syscall_linux_aarch64.inc"
102 #else
103 #include "sanitizer_syscall_generic.inc"
104 #endif
106 // --------------- sanitizer_libc.h
107 uptr internal_mmap(void *addr, uptr length, int prot, int flags, int fd,
108 OFF_T offset) {
109 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
110 return internal_syscall(SYSCALL(mmap), (uptr)addr, length, prot, flags, fd,
111 offset);
112 #else
113 // mmap2 specifies file offset in 4096-byte units.
114 CHECK(IsAligned(offset, 4096));
115 return internal_syscall(SYSCALL(mmap2), addr, length, prot, flags, fd,
116 offset / 4096);
117 #endif
120 uptr internal_munmap(void *addr, uptr length) {
121 return internal_syscall(SYSCALL(munmap), (uptr)addr, length);
124 int internal_mprotect(void *addr, uptr length, int prot) {
125 return internal_syscall(SYSCALL(mprotect), (uptr)addr, length, prot);
128 uptr internal_close(fd_t fd) {
129 return internal_syscall(SYSCALL(close), fd);
132 uptr internal_open(const char *filename, int flags) {
133 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
134 return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags);
135 #else
136 return internal_syscall(SYSCALL(open), (uptr)filename, flags);
137 #endif
140 uptr internal_open(const char *filename, int flags, u32 mode) {
141 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
142 return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags,
143 mode);
144 #else
145 return internal_syscall(SYSCALL(open), (uptr)filename, flags, mode);
146 #endif
149 uptr internal_read(fd_t fd, void *buf, uptr count) {
150 sptr res;
151 HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(read), fd, (uptr)buf,
152 count));
153 return res;
156 uptr internal_write(fd_t fd, const void *buf, uptr count) {
157 sptr res;
158 HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(write), fd, (uptr)buf,
159 count));
160 return res;
163 uptr internal_ftruncate(fd_t fd, uptr size) {
164 sptr res;
165 HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(ftruncate), fd,
166 (OFF_T)size));
167 return res;
170 #if !SANITIZER_LINUX_USES_64BIT_SYSCALLS && !SANITIZER_FREEBSD
171 static void stat64_to_stat(struct stat64 *in, struct stat *out) {
172 internal_memset(out, 0, sizeof(*out));
173 out->st_dev = in->st_dev;
174 out->st_ino = in->st_ino;
175 out->st_mode = in->st_mode;
176 out->st_nlink = in->st_nlink;
177 out->st_uid = in->st_uid;
178 out->st_gid = in->st_gid;
179 out->st_rdev = in->st_rdev;
180 out->st_size = in->st_size;
181 out->st_blksize = in->st_blksize;
182 out->st_blocks = in->st_blocks;
183 out->st_atime = in->st_atime;
184 out->st_mtime = in->st_mtime;
185 out->st_ctime = in->st_ctime;
186 out->st_ino = in->st_ino;
188 #endif
190 #if defined(__mips64)
191 static void kernel_stat_to_stat(struct kernel_stat *in, struct stat *out) {
192 internal_memset(out, 0, sizeof(*out));
193 out->st_dev = in->st_dev;
194 out->st_ino = in->st_ino;
195 out->st_mode = in->st_mode;
196 out->st_nlink = in->st_nlink;
197 out->st_uid = in->st_uid;
198 out->st_gid = in->st_gid;
199 out->st_rdev = in->st_rdev;
200 out->st_size = in->st_size;
201 out->st_blksize = in->st_blksize;
202 out->st_blocks = in->st_blocks;
203 out->st_atime = in->st_atime_nsec;
204 out->st_mtime = in->st_mtime_nsec;
205 out->st_ctime = in->st_ctime_nsec;
206 out->st_ino = in->st_ino;
208 #endif
210 uptr internal_stat(const char *path, void *buf) {
211 #if SANITIZER_FREEBSD
212 return internal_syscall(SYSCALL(stat), path, buf);
213 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
214 return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path,
215 (uptr)buf, 0);
216 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
217 # if defined(__mips64)
218 // For mips64, stat syscall fills buffer in the format of kernel_stat
219 struct kernel_stat kbuf;
220 int res = internal_syscall(SYSCALL(stat), path, &kbuf);
221 kernel_stat_to_stat(&kbuf, (struct stat *)buf);
222 return res;
223 # else
224 return internal_syscall(SYSCALL(stat), (uptr)path, (uptr)buf);
225 # endif
226 #else
227 struct stat64 buf64;
228 int res = internal_syscall(SYSCALL(stat64), path, &buf64);
229 stat64_to_stat(&buf64, (struct stat *)buf);
230 return res;
231 #endif
234 uptr internal_lstat(const char *path, void *buf) {
235 #if SANITIZER_FREEBSD
236 return internal_syscall(SYSCALL(lstat), path, buf);
237 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
238 return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path,
239 (uptr)buf, AT_SYMLINK_NOFOLLOW);
240 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
241 return internal_syscall(SYSCALL(lstat), (uptr)path, (uptr)buf);
242 #else
243 struct stat64 buf64;
244 int res = internal_syscall(SYSCALL(lstat64), path, &buf64);
245 stat64_to_stat(&buf64, (struct stat *)buf);
246 return res;
247 #endif
250 uptr internal_fstat(fd_t fd, void *buf) {
251 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
252 return internal_syscall(SYSCALL(fstat), fd, (uptr)buf);
253 #else
254 struct stat64 buf64;
255 int res = internal_syscall(SYSCALL(fstat64), fd, &buf64);
256 stat64_to_stat(&buf64, (struct stat *)buf);
257 return res;
258 #endif
261 uptr internal_filesize(fd_t fd) {
262 struct stat st;
263 if (internal_fstat(fd, &st))
264 return -1;
265 return (uptr)st.st_size;
268 uptr internal_dup2(int oldfd, int newfd) {
269 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
270 return internal_syscall(SYSCALL(dup3), oldfd, newfd, 0);
271 #else
272 return internal_syscall(SYSCALL(dup2), oldfd, newfd);
273 #endif
276 uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
277 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
278 return internal_syscall(SYSCALL(readlinkat), AT_FDCWD,
279 (uptr)path, (uptr)buf, bufsize);
280 #else
281 return internal_syscall(SYSCALL(readlink), (uptr)path, (uptr)buf, bufsize);
282 #endif
285 uptr internal_unlink(const char *path) {
286 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
287 return internal_syscall(SYSCALL(unlinkat), AT_FDCWD, (uptr)path, 0);
288 #else
289 return internal_syscall(SYSCALL(unlink), (uptr)path);
290 #endif
293 uptr internal_rename(const char *oldpath, const char *newpath) {
294 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
295 return internal_syscall(SYSCALL(renameat), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
296 (uptr)newpath);
297 #else
298 return internal_syscall(SYSCALL(rename), (uptr)oldpath, (uptr)newpath);
299 #endif
302 uptr internal_sched_yield() {
303 return internal_syscall(SYSCALL(sched_yield));
306 void internal__exit(int exitcode) {
307 #if SANITIZER_FREEBSD
308 internal_syscall(SYSCALL(exit), exitcode);
309 #else
310 internal_syscall(SYSCALL(exit_group), exitcode);
311 #endif
312 Die(); // Unreachable.
315 uptr internal_execve(const char *filename, char *const argv[],
316 char *const envp[]) {
317 return internal_syscall(SYSCALL(execve), (uptr)filename, (uptr)argv,
318 (uptr)envp);
321 // ----------------- sanitizer_common.h
322 bool FileExists(const char *filename) {
323 struct stat st;
324 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
325 if (internal_syscall(SYSCALL(newfstatat), AT_FDCWD, filename, &st, 0))
326 #else
327 if (internal_stat(filename, &st))
328 #endif
329 return false;
330 // Sanity check: filename is a regular file.
331 return S_ISREG(st.st_mode);
334 uptr GetTid() {
335 #if SANITIZER_FREEBSD
336 return (uptr)pthread_self();
337 #else
338 return internal_syscall(SYSCALL(gettid));
339 #endif
342 u64 NanoTime() {
343 #if SANITIZER_FREEBSD
344 timeval tv;
345 #else
346 kernel_timeval tv;
347 #endif
348 internal_memset(&tv, 0, sizeof(tv));
349 internal_syscall(SYSCALL(gettimeofday), (uptr)&tv, 0);
350 return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
353 // Like getenv, but reads env directly from /proc (on Linux) or parses the
354 // 'environ' array (on FreeBSD) and does not use libc. This function should be
355 // called first inside __asan_init.
356 const char *GetEnv(const char *name) {
357 #if SANITIZER_FREEBSD
358 if (::environ != 0) {
359 uptr NameLen = internal_strlen(name);
360 for (char **Env = ::environ; *Env != 0; Env++) {
361 if (internal_strncmp(*Env, name, NameLen) == 0 && (*Env)[NameLen] == '=')
362 return (*Env) + NameLen + 1;
365 return 0; // Not found.
366 #elif SANITIZER_LINUX
367 static char *environ;
368 static uptr len;
369 static bool inited;
370 if (!inited) {
371 inited = true;
372 uptr environ_size;
373 if (!ReadFileToBuffer("/proc/self/environ", &environ, &environ_size, &len))
374 environ = nullptr;
376 if (!environ || len == 0) return nullptr;
377 uptr namelen = internal_strlen(name);
378 const char *p = environ;
379 while (*p != '\0') { // will happen at the \0\0 that terminates the buffer
380 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
381 const char* endp =
382 (char*)internal_memchr(p, '\0', len - (p - environ));
383 if (!endp) // this entry isn't NUL terminated
384 return nullptr;
385 else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') // Match.
386 return p + namelen + 1; // point after =
387 p = endp + 1;
389 return nullptr; // Not found.
390 #else
391 #error "Unsupported platform"
392 #endif
395 extern "C" {
396 SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
399 #if !SANITIZER_GO
400 static void ReadNullSepFileToArray(const char *path, char ***arr,
401 int arr_size) {
402 char *buff;
403 uptr buff_size;
404 uptr buff_len;
405 *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
406 if (!ReadFileToBuffer(path, &buff, &buff_size, &buff_len, 1024 * 1024)) {
407 (*arr)[0] = nullptr;
408 return;
410 (*arr)[0] = buff;
411 int count, i;
412 for (count = 1, i = 1; ; i++) {
413 if (buff[i] == 0) {
414 if (buff[i+1] == 0) break;
415 (*arr)[count] = &buff[i+1];
416 CHECK_LE(count, arr_size - 1); // FIXME: make this more flexible.
417 count++;
420 (*arr)[count] = nullptr;
422 #endif
424 static void GetArgsAndEnv(char*** argv, char*** envp) {
425 #if !SANITIZER_GO
426 if (&__libc_stack_end) {
427 #endif
428 uptr* stack_end = (uptr*)__libc_stack_end;
429 int argc = *stack_end;
430 *argv = (char**)(stack_end + 1);
431 *envp = (char**)(stack_end + argc + 2);
432 #if !SANITIZER_GO
433 } else {
434 static const int kMaxArgv = 2000, kMaxEnvp = 2000;
435 ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
436 ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
438 #endif
441 void ReExec() {
442 char **argv, **envp;
443 GetArgsAndEnv(&argv, &envp);
444 uptr rv = internal_execve("/proc/self/exe", argv, envp);
445 int rverrno;
446 CHECK_EQ(internal_iserror(rv, &rverrno), true);
447 Printf("execve failed, errno %d\n", rverrno);
448 Die();
451 enum MutexState {
452 MtxUnlocked = 0,
453 MtxLocked = 1,
454 MtxSleeping = 2
457 BlockingMutex::BlockingMutex() {
458 internal_memset(this, 0, sizeof(*this));
461 void BlockingMutex::Lock() {
462 CHECK_EQ(owner_, 0);
463 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
464 if (atomic_exchange(m, MtxLocked, memory_order_acquire) == MtxUnlocked)
465 return;
466 while (atomic_exchange(m, MtxSleeping, memory_order_acquire) != MtxUnlocked) {
467 #if SANITIZER_FREEBSD
468 _umtx_op(m, UMTX_OP_WAIT_UINT, MtxSleeping, 0, 0);
469 #else
470 internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAIT, MtxSleeping, 0, 0, 0);
471 #endif
475 void BlockingMutex::Unlock() {
476 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
477 u32 v = atomic_exchange(m, MtxUnlocked, memory_order_relaxed);
478 CHECK_NE(v, MtxUnlocked);
479 if (v == MtxSleeping) {
480 #if SANITIZER_FREEBSD
481 _umtx_op(m, UMTX_OP_WAKE, 1, 0, 0);
482 #else
483 internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAKE, 1, 0, 0, 0);
484 #endif
488 void BlockingMutex::CheckLocked() {
489 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
490 CHECK_NE(MtxUnlocked, atomic_load(m, memory_order_relaxed));
493 // ----------------- sanitizer_linux.h
494 // The actual size of this structure is specified by d_reclen.
495 // Note that getdents64 uses a different structure format. We only provide the
496 // 32-bit syscall here.
497 struct linux_dirent {
498 #if SANITIZER_X32 || defined(__aarch64__)
499 u64 d_ino;
500 u64 d_off;
501 #else
502 unsigned long d_ino;
503 unsigned long d_off;
504 #endif
505 unsigned short d_reclen;
506 #ifdef __aarch64__
507 unsigned char d_type;
508 #endif
509 char d_name[256];
512 // Syscall wrappers.
513 uptr internal_ptrace(int request, int pid, void *addr, void *data) {
514 return internal_syscall(SYSCALL(ptrace), request, pid, (uptr)addr,
515 (uptr)data);
518 uptr internal_waitpid(int pid, int *status, int options) {
519 return internal_syscall(SYSCALL(wait4), pid, (uptr)status, options,
520 0 /* rusage */);
523 uptr internal_getpid() {
524 return internal_syscall(SYSCALL(getpid));
527 uptr internal_getppid() {
528 return internal_syscall(SYSCALL(getppid));
531 uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) {
532 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
533 return internal_syscall(SYSCALL(getdents64), fd, (uptr)dirp, count);
534 #else
535 return internal_syscall(SYSCALL(getdents), fd, (uptr)dirp, count);
536 #endif
539 uptr internal_lseek(fd_t fd, OFF_T offset, int whence) {
540 return internal_syscall(SYSCALL(lseek), fd, offset, whence);
543 #if SANITIZER_LINUX
544 uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
545 return internal_syscall(SYSCALL(prctl), option, arg2, arg3, arg4, arg5);
547 #endif
549 uptr internal_sigaltstack(const struct sigaltstack *ss,
550 struct sigaltstack *oss) {
551 return internal_syscall(SYSCALL(sigaltstack), (uptr)ss, (uptr)oss);
554 int internal_fork() {
555 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
556 return internal_syscall(SYSCALL(clone), SIGCHLD, 0);
557 #else
558 return internal_syscall(SYSCALL(fork));
559 #endif
562 #if SANITIZER_LINUX
563 #define SA_RESTORER 0x04000000
564 // Doesn't set sa_restorer, use with caution (see below).
565 int internal_sigaction_norestorer(int signum, const void *act, void *oldact) {
566 __sanitizer_kernel_sigaction_t k_act, k_oldact;
567 internal_memset(&k_act, 0, sizeof(__sanitizer_kernel_sigaction_t));
568 internal_memset(&k_oldact, 0, sizeof(__sanitizer_kernel_sigaction_t));
569 const __sanitizer_sigaction *u_act = (const __sanitizer_sigaction *)act;
570 __sanitizer_sigaction *u_oldact = (__sanitizer_sigaction *)oldact;
571 if (u_act) {
572 k_act.handler = u_act->handler;
573 k_act.sigaction = u_act->sigaction;
574 internal_memcpy(&k_act.sa_mask, &u_act->sa_mask,
575 sizeof(__sanitizer_kernel_sigset_t));
576 // Without SA_RESTORER kernel ignores the calls (probably returns EINVAL).
577 k_act.sa_flags = u_act->sa_flags | SA_RESTORER;
578 // FIXME: most often sa_restorer is unset, however the kernel requires it
579 // to point to a valid signal restorer that calls the rt_sigreturn syscall.
580 // If sa_restorer passed to the kernel is NULL, the program may crash upon
581 // signal delivery or fail to unwind the stack in the signal handler.
582 // libc implementation of sigaction() passes its own restorer to
583 // rt_sigaction, so we need to do the same (we'll need to reimplement the
584 // restorers; for x86_64 the restorer address can be obtained from
585 // oldact->sa_restorer upon a call to sigaction(xxx, NULL, oldact).
586 k_act.sa_restorer = u_act->sa_restorer;
589 uptr result = internal_syscall(SYSCALL(rt_sigaction), (uptr)signum,
590 (uptr)(u_act ? &k_act : nullptr),
591 (uptr)(u_oldact ? &k_oldact : nullptr),
592 (uptr)sizeof(__sanitizer_kernel_sigset_t));
594 if ((result == 0) && u_oldact) {
595 u_oldact->handler = k_oldact.handler;
596 u_oldact->sigaction = k_oldact.sigaction;
597 internal_memcpy(&u_oldact->sa_mask, &k_oldact.sa_mask,
598 sizeof(__sanitizer_kernel_sigset_t));
599 u_oldact->sa_flags = k_oldact.sa_flags;
600 u_oldact->sa_restorer = k_oldact.sa_restorer;
602 return result;
604 #endif // SANITIZER_LINUX
606 uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
607 __sanitizer_sigset_t *oldset) {
608 #if SANITIZER_FREEBSD
609 return internal_syscall(SYSCALL(sigprocmask), how, set, oldset);
610 #else
611 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
612 __sanitizer_kernel_sigset_t *k_oldset = (__sanitizer_kernel_sigset_t *)oldset;
613 return internal_syscall(SYSCALL(rt_sigprocmask), (uptr)how,
614 (uptr)&k_set->sig[0], (uptr)&k_oldset->sig[0],
615 sizeof(__sanitizer_kernel_sigset_t));
616 #endif
619 void internal_sigfillset(__sanitizer_sigset_t *set) {
620 internal_memset(set, 0xff, sizeof(*set));
623 #if SANITIZER_LINUX
624 void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
625 signum -= 1;
626 CHECK_GE(signum, 0);
627 CHECK_LT(signum, sizeof(*set) * 8);
628 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
629 const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
630 const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
631 k_set->sig[idx] &= ~(1 << bit);
633 #endif // SANITIZER_LINUX
635 // ThreadLister implementation.
636 ThreadLister::ThreadLister(int pid)
637 : pid_(pid),
638 descriptor_(-1),
639 buffer_(4096),
640 error_(true),
641 entry_((struct linux_dirent *)buffer_.data()),
642 bytes_read_(0) {
643 char task_directory_path[80];
644 internal_snprintf(task_directory_path, sizeof(task_directory_path),
645 "/proc/%d/task/", pid);
646 uptr openrv = internal_open(task_directory_path, O_RDONLY | O_DIRECTORY);
647 if (internal_iserror(openrv)) {
648 error_ = true;
649 Report("Can't open /proc/%d/task for reading.\n", pid);
650 } else {
651 error_ = false;
652 descriptor_ = openrv;
656 int ThreadLister::GetNextTID() {
657 int tid = -1;
658 do {
659 if (error_)
660 return -1;
661 if ((char *)entry_ >= &buffer_[bytes_read_] && !GetDirectoryEntries())
662 return -1;
663 if (entry_->d_ino != 0 && entry_->d_name[0] >= '0' &&
664 entry_->d_name[0] <= '9') {
665 // Found a valid tid.
666 tid = (int)internal_atoll(entry_->d_name);
668 entry_ = (struct linux_dirent *)(((char *)entry_) + entry_->d_reclen);
669 } while (tid < 0);
670 return tid;
673 void ThreadLister::Reset() {
674 if (error_ || descriptor_ < 0)
675 return;
676 internal_lseek(descriptor_, 0, SEEK_SET);
679 ThreadLister::~ThreadLister() {
680 if (descriptor_ >= 0)
681 internal_close(descriptor_);
684 bool ThreadLister::error() { return error_; }
686 bool ThreadLister::GetDirectoryEntries() {
687 CHECK_GE(descriptor_, 0);
688 CHECK_NE(error_, true);
689 bytes_read_ = internal_getdents(descriptor_,
690 (struct linux_dirent *)buffer_.data(),
691 buffer_.size());
692 if (internal_iserror(bytes_read_)) {
693 Report("Can't read directory entries from /proc/%d/task.\n", pid_);
694 error_ = true;
695 return false;
696 } else if (bytes_read_ == 0) {
697 return false;
699 entry_ = (struct linux_dirent *)buffer_.data();
700 return true;
703 uptr GetPageSize() {
704 #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__))
705 return EXEC_PAGESIZE;
706 #else
707 return sysconf(_SC_PAGESIZE); // EXEC_PAGESIZE may not be trustworthy.
708 #endif
711 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
712 #if SANITIZER_FREEBSD
713 const int Mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
714 const char *default_module_name = "kern.proc.pathname";
715 size_t Size = buf_len;
716 bool IsErr = (sysctl(Mib, ARRAY_SIZE(Mib), buf, &Size, NULL, 0) != 0);
717 int readlink_error = IsErr ? errno : 0;
718 uptr module_name_len = Size;
719 #else
720 const char *default_module_name = "/proc/self/exe";
721 uptr module_name_len = internal_readlink(
722 default_module_name, buf, buf_len);
723 int readlink_error;
724 bool IsErr = internal_iserror(module_name_len, &readlink_error);
725 #endif
726 if (IsErr) {
727 // We can't read binary name for some reason, assume it's unknown.
728 Report("WARNING: reading executable name failed with errno %d, "
729 "some stack frames may not be symbolized\n", readlink_error);
730 module_name_len = internal_snprintf(buf, buf_len, "%s",
731 default_module_name);
732 CHECK_LT(module_name_len, buf_len);
734 return module_name_len;
737 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len) {
738 #if SANITIZER_LINUX
739 char *tmpbuf;
740 uptr tmpsize;
741 uptr tmplen;
742 if (ReadFileToBuffer("/proc/self/cmdline", &tmpbuf, &tmpsize, &tmplen,
743 1024 * 1024)) {
744 internal_strncpy(buf, tmpbuf, buf_len);
745 UnmapOrDie(tmpbuf, tmpsize);
746 return internal_strlen(buf);
748 #endif
749 return ReadBinaryName(buf, buf_len);
752 // Match full names of the form /path/to/base_name{-,.}*
753 bool LibraryNameIs(const char *full_name, const char *base_name) {
754 const char *name = full_name;
755 // Strip path.
756 while (*name != '\0') name++;
757 while (name > full_name && *name != '/') name--;
758 if (*name == '/') name++;
759 uptr base_name_length = internal_strlen(base_name);
760 if (internal_strncmp(name, base_name, base_name_length)) return false;
761 return (name[base_name_length] == '-' || name[base_name_length] == '.');
764 #if !SANITIZER_ANDROID
765 // Call cb for each region mapped by map.
766 void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr)) {
767 CHECK_NE(map, nullptr);
768 #if !SANITIZER_FREEBSD
769 typedef ElfW(Phdr) Elf_Phdr;
770 typedef ElfW(Ehdr) Elf_Ehdr;
771 #endif // !SANITIZER_FREEBSD
772 char *base = (char *)map->l_addr;
773 Elf_Ehdr *ehdr = (Elf_Ehdr *)base;
774 char *phdrs = base + ehdr->e_phoff;
775 char *phdrs_end = phdrs + ehdr->e_phnum * ehdr->e_phentsize;
777 // Find the segment with the minimum base so we can "relocate" the p_vaddr
778 // fields. Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
779 // objects have a non-zero base.
780 uptr preferred_base = (uptr)-1;
781 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
782 Elf_Phdr *phdr = (Elf_Phdr *)iter;
783 if (phdr->p_type == PT_LOAD && preferred_base > (uptr)phdr->p_vaddr)
784 preferred_base = (uptr)phdr->p_vaddr;
787 // Compute the delta from the real base to get a relocation delta.
788 sptr delta = (uptr)base - preferred_base;
789 // Now we can figure out what the loader really mapped.
790 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
791 Elf_Phdr *phdr = (Elf_Phdr *)iter;
792 if (phdr->p_type == PT_LOAD) {
793 uptr seg_start = phdr->p_vaddr + delta;
794 uptr seg_end = seg_start + phdr->p_memsz;
795 // None of these values are aligned. We consider the ragged edges of the
796 // load command as defined, since they are mapped from the file.
797 seg_start = RoundDownTo(seg_start, GetPageSizeCached());
798 seg_end = RoundUpTo(seg_end, GetPageSizeCached());
799 cb((void *)seg_start, seg_end - seg_start);
803 #endif
805 #if defined(__x86_64__) && SANITIZER_LINUX
806 // We cannot use glibc's clone wrapper, because it messes with the child
807 // task's TLS. It writes the PID and TID of the child task to its thread
808 // descriptor, but in our case the child task shares the thread descriptor with
809 // the parent (because we don't know how to allocate a new thread
810 // descriptor to keep glibc happy). So the stock version of clone(), when
811 // used with CLONE_VM, would end up corrupting the parent's thread descriptor.
812 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
813 int *parent_tidptr, void *newtls, int *child_tidptr) {
814 long long res;
815 if (!fn || !child_stack)
816 return -EINVAL;
817 CHECK_EQ(0, (uptr)child_stack % 16);
818 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
819 ((unsigned long long *)child_stack)[0] = (uptr)fn;
820 ((unsigned long long *)child_stack)[1] = (uptr)arg;
821 register void *r8 __asm__("r8") = newtls;
822 register int *r10 __asm__("r10") = child_tidptr;
823 __asm__ __volatile__(
824 /* %rax = syscall(%rax = SYSCALL(clone),
825 * %rdi = flags,
826 * %rsi = child_stack,
827 * %rdx = parent_tidptr,
828 * %r8 = new_tls,
829 * %r10 = child_tidptr)
831 "syscall\n"
833 /* if (%rax != 0)
834 * return;
836 "testq %%rax,%%rax\n"
837 "jnz 1f\n"
839 /* In the child. Terminate unwind chain. */
840 // XXX: We should also terminate the CFI unwind chain
841 // here. Unfortunately clang 3.2 doesn't support the
842 // necessary CFI directives, so we skip that part.
843 "xorq %%rbp,%%rbp\n"
845 /* Call "fn(arg)". */
846 "popq %%rax\n"
847 "popq %%rdi\n"
848 "call *%%rax\n"
850 /* Call _exit(%rax). */
851 "movq %%rax,%%rdi\n"
852 "movq %2,%%rax\n"
853 "syscall\n"
855 /* Return to parent. */
856 "1:\n"
857 : "=a" (res)
858 : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
859 "S"(child_stack),
860 "D"(flags),
861 "d"(parent_tidptr),
862 "r"(r8),
863 "r"(r10)
864 : "rsp", "memory", "r11", "rcx");
865 return res;
867 #elif defined(__mips__)
868 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
869 int *parent_tidptr, void *newtls, int *child_tidptr) {
870 long long res;
871 if (!fn || !child_stack)
872 return -EINVAL;
873 CHECK_EQ(0, (uptr)child_stack % 16);
874 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
875 ((unsigned long long *)child_stack)[0] = (uptr)fn;
876 ((unsigned long long *)child_stack)[1] = (uptr)arg;
877 register void *a3 __asm__("$7") = newtls;
878 register int *a4 __asm__("$8") = child_tidptr;
879 // We don't have proper CFI directives here because it requires alot of code
880 // for very marginal benefits.
881 __asm__ __volatile__(
882 /* $v0 = syscall($v0 = __NR_clone,
883 * $a0 = flags,
884 * $a1 = child_stack,
885 * $a2 = parent_tidptr,
886 * $a3 = new_tls,
887 * $a4 = child_tidptr)
889 ".cprestore 16;\n"
890 "move $4,%1;\n"
891 "move $5,%2;\n"
892 "move $6,%3;\n"
893 "move $7,%4;\n"
894 /* Store the fifth argument on stack
895 * if we are using 32-bit abi.
897 #if SANITIZER_WORDSIZE == 32
898 "lw %5,16($29);\n"
899 #else
900 "move $8,%5;\n"
901 #endif
902 "li $2,%6;\n"
903 "syscall;\n"
905 /* if ($v0 != 0)
906 * return;
908 "bnez $2,1f;\n"
910 /* Call "fn(arg)". */
911 "ld $25,0($29);\n"
912 "ld $4,8($29);\n"
913 "jal $25;\n"
915 /* Call _exit($v0). */
916 "move $4,$2;\n"
917 "li $2,%7;\n"
918 "syscall;\n"
920 /* Return to parent. */
921 "1:\n"
922 : "=r" (res)
923 : "r"(flags),
924 "r"(child_stack),
925 "r"(parent_tidptr),
926 "r"(a3),
927 "r"(a4),
928 "i"(__NR_clone),
929 "i"(__NR_exit)
930 : "memory", "$29" );
931 return res;
933 #elif defined(__aarch64__)
934 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
935 int *parent_tidptr, void *newtls, int *child_tidptr) {
936 long long res;
937 if (!fn || !child_stack)
938 return -EINVAL;
939 CHECK_EQ(0, (uptr)child_stack % 16);
940 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
941 ((unsigned long long *)child_stack)[0] = (uptr)fn;
942 ((unsigned long long *)child_stack)[1] = (uptr)arg;
944 register int (*__fn)(void *) __asm__("x0") = fn;
945 register void *__stack __asm__("x1") = child_stack;
946 register int __flags __asm__("x2") = flags;
947 register void *__arg __asm__("x3") = arg;
948 register int *__ptid __asm__("x4") = parent_tidptr;
949 register void *__tls __asm__("x5") = newtls;
950 register int *__ctid __asm__("x6") = child_tidptr;
952 __asm__ __volatile__(
953 "mov x0,x2\n" /* flags */
954 "mov x2,x4\n" /* ptid */
955 "mov x3,x5\n" /* tls */
956 "mov x4,x6\n" /* ctid */
957 "mov x8,%9\n" /* clone */
959 "svc 0x0\n"
961 /* if (%r0 != 0)
962 * return %r0;
964 "cmp x0, #0\n"
965 "bne 1f\n"
967 /* In the child, now. Call "fn(arg)". */
968 "ldp x1, x0, [sp], #16\n"
969 "blr x1\n"
971 /* Call _exit(%r0). */
972 "mov x8, %10\n"
973 "svc 0x0\n"
974 "1:\n"
976 : "=r" (res)
977 : "i"(-EINVAL),
978 "r"(__fn), "r"(__stack), "r"(__flags), "r"(__arg),
979 "r"(__ptid), "r"(__tls), "r"(__ctid),
980 "i"(__NR_clone), "i"(__NR_exit)
981 : "x30", "memory");
982 return res;
984 #endif // defined(__x86_64__) && SANITIZER_LINUX
986 #if SANITIZER_ANDROID
987 #define PROP_VALUE_MAX 92
988 extern "C" SANITIZER_WEAK_ATTRIBUTE int __system_property_get(const char *name,
989 char *value);
990 void GetExtraActivationFlags(char *buf, uptr size) {
991 CHECK(size > PROP_VALUE_MAX);
992 CHECK(&__system_property_get);
993 __system_property_get("asan.options", buf);
996 #if __ANDROID_API__ < 21
997 extern "C" __attribute__((weak)) int dl_iterate_phdr(
998 int (*)(struct dl_phdr_info *, size_t, void *), void *);
999 #endif
1001 static int dl_iterate_phdr_test_cb(struct dl_phdr_info *info, size_t size,
1002 void *data) {
1003 // Any name starting with "lib" indicates a bug in L where library base names
1004 // are returned instead of paths.
1005 if (info->dlpi_name && info->dlpi_name[0] == 'l' &&
1006 info->dlpi_name[1] == 'i' && info->dlpi_name[2] == 'b') {
1007 *(bool *)data = true;
1008 return 1;
1010 return 0;
1013 static atomic_uint32_t android_api_level;
1015 static AndroidApiLevel AndroidDetectApiLevel() {
1016 if (!&dl_iterate_phdr)
1017 return ANDROID_KITKAT; // K or lower
1018 bool base_name_seen = false;
1019 dl_iterate_phdr(dl_iterate_phdr_test_cb, &base_name_seen);
1020 if (base_name_seen)
1021 return ANDROID_LOLLIPOP_MR1; // L MR1
1022 return ANDROID_POST_LOLLIPOP; // post-L
1023 // Plain L (API level 21) is completely broken wrt ASan and not very
1024 // interesting to detect.
1027 AndroidApiLevel AndroidGetApiLevel() {
1028 AndroidApiLevel level =
1029 (AndroidApiLevel)atomic_load(&android_api_level, memory_order_relaxed);
1030 if (level) return level;
1031 level = AndroidDetectApiLevel();
1032 atomic_store(&android_api_level, level, memory_order_relaxed);
1033 return level;
1036 #endif
1038 bool IsDeadlySignal(int signum) {
1039 if (common_flags()->handle_abort && signum == SIGABRT)
1040 return true;
1041 if (common_flags()->handle_sigfpe && signum == SIGFPE)
1042 return true;
1043 return (signum == SIGSEGV || signum == SIGBUS) && common_flags()->handle_segv;
1046 #ifndef SANITIZER_GO
1047 void *internal_start_thread(void(*func)(void *arg), void *arg) {
1048 // Start the thread with signals blocked, otherwise it can steal user signals.
1049 __sanitizer_sigset_t set, old;
1050 internal_sigfillset(&set);
1051 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1052 // Glibc uses SIGSETXID signal during setuid call. If this signal is blocked
1053 // on any thread, setuid call hangs (see test/tsan/setuid.c).
1054 internal_sigdelset(&set, 33);
1055 #endif
1056 internal_sigprocmask(SIG_SETMASK, &set, &old);
1057 void *th;
1058 real_pthread_create(&th, nullptr, (void*(*)(void *arg))func, arg);
1059 internal_sigprocmask(SIG_SETMASK, &old, nullptr);
1060 return th;
1063 void internal_join_thread(void *th) {
1064 real_pthread_join(th, nullptr);
1066 #else
1067 void *internal_start_thread(void (*func)(void *), void *arg) { return 0; }
1069 void internal_join_thread(void *th) {}
1070 #endif
1072 void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
1073 #if defined(__arm__)
1074 ucontext_t *ucontext = (ucontext_t*)context;
1075 *pc = ucontext->uc_mcontext.arm_pc;
1076 *bp = ucontext->uc_mcontext.arm_fp;
1077 *sp = ucontext->uc_mcontext.arm_sp;
1078 #elif defined(__aarch64__)
1079 ucontext_t *ucontext = (ucontext_t*)context;
1080 *pc = ucontext->uc_mcontext.pc;
1081 *bp = ucontext->uc_mcontext.regs[29];
1082 *sp = ucontext->uc_mcontext.sp;
1083 #elif defined(__hppa__)
1084 ucontext_t *ucontext = (ucontext_t*)context;
1085 *pc = ucontext->uc_mcontext.sc_iaoq[0];
1086 /* GCC uses %r3 whenever a frame pointer is needed. */
1087 *bp = ucontext->uc_mcontext.sc_gr[3];
1088 *sp = ucontext->uc_mcontext.sc_gr[30];
1089 #elif defined(__x86_64__)
1090 # if SANITIZER_FREEBSD
1091 ucontext_t *ucontext = (ucontext_t*)context;
1092 *pc = ucontext->uc_mcontext.mc_rip;
1093 *bp = ucontext->uc_mcontext.mc_rbp;
1094 *sp = ucontext->uc_mcontext.mc_rsp;
1095 # else
1096 ucontext_t *ucontext = (ucontext_t*)context;
1097 *pc = ucontext->uc_mcontext.gregs[REG_RIP];
1098 *bp = ucontext->uc_mcontext.gregs[REG_RBP];
1099 *sp = ucontext->uc_mcontext.gregs[REG_RSP];
1100 # endif
1101 #elif defined(__i386__)
1102 # if SANITIZER_FREEBSD
1103 ucontext_t *ucontext = (ucontext_t*)context;
1104 *pc = ucontext->uc_mcontext.mc_eip;
1105 *bp = ucontext->uc_mcontext.mc_ebp;
1106 *sp = ucontext->uc_mcontext.mc_esp;
1107 # else
1108 ucontext_t *ucontext = (ucontext_t*)context;
1109 *pc = ucontext->uc_mcontext.gregs[REG_EIP];
1110 *bp = ucontext->uc_mcontext.gregs[REG_EBP];
1111 *sp = ucontext->uc_mcontext.gregs[REG_ESP];
1112 # endif
1113 #elif defined(__powerpc__) || defined(__powerpc64__)
1114 ucontext_t *ucontext = (ucontext_t*)context;
1115 *pc = ucontext->uc_mcontext.regs->nip;
1116 *sp = ucontext->uc_mcontext.regs->gpr[PT_R1];
1117 // The powerpc{,64}-linux ABIs do not specify r31 as the frame
1118 // pointer, but GCC always uses r31 when we need a frame pointer.
1119 *bp = ucontext->uc_mcontext.regs->gpr[PT_R31];
1120 #elif defined(__sparc__)
1121 ucontext_t *ucontext = (ucontext_t*)context;
1122 uptr *stk_ptr;
1123 # if defined (__arch64__)
1124 *pc = ucontext->uc_mcontext.mc_gregs[MC_PC];
1125 *sp = ucontext->uc_mcontext.mc_gregs[MC_O6];
1126 stk_ptr = (uptr *) (*sp + 2047);
1127 *bp = stk_ptr[15];
1128 # else
1129 *pc = ucontext->uc_mcontext.gregs[REG_PC];
1130 *sp = ucontext->uc_mcontext.gregs[REG_O6];
1131 stk_ptr = (uptr *) *sp;
1132 *bp = stk_ptr[15];
1133 # endif
1134 #elif defined(__mips__)
1135 ucontext_t *ucontext = (ucontext_t*)context;
1136 *pc = ucontext->uc_mcontext.pc;
1137 *bp = ucontext->uc_mcontext.gregs[30];
1138 *sp = ucontext->uc_mcontext.gregs[29];
1139 #else
1140 # error "Unsupported arch"
1141 #endif
1144 } // namespace __sanitizer
1146 #endif // SANITIZER_FREEBSD || SANITIZER_LINUX