]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/sanitizer_common/sanitizer_linux.cc
Update lldb to trunk r290819 and resolve conflicts.
[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
17 #if SANITIZER_FREEBSD || SANITIZER_LINUX
18
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 // For mips64, syscall(__NR_stat) fills the buffer in the 'struct kernel_stat'
35 // format. Struct kernel_stat is defined as 'struct stat' in asm/stat.h. To
36 // access stat from asm/stat.h, without conflicting with definition in
37 // sys/stat.h, we use this trick.
38 #if defined(__mips64)
39 #include <asm/unistd.h>
40 #include <sys/types.h>
41 #define stat kernel_stat
42 #include <asm/stat.h>
43 #undef stat
44 #endif
45
46 #include <dlfcn.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <link.h>
50 #include <pthread.h>
51 #include <sched.h>
52 #include <sys/mman.h>
53 #include <sys/ptrace.h>
54 #include <sys/resource.h>
55 #include <sys/stat.h>
56 #include <sys/syscall.h>
57 #include <sys/time.h>
58 #include <sys/types.h>
59 #include <ucontext.h>
60 #include <unistd.h>
61
62 #if SANITIZER_FREEBSD
63 #include <sys/exec.h>
64 #include <sys/sysctl.h>
65 #include <vm/vm_param.h>
66 #include <vm/pmap.h>
67 #include <machine/atomic.h>
68 extern "C" {
69 // <sys/umtx.h> must be included after <errno.h> and <sys/types.h> on
70 // FreeBSD 9.2 and 10.0.
71 #include <sys/umtx.h>
72 }
73 extern char **environ;  // provided by crt1
74 #endif  // SANITIZER_FREEBSD
75
76 #if !SANITIZER_ANDROID
77 #include <sys/signal.h>
78 #endif
79
80 #if SANITIZER_LINUX
81 // <linux/time.h>
82 struct kernel_timeval {
83   long tv_sec;
84   long tv_usec;
85 };
86
87 // <linux/futex.h> is broken on some linux distributions.
88 const int FUTEX_WAIT = 0;
89 const int FUTEX_WAKE = 1;
90 #endif  // SANITIZER_LINUX
91
92 // Are we using 32-bit or 64-bit Linux syscalls?
93 // x32 (which defines __x86_64__) has SANITIZER_WORDSIZE == 32
94 // but it still needs to use 64-bit syscalls.
95 #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__powerpc64__) || \
96     SANITIZER_WORDSIZE == 64)
97 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 1
98 #else
99 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 0
100 #endif
101
102 #if defined(__x86_64__)
103 extern "C" {
104 extern void internal_sigreturn();
105 }
106 #endif
107
108 namespace __sanitizer {
109
110 #if SANITIZER_LINUX && defined(__x86_64__)
111 #include "sanitizer_syscall_linux_x86_64.inc"
112 #elif SANITIZER_LINUX && defined(__aarch64__)
113 #include "sanitizer_syscall_linux_aarch64.inc"
114 #else
115 #include "sanitizer_syscall_generic.inc"
116 #endif
117
118 // --------------- sanitizer_libc.h
119 #if !SANITIZER_S390
120 uptr internal_mmap(void *addr, uptr length, int prot, int flags, int fd,
121                    OFF_T offset) {
122 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
123   return internal_syscall(SYSCALL(mmap), (uptr)addr, length, prot, flags, fd,
124                           offset);
125 #else
126   // mmap2 specifies file offset in 4096-byte units.
127   CHECK(IsAligned(offset, 4096));
128   return internal_syscall(SYSCALL(mmap2), addr, length, prot, flags, fd,
129                           offset / 4096);
130 #endif
131 }
132 #endif // !SANITIZER_S390
133
134 uptr internal_munmap(void *addr, uptr length) {
135   return internal_syscall(SYSCALL(munmap), (uptr)addr, length);
136 }
137
138 int internal_mprotect(void *addr, uptr length, int prot) {
139   return internal_syscall(SYSCALL(mprotect), (uptr)addr, length, prot);
140 }
141
142 uptr internal_close(fd_t fd) {
143   return internal_syscall(SYSCALL(close), fd);
144 }
145
146 uptr internal_open(const char *filename, int flags) {
147 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
148   return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags);
149 #else
150   return internal_syscall(SYSCALL(open), (uptr)filename, flags);
151 #endif
152 }
153
154 uptr internal_open(const char *filename, int flags, u32 mode) {
155 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
156   return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags,
157                           mode);
158 #else
159   return internal_syscall(SYSCALL(open), (uptr)filename, flags, mode);
160 #endif
161 }
162
163 uptr internal_read(fd_t fd, void *buf, uptr count) {
164   sptr res;
165   HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(read), fd, (uptr)buf,
166                count));
167   return res;
168 }
169
170 uptr internal_write(fd_t fd, const void *buf, uptr count) {
171   sptr res;
172   HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(write), fd, (uptr)buf,
173                count));
174   return res;
175 }
176
177 uptr internal_ftruncate(fd_t fd, uptr size) {
178   sptr res;
179   HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(ftruncate), fd,
180                (OFF_T)size));
181   return res;
182 }
183
184 #if !SANITIZER_LINUX_USES_64BIT_SYSCALLS && !SANITIZER_FREEBSD
185 static void stat64_to_stat(struct stat64 *in, struct stat *out) {
186   internal_memset(out, 0, sizeof(*out));
187   out->st_dev = in->st_dev;
188   out->st_ino = in->st_ino;
189   out->st_mode = in->st_mode;
190   out->st_nlink = in->st_nlink;
191   out->st_uid = in->st_uid;
192   out->st_gid = in->st_gid;
193   out->st_rdev = in->st_rdev;
194   out->st_size = in->st_size;
195   out->st_blksize = in->st_blksize;
196   out->st_blocks = in->st_blocks;
197   out->st_atime = in->st_atime;
198   out->st_mtime = in->st_mtime;
199   out->st_ctime = in->st_ctime;
200   out->st_ino = in->st_ino;
201 }
202 #endif
203
204 #if defined(__mips64)
205 static void kernel_stat_to_stat(struct kernel_stat *in, struct stat *out) {
206   internal_memset(out, 0, sizeof(*out));
207   out->st_dev = in->st_dev;
208   out->st_ino = in->st_ino;
209   out->st_mode = in->st_mode;
210   out->st_nlink = in->st_nlink;
211   out->st_uid = in->st_uid;
212   out->st_gid = in->st_gid;
213   out->st_rdev = in->st_rdev;
214   out->st_size = in->st_size;
215   out->st_blksize = in->st_blksize;
216   out->st_blocks = in->st_blocks;
217   out->st_atime = in->st_atime_nsec;
218   out->st_mtime = in->st_mtime_nsec;
219   out->st_ctime = in->st_ctime_nsec;
220   out->st_ino = in->st_ino;
221 }
222 #endif
223
224 uptr internal_stat(const char *path, void *buf) {
225 #if SANITIZER_FREEBSD
226   return internal_syscall(SYSCALL(stat), path, buf);
227 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
228   return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path,
229                           (uptr)buf, 0);
230 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
231 # if defined(__mips64)
232   // For mips64, stat syscall fills buffer in the format of kernel_stat
233   struct kernel_stat kbuf;
234   int res = internal_syscall(SYSCALL(stat), path, &kbuf);
235   kernel_stat_to_stat(&kbuf, (struct stat *)buf);
236   return res;
237 # else
238   return internal_syscall(SYSCALL(stat), (uptr)path, (uptr)buf);
239 # endif
240 #else
241   struct stat64 buf64;
242   int res = internal_syscall(SYSCALL(stat64), path, &buf64);
243   stat64_to_stat(&buf64, (struct stat *)buf);
244   return res;
245 #endif
246 }
247
248 uptr internal_lstat(const char *path, void *buf) {
249 #if SANITIZER_FREEBSD
250   return internal_syscall(SYSCALL(lstat), path, buf);
251 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
252   return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path,
253                          (uptr)buf, AT_SYMLINK_NOFOLLOW);
254 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
255 # if SANITIZER_MIPS64
256   // For mips64, lstat syscall fills buffer in the format of kernel_stat
257   struct kernel_stat kbuf;
258   int res = internal_syscall(SYSCALL(lstat), path, &kbuf);
259   kernel_stat_to_stat(&kbuf, (struct stat *)buf);
260   return res;
261 # else
262   return internal_syscall(SYSCALL(lstat), (uptr)path, (uptr)buf);
263 # endif
264 #else
265   struct stat64 buf64;
266   int res = internal_syscall(SYSCALL(lstat64), path, &buf64);
267   stat64_to_stat(&buf64, (struct stat *)buf);
268   return res;
269 #endif
270 }
271
272 uptr internal_fstat(fd_t fd, void *buf) {
273 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
274 # if SANITIZER_MIPS64
275   // For mips64, fstat syscall fills buffer in the format of kernel_stat
276   struct kernel_stat kbuf;
277   int res = internal_syscall(SYSCALL(fstat), fd, &kbuf);
278   kernel_stat_to_stat(&kbuf, (struct stat *)buf);
279   return res;
280 # else
281   return internal_syscall(SYSCALL(fstat), fd, (uptr)buf);
282 # endif
283 #else
284   struct stat64 buf64;
285   int res = internal_syscall(SYSCALL(fstat64), fd, &buf64);
286   stat64_to_stat(&buf64, (struct stat *)buf);
287   return res;
288 #endif
289 }
290
291 uptr internal_filesize(fd_t fd) {
292   struct stat st;
293   if (internal_fstat(fd, &st))
294     return -1;
295   return (uptr)st.st_size;
296 }
297
298 uptr internal_dup2(int oldfd, int newfd) {
299 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
300   return internal_syscall(SYSCALL(dup3), oldfd, newfd, 0);
301 #else
302   return internal_syscall(SYSCALL(dup2), oldfd, newfd);
303 #endif
304 }
305
306 uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
307 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
308   return internal_syscall(SYSCALL(readlinkat), AT_FDCWD,
309                           (uptr)path, (uptr)buf, bufsize);
310 #else
311   return internal_syscall(SYSCALL(readlink), (uptr)path, (uptr)buf, bufsize);
312 #endif
313 }
314
315 uptr internal_unlink(const char *path) {
316 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
317   return internal_syscall(SYSCALL(unlinkat), AT_FDCWD, (uptr)path, 0);
318 #else
319   return internal_syscall(SYSCALL(unlink), (uptr)path);
320 #endif
321 }
322
323 uptr internal_rename(const char *oldpath, const char *newpath) {
324 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
325   return internal_syscall(SYSCALL(renameat), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
326                           (uptr)newpath);
327 #else
328   return internal_syscall(SYSCALL(rename), (uptr)oldpath, (uptr)newpath);
329 #endif
330 }
331
332 uptr internal_sched_yield() {
333   return internal_syscall(SYSCALL(sched_yield));
334 }
335
336 void internal__exit(int exitcode) {
337 #if SANITIZER_FREEBSD
338   internal_syscall(SYSCALL(exit), exitcode);
339 #else
340   internal_syscall(SYSCALL(exit_group), exitcode);
341 #endif
342   Die();  // Unreachable.
343 }
344
345 unsigned int internal_sleep(unsigned int seconds) {
346   struct timespec ts;
347   ts.tv_sec = 1;
348   ts.tv_nsec = 0;
349   int res = internal_syscall(SYSCALL(nanosleep), &ts, &ts);
350   if (res) return ts.tv_sec;
351   return 0;
352 }
353
354 uptr internal_execve(const char *filename, char *const argv[],
355                      char *const envp[]) {
356   return internal_syscall(SYSCALL(execve), (uptr)filename, (uptr)argv,
357                           (uptr)envp);
358 }
359
360 // ----------------- sanitizer_common.h
361 bool FileExists(const char *filename) {
362   struct stat st;
363 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
364   if (internal_syscall(SYSCALL(newfstatat), AT_FDCWD, filename, &st, 0))
365 #else
366   if (internal_stat(filename, &st))
367 #endif
368     return false;
369   // Sanity check: filename is a regular file.
370   return S_ISREG(st.st_mode);
371 }
372
373 uptr GetTid() {
374 #if SANITIZER_FREEBSD
375   return (uptr)pthread_self();
376 #else
377   return internal_syscall(SYSCALL(gettid));
378 #endif
379 }
380
381 u64 NanoTime() {
382 #if SANITIZER_FREEBSD
383   timeval tv;
384 #else
385   kernel_timeval tv;
386 #endif
387   internal_memset(&tv, 0, sizeof(tv));
388   internal_syscall(SYSCALL(gettimeofday), (uptr)&tv, 0);
389   return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
390 }
391
392 // Like getenv, but reads env directly from /proc (on Linux) or parses the
393 // 'environ' array (on FreeBSD) and does not use libc. This function should be
394 // called first inside __asan_init.
395 const char *GetEnv(const char *name) {
396 #if SANITIZER_FREEBSD
397   if (::environ != 0) {
398     uptr NameLen = internal_strlen(name);
399     for (char **Env = ::environ; *Env != 0; Env++) {
400       if (internal_strncmp(*Env, name, NameLen) == 0 && (*Env)[NameLen] == '=')
401         return (*Env) + NameLen + 1;
402     }
403   }
404   return 0;  // Not found.
405 #elif SANITIZER_LINUX
406   static char *environ;
407   static uptr len;
408   static bool inited;
409   if (!inited) {
410     inited = true;
411     uptr environ_size;
412     if (!ReadFileToBuffer("/proc/self/environ", &environ, &environ_size, &len))
413       environ = nullptr;
414   }
415   if (!environ || len == 0) return nullptr;
416   uptr namelen = internal_strlen(name);
417   const char *p = environ;
418   while (*p != '\0') {  // will happen at the \0\0 that terminates the buffer
419     // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
420     const char* endp =
421         (char*)internal_memchr(p, '\0', len - (p - environ));
422     if (!endp)  // this entry isn't NUL terminated
423       return nullptr;
424     else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=')  // Match.
425       return p + namelen + 1;  // point after =
426     p = endp + 1;
427   }
428   return nullptr;  // Not found.
429 #else
430 #error "Unsupported platform"
431 #endif
432 }
433
434 #if !SANITIZER_FREEBSD
435 extern "C" {
436   SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
437 }
438 #endif
439
440 #if !SANITIZER_GO && !SANITIZER_FREEBSD
441 static void ReadNullSepFileToArray(const char *path, char ***arr,
442                                    int arr_size) {
443   char *buff;
444   uptr buff_size;
445   uptr buff_len;
446   *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
447   if (!ReadFileToBuffer(path, &buff, &buff_size, &buff_len, 1024 * 1024)) {
448     (*arr)[0] = nullptr;
449     return;
450   }
451   (*arr)[0] = buff;
452   int count, i;
453   for (count = 1, i = 1; ; i++) {
454     if (buff[i] == 0) {
455       if (buff[i+1] == 0) break;
456       (*arr)[count] = &buff[i+1];
457       CHECK_LE(count, arr_size - 1);  // FIXME: make this more flexible.
458       count++;
459     }
460   }
461   (*arr)[count] = nullptr;
462 }
463 #endif
464
465 static void GetArgsAndEnv(char ***argv, char ***envp) {
466 #if !SANITIZER_FREEBSD
467 #if !SANITIZER_GO
468   if (&__libc_stack_end) {
469 #endif
470     uptr* stack_end = (uptr*)__libc_stack_end;
471     int argc = *stack_end;
472     *argv = (char**)(stack_end + 1);
473     *envp = (char**)(stack_end + argc + 2);
474 #if !SANITIZER_GO
475   } else {
476     static const int kMaxArgv = 2000, kMaxEnvp = 2000;
477     ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
478     ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
479   }
480 #endif
481 #else
482   // On FreeBSD, retrieving the argument and environment arrays is done via the
483   // kern.ps_strings sysctl, which returns a pointer to a structure containing
484   // this information. See also <sys/exec.h>.
485   ps_strings *pss;
486   size_t sz = sizeof(pss);
487   if (sysctlbyname("kern.ps_strings", &pss, &sz, NULL, 0) == -1) {
488     Printf("sysctl kern.ps_strings failed\n");
489     Die();
490   }
491   *argv = pss->ps_argvstr;
492   *envp = pss->ps_envstr;
493 #endif
494 }
495
496 char **GetArgv() {
497   char **argv, **envp;
498   GetArgsAndEnv(&argv, &envp);
499   return argv;
500 }
501
502 void ReExec() {
503   char **argv, **envp;
504   GetArgsAndEnv(&argv, &envp);
505   uptr rv = internal_execve("/proc/self/exe", argv, envp);
506   int rverrno;
507   CHECK_EQ(internal_iserror(rv, &rverrno), true);
508   Printf("execve failed, errno %d\n", rverrno);
509   Die();
510 }
511
512 enum MutexState {
513   MtxUnlocked = 0,
514   MtxLocked = 1,
515   MtxSleeping = 2
516 };
517
518 BlockingMutex::BlockingMutex() {
519   internal_memset(this, 0, sizeof(*this));
520 }
521
522 void BlockingMutex::Lock() {
523   CHECK_EQ(owner_, 0);
524   atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
525   if (atomic_exchange(m, MtxLocked, memory_order_acquire) == MtxUnlocked)
526     return;
527   while (atomic_exchange(m, MtxSleeping, memory_order_acquire) != MtxUnlocked) {
528 #if SANITIZER_FREEBSD
529     _umtx_op(m, UMTX_OP_WAIT_UINT, MtxSleeping, 0, 0);
530 #else
531     internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAIT, MtxSleeping, 0, 0, 0);
532 #endif
533   }
534 }
535
536 void BlockingMutex::Unlock() {
537   atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
538   u32 v = atomic_exchange(m, MtxUnlocked, memory_order_relaxed);
539   CHECK_NE(v, MtxUnlocked);
540   if (v == MtxSleeping) {
541 #if SANITIZER_FREEBSD
542     _umtx_op(m, UMTX_OP_WAKE, 1, 0, 0);
543 #else
544     internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAKE, 1, 0, 0, 0);
545 #endif
546   }
547 }
548
549 void BlockingMutex::CheckLocked() {
550   atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
551   CHECK_NE(MtxUnlocked, atomic_load(m, memory_order_relaxed));
552 }
553
554 // ----------------- sanitizer_linux.h
555 // The actual size of this structure is specified by d_reclen.
556 // Note that getdents64 uses a different structure format. We only provide the
557 // 32-bit syscall here.
558 struct linux_dirent {
559 #if SANITIZER_X32 || defined(__aarch64__)
560   u64 d_ino;
561   u64 d_off;
562 #else
563   unsigned long      d_ino;
564   unsigned long      d_off;
565 #endif
566   unsigned short     d_reclen;
567 #ifdef __aarch64__
568   unsigned char      d_type;
569 #endif
570   char               d_name[256];
571 };
572
573 // Syscall wrappers.
574 uptr internal_ptrace(int request, int pid, void *addr, void *data) {
575   return internal_syscall(SYSCALL(ptrace), request, pid, (uptr)addr,
576                           (uptr)data);
577 }
578
579 uptr internal_waitpid(int pid, int *status, int options) {
580   return internal_syscall(SYSCALL(wait4), pid, (uptr)status, options,
581                           0 /* rusage */);
582 }
583
584 uptr internal_getpid() {
585   return internal_syscall(SYSCALL(getpid));
586 }
587
588 uptr internal_getppid() {
589   return internal_syscall(SYSCALL(getppid));
590 }
591
592 uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) {
593 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
594   return internal_syscall(SYSCALL(getdents64), fd, (uptr)dirp, count);
595 #else
596   return internal_syscall(SYSCALL(getdents), fd, (uptr)dirp, count);
597 #endif
598 }
599
600 uptr internal_lseek(fd_t fd, OFF_T offset, int whence) {
601   return internal_syscall(SYSCALL(lseek), fd, offset, whence);
602 }
603
604 #if SANITIZER_LINUX
605 uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
606   return internal_syscall(SYSCALL(prctl), option, arg2, arg3, arg4, arg5);
607 }
608 #endif
609
610 uptr internal_sigaltstack(const struct sigaltstack *ss,
611                          struct sigaltstack *oss) {
612   return internal_syscall(SYSCALL(sigaltstack), (uptr)ss, (uptr)oss);
613 }
614
615 int internal_fork() {
616 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
617   return internal_syscall(SYSCALL(clone), SIGCHLD, 0);
618 #else
619   return internal_syscall(SYSCALL(fork));
620 #endif
621 }
622
623 #if SANITIZER_LINUX
624 #define SA_RESTORER 0x04000000
625 // Doesn't set sa_restorer if the caller did not set it, so use with caution
626 //(see below).
627 int internal_sigaction_norestorer(int signum, const void *act, void *oldact) {
628   __sanitizer_kernel_sigaction_t k_act, k_oldact;
629   internal_memset(&k_act, 0, sizeof(__sanitizer_kernel_sigaction_t));
630   internal_memset(&k_oldact, 0, sizeof(__sanitizer_kernel_sigaction_t));
631   const __sanitizer_sigaction *u_act = (const __sanitizer_sigaction *)act;
632   __sanitizer_sigaction *u_oldact = (__sanitizer_sigaction *)oldact;
633   if (u_act) {
634     k_act.handler = u_act->handler;
635     k_act.sigaction = u_act->sigaction;
636     internal_memcpy(&k_act.sa_mask, &u_act->sa_mask,
637                     sizeof(__sanitizer_kernel_sigset_t));
638     // Without SA_RESTORER kernel ignores the calls (probably returns EINVAL).
639     k_act.sa_flags = u_act->sa_flags | SA_RESTORER;
640     // FIXME: most often sa_restorer is unset, however the kernel requires it
641     // to point to a valid signal restorer that calls the rt_sigreturn syscall.
642     // If sa_restorer passed to the kernel is NULL, the program may crash upon
643     // signal delivery or fail to unwind the stack in the signal handler.
644     // libc implementation of sigaction() passes its own restorer to
645     // rt_sigaction, so we need to do the same (we'll need to reimplement the
646     // restorers; for x86_64 the restorer address can be obtained from
647     // oldact->sa_restorer upon a call to sigaction(xxx, NULL, oldact).
648 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
649     k_act.sa_restorer = u_act->sa_restorer;
650 #endif
651   }
652
653   uptr result = internal_syscall(SYSCALL(rt_sigaction), (uptr)signum,
654       (uptr)(u_act ? &k_act : nullptr),
655       (uptr)(u_oldact ? &k_oldact : nullptr),
656       (uptr)sizeof(__sanitizer_kernel_sigset_t));
657
658   if ((result == 0) && u_oldact) {
659     u_oldact->handler = k_oldact.handler;
660     u_oldact->sigaction = k_oldact.sigaction;
661     internal_memcpy(&u_oldact->sa_mask, &k_oldact.sa_mask,
662                     sizeof(__sanitizer_kernel_sigset_t));
663     u_oldact->sa_flags = k_oldact.sa_flags;
664 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
665     u_oldact->sa_restorer = k_oldact.sa_restorer;
666 #endif
667   }
668   return result;
669 }
670
671 // Invokes sigaction via a raw syscall with a restorer, but does not support
672 // all platforms yet.
673 // We disable for Go simply because we have not yet added to buildgo.sh.
674 #if defined(__x86_64__) && !SANITIZER_GO
675 int internal_sigaction_syscall(int signum, const void *act, void *oldact) {
676   if (act == nullptr)
677     return internal_sigaction_norestorer(signum, act, oldact);
678   __sanitizer_sigaction u_adjust;
679   internal_memcpy(&u_adjust, act, sizeof(u_adjust));
680 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
681     if (u_adjust.sa_restorer == nullptr) {
682       u_adjust.sa_restorer = internal_sigreturn;
683     }
684 #endif
685     return internal_sigaction_norestorer(signum, (const void *)&u_adjust,
686                                          oldact);
687 }
688 #endif // defined(__x86_64__) && !SANITIZER_GO
689 #endif  // SANITIZER_LINUX
690
691 uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
692     __sanitizer_sigset_t *oldset) {
693 #if SANITIZER_FREEBSD
694   return internal_syscall(SYSCALL(sigprocmask), how, set, oldset);
695 #else
696   __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
697   __sanitizer_kernel_sigset_t *k_oldset = (__sanitizer_kernel_sigset_t *)oldset;
698   return internal_syscall(SYSCALL(rt_sigprocmask), (uptr)how,
699                           (uptr)&k_set->sig[0], (uptr)&k_oldset->sig[0],
700                           sizeof(__sanitizer_kernel_sigset_t));
701 #endif
702 }
703
704 void internal_sigfillset(__sanitizer_sigset_t *set) {
705   internal_memset(set, 0xff, sizeof(*set));
706 }
707
708 void internal_sigemptyset(__sanitizer_sigset_t *set) {
709   internal_memset(set, 0, sizeof(*set));
710 }
711
712 #if SANITIZER_LINUX
713 void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
714   signum -= 1;
715   CHECK_GE(signum, 0);
716   CHECK_LT(signum, sizeof(*set) * 8);
717   __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
718   const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
719   const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
720   k_set->sig[idx] &= ~(1 << bit);
721 }
722
723 bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
724   signum -= 1;
725   CHECK_GE(signum, 0);
726   CHECK_LT(signum, sizeof(*set) * 8);
727   __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
728   const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
729   const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
730   return k_set->sig[idx] & (1 << bit);
731 }
732 #endif  // SANITIZER_LINUX
733
734 // ThreadLister implementation.
735 ThreadLister::ThreadLister(int pid)
736   : pid_(pid),
737     descriptor_(-1),
738     buffer_(4096),
739     error_(true),
740     entry_((struct linux_dirent *)buffer_.data()),
741     bytes_read_(0) {
742   char task_directory_path[80];
743   internal_snprintf(task_directory_path, sizeof(task_directory_path),
744                     "/proc/%d/task/", pid);
745   uptr openrv = internal_open(task_directory_path, O_RDONLY | O_DIRECTORY);
746   if (internal_iserror(openrv)) {
747     error_ = true;
748     Report("Can't open /proc/%d/task for reading.\n", pid);
749   } else {
750     error_ = false;
751     descriptor_ = openrv;
752   }
753 }
754
755 int ThreadLister::GetNextTID() {
756   int tid = -1;
757   do {
758     if (error_)
759       return -1;
760     if ((char *)entry_ >= &buffer_[bytes_read_] && !GetDirectoryEntries())
761       return -1;
762     if (entry_->d_ino != 0 && entry_->d_name[0] >= '0' &&
763         entry_->d_name[0] <= '9') {
764       // Found a valid tid.
765       tid = (int)internal_atoll(entry_->d_name);
766     }
767     entry_ = (struct linux_dirent *)(((char *)entry_) + entry_->d_reclen);
768   } while (tid < 0);
769   return tid;
770 }
771
772 void ThreadLister::Reset() {
773   if (error_ || descriptor_ < 0)
774     return;
775   internal_lseek(descriptor_, 0, SEEK_SET);
776 }
777
778 ThreadLister::~ThreadLister() {
779   if (descriptor_ >= 0)
780     internal_close(descriptor_);
781 }
782
783 bool ThreadLister::error() { return error_; }
784
785 bool ThreadLister::GetDirectoryEntries() {
786   CHECK_GE(descriptor_, 0);
787   CHECK_NE(error_, true);
788   bytes_read_ = internal_getdents(descriptor_,
789                                   (struct linux_dirent *)buffer_.data(),
790                                   buffer_.size());
791   if (internal_iserror(bytes_read_)) {
792     Report("Can't read directory entries from /proc/%d/task.\n", pid_);
793     error_ = true;
794     return false;
795   } else if (bytes_read_ == 0) {
796     return false;
797   }
798   entry_ = (struct linux_dirent *)buffer_.data();
799   return true;
800 }
801
802 uptr GetPageSize() {
803 // Android post-M sysconf(_SC_PAGESIZE) crashes if called from .preinit_array.
804 #if (SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__))) || \
805     SANITIZER_ANDROID
806   return EXEC_PAGESIZE;
807 #else
808   return sysconf(_SC_PAGESIZE);  // EXEC_PAGESIZE may not be trustworthy.
809 #endif
810 }
811
812 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
813 #if SANITIZER_FREEBSD
814   const int Mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
815   const char *default_module_name = "kern.proc.pathname";
816   size_t Size = buf_len;
817   bool IsErr = (sysctl(Mib, ARRAY_SIZE(Mib), buf, &Size, NULL, 0) != 0);
818   int readlink_error = IsErr ? errno : 0;
819   uptr module_name_len = Size;
820 #else
821   const char *default_module_name = "/proc/self/exe";
822   uptr module_name_len = internal_readlink(
823       default_module_name, buf, buf_len);
824   int readlink_error;
825   bool IsErr = internal_iserror(module_name_len, &readlink_error);
826 #endif
827   if (IsErr) {
828     // We can't read binary name for some reason, assume it's unknown.
829     Report("WARNING: reading executable name failed with errno %d, "
830            "some stack frames may not be symbolized\n", readlink_error);
831     module_name_len = internal_snprintf(buf, buf_len, "%s",
832                                         default_module_name);
833     CHECK_LT(module_name_len, buf_len);
834   }
835   return module_name_len;
836 }
837
838 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len) {
839 #if SANITIZER_LINUX
840   char *tmpbuf;
841   uptr tmpsize;
842   uptr tmplen;
843   if (ReadFileToBuffer("/proc/self/cmdline", &tmpbuf, &tmpsize, &tmplen,
844                        1024 * 1024)) {
845     internal_strncpy(buf, tmpbuf, buf_len);
846     UnmapOrDie(tmpbuf, tmpsize);
847     return internal_strlen(buf);
848   }
849 #endif
850   return ReadBinaryName(buf, buf_len);
851 }
852
853 // Match full names of the form /path/to/base_name{-,.}*
854 bool LibraryNameIs(const char *full_name, const char *base_name) {
855   const char *name = full_name;
856   // Strip path.
857   while (*name != '\0') name++;
858   while (name > full_name && *name != '/') name--;
859   if (*name == '/') name++;
860   uptr base_name_length = internal_strlen(base_name);
861   if (internal_strncmp(name, base_name, base_name_length)) return false;
862   return (name[base_name_length] == '-' || name[base_name_length] == '.');
863 }
864
865 #if !SANITIZER_ANDROID
866 // Call cb for each region mapped by map.
867 void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr)) {
868   CHECK_NE(map, nullptr);
869 #if !SANITIZER_FREEBSD
870   typedef ElfW(Phdr) Elf_Phdr;
871   typedef ElfW(Ehdr) Elf_Ehdr;
872 #endif  // !SANITIZER_FREEBSD
873   char *base = (char *)map->l_addr;
874   Elf_Ehdr *ehdr = (Elf_Ehdr *)base;
875   char *phdrs = base + ehdr->e_phoff;
876   char *phdrs_end = phdrs + ehdr->e_phnum * ehdr->e_phentsize;
877
878   // Find the segment with the minimum base so we can "relocate" the p_vaddr
879   // fields.  Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
880   // objects have a non-zero base.
881   uptr preferred_base = (uptr)-1;
882   for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
883     Elf_Phdr *phdr = (Elf_Phdr *)iter;
884     if (phdr->p_type == PT_LOAD && preferred_base > (uptr)phdr->p_vaddr)
885       preferred_base = (uptr)phdr->p_vaddr;
886   }
887
888   // Compute the delta from the real base to get a relocation delta.
889   sptr delta = (uptr)base - preferred_base;
890   // Now we can figure out what the loader really mapped.
891   for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
892     Elf_Phdr *phdr = (Elf_Phdr *)iter;
893     if (phdr->p_type == PT_LOAD) {
894       uptr seg_start = phdr->p_vaddr + delta;
895       uptr seg_end = seg_start + phdr->p_memsz;
896       // None of these values are aligned.  We consider the ragged edges of the
897       // load command as defined, since they are mapped from the file.
898       seg_start = RoundDownTo(seg_start, GetPageSizeCached());
899       seg_end = RoundUpTo(seg_end, GetPageSizeCached());
900       cb((void *)seg_start, seg_end - seg_start);
901     }
902   }
903 }
904 #endif
905
906 #if defined(__x86_64__) && SANITIZER_LINUX
907 // We cannot use glibc's clone wrapper, because it messes with the child
908 // task's TLS. It writes the PID and TID of the child task to its thread
909 // descriptor, but in our case the child task shares the thread descriptor with
910 // the parent (because we don't know how to allocate a new thread
911 // descriptor to keep glibc happy). So the stock version of clone(), when
912 // used with CLONE_VM, would end up corrupting the parent's thread descriptor.
913 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
914                     int *parent_tidptr, void *newtls, int *child_tidptr) {
915   long long res;
916   if (!fn || !child_stack)
917     return -EINVAL;
918   CHECK_EQ(0, (uptr)child_stack % 16);
919   child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
920   ((unsigned long long *)child_stack)[0] = (uptr)fn;
921   ((unsigned long long *)child_stack)[1] = (uptr)arg;
922   register void *r8 __asm__("r8") = newtls;
923   register int *r10 __asm__("r10") = child_tidptr;
924   __asm__ __volatile__(
925                        /* %rax = syscall(%rax = SYSCALL(clone),
926                         *                %rdi = flags,
927                         *                %rsi = child_stack,
928                         *                %rdx = parent_tidptr,
929                         *                %r8  = new_tls,
930                         *                %r10 = child_tidptr)
931                         */
932                        "syscall\n"
933
934                        /* if (%rax != 0)
935                         *   return;
936                         */
937                        "testq  %%rax,%%rax\n"
938                        "jnz    1f\n"
939
940                        /* In the child. Terminate unwind chain. */
941                        // XXX: We should also terminate the CFI unwind chain
942                        // here. Unfortunately clang 3.2 doesn't support the
943                        // necessary CFI directives, so we skip that part.
944                        "xorq   %%rbp,%%rbp\n"
945
946                        /* Call "fn(arg)". */
947                        "popq   %%rax\n"
948                        "popq   %%rdi\n"
949                        "call   *%%rax\n"
950
951                        /* Call _exit(%rax). */
952                        "movq   %%rax,%%rdi\n"
953                        "movq   %2,%%rax\n"
954                        "syscall\n"
955
956                        /* Return to parent. */
957                      "1:\n"
958                        : "=a" (res)
959                        : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
960                          "S"(child_stack),
961                          "D"(flags),
962                          "d"(parent_tidptr),
963                          "r"(r8),
964                          "r"(r10)
965                        : "rsp", "memory", "r11", "rcx");
966   return res;
967 }
968 #elif defined(__mips__)
969 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
970                     int *parent_tidptr, void *newtls, int *child_tidptr) {
971   long long res;
972   if (!fn || !child_stack)
973     return -EINVAL;
974   CHECK_EQ(0, (uptr)child_stack % 16);
975   child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
976   ((unsigned long long *)child_stack)[0] = (uptr)fn;
977   ((unsigned long long *)child_stack)[1] = (uptr)arg;
978   register void *a3 __asm__("$7") = newtls;
979   register int *a4 __asm__("$8") = child_tidptr;
980   // We don't have proper CFI directives here because it requires alot of code
981   // for very marginal benefits.
982   __asm__ __volatile__(
983                        /* $v0 = syscall($v0 = __NR_clone,
984                         * $a0 = flags,
985                         * $a1 = child_stack,
986                         * $a2 = parent_tidptr,
987                         * $a3 = new_tls,
988                         * $a4 = child_tidptr)
989                         */
990                        ".cprestore 16;\n"
991                        "move $4,%1;\n"
992                        "move $5,%2;\n"
993                        "move $6,%3;\n"
994                        "move $7,%4;\n"
995                        /* Store the fifth argument on stack
996                         * if we are using 32-bit abi.
997                         */
998 #if SANITIZER_WORDSIZE == 32
999                        "lw %5,16($29);\n"
1000 #else
1001                        "move $8,%5;\n"
1002 #endif
1003                        "li $2,%6;\n"
1004                        "syscall;\n"
1005
1006                        /* if ($v0 != 0)
1007                         * return;
1008                         */
1009                        "bnez $2,1f;\n"
1010
1011                        /* Call "fn(arg)". */
1012 #if SANITIZER_WORDSIZE == 32
1013 #ifdef __BIG_ENDIAN__
1014                        "lw $25,4($29);\n"
1015                        "lw $4,12($29);\n"
1016 #else
1017                        "lw $25,0($29);\n"
1018                        "lw $4,8($29);\n"
1019 #endif
1020 #else
1021                        "ld $25,0($29);\n"
1022                        "ld $4,8($29);\n"
1023 #endif
1024                        "jal $25;\n"
1025
1026                        /* Call _exit($v0). */
1027                        "move $4,$2;\n"
1028                        "li $2,%7;\n"
1029                        "syscall;\n"
1030
1031                        /* Return to parent. */
1032                      "1:\n"
1033                        : "=r" (res)
1034                        : "r"(flags),
1035                          "r"(child_stack),
1036                          "r"(parent_tidptr),
1037                          "r"(a3),
1038                          "r"(a4),
1039                          "i"(__NR_clone),
1040                          "i"(__NR_exit)
1041                        : "memory", "$29" );
1042   return res;
1043 }
1044 #elif defined(__aarch64__)
1045 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1046                     int *parent_tidptr, void *newtls, int *child_tidptr) {
1047   long long res;
1048   if (!fn || !child_stack)
1049     return -EINVAL;
1050   CHECK_EQ(0, (uptr)child_stack % 16);
1051   child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1052   ((unsigned long long *)child_stack)[0] = (uptr)fn;
1053   ((unsigned long long *)child_stack)[1] = (uptr)arg;
1054
1055   register int (*__fn)(void *)  __asm__("x0") = fn;
1056   register void *__stack __asm__("x1") = child_stack;
1057   register int   __flags __asm__("x2") = flags;
1058   register void *__arg   __asm__("x3") = arg;
1059   register int  *__ptid  __asm__("x4") = parent_tidptr;
1060   register void *__tls   __asm__("x5") = newtls;
1061   register int  *__ctid  __asm__("x6") = child_tidptr;
1062
1063   __asm__ __volatile__(
1064                        "mov x0,x2\n" /* flags  */
1065                        "mov x2,x4\n" /* ptid  */
1066                        "mov x3,x5\n" /* tls  */
1067                        "mov x4,x6\n" /* ctid  */
1068                        "mov x8,%9\n" /* clone  */
1069
1070                        "svc 0x0\n"
1071
1072                        /* if (%r0 != 0)
1073                         *   return %r0;
1074                         */
1075                        "cmp x0, #0\n"
1076                        "bne 1f\n"
1077
1078                        /* In the child, now. Call "fn(arg)". */
1079                        "ldp x1, x0, [sp], #16\n"
1080                        "blr x1\n"
1081
1082                        /* Call _exit(%r0).  */
1083                        "mov x8, %10\n"
1084                        "svc 0x0\n"
1085                      "1:\n"
1086
1087                        : "=r" (res)
1088                        : "i"(-EINVAL),
1089                          "r"(__fn), "r"(__stack), "r"(__flags), "r"(__arg),
1090                          "r"(__ptid), "r"(__tls), "r"(__ctid),
1091                          "i"(__NR_clone), "i"(__NR_exit)
1092                        : "x30", "memory");
1093   return res;
1094 }
1095 #elif defined(__powerpc64__)
1096 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1097                    int *parent_tidptr, void *newtls, int *child_tidptr) {
1098   long long res;
1099 /* Stack frame offsets.  */
1100 #if _CALL_ELF != 2
1101 #define FRAME_MIN_SIZE         112
1102 #define FRAME_TOC_SAVE         40
1103 #else
1104 #define FRAME_MIN_SIZE         32
1105 #define FRAME_TOC_SAVE         24
1106 #endif
1107   if (!fn || !child_stack)
1108     return -EINVAL;
1109   CHECK_EQ(0, (uptr)child_stack % 16);
1110   child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1111   ((unsigned long long *)child_stack)[0] = (uptr)fn;
1112   ((unsigned long long *)child_stack)[1] = (uptr)arg;
1113
1114   register int (*__fn)(void *) __asm__("r3") = fn;
1115   register void *__cstack      __asm__("r4") = child_stack;
1116   register int __flags         __asm__("r5") = flags;
1117   register void * __arg        __asm__("r6") = arg;
1118   register int * __ptidptr     __asm__("r7") = parent_tidptr;
1119   register void * __newtls     __asm__("r8") = newtls;
1120   register int * __ctidptr     __asm__("r9") = child_tidptr;
1121
1122  __asm__ __volatile__(
1123            /* fn, arg, child_stack are saved acrVoss the syscall */
1124            "mr 28, %5\n\t"
1125            "mr 29, %6\n\t"
1126            "mr 27, %8\n\t"
1127
1128            /* syscall
1129              r3 == flags
1130              r4 == child_stack
1131              r5 == parent_tidptr
1132              r6 == newtls
1133              r7 == child_tidptr */
1134            "mr 3, %7\n\t"
1135            "mr 5, %9\n\t"
1136            "mr 6, %10\n\t"
1137            "mr 7, %11\n\t"
1138            "li 0, %3\n\t"
1139            "sc\n\t"
1140
1141            /* Test if syscall was successful */
1142            "cmpdi  cr1, 3, 0\n\t"
1143            "crandc cr1*4+eq, cr1*4+eq, cr0*4+so\n\t"
1144            "bne-   cr1, 1f\n\t"
1145
1146            /* Do the function call */
1147            "std   2, %13(1)\n\t"
1148 #if _CALL_ELF != 2
1149            "ld    0, 0(28)\n\t"
1150            "ld    2, 8(28)\n\t"
1151            "mtctr 0\n\t"
1152 #else
1153            "mr    12, 28\n\t"
1154            "mtctr 12\n\t"
1155 #endif
1156            "mr    3, 27\n\t"
1157            "bctrl\n\t"
1158            "ld    2, %13(1)\n\t"
1159
1160            /* Call _exit(r3) */
1161            "li 0, %4\n\t"
1162            "sc\n\t"
1163
1164            /* Return to parent */
1165            "1:\n\t"
1166            "mr %0, 3\n\t"
1167              : "=r" (res)
1168              : "0" (-1), "i" (EINVAL),
1169                "i" (__NR_clone), "i" (__NR_exit),
1170                "r" (__fn), "r" (__cstack), "r" (__flags),
1171                "r" (__arg), "r" (__ptidptr), "r" (__newtls),
1172                "r" (__ctidptr), "i" (FRAME_MIN_SIZE), "i" (FRAME_TOC_SAVE)
1173              : "cr0", "cr1", "memory", "ctr",
1174                "r0", "r29", "r27", "r28");
1175   return res;
1176 }
1177 #endif  // defined(__x86_64__) && SANITIZER_LINUX
1178
1179 #if SANITIZER_ANDROID
1180 #if __ANDROID_API__ < 21
1181 extern "C" __attribute__((weak)) int dl_iterate_phdr(
1182     int (*)(struct dl_phdr_info *, size_t, void *), void *);
1183 #endif
1184
1185 static int dl_iterate_phdr_test_cb(struct dl_phdr_info *info, size_t size,
1186                                    void *data) {
1187   // Any name starting with "lib" indicates a bug in L where library base names
1188   // are returned instead of paths.
1189   if (info->dlpi_name && info->dlpi_name[0] == 'l' &&
1190       info->dlpi_name[1] == 'i' && info->dlpi_name[2] == 'b') {
1191     *(bool *)data = true;
1192     return 1;
1193   }
1194   return 0;
1195 }
1196
1197 static atomic_uint32_t android_api_level;
1198
1199 static AndroidApiLevel AndroidDetectApiLevel() {
1200   if (!&dl_iterate_phdr)
1201     return ANDROID_KITKAT; // K or lower
1202   bool base_name_seen = false;
1203   dl_iterate_phdr(dl_iterate_phdr_test_cb, &base_name_seen);
1204   if (base_name_seen)
1205     return ANDROID_LOLLIPOP_MR1; // L MR1
1206   return ANDROID_POST_LOLLIPOP;   // post-L
1207   // Plain L (API level 21) is completely broken wrt ASan and not very
1208   // interesting to detect.
1209 }
1210
1211 AndroidApiLevel AndroidGetApiLevel() {
1212   AndroidApiLevel level =
1213       (AndroidApiLevel)atomic_load(&android_api_level, memory_order_relaxed);
1214   if (level) return level;
1215   level = AndroidDetectApiLevel();
1216   atomic_store(&android_api_level, level, memory_order_relaxed);
1217   return level;
1218 }
1219
1220 #endif
1221
1222 bool IsHandledDeadlySignal(int signum) {
1223   if (common_flags()->handle_abort && signum == SIGABRT)
1224     return true;
1225   if (common_flags()->handle_sigill && signum == SIGILL)
1226     return true;
1227   if (common_flags()->handle_sigfpe && signum == SIGFPE)
1228     return true;
1229   return (signum == SIGSEGV || signum == SIGBUS) && common_flags()->handle_segv;
1230 }
1231
1232 #ifndef SANITIZER_GO
1233 void *internal_start_thread(void(*func)(void *arg), void *arg) {
1234   // Start the thread with signals blocked, otherwise it can steal user signals.
1235   __sanitizer_sigset_t set, old;
1236   internal_sigfillset(&set);
1237 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1238   // Glibc uses SIGSETXID signal during setuid call. If this signal is blocked
1239   // on any thread, setuid call hangs (see test/tsan/setuid.c).
1240   internal_sigdelset(&set, 33);
1241 #endif
1242   internal_sigprocmask(SIG_SETMASK, &set, &old);
1243   void *th;
1244   real_pthread_create(&th, nullptr, (void*(*)(void *arg))func, arg);
1245   internal_sigprocmask(SIG_SETMASK, &old, nullptr);
1246   return th;
1247 }
1248
1249 void internal_join_thread(void *th) {
1250   real_pthread_join(th, nullptr);
1251 }
1252 #else
1253 void *internal_start_thread(void (*func)(void *), void *arg) { return 0; }
1254
1255 void internal_join_thread(void *th) {}
1256 #endif
1257
1258 #if defined(__aarch64__)
1259 // Android headers in the older NDK releases miss this definition.
1260 struct __sanitizer_esr_context {
1261   struct _aarch64_ctx head;
1262   uint64_t esr;
1263 };
1264
1265 static bool Aarch64GetESR(ucontext_t *ucontext, u64 *esr) {
1266   static const u32 kEsrMagic = 0x45535201;
1267   u8 *aux = ucontext->uc_mcontext.__reserved;
1268   while (true) {
1269     _aarch64_ctx *ctx = (_aarch64_ctx *)aux;
1270     if (ctx->size == 0) break;
1271     if (ctx->magic == kEsrMagic) {
1272       *esr = ((__sanitizer_esr_context *)ctx)->esr;
1273       return true;
1274     }
1275     aux += ctx->size;
1276   }
1277   return false;
1278 }
1279 #endif
1280
1281 SignalContext::WriteFlag SignalContext::GetWriteFlag(void *context) {
1282   ucontext_t *ucontext = (ucontext_t *)context;
1283 #if defined(__x86_64__) || defined(__i386__)
1284   static const uptr PF_WRITE = 1U << 1;
1285 #if SANITIZER_FREEBSD
1286   uptr err = ucontext->uc_mcontext.mc_err;
1287 #else
1288   uptr err = ucontext->uc_mcontext.gregs[REG_ERR];
1289 #endif
1290   return err & PF_WRITE ? WRITE : READ;
1291 #elif defined(__arm__)
1292   static const uptr FSR_WRITE = 1U << 11;
1293   uptr fsr = ucontext->uc_mcontext.error_code;
1294   // FSR bits 5:0 describe the abort type, and are never 0 (or so it seems).
1295   // Zero FSR indicates an older kernel that does not pass this information to
1296   // the userspace.
1297   if (fsr == 0) return UNKNOWN;
1298   return fsr & FSR_WRITE ? WRITE : READ;
1299 #elif defined(__aarch64__)
1300   static const u64 ESR_ELx_WNR = 1U << 6;
1301   u64 esr;
1302   if (!Aarch64GetESR(ucontext, &esr)) return UNKNOWN;
1303   return esr & ESR_ELx_WNR ? WRITE : READ;
1304 #else
1305   (void)ucontext;
1306   return UNKNOWN;  // FIXME: Implement.
1307 #endif
1308 }
1309
1310 void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
1311 #if defined(__arm__)
1312   ucontext_t *ucontext = (ucontext_t*)context;
1313   *pc = ucontext->uc_mcontext.arm_pc;
1314   *bp = ucontext->uc_mcontext.arm_fp;
1315   *sp = ucontext->uc_mcontext.arm_sp;
1316 #elif defined(__aarch64__)
1317   ucontext_t *ucontext = (ucontext_t*)context;
1318   *pc = ucontext->uc_mcontext.pc;
1319   *bp = ucontext->uc_mcontext.regs[29];
1320   *sp = ucontext->uc_mcontext.sp;
1321 #elif defined(__hppa__)
1322   ucontext_t *ucontext = (ucontext_t*)context;
1323   *pc = ucontext->uc_mcontext.sc_iaoq[0];
1324   /* GCC uses %r3 whenever a frame pointer is needed.  */
1325   *bp = ucontext->uc_mcontext.sc_gr[3];
1326   *sp = ucontext->uc_mcontext.sc_gr[30];
1327 #elif defined(__x86_64__)
1328 # if SANITIZER_FREEBSD
1329   ucontext_t *ucontext = (ucontext_t*)context;
1330   *pc = ucontext->uc_mcontext.mc_rip;
1331   *bp = ucontext->uc_mcontext.mc_rbp;
1332   *sp = ucontext->uc_mcontext.mc_rsp;
1333 # else
1334   ucontext_t *ucontext = (ucontext_t*)context;
1335   *pc = ucontext->uc_mcontext.gregs[REG_RIP];
1336   *bp = ucontext->uc_mcontext.gregs[REG_RBP];
1337   *sp = ucontext->uc_mcontext.gregs[REG_RSP];
1338 # endif
1339 #elif defined(__i386__)
1340 # if SANITIZER_FREEBSD
1341   ucontext_t *ucontext = (ucontext_t*)context;
1342   *pc = ucontext->uc_mcontext.mc_eip;
1343   *bp = ucontext->uc_mcontext.mc_ebp;
1344   *sp = ucontext->uc_mcontext.mc_esp;
1345 # else
1346   ucontext_t *ucontext = (ucontext_t*)context;
1347   *pc = ucontext->uc_mcontext.gregs[REG_EIP];
1348   *bp = ucontext->uc_mcontext.gregs[REG_EBP];
1349   *sp = ucontext->uc_mcontext.gregs[REG_ESP];
1350 # endif
1351 #elif defined(__powerpc__) || defined(__powerpc64__)
1352   ucontext_t *ucontext = (ucontext_t*)context;
1353   *pc = ucontext->uc_mcontext.regs->nip;
1354   *sp = ucontext->uc_mcontext.regs->gpr[PT_R1];
1355   // The powerpc{,64}-linux ABIs do not specify r31 as the frame
1356   // pointer, but GCC always uses r31 when we need a frame pointer.
1357   *bp = ucontext->uc_mcontext.regs->gpr[PT_R31];
1358 #elif defined(__sparc__)
1359   ucontext_t *ucontext = (ucontext_t*)context;
1360   uptr *stk_ptr;
1361 # if defined (__arch64__)
1362   *pc = ucontext->uc_mcontext.mc_gregs[MC_PC];
1363   *sp = ucontext->uc_mcontext.mc_gregs[MC_O6];
1364   stk_ptr = (uptr *) (*sp + 2047);
1365   *bp = stk_ptr[15];
1366 # else
1367   *pc = ucontext->uc_mcontext.gregs[REG_PC];
1368   *sp = ucontext->uc_mcontext.gregs[REG_O6];
1369   stk_ptr = (uptr *) *sp;
1370   *bp = stk_ptr[15];
1371 # endif
1372 #elif defined(__mips__)
1373   ucontext_t *ucontext = (ucontext_t*)context;
1374   *pc = ucontext->uc_mcontext.pc;
1375   *bp = ucontext->uc_mcontext.gregs[30];
1376   *sp = ucontext->uc_mcontext.gregs[29];
1377 #elif defined(__s390__)
1378   ucontext_t *ucontext = (ucontext_t*)context;
1379 # if defined(__s390x__)
1380   *pc = ucontext->uc_mcontext.psw.addr;
1381 # else
1382   *pc = ucontext->uc_mcontext.psw.addr & 0x7fffffff;
1383 # endif
1384   *bp = ucontext->uc_mcontext.gregs[11];
1385   *sp = ucontext->uc_mcontext.gregs[15];
1386 #else
1387 # error "Unsupported arch"
1388 #endif
1389 }
1390
1391 void MaybeReexec() {
1392   // No need to re-exec on Linux.
1393 }
1394
1395 } // namespace __sanitizer
1396
1397 #endif // SANITIZER_FREEBSD || SANITIZER_LINUX