* gcc.target/i386/fuse-caller-save-xmm.c (dg-options): Use
[official-gcc.git] / libsanitizer / sanitizer_common / sanitizer_linux.cc
blobfaa85acd696eb626330de3905f41098877d551e5
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"
14 #if SANITIZER_FREEBSD || SANITIZER_LINUX
16 #include "sanitizer_common.h"
17 #include "sanitizer_flags.h"
18 #include "sanitizer_internal_defs.h"
19 #include "sanitizer_libc.h"
20 #include "sanitizer_linux.h"
21 #include "sanitizer_mutex.h"
22 #include "sanitizer_placement_new.h"
23 #include "sanitizer_procmaps.h"
24 #include "sanitizer_stacktrace.h"
25 #include "sanitizer_symbolizer.h"
27 #if !SANITIZER_FREEBSD
28 #include <asm/param.h>
29 #endif
31 #include <dlfcn.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #if !SANITIZER_ANDROID
35 #include <link.h>
36 #endif
37 #include <pthread.h>
38 #include <sched.h>
39 #include <sys/mman.h>
40 #include <sys/ptrace.h>
41 #include <sys/resource.h>
42 #include <sys/stat.h>
43 #include <sys/syscall.h>
44 #include <sys/time.h>
45 #include <sys/types.h>
46 #include <unistd.h>
47 #include <unwind.h>
49 #if SANITIZER_FREEBSD
50 #include <machine/atomic.h>
51 extern "C" {
52 // <sys/umtx.h> must be included after <errno.h> and <sys/types.h> on
53 // FreeBSD 9.2 and 10.0.
54 #include <sys/umtx.h>
56 #endif // SANITIZER_FREEBSD
58 #if !SANITIZER_ANDROID
59 #include <sys/signal.h>
60 #endif
62 #if SANITIZER_ANDROID
63 #include <android/log.h>
64 #include <sys/system_properties.h>
65 #endif
67 #if SANITIZER_LINUX
68 // <linux/time.h>
69 struct kernel_timeval {
70 long tv_sec;
71 long tv_usec;
74 // <linux/futex.h> is broken on some linux distributions.
75 const int FUTEX_WAIT = 0;
76 const int FUTEX_WAKE = 1;
77 #endif // SANITIZER_LINUX
79 // Are we using 32-bit or 64-bit Linux syscalls?
80 // x32 (which defines __x86_64__) has SANITIZER_WORDSIZE == 32
81 // but it still needs to use 64-bit syscalls.
82 #if SANITIZER_LINUX && (defined(__x86_64__) || SANITIZER_WORDSIZE == 64)
83 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 1
84 #else
85 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 0
86 #endif
88 namespace __sanitizer {
90 #if SANITIZER_LINUX && defined(__x86_64__)
91 #include "sanitizer_syscall_linux_x86_64.inc"
92 #else
93 #include "sanitizer_syscall_generic.inc"
94 #endif
96 // --------------- sanitizer_libc.h
97 uptr internal_mmap(void *addr, uptr length, int prot, int flags,
98 int fd, u64 offset) {
99 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
100 return internal_syscall(SYSCALL(mmap), (uptr)addr, length, prot, flags, fd,
101 offset);
102 #else
103 return internal_syscall(SYSCALL(mmap2), addr, length, prot, flags, fd,
104 offset);
105 #endif
108 uptr internal_munmap(void *addr, uptr length) {
109 return internal_syscall(SYSCALL(munmap), (uptr)addr, length);
112 uptr internal_close(fd_t fd) {
113 return internal_syscall(SYSCALL(close), fd);
116 uptr internal_open(const char *filename, int flags) {
117 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
118 return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags);
119 #else
120 return internal_syscall(SYSCALL(open), (uptr)filename, flags);
121 #endif
124 uptr internal_open(const char *filename, int flags, u32 mode) {
125 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
126 return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags,
127 mode);
128 #else
129 return internal_syscall(SYSCALL(open), (uptr)filename, flags, mode);
130 #endif
133 uptr OpenFile(const char *filename, bool write) {
134 return internal_open(filename,
135 write ? O_WRONLY | O_CREAT /*| O_CLOEXEC*/ : O_RDONLY, 0660);
138 uptr internal_read(fd_t fd, void *buf, uptr count) {
139 sptr res;
140 HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(read), fd, (uptr)buf,
141 count));
142 return res;
145 uptr internal_write(fd_t fd, const void *buf, uptr count) {
146 sptr res;
147 HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(write), fd, (uptr)buf,
148 count));
149 return res;
152 #if !SANITIZER_LINUX_USES_64BIT_SYSCALLS && !SANITIZER_FREEBSD
153 static void stat64_to_stat(struct stat64 *in, struct stat *out) {
154 internal_memset(out, 0, sizeof(*out));
155 out->st_dev = in->st_dev;
156 out->st_ino = in->st_ino;
157 out->st_mode = in->st_mode;
158 out->st_nlink = in->st_nlink;
159 out->st_uid = in->st_uid;
160 out->st_gid = in->st_gid;
161 out->st_rdev = in->st_rdev;
162 out->st_size = in->st_size;
163 out->st_blksize = in->st_blksize;
164 out->st_blocks = in->st_blocks;
165 out->st_atime = in->st_atime;
166 out->st_mtime = in->st_mtime;
167 out->st_ctime = in->st_ctime;
168 out->st_ino = in->st_ino;
170 #endif
172 uptr internal_stat(const char *path, void *buf) {
173 #if SANITIZER_FREEBSD
174 return internal_syscall(SYSCALL(stat), path, buf);
175 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
176 return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path,
177 (uptr)buf, 0);
178 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
179 return internal_syscall(SYSCALL(stat), (uptr)path, (uptr)buf);
180 #else
181 struct stat64 buf64;
182 int res = internal_syscall(SYSCALL(stat64), path, &buf64);
183 stat64_to_stat(&buf64, (struct stat *)buf);
184 return res;
185 #endif
188 uptr internal_lstat(const char *path, void *buf) {
189 #if SANITIZER_FREEBSD
190 return internal_syscall(SYSCALL(lstat), path, buf);
191 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
192 return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path,
193 (uptr)buf, AT_SYMLINK_NOFOLLOW);
194 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
195 return internal_syscall(SYSCALL(lstat), (uptr)path, (uptr)buf);
196 #else
197 struct stat64 buf64;
198 int res = internal_syscall(SYSCALL(lstat64), path, &buf64);
199 stat64_to_stat(&buf64, (struct stat *)buf);
200 return res;
201 #endif
204 uptr internal_fstat(fd_t fd, void *buf) {
205 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
206 return internal_syscall(SYSCALL(fstat), fd, (uptr)buf);
207 #else
208 struct stat64 buf64;
209 int res = internal_syscall(SYSCALL(fstat64), fd, &buf64);
210 stat64_to_stat(&buf64, (struct stat *)buf);
211 return res;
212 #endif
215 uptr internal_filesize(fd_t fd) {
216 struct stat st;
217 if (internal_fstat(fd, &st))
218 return -1;
219 return (uptr)st.st_size;
222 uptr internal_dup2(int oldfd, int newfd) {
223 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
224 return internal_syscall(SYSCALL(dup3), oldfd, newfd, 0);
225 #else
226 return internal_syscall(SYSCALL(dup2), oldfd, newfd);
227 #endif
230 uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
231 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
232 return internal_syscall(SYSCALL(readlinkat), AT_FDCWD,
233 (uptr)path, (uptr)buf, bufsize);
234 #else
235 return internal_syscall(SYSCALL(readlink), (uptr)path, (uptr)buf, bufsize);
236 #endif
239 uptr internal_unlink(const char *path) {
240 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
241 return internal_syscall(SYSCALL(unlinkat), AT_FDCWD, (uptr)path, 0);
242 #else
243 return internal_syscall(SYSCALL(unlink), (uptr)path);
244 #endif
247 uptr internal_sched_yield() {
248 return internal_syscall(SYSCALL(sched_yield));
251 void internal__exit(int exitcode) {
252 #if SANITIZER_FREEBSD
253 internal_syscall(SYSCALL(exit), exitcode);
254 #else
255 internal_syscall(SYSCALL(exit_group), exitcode);
256 #endif
257 Die(); // Unreachable.
260 uptr internal_execve(const char *filename, char *const argv[],
261 char *const envp[]) {
262 return internal_syscall(SYSCALL(execve), (uptr)filename, (uptr)argv,
263 (uptr)envp);
266 // ----------------- sanitizer_common.h
267 bool FileExists(const char *filename) {
268 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
269 struct stat st;
270 if (internal_syscall(SYSCALL(newfstatat), AT_FDCWD, filename, &st, 0))
271 return false;
272 #else
273 struct stat st;
274 if (internal_stat(filename, &st))
275 return false;
276 // Sanity check: filename is a regular file.
277 return S_ISREG(st.st_mode);
278 #endif
281 uptr GetTid() {
282 #if SANITIZER_FREEBSD
283 return (uptr)pthread_self();
284 #else
285 return internal_syscall(SYSCALL(gettid));
286 #endif
289 u64 NanoTime() {
290 #if SANITIZER_FREEBSD
291 timeval tv;
292 #else
293 kernel_timeval tv;
294 #endif
295 internal_memset(&tv, 0, sizeof(tv));
296 internal_syscall(SYSCALL(gettimeofday), (uptr)&tv, 0);
297 return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
300 // Like getenv, but reads env directly from /proc and does not use libc.
301 // This function should be called first inside __asan_init.
302 const char *GetEnv(const char *name) {
303 static char *environ;
304 static uptr len;
305 static bool inited;
306 if (!inited) {
307 inited = true;
308 uptr environ_size;
309 len = ReadFileToBuffer("/proc/self/environ",
310 &environ, &environ_size, 1 << 26);
312 if (!environ || len == 0) return 0;
313 uptr namelen = internal_strlen(name);
314 const char *p = environ;
315 while (*p != '\0') { // will happen at the \0\0 that terminates the buffer
316 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
317 const char* endp =
318 (char*)internal_memchr(p, '\0', len - (p - environ));
319 if (endp == 0) // this entry isn't NUL terminated
320 return 0;
321 else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') // Match.
322 return p + namelen + 1; // point after =
323 p = endp + 1;
325 return 0; // Not found.
328 extern "C" {
329 SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
332 #if !SANITIZER_GO
333 static void ReadNullSepFileToArray(const char *path, char ***arr,
334 int arr_size) {
335 char *buff;
336 uptr buff_size = 0;
337 *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
338 ReadFileToBuffer(path, &buff, &buff_size, 1024 * 1024);
339 (*arr)[0] = buff;
340 int count, i;
341 for (count = 1, i = 1; ; i++) {
342 if (buff[i] == 0) {
343 if (buff[i+1] == 0) break;
344 (*arr)[count] = &buff[i+1];
345 CHECK_LE(count, arr_size - 1); // FIXME: make this more flexible.
346 count++;
349 (*arr)[count] = 0;
351 #endif
353 static void GetArgsAndEnv(char*** argv, char*** envp) {
354 #if !SANITIZER_GO
355 if (&__libc_stack_end) {
356 #endif
357 uptr* stack_end = (uptr*)__libc_stack_end;
358 int argc = *stack_end;
359 *argv = (char**)(stack_end + 1);
360 *envp = (char**)(stack_end + argc + 2);
361 #if !SANITIZER_GO
362 } else {
363 static const int kMaxArgv = 2000, kMaxEnvp = 2000;
364 ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
365 ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
367 #endif
370 void ReExec() {
371 char **argv, **envp;
372 GetArgsAndEnv(&argv, &envp);
373 uptr rv = internal_execve("/proc/self/exe", argv, envp);
374 int rverrno;
375 CHECK_EQ(internal_iserror(rv, &rverrno), true);
376 Printf("execve failed, errno %d\n", rverrno);
377 Die();
380 // Stub implementation of GetThreadStackAndTls for Go.
381 #if SANITIZER_GO
382 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
383 uptr *tls_addr, uptr *tls_size) {
384 *stk_addr = 0;
385 *stk_size = 0;
386 *tls_addr = 0;
387 *tls_size = 0;
389 #endif // SANITIZER_GO
391 void PrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
392 // Some kinds of sandboxes may forbid filesystem access, so we won't be able
393 // to read the file mappings from /proc/self/maps. Luckily, neither the
394 // process will be able to load additional libraries, so it's fine to use the
395 // cached mappings.
396 MemoryMappingLayout::CacheMemoryMappings();
397 // Same for /proc/self/exe in the symbolizer.
398 #if !SANITIZER_GO
399 if (Symbolizer *sym = Symbolizer::GetOrNull())
400 sym->PrepareForSandboxing();
401 CovPrepareForSandboxing(args);
402 #endif
405 enum MutexState {
406 MtxUnlocked = 0,
407 MtxLocked = 1,
408 MtxSleeping = 2
411 BlockingMutex::BlockingMutex(LinkerInitialized) {
412 CHECK_EQ(owner_, 0);
415 BlockingMutex::BlockingMutex() {
416 internal_memset(this, 0, sizeof(*this));
419 void BlockingMutex::Lock() {
420 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
421 if (atomic_exchange(m, MtxLocked, memory_order_acquire) == MtxUnlocked)
422 return;
423 while (atomic_exchange(m, MtxSleeping, memory_order_acquire) != MtxUnlocked) {
424 #if SANITIZER_FREEBSD
425 _umtx_op(m, UMTX_OP_WAIT_UINT, MtxSleeping, 0, 0);
426 #else
427 internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAIT, MtxSleeping, 0, 0, 0);
428 #endif
432 void BlockingMutex::Unlock() {
433 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
434 u32 v = atomic_exchange(m, MtxUnlocked, memory_order_relaxed);
435 CHECK_NE(v, MtxUnlocked);
436 if (v == MtxSleeping) {
437 #if SANITIZER_FREEBSD
438 _umtx_op(m, UMTX_OP_WAKE, 1, 0, 0);
439 #else
440 internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAKE, 1, 0, 0, 0);
441 #endif
445 void BlockingMutex::CheckLocked() {
446 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
447 CHECK_NE(MtxUnlocked, atomic_load(m, memory_order_relaxed));
450 // ----------------- sanitizer_linux.h
451 // The actual size of this structure is specified by d_reclen.
452 // Note that getdents64 uses a different structure format. We only provide the
453 // 32-bit syscall here.
454 struct linux_dirent {
455 #if SANITIZER_X32
456 u64 d_ino;
457 u64 d_off;
458 #else
459 unsigned long d_ino;
460 unsigned long d_off;
461 #endif
462 unsigned short d_reclen;
463 char d_name[256];
466 // Syscall wrappers.
467 uptr internal_ptrace(int request, int pid, void *addr, void *data) {
468 return internal_syscall(SYSCALL(ptrace), request, pid, (uptr)addr,
469 (uptr)data);
472 uptr internal_waitpid(int pid, int *status, int options) {
473 return internal_syscall(SYSCALL(wait4), pid, (uptr)status, options,
474 0 /* rusage */);
477 uptr internal_getpid() {
478 return internal_syscall(SYSCALL(getpid));
481 uptr internal_getppid() {
482 return internal_syscall(SYSCALL(getppid));
485 uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) {
486 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
487 return internal_syscall(SYSCALL(getdents64), fd, (uptr)dirp, count);
488 #else
489 return internal_syscall(SYSCALL(getdents), fd, (uptr)dirp, count);
490 #endif
493 uptr internal_lseek(fd_t fd, OFF_T offset, int whence) {
494 return internal_syscall(SYSCALL(lseek), fd, offset, whence);
497 #if SANITIZER_LINUX
498 uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
499 return internal_syscall(SYSCALL(prctl), option, arg2, arg3, arg4, arg5);
501 #endif
503 uptr internal_sigaltstack(const struct sigaltstack *ss,
504 struct sigaltstack *oss) {
505 return internal_syscall(SYSCALL(sigaltstack), (uptr)ss, (uptr)oss);
508 int internal_fork() {
509 return internal_syscall(SYSCALL(fork));
512 #if SANITIZER_LINUX
513 // Doesn't set sa_restorer, use with caution (see below).
514 int internal_sigaction_norestorer(int signum, const void *act, void *oldact) {
515 __sanitizer_kernel_sigaction_t k_act, k_oldact;
516 internal_memset(&k_act, 0, sizeof(__sanitizer_kernel_sigaction_t));
517 internal_memset(&k_oldact, 0, sizeof(__sanitizer_kernel_sigaction_t));
518 const __sanitizer_sigaction *u_act = (__sanitizer_sigaction *)act;
519 __sanitizer_sigaction *u_oldact = (__sanitizer_sigaction *)oldact;
520 if (u_act) {
521 k_act.handler = u_act->handler;
522 k_act.sigaction = u_act->sigaction;
523 internal_memcpy(&k_act.sa_mask, &u_act->sa_mask,
524 sizeof(__sanitizer_kernel_sigset_t));
525 k_act.sa_flags = u_act->sa_flags;
526 // FIXME: most often sa_restorer is unset, however the kernel requires it
527 // to point to a valid signal restorer that calls the rt_sigreturn syscall.
528 // If sa_restorer passed to the kernel is NULL, the program may crash upon
529 // signal delivery or fail to unwind the stack in the signal handler.
530 // libc implementation of sigaction() passes its own restorer to
531 // rt_sigaction, so we need to do the same (we'll need to reimplement the
532 // restorers; for x86_64 the restorer address can be obtained from
533 // oldact->sa_restorer upon a call to sigaction(xxx, NULL, oldact).
534 k_act.sa_restorer = u_act->sa_restorer;
537 uptr result = internal_syscall(SYSCALL(rt_sigaction), (uptr)signum,
538 (uptr)(u_act ? &k_act : NULL),
539 (uptr)(u_oldact ? &k_oldact : NULL),
540 (uptr)sizeof(__sanitizer_kernel_sigset_t));
542 if ((result == 0) && u_oldact) {
543 u_oldact->handler = k_oldact.handler;
544 u_oldact->sigaction = k_oldact.sigaction;
545 internal_memcpy(&u_oldact->sa_mask, &k_oldact.sa_mask,
546 sizeof(__sanitizer_kernel_sigset_t));
547 u_oldact->sa_flags = k_oldact.sa_flags;
548 u_oldact->sa_restorer = k_oldact.sa_restorer;
550 return result;
552 #endif // SANITIZER_LINUX
554 uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
555 __sanitizer_sigset_t *oldset) {
556 #if SANITIZER_FREEBSD
557 return internal_syscall(SYSCALL(sigprocmask), how, set, oldset);
558 #else
559 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
560 __sanitizer_kernel_sigset_t *k_oldset = (__sanitizer_kernel_sigset_t *)oldset;
561 return internal_syscall(SYSCALL(rt_sigprocmask), (uptr)how,
562 (uptr)&k_set->sig[0], (uptr)&k_oldset->sig[0],
563 sizeof(__sanitizer_kernel_sigset_t));
564 #endif
567 void internal_sigfillset(__sanitizer_sigset_t *set) {
568 internal_memset(set, 0xff, sizeof(*set));
571 #if SANITIZER_LINUX
572 void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
573 signum -= 1;
574 CHECK_GE(signum, 0);
575 CHECK_LT(signum, sizeof(*set) * 8);
576 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
577 const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
578 const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
579 k_set->sig[idx] &= ~(1 << bit);
581 #endif // SANITIZER_LINUX
583 // ThreadLister implementation.
584 ThreadLister::ThreadLister(int pid)
585 : pid_(pid),
586 descriptor_(-1),
587 buffer_(4096),
588 error_(true),
589 entry_((struct linux_dirent *)buffer_.data()),
590 bytes_read_(0) {
591 char task_directory_path[80];
592 internal_snprintf(task_directory_path, sizeof(task_directory_path),
593 "/proc/%d/task/", pid);
594 uptr openrv = internal_open(task_directory_path, O_RDONLY | O_DIRECTORY);
595 if (internal_iserror(openrv)) {
596 error_ = true;
597 Report("Can't open /proc/%d/task for reading.\n", pid);
598 } else {
599 error_ = false;
600 descriptor_ = openrv;
604 int ThreadLister::GetNextTID() {
605 int tid = -1;
606 do {
607 if (error_)
608 return -1;
609 if ((char *)entry_ >= &buffer_[bytes_read_] && !GetDirectoryEntries())
610 return -1;
611 if (entry_->d_ino != 0 && entry_->d_name[0] >= '0' &&
612 entry_->d_name[0] <= '9') {
613 // Found a valid tid.
614 tid = (int)internal_atoll(entry_->d_name);
616 entry_ = (struct linux_dirent *)(((char *)entry_) + entry_->d_reclen);
617 } while (tid < 0);
618 return tid;
621 void ThreadLister::Reset() {
622 if (error_ || descriptor_ < 0)
623 return;
624 internal_lseek(descriptor_, 0, SEEK_SET);
627 ThreadLister::~ThreadLister() {
628 if (descriptor_ >= 0)
629 internal_close(descriptor_);
632 bool ThreadLister::error() { return error_; }
634 bool ThreadLister::GetDirectoryEntries() {
635 CHECK_GE(descriptor_, 0);
636 CHECK_NE(error_, true);
637 bytes_read_ = internal_getdents(descriptor_,
638 (struct linux_dirent *)buffer_.data(),
639 buffer_.size());
640 if (internal_iserror(bytes_read_)) {
641 Report("Can't read directory entries from /proc/%d/task.\n", pid_);
642 error_ = true;
643 return false;
644 } else if (bytes_read_ == 0) {
645 return false;
647 entry_ = (struct linux_dirent *)buffer_.data();
648 return true;
651 uptr GetPageSize() {
652 #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__))
653 return EXEC_PAGESIZE;
654 #else
655 return sysconf(_SC_PAGESIZE); // EXEC_PAGESIZE may not be trustworthy.
656 #endif
659 static char proc_self_exe_cache_str[kMaxPathLength];
660 static uptr proc_self_exe_cache_len = 0;
662 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
663 uptr module_name_len = internal_readlink(
664 "/proc/self/exe", buf, buf_len);
665 int readlink_error;
666 if (internal_iserror(module_name_len, &readlink_error)) {
667 if (proc_self_exe_cache_len) {
668 // If available, use the cached module name.
669 CHECK_LE(proc_self_exe_cache_len, buf_len);
670 internal_strncpy(buf, proc_self_exe_cache_str, buf_len);
671 module_name_len = internal_strlen(proc_self_exe_cache_str);
672 } else {
673 // We can't read /proc/self/exe for some reason, assume the name of the
674 // binary is unknown.
675 Report("WARNING: readlink(\"/proc/self/exe\") failed with errno %d, "
676 "some stack frames may not be symbolized\n", readlink_error);
677 module_name_len = internal_snprintf(buf, buf_len, "/proc/self/exe");
679 CHECK_LT(module_name_len, buf_len);
680 buf[module_name_len] = '\0';
682 return module_name_len;
685 void CacheBinaryName() {
686 if (!proc_self_exe_cache_len) {
687 proc_self_exe_cache_len =
688 ReadBinaryName(proc_self_exe_cache_str, kMaxPathLength);
692 // Match full names of the form /path/to/base_name{-,.}*
693 bool LibraryNameIs(const char *full_name, const char *base_name) {
694 const char *name = full_name;
695 // Strip path.
696 while (*name != '\0') name++;
697 while (name > full_name && *name != '/') name--;
698 if (*name == '/') name++;
699 uptr base_name_length = internal_strlen(base_name);
700 if (internal_strncmp(name, base_name, base_name_length)) return false;
701 return (name[base_name_length] == '-' || name[base_name_length] == '.');
704 #if !SANITIZER_ANDROID
705 // Call cb for each region mapped by map.
706 void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr)) {
707 #if !SANITIZER_FREEBSD
708 typedef ElfW(Phdr) Elf_Phdr;
709 typedef ElfW(Ehdr) Elf_Ehdr;
710 #endif // !SANITIZER_FREEBSD
711 char *base = (char *)map->l_addr;
712 Elf_Ehdr *ehdr = (Elf_Ehdr *)base;
713 char *phdrs = base + ehdr->e_phoff;
714 char *phdrs_end = phdrs + ehdr->e_phnum * ehdr->e_phentsize;
716 // Find the segment with the minimum base so we can "relocate" the p_vaddr
717 // fields. Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
718 // objects have a non-zero base.
719 uptr preferred_base = (uptr)-1;
720 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
721 Elf_Phdr *phdr = (Elf_Phdr *)iter;
722 if (phdr->p_type == PT_LOAD && preferred_base > (uptr)phdr->p_vaddr)
723 preferred_base = (uptr)phdr->p_vaddr;
726 // Compute the delta from the real base to get a relocation delta.
727 sptr delta = (uptr)base - preferred_base;
728 // Now we can figure out what the loader really mapped.
729 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
730 Elf_Phdr *phdr = (Elf_Phdr *)iter;
731 if (phdr->p_type == PT_LOAD) {
732 uptr seg_start = phdr->p_vaddr + delta;
733 uptr seg_end = seg_start + phdr->p_memsz;
734 // None of these values are aligned. We consider the ragged edges of the
735 // load command as defined, since they are mapped from the file.
736 seg_start = RoundDownTo(seg_start, GetPageSizeCached());
737 seg_end = RoundUpTo(seg_end, GetPageSizeCached());
738 cb((void *)seg_start, seg_end - seg_start);
742 #endif
744 #if defined(__x86_64__) && SANITIZER_LINUX
745 // We cannot use glibc's clone wrapper, because it messes with the child
746 // task's TLS. It writes the PID and TID of the child task to its thread
747 // descriptor, but in our case the child task shares the thread descriptor with
748 // the parent (because we don't know how to allocate a new thread
749 // descriptor to keep glibc happy). So the stock version of clone(), when
750 // used with CLONE_VM, would end up corrupting the parent's thread descriptor.
751 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
752 int *parent_tidptr, void *newtls, int *child_tidptr) {
753 long long res;
754 if (!fn || !child_stack)
755 return -EINVAL;
756 CHECK_EQ(0, (uptr)child_stack % 16);
757 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
758 ((unsigned long long *)child_stack)[0] = (uptr)fn;
759 ((unsigned long long *)child_stack)[1] = (uptr)arg;
760 register void *r8 __asm__("r8") = newtls;
761 register int *r10 __asm__("r10") = child_tidptr;
762 __asm__ __volatile__(
763 /* %rax = syscall(%rax = SYSCALL(clone),
764 * %rdi = flags,
765 * %rsi = child_stack,
766 * %rdx = parent_tidptr,
767 * %r8 = new_tls,
768 * %r10 = child_tidptr)
770 "syscall\n"
772 /* if (%rax != 0)
773 * return;
775 "testq %%rax,%%rax\n"
776 "jnz 1f\n"
778 /* In the child. Terminate unwind chain. */
779 // XXX: We should also terminate the CFI unwind chain
780 // here. Unfortunately clang 3.2 doesn't support the
781 // necessary CFI directives, so we skip that part.
782 "xorq %%rbp,%%rbp\n"
784 /* Call "fn(arg)". */
785 "popq %%rax\n"
786 "popq %%rdi\n"
787 "call *%%rax\n"
789 /* Call _exit(%rax). */
790 "movq %%rax,%%rdi\n"
791 "movq %2,%%rax\n"
792 "syscall\n"
794 /* Return to parent. */
795 "1:\n"
796 : "=a" (res)
797 : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
798 "S"(child_stack),
799 "D"(flags),
800 "d"(parent_tidptr),
801 "r"(r8),
802 "r"(r10)
803 : "rsp", "memory", "r11", "rcx");
804 return res;
806 #endif // defined(__x86_64__) && SANITIZER_LINUX
808 #if SANITIZER_ANDROID
809 // This thing is not, strictly speaking, async signal safe, but it does not seem
810 // to cause any issues. Alternative is writing to log devices directly, but
811 // their location and message format might change in the future, so we'd really
812 // like to avoid that.
813 void AndroidLogWrite(const char *buffer) {
814 char *copy = internal_strdup(buffer);
815 char *p = copy;
816 char *q;
817 // __android_log_write has an implicit message length limit.
818 // Print one line at a time.
819 do {
820 q = internal_strchr(p, '\n');
821 if (q) *q = '\0';
822 __android_log_write(ANDROID_LOG_INFO, NULL, p);
823 if (q) p = q + 1;
824 } while (q);
825 InternalFree(copy);
828 void GetExtraActivationFlags(char *buf, uptr size) {
829 CHECK(size > PROP_VALUE_MAX);
830 __system_property_get("asan.options", buf);
832 #endif
834 bool IsDeadlySignal(int signum) {
835 return (signum == SIGSEGV) && common_flags()->handle_segv;
838 } // namespace __sanitizer
840 #endif // SANITIZER_FREEBSD || SANITIZER_LINUX