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