* Add missing ChangeLog entry.
[official-gcc.git] / libsanitizer / sanitizer_common / sanitizer_linux.cc
blob8c7979fc6b56405005cc83f1e8e8afd6bf1201a2
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>
48 #if SANITIZER_FREEBSD
49 #include <sys/sysctl.h>
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 extern char **environ; // provided by crt1
57 #endif // SANITIZER_FREEBSD
59 #if !SANITIZER_ANDROID
60 #include <sys/signal.h>
61 #endif
63 #if SANITIZER_ANDROID
64 #include <android/log.h>
65 #include <sys/system_properties.h>
66 #endif
68 #if SANITIZER_LINUX
69 // <linux/time.h>
70 struct kernel_timeval {
71 long tv_sec;
72 long tv_usec;
75 // <linux/futex.h> is broken on some linux distributions.
76 const int FUTEX_WAIT = 0;
77 const int FUTEX_WAKE = 1;
78 #endif // SANITIZER_LINUX
80 // Are we using 32-bit or 64-bit Linux syscalls?
81 // x32 (which defines __x86_64__) has SANITIZER_WORDSIZE == 32
82 // but it still needs to use 64-bit syscalls.
83 #if SANITIZER_LINUX && (defined(__x86_64__) || SANITIZER_WORDSIZE == 64)
84 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 1
85 #else
86 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 0
87 #endif
89 namespace __sanitizer {
91 #if SANITIZER_LINUX && defined(__x86_64__)
92 #include "sanitizer_syscall_linux_x86_64.inc"
93 #else
94 #include "sanitizer_syscall_generic.inc"
95 #endif
97 // --------------- sanitizer_libc.h
98 uptr internal_mmap(void *addr, uptr length, int prot, int flags,
99 int fd, u64 offset) {
100 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
101 return internal_syscall(SYSCALL(mmap), (uptr)addr, length, prot, flags, fd,
102 offset);
103 #else
104 return internal_syscall(SYSCALL(mmap2), addr, length, prot, flags, fd,
105 offset);
106 #endif
109 uptr internal_munmap(void *addr, uptr length) {
110 return internal_syscall(SYSCALL(munmap), (uptr)addr, length);
113 uptr internal_close(fd_t fd) {
114 return internal_syscall(SYSCALL(close), fd);
117 uptr internal_open(const char *filename, int flags) {
118 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
119 return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags);
120 #else
121 return internal_syscall(SYSCALL(open), (uptr)filename, flags);
122 #endif
125 uptr internal_open(const char *filename, int flags, u32 mode) {
126 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
127 return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags,
128 mode);
129 #else
130 return internal_syscall(SYSCALL(open), (uptr)filename, flags, mode);
131 #endif
134 uptr OpenFile(const char *filename, bool write) {
135 return internal_open(filename,
136 write ? O_RDWR | O_CREAT /*| O_CLOEXEC*/ : O_RDONLY, 0660);
139 uptr internal_read(fd_t fd, void *buf, uptr count) {
140 sptr res;
141 HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(read), fd, (uptr)buf,
142 count));
143 return res;
146 uptr internal_write(fd_t fd, const void *buf, uptr count) {
147 sptr res;
148 HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(write), fd, (uptr)buf,
149 count));
150 return res;
153 uptr internal_ftruncate(fd_t fd, uptr size) {
154 sptr res;
155 HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(ftruncate), fd, size));
156 return res;
159 #if !SANITIZER_LINUX_USES_64BIT_SYSCALLS && !SANITIZER_FREEBSD
160 static void stat64_to_stat(struct stat64 *in, struct stat *out) {
161 internal_memset(out, 0, sizeof(*out));
162 out->st_dev = in->st_dev;
163 out->st_ino = in->st_ino;
164 out->st_mode = in->st_mode;
165 out->st_nlink = in->st_nlink;
166 out->st_uid = in->st_uid;
167 out->st_gid = in->st_gid;
168 out->st_rdev = in->st_rdev;
169 out->st_size = in->st_size;
170 out->st_blksize = in->st_blksize;
171 out->st_blocks = in->st_blocks;
172 out->st_atime = in->st_atime;
173 out->st_mtime = in->st_mtime;
174 out->st_ctime = in->st_ctime;
175 out->st_ino = in->st_ino;
177 #endif
179 uptr internal_stat(const char *path, void *buf) {
180 #if SANITIZER_FREEBSD
181 return internal_syscall(SYSCALL(stat), path, buf);
182 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
183 return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path,
184 (uptr)buf, 0);
185 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
186 return internal_syscall(SYSCALL(stat), (uptr)path, (uptr)buf);
187 #else
188 struct stat64 buf64;
189 int res = internal_syscall(SYSCALL(stat64), path, &buf64);
190 stat64_to_stat(&buf64, (struct stat *)buf);
191 return res;
192 #endif
195 uptr internal_lstat(const char *path, void *buf) {
196 #if SANITIZER_FREEBSD
197 return internal_syscall(SYSCALL(lstat), path, buf);
198 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
199 return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path,
200 (uptr)buf, AT_SYMLINK_NOFOLLOW);
201 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
202 return internal_syscall(SYSCALL(lstat), (uptr)path, (uptr)buf);
203 #else
204 struct stat64 buf64;
205 int res = internal_syscall(SYSCALL(lstat64), path, &buf64);
206 stat64_to_stat(&buf64, (struct stat *)buf);
207 return res;
208 #endif
211 uptr internal_fstat(fd_t fd, void *buf) {
212 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
213 return internal_syscall(SYSCALL(fstat), fd, (uptr)buf);
214 #else
215 struct stat64 buf64;
216 int res = internal_syscall(SYSCALL(fstat64), fd, &buf64);
217 stat64_to_stat(&buf64, (struct stat *)buf);
218 return res;
219 #endif
222 uptr internal_filesize(fd_t fd) {
223 struct stat st;
224 if (internal_fstat(fd, &st))
225 return -1;
226 return (uptr)st.st_size;
229 uptr internal_dup2(int oldfd, int newfd) {
230 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
231 return internal_syscall(SYSCALL(dup3), oldfd, newfd, 0);
232 #else
233 return internal_syscall(SYSCALL(dup2), oldfd, newfd);
234 #endif
237 uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
238 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
239 return internal_syscall(SYSCALL(readlinkat), AT_FDCWD,
240 (uptr)path, (uptr)buf, bufsize);
241 #else
242 return internal_syscall(SYSCALL(readlink), (uptr)path, (uptr)buf, bufsize);
243 #endif
246 uptr internal_unlink(const char *path) {
247 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
248 return internal_syscall(SYSCALL(unlinkat), AT_FDCWD, (uptr)path, 0);
249 #else
250 return internal_syscall(SYSCALL(unlink), (uptr)path);
251 #endif
254 uptr internal_rename(const char *oldpath, const char *newpath) {
255 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
256 return internal_syscall(SYSCALL(renameat), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
257 (uptr)newpath);
258 #else
259 return internal_syscall(SYSCALL(rename), (uptr)oldpath, (uptr)newpath);
260 #endif
263 uptr internal_sched_yield() {
264 return internal_syscall(SYSCALL(sched_yield));
267 void internal__exit(int exitcode) {
268 #if SANITIZER_FREEBSD
269 internal_syscall(SYSCALL(exit), exitcode);
270 #else
271 internal_syscall(SYSCALL(exit_group), exitcode);
272 #endif
273 Die(); // Unreachable.
276 uptr internal_execve(const char *filename, char *const argv[],
277 char *const envp[]) {
278 return internal_syscall(SYSCALL(execve), (uptr)filename, (uptr)argv,
279 (uptr)envp);
282 // ----------------- sanitizer_common.h
283 bool FileExists(const char *filename) {
284 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
285 struct stat st;
286 if (internal_syscall(SYSCALL(newfstatat), AT_FDCWD, filename, &st, 0))
287 return false;
288 #else
289 struct stat st;
290 if (internal_stat(filename, &st))
291 return false;
292 // Sanity check: filename is a regular file.
293 return S_ISREG(st.st_mode);
294 #endif
297 uptr GetTid() {
298 #if SANITIZER_FREEBSD
299 return (uptr)pthread_self();
300 #else
301 return internal_syscall(SYSCALL(gettid));
302 #endif
305 u64 NanoTime() {
306 #if SANITIZER_FREEBSD
307 timeval tv;
308 #else
309 kernel_timeval tv;
310 #endif
311 internal_memset(&tv, 0, sizeof(tv));
312 internal_syscall(SYSCALL(gettimeofday), (uptr)&tv, 0);
313 return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
316 // Like getenv, but reads env directly from /proc (on Linux) or parses the
317 // 'environ' array (on FreeBSD) and does not use libc. This function should be
318 // called first inside __asan_init.
319 const char *GetEnv(const char *name) {
320 #if SANITIZER_FREEBSD
321 if (::environ != 0) {
322 uptr NameLen = internal_strlen(name);
323 for (char **Env = ::environ; *Env != 0; Env++) {
324 if (internal_strncmp(*Env, name, NameLen) == 0 && (*Env)[NameLen] == '=')
325 return (*Env) + NameLen + 1;
328 return 0; // Not found.
329 #elif SANITIZER_LINUX
330 static char *environ;
331 static uptr len;
332 static bool inited;
333 if (!inited) {
334 inited = true;
335 uptr environ_size;
336 len = ReadFileToBuffer("/proc/self/environ",
337 &environ, &environ_size, 1 << 26);
339 if (!environ || len == 0) return 0;
340 uptr namelen = internal_strlen(name);
341 const char *p = environ;
342 while (*p != '\0') { // will happen at the \0\0 that terminates the buffer
343 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
344 const char* endp =
345 (char*)internal_memchr(p, '\0', len - (p - environ));
346 if (endp == 0) // this entry isn't NUL terminated
347 return 0;
348 else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') // Match.
349 return p + namelen + 1; // point after =
350 p = endp + 1;
352 return 0; // Not found.
353 #else
354 #error "Unsupported platform"
355 #endif
358 extern "C" {
359 SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
362 #if !SANITIZER_GO
363 static void ReadNullSepFileToArray(const char *path, char ***arr,
364 int arr_size) {
365 char *buff;
366 uptr buff_size = 0;
367 *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
368 ReadFileToBuffer(path, &buff, &buff_size, 1024 * 1024);
369 (*arr)[0] = buff;
370 int count, i;
371 for (count = 1, i = 1; ; i++) {
372 if (buff[i] == 0) {
373 if (buff[i+1] == 0) break;
374 (*arr)[count] = &buff[i+1];
375 CHECK_LE(count, arr_size - 1); // FIXME: make this more flexible.
376 count++;
379 (*arr)[count] = 0;
381 #endif
383 static void GetArgsAndEnv(char*** argv, char*** envp) {
384 #if !SANITIZER_GO
385 if (&__libc_stack_end) {
386 #endif
387 uptr* stack_end = (uptr*)__libc_stack_end;
388 int argc = *stack_end;
389 *argv = (char**)(stack_end + 1);
390 *envp = (char**)(stack_end + argc + 2);
391 #if !SANITIZER_GO
392 } else {
393 static const int kMaxArgv = 2000, kMaxEnvp = 2000;
394 ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
395 ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
397 #endif
400 void ReExec() {
401 char **argv, **envp;
402 GetArgsAndEnv(&argv, &envp);
403 uptr rv = internal_execve("/proc/self/exe", argv, envp);
404 int rverrno;
405 CHECK_EQ(internal_iserror(rv, &rverrno), true);
406 Printf("execve failed, errno %d\n", rverrno);
407 Die();
410 // Stub implementation of GetThreadStackAndTls for Go.
411 #if SANITIZER_GO
412 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
413 uptr *tls_addr, uptr *tls_size) {
414 *stk_addr = 0;
415 *stk_size = 0;
416 *tls_addr = 0;
417 *tls_size = 0;
419 #endif // SANITIZER_GO
421 enum MutexState {
422 MtxUnlocked = 0,
423 MtxLocked = 1,
424 MtxSleeping = 2
427 BlockingMutex::BlockingMutex(LinkerInitialized) {
428 CHECK_EQ(owner_, 0);
431 BlockingMutex::BlockingMutex() {
432 internal_memset(this, 0, sizeof(*this));
435 void BlockingMutex::Lock() {
436 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
437 if (atomic_exchange(m, MtxLocked, memory_order_acquire) == MtxUnlocked)
438 return;
439 while (atomic_exchange(m, MtxSleeping, memory_order_acquire) != MtxUnlocked) {
440 #if SANITIZER_FREEBSD
441 _umtx_op(m, UMTX_OP_WAIT_UINT, MtxSleeping, 0, 0);
442 #else
443 internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAIT, MtxSleeping, 0, 0, 0);
444 #endif
448 void BlockingMutex::Unlock() {
449 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
450 u32 v = atomic_exchange(m, MtxUnlocked, memory_order_relaxed);
451 CHECK_NE(v, MtxUnlocked);
452 if (v == MtxSleeping) {
453 #if SANITIZER_FREEBSD
454 _umtx_op(m, UMTX_OP_WAKE, 1, 0, 0);
455 #else
456 internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAKE, 1, 0, 0, 0);
457 #endif
461 void BlockingMutex::CheckLocked() {
462 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
463 CHECK_NE(MtxUnlocked, atomic_load(m, memory_order_relaxed));
466 // ----------------- sanitizer_linux.h
467 // The actual size of this structure is specified by d_reclen.
468 // Note that getdents64 uses a different structure format. We only provide the
469 // 32-bit syscall here.
470 struct linux_dirent {
471 #if SANITIZER_X32
472 u64 d_ino;
473 u64 d_off;
474 #else
475 unsigned long d_ino;
476 unsigned long d_off;
477 #endif
478 unsigned short d_reclen;
479 char d_name[256];
482 // Syscall wrappers.
483 uptr internal_ptrace(int request, int pid, void *addr, void *data) {
484 return internal_syscall(SYSCALL(ptrace), request, pid, (uptr)addr,
485 (uptr)data);
488 uptr internal_waitpid(int pid, int *status, int options) {
489 return internal_syscall(SYSCALL(wait4), pid, (uptr)status, options,
490 0 /* rusage */);
493 uptr internal_getpid() {
494 return internal_syscall(SYSCALL(getpid));
497 uptr internal_getppid() {
498 return internal_syscall(SYSCALL(getppid));
501 uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) {
502 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
503 return internal_syscall(SYSCALL(getdents64), fd, (uptr)dirp, count);
504 #else
505 return internal_syscall(SYSCALL(getdents), fd, (uptr)dirp, count);
506 #endif
509 uptr internal_lseek(fd_t fd, OFF_T offset, int whence) {
510 return internal_syscall(SYSCALL(lseek), fd, offset, whence);
513 #if SANITIZER_LINUX
514 uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
515 return internal_syscall(SYSCALL(prctl), option, arg2, arg3, arg4, arg5);
517 #endif
519 uptr internal_sigaltstack(const struct sigaltstack *ss,
520 struct sigaltstack *oss) {
521 return internal_syscall(SYSCALL(sigaltstack), (uptr)ss, (uptr)oss);
524 int internal_fork() {
525 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
526 return internal_syscall(SYSCALL(clone), SIGCHLD, 0);
527 #else
528 return internal_syscall(SYSCALL(fork));
529 #endif
532 #if SANITIZER_LINUX
533 // Doesn't set sa_restorer, use with caution (see below).
534 int internal_sigaction_norestorer(int signum, const void *act, void *oldact) {
535 __sanitizer_kernel_sigaction_t k_act, k_oldact;
536 internal_memset(&k_act, 0, sizeof(__sanitizer_kernel_sigaction_t));
537 internal_memset(&k_oldact, 0, sizeof(__sanitizer_kernel_sigaction_t));
538 const __sanitizer_sigaction *u_act = (__sanitizer_sigaction *)act;
539 __sanitizer_sigaction *u_oldact = (__sanitizer_sigaction *)oldact;
540 if (u_act) {
541 k_act.handler = u_act->handler;
542 k_act.sigaction = u_act->sigaction;
543 internal_memcpy(&k_act.sa_mask, &u_act->sa_mask,
544 sizeof(__sanitizer_kernel_sigset_t));
545 k_act.sa_flags = u_act->sa_flags;
546 // FIXME: most often sa_restorer is unset, however the kernel requires it
547 // to point to a valid signal restorer that calls the rt_sigreturn syscall.
548 // If sa_restorer passed to the kernel is NULL, the program may crash upon
549 // signal delivery or fail to unwind the stack in the signal handler.
550 // libc implementation of sigaction() passes its own restorer to
551 // rt_sigaction, so we need to do the same (we'll need to reimplement the
552 // restorers; for x86_64 the restorer address can be obtained from
553 // oldact->sa_restorer upon a call to sigaction(xxx, NULL, oldact).
554 k_act.sa_restorer = u_act->sa_restorer;
557 uptr result = internal_syscall(SYSCALL(rt_sigaction), (uptr)signum,
558 (uptr)(u_act ? &k_act : NULL),
559 (uptr)(u_oldact ? &k_oldact : NULL),
560 (uptr)sizeof(__sanitizer_kernel_sigset_t));
562 if ((result == 0) && u_oldact) {
563 u_oldact->handler = k_oldact.handler;
564 u_oldact->sigaction = k_oldact.sigaction;
565 internal_memcpy(&u_oldact->sa_mask, &k_oldact.sa_mask,
566 sizeof(__sanitizer_kernel_sigset_t));
567 u_oldact->sa_flags = k_oldact.sa_flags;
568 u_oldact->sa_restorer = k_oldact.sa_restorer;
570 return result;
572 #endif // SANITIZER_LINUX
574 uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
575 __sanitizer_sigset_t *oldset) {
576 #if SANITIZER_FREEBSD
577 return internal_syscall(SYSCALL(sigprocmask), how, set, oldset);
578 #else
579 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
580 __sanitizer_kernel_sigset_t *k_oldset = (__sanitizer_kernel_sigset_t *)oldset;
581 return internal_syscall(SYSCALL(rt_sigprocmask), (uptr)how,
582 (uptr)&k_set->sig[0], (uptr)&k_oldset->sig[0],
583 sizeof(__sanitizer_kernel_sigset_t));
584 #endif
587 void internal_sigfillset(__sanitizer_sigset_t *set) {
588 internal_memset(set, 0xff, sizeof(*set));
591 #if SANITIZER_LINUX
592 void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
593 signum -= 1;
594 CHECK_GE(signum, 0);
595 CHECK_LT(signum, sizeof(*set) * 8);
596 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
597 const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
598 const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
599 k_set->sig[idx] &= ~(1 << bit);
601 #endif // SANITIZER_LINUX
603 // ThreadLister implementation.
604 ThreadLister::ThreadLister(int pid)
605 : pid_(pid),
606 descriptor_(-1),
607 buffer_(4096),
608 error_(true),
609 entry_((struct linux_dirent *)buffer_.data()),
610 bytes_read_(0) {
611 char task_directory_path[80];
612 internal_snprintf(task_directory_path, sizeof(task_directory_path),
613 "/proc/%d/task/", pid);
614 uptr openrv = internal_open(task_directory_path, O_RDONLY | O_DIRECTORY);
615 if (internal_iserror(openrv)) {
616 error_ = true;
617 Report("Can't open /proc/%d/task for reading.\n", pid);
618 } else {
619 error_ = false;
620 descriptor_ = openrv;
624 int ThreadLister::GetNextTID() {
625 int tid = -1;
626 do {
627 if (error_)
628 return -1;
629 if ((char *)entry_ >= &buffer_[bytes_read_] && !GetDirectoryEntries())
630 return -1;
631 if (entry_->d_ino != 0 && entry_->d_name[0] >= '0' &&
632 entry_->d_name[0] <= '9') {
633 // Found a valid tid.
634 tid = (int)internal_atoll(entry_->d_name);
636 entry_ = (struct linux_dirent *)(((char *)entry_) + entry_->d_reclen);
637 } while (tid < 0);
638 return tid;
641 void ThreadLister::Reset() {
642 if (error_ || descriptor_ < 0)
643 return;
644 internal_lseek(descriptor_, 0, SEEK_SET);
647 ThreadLister::~ThreadLister() {
648 if (descriptor_ >= 0)
649 internal_close(descriptor_);
652 bool ThreadLister::error() { return error_; }
654 bool ThreadLister::GetDirectoryEntries() {
655 CHECK_GE(descriptor_, 0);
656 CHECK_NE(error_, true);
657 bytes_read_ = internal_getdents(descriptor_,
658 (struct linux_dirent *)buffer_.data(),
659 buffer_.size());
660 if (internal_iserror(bytes_read_)) {
661 Report("Can't read directory entries from /proc/%d/task.\n", pid_);
662 error_ = true;
663 return false;
664 } else if (bytes_read_ == 0) {
665 return false;
667 entry_ = (struct linux_dirent *)buffer_.data();
668 return true;
671 uptr GetPageSize() {
672 #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__))
673 return EXEC_PAGESIZE;
674 #else
675 return sysconf(_SC_PAGESIZE); // EXEC_PAGESIZE may not be trustworthy.
676 #endif
679 static char proc_self_exe_cache_str[kMaxPathLength];
680 static uptr proc_self_exe_cache_len = 0;
682 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
683 if (proc_self_exe_cache_len > 0) {
684 // If available, use the cached module name.
685 uptr module_name_len =
686 internal_snprintf(buf, buf_len, "%s", proc_self_exe_cache_str);
687 CHECK_LT(module_name_len, buf_len);
688 return module_name_len;
690 #if SANITIZER_FREEBSD
691 const int Mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
692 size_t Size = buf_len;
693 bool IsErr = (sysctl(Mib, 4, buf, &Size, NULL, 0) != 0);
694 int readlink_error = IsErr ? errno : 0;
695 uptr module_name_len = Size;
696 #else
697 uptr module_name_len = internal_readlink(
698 "/proc/self/exe", buf, buf_len);
699 int readlink_error;
700 bool IsErr = internal_iserror(module_name_len, &readlink_error);
701 #endif
702 if (IsErr) {
703 // We can't read /proc/self/exe for some reason, assume the name of the
704 // binary is unknown.
705 Report("WARNING: readlink(\"/proc/self/exe\") failed with errno %d, "
706 "some stack frames may not be symbolized\n", readlink_error);
707 module_name_len = internal_snprintf(buf, buf_len, "/proc/self/exe");
708 CHECK_LT(module_name_len, buf_len);
710 return module_name_len;
713 void CacheBinaryName() {
714 if (!proc_self_exe_cache_len) {
715 proc_self_exe_cache_len =
716 ReadBinaryName(proc_self_exe_cache_str, kMaxPathLength);
720 // Match full names of the form /path/to/base_name{-,.}*
721 bool LibraryNameIs(const char *full_name, const char *base_name) {
722 const char *name = full_name;
723 // Strip path.
724 while (*name != '\0') name++;
725 while (name > full_name && *name != '/') name--;
726 if (*name == '/') name++;
727 uptr base_name_length = internal_strlen(base_name);
728 if (internal_strncmp(name, base_name, base_name_length)) return false;
729 return (name[base_name_length] == '-' || name[base_name_length] == '.');
732 #if !SANITIZER_ANDROID
733 // Call cb for each region mapped by map.
734 void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr)) {
735 #if !SANITIZER_FREEBSD
736 typedef ElfW(Phdr) Elf_Phdr;
737 typedef ElfW(Ehdr) Elf_Ehdr;
738 #endif // !SANITIZER_FREEBSD
739 char *base = (char *)map->l_addr;
740 Elf_Ehdr *ehdr = (Elf_Ehdr *)base;
741 char *phdrs = base + ehdr->e_phoff;
742 char *phdrs_end = phdrs + ehdr->e_phnum * ehdr->e_phentsize;
744 // Find the segment with the minimum base so we can "relocate" the p_vaddr
745 // fields. Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
746 // objects have a non-zero base.
747 uptr preferred_base = (uptr)-1;
748 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
749 Elf_Phdr *phdr = (Elf_Phdr *)iter;
750 if (phdr->p_type == PT_LOAD && preferred_base > (uptr)phdr->p_vaddr)
751 preferred_base = (uptr)phdr->p_vaddr;
754 // Compute the delta from the real base to get a relocation delta.
755 sptr delta = (uptr)base - preferred_base;
756 // Now we can figure out what the loader really mapped.
757 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
758 Elf_Phdr *phdr = (Elf_Phdr *)iter;
759 if (phdr->p_type == PT_LOAD) {
760 uptr seg_start = phdr->p_vaddr + delta;
761 uptr seg_end = seg_start + phdr->p_memsz;
762 // None of these values are aligned. We consider the ragged edges of the
763 // load command as defined, since they are mapped from the file.
764 seg_start = RoundDownTo(seg_start, GetPageSizeCached());
765 seg_end = RoundUpTo(seg_end, GetPageSizeCached());
766 cb((void *)seg_start, seg_end - seg_start);
770 #endif
772 #if defined(__x86_64__) && SANITIZER_LINUX
773 // We cannot use glibc's clone wrapper, because it messes with the child
774 // task's TLS. It writes the PID and TID of the child task to its thread
775 // descriptor, but in our case the child task shares the thread descriptor with
776 // the parent (because we don't know how to allocate a new thread
777 // descriptor to keep glibc happy). So the stock version of clone(), when
778 // used with CLONE_VM, would end up corrupting the parent's thread descriptor.
779 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
780 int *parent_tidptr, void *newtls, int *child_tidptr) {
781 long long res;
782 if (!fn || !child_stack)
783 return -EINVAL;
784 CHECK_EQ(0, (uptr)child_stack % 16);
785 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
786 ((unsigned long long *)child_stack)[0] = (uptr)fn;
787 ((unsigned long long *)child_stack)[1] = (uptr)arg;
788 register void *r8 __asm__("r8") = newtls;
789 register int *r10 __asm__("r10") = child_tidptr;
790 __asm__ __volatile__(
791 /* %rax = syscall(%rax = SYSCALL(clone),
792 * %rdi = flags,
793 * %rsi = child_stack,
794 * %rdx = parent_tidptr,
795 * %r8 = new_tls,
796 * %r10 = child_tidptr)
798 "syscall\n"
800 /* if (%rax != 0)
801 * return;
803 "testq %%rax,%%rax\n"
804 "jnz 1f\n"
806 /* In the child. Terminate unwind chain. */
807 // XXX: We should also terminate the CFI unwind chain
808 // here. Unfortunately clang 3.2 doesn't support the
809 // necessary CFI directives, so we skip that part.
810 "xorq %%rbp,%%rbp\n"
812 /* Call "fn(arg)". */
813 "popq %%rax\n"
814 "popq %%rdi\n"
815 "call *%%rax\n"
817 /* Call _exit(%rax). */
818 "movq %%rax,%%rdi\n"
819 "movq %2,%%rax\n"
820 "syscall\n"
822 /* Return to parent. */
823 "1:\n"
824 : "=a" (res)
825 : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
826 "S"(child_stack),
827 "D"(flags),
828 "d"(parent_tidptr),
829 "r"(r8),
830 "r"(r10)
831 : "rsp", "memory", "r11", "rcx");
832 return res;
834 #endif // defined(__x86_64__) && SANITIZER_LINUX
836 #if SANITIZER_ANDROID
837 static atomic_uint8_t android_log_initialized;
839 void AndroidLogInit() {
840 atomic_store(&android_log_initialized, 1, memory_order_release);
842 // This thing is not, strictly speaking, async signal safe, but it does not seem
843 // to cause any issues. Alternative is writing to log devices directly, but
844 // their location and message format might change in the future, so we'd really
845 // like to avoid that.
846 void AndroidLogWrite(const char *buffer) {
847 if (!atomic_load(&android_log_initialized, memory_order_acquire))
848 return;
850 char *copy = internal_strdup(buffer);
851 char *p = copy;
852 char *q;
853 // __android_log_write has an implicit message length limit.
854 // Print one line at a time.
855 do {
856 q = internal_strchr(p, '\n');
857 if (q) *q = '\0';
858 __android_log_write(ANDROID_LOG_INFO, NULL, p);
859 if (q) p = q + 1;
860 } while (q);
861 InternalFree(copy);
864 void GetExtraActivationFlags(char *buf, uptr size) {
865 CHECK(size > PROP_VALUE_MAX);
866 __system_property_get("asan.options", buf);
868 #endif
870 bool IsDeadlySignal(int signum) {
871 return (signum == SIGSEGV) && common_flags()->handle_segv;
874 } // namespace __sanitizer
876 #endif // SANITIZER_FREEBSD || SANITIZER_LINUX