]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/sanitizer_common/sanitizer_linux.cc
Merge clang 7.0.1 and several follow-up changes
[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 || SANITIZER_NETBSD || \
18     SANITIZER_OPENBSD || SANITIZER_SOLARIS
19
20 #include "sanitizer_common.h"
21 #include "sanitizer_flags.h"
22 #include "sanitizer_getauxval.h"
23 #include "sanitizer_internal_defs.h"
24 #include "sanitizer_libc.h"
25 #include "sanitizer_linux.h"
26 #include "sanitizer_mutex.h"
27 #include "sanitizer_placement_new.h"
28 #include "sanitizer_procmaps.h"
29
30 #if SANITIZER_LINUX
31 #include <asm/param.h>
32 #endif
33
34 #if SANITIZER_NETBSD
35 #include <lwp.h>
36 #endif
37
38 // For mips64, syscall(__NR_stat) fills the buffer in the 'struct kernel_stat'
39 // format. Struct kernel_stat is defined as 'struct stat' in asm/stat.h. To
40 // access stat from asm/stat.h, without conflicting with definition in
41 // sys/stat.h, we use this trick.
42 #if defined(__mips64)
43 #include <asm/unistd.h>
44 #include <sys/types.h>
45 #define stat kernel_stat
46 #include <asm/stat.h>
47 #undef stat
48 #endif
49
50 #include <dlfcn.h>
51 #include <errno.h>
52 #include <fcntl.h>
53 #include <link.h>
54 #include <pthread.h>
55 #include <sched.h>
56 #include <signal.h>
57 #include <sys/mman.h>
58 #if !SANITIZER_SOLARIS
59 #include <sys/ptrace.h>
60 #endif
61 #include <sys/resource.h>
62 #include <sys/stat.h>
63 #include <sys/syscall.h>
64 #include <sys/time.h>
65 #include <sys/types.h>
66 #if !SANITIZER_OPENBSD
67 #include <ucontext.h>
68 #endif
69 #if SANITIZER_OPENBSD
70 #include <sys/futex.h>
71 #endif
72 #include <unistd.h>
73
74 #if SANITIZER_LINUX
75 #include <sys/utsname.h>
76 #endif
77
78 #if SANITIZER_LINUX && !SANITIZER_ANDROID
79 #include <sys/personality.h>
80 #endif
81
82 #if SANITIZER_FREEBSD
83 #include <sys/exec.h>
84 #include <sys/sysctl.h>
85 #include <machine/atomic.h>
86 extern "C" {
87 // <sys/umtx.h> must be included after <errno.h> and <sys/types.h> on
88 // FreeBSD 9.2 and 10.0.
89 #include <sys/umtx.h>
90 }
91 #include <sys/thr.h>
92 #endif  // SANITIZER_FREEBSD
93
94 #if SANITIZER_NETBSD
95 #include <limits.h>  // For NAME_MAX
96 #include <sys/sysctl.h>
97 #include <sys/exec.h>
98 extern struct ps_strings *__ps_strings;
99 #endif  // SANITIZER_NETBSD
100
101 #if SANITIZER_SOLARIS
102 #include <stdlib.h>
103 #include <thread.h>
104 #define environ _environ
105 #endif
106
107 extern char **environ;
108
109 #if SANITIZER_LINUX
110 // <linux/time.h>
111 struct kernel_timeval {
112   long tv_sec;
113   long tv_usec;
114 };
115
116 // <linux/futex.h> is broken on some linux distributions.
117 const int FUTEX_WAIT = 0;
118 const int FUTEX_WAKE = 1;
119 #endif  // SANITIZER_LINUX
120
121 // Are we using 32-bit or 64-bit Linux syscalls?
122 // x32 (which defines __x86_64__) has SANITIZER_WORDSIZE == 32
123 // but it still needs to use 64-bit syscalls.
124 #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__powerpc64__) ||       \
125                         SANITIZER_WORDSIZE == 64)
126 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 1
127 #else
128 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 0
129 #endif
130
131 #if defined(__x86_64__) || SANITIZER_MIPS64
132 extern "C" {
133 extern void internal_sigreturn();
134 }
135 #endif
136
137 // Note : FreeBSD had implemented both
138 // Linux and OpenBSD apis, available from
139 // future 12.x version most likely
140 #if SANITIZER_LINUX && defined(__NR_getrandom)
141 # if !defined(GRND_NONBLOCK)
142 #  define GRND_NONBLOCK 1
143 # endif
144 # define SANITIZER_USE_GETRANDOM 1
145 #else
146 # define SANITIZER_USE_GETRANDOM 0
147 #endif  // SANITIZER_LINUX && defined(__NR_getrandom)
148
149 #if SANITIZER_OPENBSD
150 # define SANITIZER_USE_GETENTROPY 1
151 #else
152 # define SANITIZER_USE_GETENTROPY 0
153 #endif // SANITIZER_USE_GETENTROPY
154
155 namespace __sanitizer {
156
157 #if SANITIZER_LINUX && defined(__x86_64__)
158 #include "sanitizer_syscall_linux_x86_64.inc"
159 #elif SANITIZER_LINUX && defined(__aarch64__)
160 #include "sanitizer_syscall_linux_aarch64.inc"
161 #elif SANITIZER_LINUX && defined(__arm__)
162 #include "sanitizer_syscall_linux_arm.inc"
163 #else
164 #include "sanitizer_syscall_generic.inc"
165 #endif
166
167 // --------------- sanitizer_libc.h
168 #if !SANITIZER_SOLARIS
169 #if !SANITIZER_S390 && !SANITIZER_OPENBSD
170 uptr internal_mmap(void *addr, uptr length, int prot, int flags, int fd,
171                    OFF_T offset) {
172 #if SANITIZER_NETBSD
173   return internal_syscall64(SYSCALL(mmap), addr, length, prot, flags, fd,
174                               (long)0, offset);
175 #elif SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
176   return internal_syscall(SYSCALL(mmap), (uptr)addr, length, prot, flags, fd,
177                           offset);
178 #else
179   // mmap2 specifies file offset in 4096-byte units.
180   CHECK(IsAligned(offset, 4096));
181   return internal_syscall(SYSCALL(mmap2), addr, length, prot, flags, fd,
182                           offset / 4096);
183 #endif
184 }
185 #endif // !SANITIZER_S390 && !SANITIZER_OPENBSD
186
187 #if !SANITIZER_OPENBSD
188 uptr internal_munmap(void *addr, uptr length) {
189   return internal_syscall_ptr(SYSCALL(munmap), (uptr)addr, length);
190 }
191
192 int internal_mprotect(void *addr, uptr length, int prot) {
193   return internal_syscall_ptr(SYSCALL(mprotect), (uptr)addr, length, prot);
194 }
195 #endif
196
197 uptr internal_close(fd_t fd) {
198   return internal_syscall(SYSCALL(close), fd);
199 }
200
201 uptr internal_open(const char *filename, int flags) {
202 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
203   return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags);
204 #else
205   return internal_syscall_ptr(SYSCALL(open), (uptr)filename, flags);
206 #endif
207 }
208
209 uptr internal_open(const char *filename, int flags, u32 mode) {
210 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
211   return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags,
212                           mode);
213 #else
214   return internal_syscall_ptr(SYSCALL(open), (uptr)filename, flags, mode);
215 #endif
216 }
217
218 uptr internal_read(fd_t fd, void *buf, uptr count) {
219   sptr res;
220   HANDLE_EINTR(res, (sptr)internal_syscall_ptr(SYSCALL(read), fd, (uptr)buf,
221                count));
222   return res;
223 }
224
225 uptr internal_write(fd_t fd, const void *buf, uptr count) {
226   sptr res;
227   HANDLE_EINTR(res, (sptr)internal_syscall_ptr(SYSCALL(write), fd, (uptr)buf,
228                count));
229   return res;
230 }
231
232 uptr internal_ftruncate(fd_t fd, uptr size) {
233   sptr res;
234 #if SANITIZER_NETBSD
235   HANDLE_EINTR(res, internal_syscall64(SYSCALL(ftruncate), fd, 0, (s64)size));
236 #else
237   HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(ftruncate), fd,
238                (OFF_T)size));
239 #endif
240   return res;
241 }
242
243 #if !SANITIZER_LINUX_USES_64BIT_SYSCALLS && SANITIZER_LINUX
244 static void stat64_to_stat(struct stat64 *in, struct stat *out) {
245   internal_memset(out, 0, sizeof(*out));
246   out->st_dev = in->st_dev;
247   out->st_ino = in->st_ino;
248   out->st_mode = in->st_mode;
249   out->st_nlink = in->st_nlink;
250   out->st_uid = in->st_uid;
251   out->st_gid = in->st_gid;
252   out->st_rdev = in->st_rdev;
253   out->st_size = in->st_size;
254   out->st_blksize = in->st_blksize;
255   out->st_blocks = in->st_blocks;
256   out->st_atime = in->st_atime;
257   out->st_mtime = in->st_mtime;
258   out->st_ctime = in->st_ctime;
259 }
260 #endif
261
262 #if defined(__mips64)
263 // Undefine compatibility macros from <sys/stat.h>
264 // so that they would not clash with the kernel_stat
265 // st_[a|m|c]time fields
266 #undef st_atime
267 #undef st_mtime
268 #undef st_ctime
269 #if defined(SANITIZER_ANDROID)
270 // Bionic sys/stat.h defines additional macros
271 // for compatibility with the old NDKs and
272 // they clash with the kernel_stat structure
273 // st_[a|m|c]time_nsec fields.
274 #undef st_atime_nsec
275 #undef st_mtime_nsec
276 #undef st_ctime_nsec
277 #endif
278 static void kernel_stat_to_stat(struct kernel_stat *in, struct stat *out) {
279   internal_memset(out, 0, sizeof(*out));
280   out->st_dev = in->st_dev;
281   out->st_ino = in->st_ino;
282   out->st_mode = in->st_mode;
283   out->st_nlink = in->st_nlink;
284   out->st_uid = in->st_uid;
285   out->st_gid = in->st_gid;
286   out->st_rdev = in->st_rdev;
287   out->st_size = in->st_size;
288   out->st_blksize = in->st_blksize;
289   out->st_blocks = in->st_blocks;
290 #if defined(__USE_MISC)     || \
291     defined(__USE_XOPEN2K8) || \
292     defined(SANITIZER_ANDROID)
293   out->st_atim.tv_sec = in->st_atime;
294   out->st_atim.tv_nsec = in->st_atime_nsec;
295   out->st_mtim.tv_sec = in->st_mtime;
296   out->st_mtim.tv_nsec = in->st_mtime_nsec;
297   out->st_ctim.tv_sec = in->st_ctime;
298   out->st_ctim.tv_nsec = in->st_ctime_nsec;
299 #else
300   out->st_atime = in->st_atime;
301   out->st_atimensec = in->st_atime_nsec;
302   out->st_mtime = in->st_mtime;
303   out->st_mtimensec = in->st_mtime_nsec;
304   out->st_ctime = in->st_ctime;
305   out->st_atimensec = in->st_ctime_nsec;
306 #endif
307 }
308 #endif
309
310 uptr internal_stat(const char *path, void *buf) {
311 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD
312   return internal_syscall_ptr(SYSCALL(fstatat), AT_FDCWD, (uptr)path, (uptr)buf,
313                               0);
314 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
315   return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path, (uptr)buf,
316                           0);
317 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
318 # if defined(__mips64)
319   // For mips64, stat syscall fills buffer in the format of kernel_stat
320   struct kernel_stat kbuf;
321   int res = internal_syscall(SYSCALL(stat), path, &kbuf);
322   kernel_stat_to_stat(&kbuf, (struct stat *)buf);
323   return res;
324 # else
325   return internal_syscall(SYSCALL(stat), (uptr)path, (uptr)buf);
326 # endif
327 #else
328   struct stat64 buf64;
329   int res = internal_syscall(SYSCALL(stat64), path, &buf64);
330   stat64_to_stat(&buf64, (struct stat *)buf);
331   return res;
332 #endif
333 }
334
335 uptr internal_lstat(const char *path, void *buf) {
336 #if SANITIZER_NETBSD
337   return internal_syscall_ptr(SYSCALL(lstat), path, buf);
338 #elif SANITIZER_FREEBSD || SANITIZER_OPENBSD
339   return internal_syscall(SYSCALL(fstatat), AT_FDCWD, (uptr)path, (uptr)buf,
340                           AT_SYMLINK_NOFOLLOW);
341 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
342   return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path, (uptr)buf,
343                           AT_SYMLINK_NOFOLLOW);
344 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
345 # if SANITIZER_MIPS64
346   // For mips64, lstat syscall fills buffer in the format of kernel_stat
347   struct kernel_stat kbuf;
348   int res = internal_syscall(SYSCALL(lstat), path, &kbuf);
349   kernel_stat_to_stat(&kbuf, (struct stat *)buf);
350   return res;
351 # else
352   return internal_syscall(SYSCALL(lstat), (uptr)path, (uptr)buf);
353 # endif
354 #else
355   struct stat64 buf64;
356   int res = internal_syscall(SYSCALL(lstat64), path, &buf64);
357   stat64_to_stat(&buf64, (struct stat *)buf);
358   return res;
359 #endif
360 }
361
362 uptr internal_fstat(fd_t fd, void *buf) {
363 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD ||              \
364     SANITIZER_LINUX_USES_64BIT_SYSCALLS
365 #if SANITIZER_MIPS64 && !SANITIZER_NETBSD && !SANITIZER_OPENBSD
366   // For mips64, fstat syscall fills buffer in the format of kernel_stat
367   struct kernel_stat kbuf;
368   int res = internal_syscall(SYSCALL(fstat), fd, &kbuf);
369   kernel_stat_to_stat(&kbuf, (struct stat *)buf);
370   return res;
371 # else
372   return internal_syscall_ptr(SYSCALL(fstat), fd, (uptr)buf);
373 # endif
374 #else
375   struct stat64 buf64;
376   int res = internal_syscall(SYSCALL(fstat64), fd, &buf64);
377   stat64_to_stat(&buf64, (struct stat *)buf);
378   return res;
379 #endif
380 }
381
382 uptr internal_filesize(fd_t fd) {
383   struct stat st;
384   if (internal_fstat(fd, &st))
385     return -1;
386   return (uptr)st.st_size;
387 }
388
389 uptr internal_dup2(int oldfd, int newfd) {
390 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
391   return internal_syscall(SYSCALL(dup3), oldfd, newfd, 0);
392 #else
393   return internal_syscall(SYSCALL(dup2), oldfd, newfd);
394 #endif
395 }
396
397 uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
398 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
399   return internal_syscall(SYSCALL(readlinkat), AT_FDCWD, (uptr)path, (uptr)buf,
400                           bufsize);
401 #elif SANITIZER_OPENBSD
402   return internal_syscall_ptr(SYSCALL(readlinkat), AT_FDCWD, (uptr)path,
403                               (uptr)buf, bufsize);
404 #else
405   return internal_syscall_ptr(SYSCALL(readlink), path, buf, bufsize);
406 #endif
407 }
408
409 uptr internal_unlink(const char *path) {
410 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS || SANITIZER_OPENBSD
411   return internal_syscall(SYSCALL(unlinkat), AT_FDCWD, (uptr)path, 0);
412 #else
413   return internal_syscall_ptr(SYSCALL(unlink), (uptr)path);
414 #endif
415 }
416
417 uptr internal_rename(const char *oldpath, const char *newpath) {
418 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS || SANITIZER_OPENBSD
419   return internal_syscall(SYSCALL(renameat), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
420                           (uptr)newpath);
421 #else
422   return internal_syscall_ptr(SYSCALL(rename), (uptr)oldpath, (uptr)newpath);
423 #endif
424 }
425
426 uptr internal_sched_yield() {
427   return internal_syscall(SYSCALL(sched_yield));
428 }
429
430 void internal__exit(int exitcode) {
431 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD
432   internal_syscall(SYSCALL(exit), exitcode);
433 #else
434   internal_syscall(SYSCALL(exit_group), exitcode);
435 #endif
436   Die();  // Unreachable.
437 }
438
439 unsigned int internal_sleep(unsigned int seconds) {
440   struct timespec ts;
441   ts.tv_sec = 1;
442   ts.tv_nsec = 0;
443   int res = internal_syscall_ptr(SYSCALL(nanosleep), &ts, &ts);
444   if (res) return ts.tv_sec;
445   return 0;
446 }
447
448 uptr internal_execve(const char *filename, char *const argv[],
449                      char *const envp[]) {
450   return internal_syscall_ptr(SYSCALL(execve), (uptr)filename, (uptr)argv,
451                               (uptr)envp);
452 }
453 #endif // !SANITIZER_SOLARIS
454
455 // ----------------- sanitizer_common.h
456 bool FileExists(const char *filename) {
457   struct stat st;
458 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
459   if (internal_syscall(SYSCALL(newfstatat), AT_FDCWD, filename, &st, 0))
460 #else
461   if (internal_stat(filename, &st))
462 #endif
463     return false;
464   // Sanity check: filename is a regular file.
465   return S_ISREG(st.st_mode);
466 }
467
468 tid_t GetTid() {
469 #if SANITIZER_FREEBSD
470   long Tid;
471   thr_self(&Tid);
472   return Tid;
473 #elif SANITIZER_OPENBSD
474   return internal_syscall(SYSCALL(getthrid));
475 #elif SANITIZER_NETBSD
476   return _lwp_self();
477 #elif SANITIZER_SOLARIS
478   return thr_self();
479 #else
480   return internal_syscall(SYSCALL(gettid));
481 #endif
482 }
483
484 #if !SANITIZER_SOLARIS
485 u64 NanoTime() {
486 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD
487   timeval tv;
488 #else
489   kernel_timeval tv;
490 #endif
491   internal_memset(&tv, 0, sizeof(tv));
492   internal_syscall_ptr(SYSCALL(gettimeofday), &tv, 0);
493   return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
494 }
495
496 uptr internal_clock_gettime(__sanitizer_clockid_t clk_id, void *tp) {
497   return internal_syscall_ptr(SYSCALL(clock_gettime), clk_id, tp);
498 }
499 #endif // !SANITIZER_SOLARIS
500
501 // Like getenv, but reads env directly from /proc (on Linux) or parses the
502 // 'environ' array (on some others) and does not use libc. This function
503 // should be called first inside __asan_init.
504 const char *GetEnv(const char *name) {
505 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD ||              \
506     SANITIZER_SOLARIS
507   if (::environ != 0) {
508     uptr NameLen = internal_strlen(name);
509     for (char **Env = ::environ; *Env != 0; Env++) {
510       if (internal_strncmp(*Env, name, NameLen) == 0 && (*Env)[NameLen] == '=')
511         return (*Env) + NameLen + 1;
512     }
513   }
514   return 0;  // Not found.
515 #elif SANITIZER_LINUX
516   static char *environ;
517   static uptr len;
518   static bool inited;
519   if (!inited) {
520     inited = true;
521     uptr environ_size;
522     if (!ReadFileToBuffer("/proc/self/environ", &environ, &environ_size, &len))
523       environ = nullptr;
524   }
525   if (!environ || len == 0) return nullptr;
526   uptr namelen = internal_strlen(name);
527   const char *p = environ;
528   while (*p != '\0') {  // will happen at the \0\0 that terminates the buffer
529     // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
530     const char* endp =
531         (char*)internal_memchr(p, '\0', len - (p - environ));
532     if (!endp)  // this entry isn't NUL terminated
533       return nullptr;
534     else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=')  // Match.
535       return p + namelen + 1;  // point after =
536     p = endp + 1;
537   }
538   return nullptr;  // Not found.
539 #else
540 #error "Unsupported platform"
541 #endif
542 }
543
544 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD && !SANITIZER_OPENBSD
545 extern "C" {
546 SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
547 }
548 #endif
549
550 #if !SANITIZER_GO && !SANITIZER_FREEBSD && !SANITIZER_NETBSD &&                \
551     !SANITIZER_OPENBSD
552 static void ReadNullSepFileToArray(const char *path, char ***arr,
553                                    int arr_size) {
554   char *buff;
555   uptr buff_size;
556   uptr buff_len;
557   *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
558   if (!ReadFileToBuffer(path, &buff, &buff_size, &buff_len, 1024 * 1024)) {
559     (*arr)[0] = nullptr;
560     return;
561   }
562   (*arr)[0] = buff;
563   int count, i;
564   for (count = 1, i = 1; ; i++) {
565     if (buff[i] == 0) {
566       if (buff[i+1] == 0) break;
567       (*arr)[count] = &buff[i+1];
568       CHECK_LE(count, arr_size - 1);  // FIXME: make this more flexible.
569       count++;
570     }
571   }
572   (*arr)[count] = nullptr;
573 }
574 #endif
575
576 #if !SANITIZER_OPENBSD
577 static void GetArgsAndEnv(char ***argv, char ***envp) {
578 #if SANITIZER_FREEBSD
579   // On FreeBSD, retrieving the argument and environment arrays is done via the
580   // kern.ps_strings sysctl, which returns a pointer to a structure containing
581   // this information. See also <sys/exec.h>.
582   ps_strings *pss;
583   size_t sz = sizeof(pss);
584   if (sysctlbyname("kern.ps_strings", &pss, &sz, NULL, 0) == -1) {
585     Printf("sysctl kern.ps_strings failed\n");
586     Die();
587   }
588   *argv = pss->ps_argvstr;
589   *envp = pss->ps_envstr;
590 #elif SANITIZER_NETBSD
591   *argv = __ps_strings->ps_argvstr;
592   *envp = __ps_strings->ps_envstr;
593 #else // SANITIZER_FREEBSD
594 #if !SANITIZER_GO
595   if (&__libc_stack_end) {
596 #endif // !SANITIZER_GO
597     uptr* stack_end = (uptr*)__libc_stack_end;
598     int argc = *stack_end;
599     *argv = (char**)(stack_end + 1);
600     *envp = (char**)(stack_end + argc + 2);
601 #if !SANITIZER_GO
602   } else {
603     static const int kMaxArgv = 2000, kMaxEnvp = 2000;
604     ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
605     ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
606   }
607 #endif // !SANITIZER_GO
608 #endif // SANITIZER_FREEBSD
609 }
610
611 char **GetArgv() {
612   char **argv, **envp;
613   GetArgsAndEnv(&argv, &envp);
614   return argv;
615 }
616
617 void ReExec() {
618   char **argv, **envp;
619   const char *pathname = "/proc/self/exe";
620
621 #if SANITIZER_NETBSD
622   static const int name[] = {
623     CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME,
624   };
625   char path[400];
626   size_t len;
627
628   len = sizeof(path);
629   if (sysctl(name, ARRAY_SIZE(name), path, &len, NULL, 0) != -1)
630     pathname = path;
631 #elif SANITIZER_SOLARIS
632   pathname = getexecname();
633   CHECK_NE(pathname, NULL);
634 #endif
635
636   GetArgsAndEnv(&argv, &envp);
637   uptr rv = internal_execve(pathname, argv, envp);
638   int rverrno;
639   CHECK_EQ(internal_iserror(rv, &rverrno), true);
640   Printf("execve failed, errno %d\n", rverrno);
641   Die();
642 }
643 #endif
644
645 #if !SANITIZER_SOLARIS
646 enum MutexState {
647   MtxUnlocked = 0,
648   MtxLocked = 1,
649   MtxSleeping = 2
650 };
651
652 BlockingMutex::BlockingMutex() {
653   internal_memset(this, 0, sizeof(*this));
654 }
655
656 void BlockingMutex::Lock() {
657   CHECK_EQ(owner_, 0);
658   atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
659   if (atomic_exchange(m, MtxLocked, memory_order_acquire) == MtxUnlocked)
660     return;
661   while (atomic_exchange(m, MtxSleeping, memory_order_acquire) != MtxUnlocked) {
662 #if SANITIZER_FREEBSD
663     _umtx_op(m, UMTX_OP_WAIT_UINT, MtxSleeping, 0, 0);
664 #elif SANITIZER_NETBSD
665     sched_yield(); /* No userspace futex-like synchronization */
666 #else
667     internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAIT, MtxSleeping, 0, 0, 0);
668 #endif
669   }
670 }
671
672 void BlockingMutex::Unlock() {
673   atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
674   u32 v = atomic_exchange(m, MtxUnlocked, memory_order_release);
675   CHECK_NE(v, MtxUnlocked);
676   if (v == MtxSleeping) {
677 #if SANITIZER_FREEBSD
678     _umtx_op(m, UMTX_OP_WAKE, 1, 0, 0);
679 #elif SANITIZER_NETBSD
680                    /* No userspace futex-like synchronization */
681 #else
682     internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAKE, 1, 0, 0, 0);
683 #endif
684   }
685 }
686
687 void BlockingMutex::CheckLocked() {
688   atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
689   CHECK_NE(MtxUnlocked, atomic_load(m, memory_order_relaxed));
690 }
691 #endif // !SANITIZER_SOLARIS
692
693 // ----------------- sanitizer_linux.h
694 // The actual size of this structure is specified by d_reclen.
695 // Note that getdents64 uses a different structure format. We only provide the
696 // 32-bit syscall here.
697 #if SANITIZER_NETBSD || SANITIZER_OPENBSD
698 // struct dirent is different for Linux and us. At this moment, we use only
699 // d_fileno (Linux call this d_ino), d_reclen, and d_name.
700 struct linux_dirent {
701   u64 d_ino;  // d_fileno
702   u16 d_reclen;
703   u16 d_namlen;  // not used
704   u8 d_type;     // not used
705   char d_name[NAME_MAX + 1];
706 };
707 #else
708 struct linux_dirent {
709 #if SANITIZER_X32 || defined(__aarch64__)
710   u64 d_ino;
711   u64 d_off;
712 #else
713   unsigned long      d_ino;
714   unsigned long      d_off;
715 #endif
716   unsigned short     d_reclen;
717 #ifdef __aarch64__
718   unsigned char      d_type;
719 #endif
720   char               d_name[256];
721 };
722 #endif
723
724 #if !SANITIZER_SOLARIS
725 // Syscall wrappers.
726 uptr internal_ptrace(int request, int pid, void *addr, void *data) {
727 #if SANITIZER_NETBSD
728   // XXX We need additional work for ptrace:
729   //   - for request, we use PT_FOO whereas Linux uses PTRACE_FOO
730   //   - data is int for us, but void * for Linux
731   //   - Linux sometimes uses data in the case where we use addr instead
732   // At this moment, this function is used only within
733   // "#if SANITIZER_LINUX && defined(__x86_64__)" block in
734   // sanitizer_stoptheworld_linux_libcdep.cc.
735   return internal_syscall_ptr(SYSCALL(ptrace), request, pid, (uptr)addr,
736                               (uptr)data);
737 #else
738   return internal_syscall(SYSCALL(ptrace), request, pid, (uptr)addr,
739                           (uptr)data);
740 #endif
741 }
742
743 uptr internal_waitpid(int pid, int *status, int options) {
744   return internal_syscall_ptr(SYSCALL(wait4), pid, (uptr)status, options,
745                           0 /* rusage */);
746 }
747
748 uptr internal_getpid() {
749   return internal_syscall(SYSCALL(getpid));
750 }
751
752 uptr internal_getppid() {
753   return internal_syscall(SYSCALL(getppid));
754 }
755
756 uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) {
757 #if SANITIZER_FREEBSD
758   return internal_syscall(SYSCALL(getdirentries), fd, (uptr)dirp, count, NULL);
759 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
760   return internal_syscall(SYSCALL(getdents64), fd, (uptr)dirp, count);
761 #else
762   return internal_syscall_ptr(SYSCALL(getdents), fd, (uptr)dirp, count);
763 #endif
764 }
765
766 uptr internal_lseek(fd_t fd, OFF_T offset, int whence) {
767 #if SANITIZER_NETBSD
768   return internal_syscall64(SYSCALL(lseek), fd, 0, offset, whence);
769 #else
770   return internal_syscall(SYSCALL(lseek), fd, offset, whence);
771 #endif
772 }
773
774 #if SANITIZER_LINUX
775 uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
776   return internal_syscall(SYSCALL(prctl), option, arg2, arg3, arg4, arg5);
777 }
778 #endif
779
780 uptr internal_sigaltstack(const void *ss, void *oss) {
781   return internal_syscall_ptr(SYSCALL(sigaltstack), (uptr)ss, (uptr)oss);
782 }
783
784 int internal_fork() {
785 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
786   return internal_syscall(SYSCALL(clone), SIGCHLD, 0);
787 #else
788   return internal_syscall(SYSCALL(fork));
789 #endif
790 }
791
792 #if SANITIZER_LINUX
793 #define SA_RESTORER 0x04000000
794 // Doesn't set sa_restorer if the caller did not set it, so use with caution
795 //(see below).
796 int internal_sigaction_norestorer(int signum, const void *act, void *oldact) {
797   __sanitizer_kernel_sigaction_t k_act, k_oldact;
798   internal_memset(&k_act, 0, sizeof(__sanitizer_kernel_sigaction_t));
799   internal_memset(&k_oldact, 0, sizeof(__sanitizer_kernel_sigaction_t));
800   const __sanitizer_sigaction *u_act = (const __sanitizer_sigaction *)act;
801   __sanitizer_sigaction *u_oldact = (__sanitizer_sigaction *)oldact;
802   if (u_act) {
803     k_act.handler = u_act->handler;
804     k_act.sigaction = u_act->sigaction;
805     internal_memcpy(&k_act.sa_mask, &u_act->sa_mask,
806                     sizeof(__sanitizer_kernel_sigset_t));
807     // Without SA_RESTORER kernel ignores the calls (probably returns EINVAL).
808     k_act.sa_flags = u_act->sa_flags | SA_RESTORER;
809     // FIXME: most often sa_restorer is unset, however the kernel requires it
810     // to point to a valid signal restorer that calls the rt_sigreturn syscall.
811     // If sa_restorer passed to the kernel is NULL, the program may crash upon
812     // signal delivery or fail to unwind the stack in the signal handler.
813     // libc implementation of sigaction() passes its own restorer to
814     // rt_sigaction, so we need to do the same (we'll need to reimplement the
815     // restorers; for x86_64 the restorer address can be obtained from
816     // oldact->sa_restorer upon a call to sigaction(xxx, NULL, oldact).
817 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
818     k_act.sa_restorer = u_act->sa_restorer;
819 #endif
820   }
821
822   uptr result = internal_syscall(SYSCALL(rt_sigaction), (uptr)signum,
823       (uptr)(u_act ? &k_act : nullptr),
824       (uptr)(u_oldact ? &k_oldact : nullptr),
825       (uptr)sizeof(__sanitizer_kernel_sigset_t));
826
827   if ((result == 0) && u_oldact) {
828     u_oldact->handler = k_oldact.handler;
829     u_oldact->sigaction = k_oldact.sigaction;
830     internal_memcpy(&u_oldact->sa_mask, &k_oldact.sa_mask,
831                     sizeof(__sanitizer_kernel_sigset_t));
832     u_oldact->sa_flags = k_oldact.sa_flags;
833 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
834     u_oldact->sa_restorer = k_oldact.sa_restorer;
835 #endif
836   }
837   return result;
838 }
839
840 // Invokes sigaction via a raw syscall with a restorer, but does not support
841 // all platforms yet.
842 // We disable for Go simply because we have not yet added to buildgo.sh.
843 #if (defined(__x86_64__) || SANITIZER_MIPS64) && !SANITIZER_GO
844 int internal_sigaction_syscall(int signum, const void *act, void *oldact) {
845   if (act == nullptr)
846     return internal_sigaction_norestorer(signum, act, oldact);
847   __sanitizer_sigaction u_adjust;
848   internal_memcpy(&u_adjust, act, sizeof(u_adjust));
849 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
850   if (u_adjust.sa_restorer == nullptr) {
851     u_adjust.sa_restorer = internal_sigreturn;
852   }
853 #endif
854   return internal_sigaction_norestorer(signum, (const void *)&u_adjust, oldact);
855 }
856 #endif  // defined(__x86_64__) && !SANITIZER_GO
857 #endif  // SANITIZER_LINUX
858
859 uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
860                           __sanitizer_sigset_t *oldset) {
861 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD
862   return internal_syscall_ptr(SYSCALL(sigprocmask), how, set, oldset);
863 #else
864   __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
865   __sanitizer_kernel_sigset_t *k_oldset = (__sanitizer_kernel_sigset_t *)oldset;
866   return internal_syscall(SYSCALL(rt_sigprocmask), (uptr)how,
867                           (uptr)&k_set->sig[0], (uptr)&k_oldset->sig[0],
868                           sizeof(__sanitizer_kernel_sigset_t));
869 #endif
870 }
871
872 void internal_sigfillset(__sanitizer_sigset_t *set) {
873   internal_memset(set, 0xff, sizeof(*set));
874 }
875
876 void internal_sigemptyset(__sanitizer_sigset_t *set) {
877   internal_memset(set, 0, sizeof(*set));
878 }
879
880 #if SANITIZER_LINUX
881 void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
882   signum -= 1;
883   CHECK_GE(signum, 0);
884   CHECK_LT(signum, sizeof(*set) * 8);
885   __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
886   const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
887   const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
888   k_set->sig[idx] &= ~(1 << bit);
889 }
890
891 bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
892   signum -= 1;
893   CHECK_GE(signum, 0);
894   CHECK_LT(signum, sizeof(*set) * 8);
895   __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
896   const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
897   const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
898   return k_set->sig[idx] & (1 << bit);
899 }
900 #endif  // SANITIZER_LINUX
901 #endif // !SANITIZER_SOLARIS
902
903 // ThreadLister implementation.
904 ThreadLister::ThreadLister(pid_t pid) : pid_(pid), buffer_(4096) {
905   char task_directory_path[80];
906   internal_snprintf(task_directory_path, sizeof(task_directory_path),
907                     "/proc/%d/task/", pid);
908   descriptor_ = internal_open(task_directory_path, O_RDONLY | O_DIRECTORY);
909   if (internal_iserror(descriptor_)) {
910     Report("Can't open /proc/%d/task for reading.\n", pid);
911   }
912 }
913
914 ThreadLister::Result ThreadLister::ListThreads(
915     InternalMmapVector<tid_t> *threads) {
916   if (internal_iserror(descriptor_))
917     return Error;
918   internal_lseek(descriptor_, 0, SEEK_SET);
919   threads->clear();
920
921   Result result = Ok;
922   for (bool first_read = true;; first_read = false) {
923     // Resize to max capacity if it was downsized by IsAlive.
924     buffer_.resize(buffer_.capacity());
925     CHECK_GE(buffer_.size(), 4096);
926     uptr read = internal_getdents(
927         descriptor_, (struct linux_dirent *)buffer_.data(), buffer_.size());
928     if (!read)
929       return result;
930     if (internal_iserror(read)) {
931       Report("Can't read directory entries from /proc/%d/task.\n", pid_);
932       return Error;
933     }
934
935     for (uptr begin = (uptr)buffer_.data(), end = begin + read; begin < end;) {
936       struct linux_dirent *entry = (struct linux_dirent *)begin;
937       begin += entry->d_reclen;
938       if (entry->d_ino == 1) {
939         // Inode 1 is for bad blocks and also can be a reason for early return.
940         // Should be emitted if kernel tried to output terminating thread.
941         // See proc_task_readdir implementation in Linux.
942         result = Incomplete;
943       }
944       if (entry->d_ino && *entry->d_name >= '0' && *entry->d_name <= '9')
945         threads->push_back(internal_atoll(entry->d_name));
946     }
947
948     // Now we are going to detect short-read or early EOF. In such cases Linux
949     // can return inconsistent list with missing alive threads.
950     // Code will just remember that the list can be incomplete but it will
951     // continue reads to return as much as possible.
952     if (!first_read) {
953       // The first one was a short-read by definition.
954       result = Incomplete;
955     } else if (read > buffer_.size() - 1024) {
956       // Read was close to the buffer size. So double the size and assume the
957       // worst.
958       buffer_.resize(buffer_.size() * 2);
959       result = Incomplete;
960     } else if (!threads->empty() && !IsAlive(threads->back())) {
961       // Maybe Linux early returned from read on terminated thread (!pid_alive)
962       // and failed to restore read position.
963       // See next_tid and proc_task_instantiate in Linux.
964       result = Incomplete;
965     }
966   }
967 }
968
969 bool ThreadLister::IsAlive(int tid) {
970   // /proc/%d/task/%d/status uses same call to detect alive threads as
971   // proc_task_readdir. See task_state implementation in Linux.
972   char path[80];
973   internal_snprintf(path, sizeof(path), "/proc/%d/task/%d/status", pid_, tid);
974   if (!ReadFileToVector(path, &buffer_) || buffer_.empty())
975     return false;
976   buffer_.push_back(0);
977   static const char kPrefix[] = "\nPPid:";
978   const char *field = internal_strstr(buffer_.data(), kPrefix);
979   if (!field)
980     return false;
981   field += internal_strlen(kPrefix);
982   return (int)internal_atoll(field) != 0;
983 }
984
985 ThreadLister::~ThreadLister() {
986   if (!internal_iserror(descriptor_))
987     internal_close(descriptor_);
988 }
989
990 #if SANITIZER_WORDSIZE == 32
991 // Take care of unusable kernel area in top gigabyte.
992 static uptr GetKernelAreaSize() {
993 #if SANITIZER_LINUX && !SANITIZER_X32
994   const uptr gbyte = 1UL << 30;
995
996   // Firstly check if there are writable segments
997   // mapped to top gigabyte (e.g. stack).
998   MemoryMappingLayout proc_maps(/*cache_enabled*/true);
999   MemoryMappedSegment segment;
1000   while (proc_maps.Next(&segment)) {
1001     if ((segment.end >= 3 * gbyte) && segment.IsWritable()) return 0;
1002   }
1003
1004 #if !SANITIZER_ANDROID
1005   // Even if nothing is mapped, top Gb may still be accessible
1006   // if we are running on 64-bit kernel.
1007   // Uname may report misleading results if personality type
1008   // is modified (e.g. under schroot) so check this as well.
1009   struct utsname uname_info;
1010   int pers = personality(0xffffffffUL);
1011   if (!(pers & PER_MASK)
1012       && uname(&uname_info) == 0
1013       && internal_strstr(uname_info.machine, "64"))
1014     return 0;
1015 #endif  // SANITIZER_ANDROID
1016
1017   // Top gigabyte is reserved for kernel.
1018   return gbyte;
1019 #else
1020   return 0;
1021 #endif  // SANITIZER_LINUX && !SANITIZER_X32
1022 }
1023 #endif  // SANITIZER_WORDSIZE == 32
1024
1025 uptr GetMaxVirtualAddress() {
1026 #if (SANITIZER_NETBSD || SANITIZER_OPENBSD) && defined(__x86_64__)
1027   return 0x7f7ffffff000ULL;  // (0x00007f8000000000 - PAGE_SIZE)
1028 #elif SANITIZER_WORDSIZE == 64
1029 # if defined(__powerpc64__) || defined(__aarch64__)
1030   // On PowerPC64 we have two different address space layouts: 44- and 46-bit.
1031   // We somehow need to figure out which one we are using now and choose
1032   // one of 0x00000fffffffffffUL and 0x00003fffffffffffUL.
1033   // Note that with 'ulimit -s unlimited' the stack is moved away from the top
1034   // of the address space, so simply checking the stack address is not enough.
1035   // This should (does) work for both PowerPC64 Endian modes.
1036   // Similarly, aarch64 has multiple address space layouts: 39, 42 and 47-bit.
1037   return (1ULL << (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1)) - 1;
1038 # elif defined(__mips64)
1039   return (1ULL << 40) - 1;  // 0x000000ffffffffffUL;
1040 # elif defined(__s390x__)
1041   return (1ULL << 53) - 1;  // 0x001fffffffffffffUL;
1042 # else
1043   return (1ULL << 47) - 1;  // 0x00007fffffffffffUL;
1044 # endif
1045 #else  // SANITIZER_WORDSIZE == 32
1046 # if defined(__s390__)
1047   return (1ULL << 31) - 1;  // 0x7fffffff;
1048 # else
1049   return (1ULL << 32) - 1;  // 0xffffffff;
1050 # endif
1051 #endif  // SANITIZER_WORDSIZE
1052 }
1053
1054 uptr GetMaxUserVirtualAddress() {
1055   uptr addr = GetMaxVirtualAddress();
1056 #if SANITIZER_WORDSIZE == 32 && !defined(__s390__)
1057   if (!common_flags()->full_address_space)
1058     addr -= GetKernelAreaSize();
1059   CHECK_LT(reinterpret_cast<uptr>(&addr), addr);
1060 #endif
1061   return addr;
1062 }
1063
1064 uptr GetPageSize() {
1065 // Android post-M sysconf(_SC_PAGESIZE) crashes if called from .preinit_array.
1066 #if SANITIZER_ANDROID
1067   return 4096;
1068 #elif SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__))
1069   return EXEC_PAGESIZE;
1070 #elif SANITIZER_USE_GETAUXVAL
1071   return getauxval(AT_PAGESZ);
1072 #else
1073   return sysconf(_SC_PAGESIZE);  // EXEC_PAGESIZE may not be trustworthy.
1074 #endif
1075 }
1076
1077 #if !SANITIZER_OPENBSD
1078 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
1079 #if SANITIZER_SOLARIS
1080   const char *default_module_name = getexecname();
1081   CHECK_NE(default_module_name, NULL);
1082   return internal_snprintf(buf, buf_len, "%s", default_module_name);
1083 #else
1084 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
1085 #if SANITIZER_FREEBSD
1086   const int Mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
1087 #else
1088   const int Mib[4] = {CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME};
1089 #endif
1090   const char *default_module_name = "kern.proc.pathname";
1091   size_t Size = buf_len;
1092   bool IsErr = (sysctl(Mib, ARRAY_SIZE(Mib), buf, &Size, NULL, 0) != 0);
1093   int readlink_error = IsErr ? errno : 0;
1094   uptr module_name_len = Size;
1095 #else
1096   const char *default_module_name = "/proc/self/exe";
1097   uptr module_name_len = internal_readlink(
1098       default_module_name, buf, buf_len);
1099   int readlink_error;
1100   bool IsErr = internal_iserror(module_name_len, &readlink_error);
1101 #endif  // SANITIZER_SOLARIS
1102   if (IsErr) {
1103     // We can't read binary name for some reason, assume it's unknown.
1104     Report("WARNING: reading executable name failed with errno %d, "
1105            "some stack frames may not be symbolized\n", readlink_error);
1106     module_name_len = internal_snprintf(buf, buf_len, "%s",
1107                                         default_module_name);
1108     CHECK_LT(module_name_len, buf_len);
1109   }
1110   return module_name_len;
1111 #endif
1112 }
1113 #endif // !SANITIZER_OPENBSD
1114
1115 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len) {
1116 #if SANITIZER_LINUX
1117   char *tmpbuf;
1118   uptr tmpsize;
1119   uptr tmplen;
1120   if (ReadFileToBuffer("/proc/self/cmdline", &tmpbuf, &tmpsize, &tmplen,
1121                        1024 * 1024)) {
1122     internal_strncpy(buf, tmpbuf, buf_len);
1123     UnmapOrDie(tmpbuf, tmpsize);
1124     return internal_strlen(buf);
1125   }
1126 #endif
1127   return ReadBinaryName(buf, buf_len);
1128 }
1129
1130 // Match full names of the form /path/to/base_name{-,.}*
1131 bool LibraryNameIs(const char *full_name, const char *base_name) {
1132   const char *name = full_name;
1133   // Strip path.
1134   while (*name != '\0') name++;
1135   while (name > full_name && *name != '/') name--;
1136   if (*name == '/') name++;
1137   uptr base_name_length = internal_strlen(base_name);
1138   if (internal_strncmp(name, base_name, base_name_length)) return false;
1139   return (name[base_name_length] == '-' || name[base_name_length] == '.');
1140 }
1141
1142 #if !SANITIZER_ANDROID
1143 // Call cb for each region mapped by map.
1144 void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr)) {
1145   CHECK_NE(map, nullptr);
1146 #if !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
1147   typedef ElfW(Phdr) Elf_Phdr;
1148   typedef ElfW(Ehdr) Elf_Ehdr;
1149 #endif // !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
1150   char *base = (char *)map->l_addr;
1151   Elf_Ehdr *ehdr = (Elf_Ehdr *)base;
1152   char *phdrs = base + ehdr->e_phoff;
1153   char *phdrs_end = phdrs + ehdr->e_phnum * ehdr->e_phentsize;
1154
1155   // Find the segment with the minimum base so we can "relocate" the p_vaddr
1156   // fields.  Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
1157   // objects have a non-zero base.
1158   uptr preferred_base = (uptr)-1;
1159   for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
1160     Elf_Phdr *phdr = (Elf_Phdr *)iter;
1161     if (phdr->p_type == PT_LOAD && preferred_base > (uptr)phdr->p_vaddr)
1162       preferred_base = (uptr)phdr->p_vaddr;
1163   }
1164
1165   // Compute the delta from the real base to get a relocation delta.
1166   sptr delta = (uptr)base - preferred_base;
1167   // Now we can figure out what the loader really mapped.
1168   for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
1169     Elf_Phdr *phdr = (Elf_Phdr *)iter;
1170     if (phdr->p_type == PT_LOAD) {
1171       uptr seg_start = phdr->p_vaddr + delta;
1172       uptr seg_end = seg_start + phdr->p_memsz;
1173       // None of these values are aligned.  We consider the ragged edges of the
1174       // load command as defined, since they are mapped from the file.
1175       seg_start = RoundDownTo(seg_start, GetPageSizeCached());
1176       seg_end = RoundUpTo(seg_end, GetPageSizeCached());
1177       cb((void *)seg_start, seg_end - seg_start);
1178     }
1179   }
1180 }
1181 #endif
1182
1183 #if defined(__x86_64__) && SANITIZER_LINUX
1184 // We cannot use glibc's clone wrapper, because it messes with the child
1185 // task's TLS. It writes the PID and TID of the child task to its thread
1186 // descriptor, but in our case the child task shares the thread descriptor with
1187 // the parent (because we don't know how to allocate a new thread
1188 // descriptor to keep glibc happy). So the stock version of clone(), when
1189 // used with CLONE_VM, would end up corrupting the parent's thread descriptor.
1190 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1191                     int *parent_tidptr, void *newtls, int *child_tidptr) {
1192   long long res;
1193   if (!fn || !child_stack)
1194     return -EINVAL;
1195   CHECK_EQ(0, (uptr)child_stack % 16);
1196   child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1197   ((unsigned long long *)child_stack)[0] = (uptr)fn;
1198   ((unsigned long long *)child_stack)[1] = (uptr)arg;
1199   register void *r8 __asm__("r8") = newtls;
1200   register int *r10 __asm__("r10") = child_tidptr;
1201   __asm__ __volatile__(
1202                        /* %rax = syscall(%rax = SYSCALL(clone),
1203                         *                %rdi = flags,
1204                         *                %rsi = child_stack,
1205                         *                %rdx = parent_tidptr,
1206                         *                %r8  = new_tls,
1207                         *                %r10 = child_tidptr)
1208                         */
1209                        "syscall\n"
1210
1211                        /* if (%rax != 0)
1212                         *   return;
1213                         */
1214                        "testq  %%rax,%%rax\n"
1215                        "jnz    1f\n"
1216
1217                        /* In the child. Terminate unwind chain. */
1218                        // XXX: We should also terminate the CFI unwind chain
1219                        // here. Unfortunately clang 3.2 doesn't support the
1220                        // necessary CFI directives, so we skip that part.
1221                        "xorq   %%rbp,%%rbp\n"
1222
1223                        /* Call "fn(arg)". */
1224                        "popq   %%rax\n"
1225                        "popq   %%rdi\n"
1226                        "call   *%%rax\n"
1227
1228                        /* Call _exit(%rax). */
1229                        "movq   %%rax,%%rdi\n"
1230                        "movq   %2,%%rax\n"
1231                        "syscall\n"
1232
1233                        /* Return to parent. */
1234                      "1:\n"
1235                        : "=a" (res)
1236                        : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
1237                          "S"(child_stack),
1238                          "D"(flags),
1239                          "d"(parent_tidptr),
1240                          "r"(r8),
1241                          "r"(r10)
1242                        : "rsp", "memory", "r11", "rcx");
1243   return res;
1244 }
1245 #elif defined(__mips__)
1246 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1247                     int *parent_tidptr, void *newtls, int *child_tidptr) {
1248   long long res;
1249   if (!fn || !child_stack)
1250     return -EINVAL;
1251   CHECK_EQ(0, (uptr)child_stack % 16);
1252   child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1253   ((unsigned long long *)child_stack)[0] = (uptr)fn;
1254   ((unsigned long long *)child_stack)[1] = (uptr)arg;
1255   register void *a3 __asm__("$7") = newtls;
1256   register int *a4 __asm__("$8") = child_tidptr;
1257   // We don't have proper CFI directives here because it requires alot of code
1258   // for very marginal benefits.
1259   __asm__ __volatile__(
1260                        /* $v0 = syscall($v0 = __NR_clone,
1261                         * $a0 = flags,
1262                         * $a1 = child_stack,
1263                         * $a2 = parent_tidptr,
1264                         * $a3 = new_tls,
1265                         * $a4 = child_tidptr)
1266                         */
1267                        ".cprestore 16;\n"
1268                        "move $4,%1;\n"
1269                        "move $5,%2;\n"
1270                        "move $6,%3;\n"
1271                        "move $7,%4;\n"
1272                        /* Store the fifth argument on stack
1273                         * if we are using 32-bit abi.
1274                         */
1275 #if SANITIZER_WORDSIZE == 32
1276                        "lw %5,16($29);\n"
1277 #else
1278                        "move $8,%5;\n"
1279 #endif
1280                        "li $2,%6;\n"
1281                        "syscall;\n"
1282
1283                        /* if ($v0 != 0)
1284                         * return;
1285                         */
1286                        "bnez $2,1f;\n"
1287
1288                        /* Call "fn(arg)". */
1289 #if SANITIZER_WORDSIZE == 32
1290 #ifdef __BIG_ENDIAN__
1291                        "lw $25,4($29);\n"
1292                        "lw $4,12($29);\n"
1293 #else
1294                        "lw $25,0($29);\n"
1295                        "lw $4,8($29);\n"
1296 #endif
1297 #else
1298                        "ld $25,0($29);\n"
1299                        "ld $4,8($29);\n"
1300 #endif
1301                        "jal $25;\n"
1302
1303                        /* Call _exit($v0). */
1304                        "move $4,$2;\n"
1305                        "li $2,%7;\n"
1306                        "syscall;\n"
1307
1308                        /* Return to parent. */
1309                      "1:\n"
1310                        : "=r" (res)
1311                        : "r"(flags),
1312                          "r"(child_stack),
1313                          "r"(parent_tidptr),
1314                          "r"(a3),
1315                          "r"(a4),
1316                          "i"(__NR_clone),
1317                          "i"(__NR_exit)
1318                        : "memory", "$29" );
1319   return res;
1320 }
1321 #elif defined(__aarch64__)
1322 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1323                     int *parent_tidptr, void *newtls, int *child_tidptr) {
1324   long long res;
1325   if (!fn || !child_stack)
1326     return -EINVAL;
1327   CHECK_EQ(0, (uptr)child_stack % 16);
1328   child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1329   ((unsigned long long *)child_stack)[0] = (uptr)fn;
1330   ((unsigned long long *)child_stack)[1] = (uptr)arg;
1331
1332   register int (*__fn)(void *)  __asm__("x0") = fn;
1333   register void *__stack __asm__("x1") = child_stack;
1334   register int   __flags __asm__("x2") = flags;
1335   register void *__arg   __asm__("x3") = arg;
1336   register int  *__ptid  __asm__("x4") = parent_tidptr;
1337   register void *__tls   __asm__("x5") = newtls;
1338   register int  *__ctid  __asm__("x6") = child_tidptr;
1339
1340   __asm__ __volatile__(
1341                        "mov x0,x2\n" /* flags  */
1342                        "mov x2,x4\n" /* ptid  */
1343                        "mov x3,x5\n" /* tls  */
1344                        "mov x4,x6\n" /* ctid  */
1345                        "mov x8,%9\n" /* clone  */
1346
1347                        "svc 0x0\n"
1348
1349                        /* if (%r0 != 0)
1350                         *   return %r0;
1351                         */
1352                        "cmp x0, #0\n"
1353                        "bne 1f\n"
1354
1355                        /* In the child, now. Call "fn(arg)". */
1356                        "ldp x1, x0, [sp], #16\n"
1357                        "blr x1\n"
1358
1359                        /* Call _exit(%r0).  */
1360                        "mov x8, %10\n"
1361                        "svc 0x0\n"
1362                      "1:\n"
1363
1364                        : "=r" (res)
1365                        : "i"(-EINVAL),
1366                          "r"(__fn), "r"(__stack), "r"(__flags), "r"(__arg),
1367                          "r"(__ptid), "r"(__tls), "r"(__ctid),
1368                          "i"(__NR_clone), "i"(__NR_exit)
1369                        : "x30", "memory");
1370   return res;
1371 }
1372 #elif defined(__powerpc64__)
1373 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1374                    int *parent_tidptr, void *newtls, int *child_tidptr) {
1375   long long res;
1376 // Stack frame structure.
1377 #if SANITIZER_PPC64V1
1378 //   Back chain == 0        (SP + 112)
1379 // Frame (112 bytes):
1380 //   Parameter save area    (SP + 48), 8 doublewords
1381 //   TOC save area          (SP + 40)
1382 //   Link editor doubleword (SP + 32)
1383 //   Compiler doubleword    (SP + 24)
1384 //   LR save area           (SP + 16)
1385 //   CR save area           (SP + 8)
1386 //   Back chain             (SP + 0)
1387 # define FRAME_SIZE 112
1388 # define FRAME_TOC_SAVE_OFFSET 40
1389 #elif SANITIZER_PPC64V2
1390 //   Back chain == 0        (SP + 32)
1391 // Frame (32 bytes):
1392 //   TOC save area          (SP + 24)
1393 //   LR save area           (SP + 16)
1394 //   CR save area           (SP + 8)
1395 //   Back chain             (SP + 0)
1396 # define FRAME_SIZE 32
1397 # define FRAME_TOC_SAVE_OFFSET 24
1398 #else
1399 # error "Unsupported PPC64 ABI"
1400 #endif
1401   if (!fn || !child_stack)
1402     return -EINVAL;
1403   CHECK_EQ(0, (uptr)child_stack % 16);
1404
1405   register int (*__fn)(void *) __asm__("r3") = fn;
1406   register void *__cstack      __asm__("r4") = child_stack;
1407   register int __flags         __asm__("r5") = flags;
1408   register void *__arg         __asm__("r6") = arg;
1409   register int *__ptidptr      __asm__("r7") = parent_tidptr;
1410   register void *__newtls      __asm__("r8") = newtls;
1411   register int *__ctidptr      __asm__("r9") = child_tidptr;
1412
1413  __asm__ __volatile__(
1414            /* fn and arg are saved across the syscall */
1415            "mr 28, %5\n\t"
1416            "mr 27, %8\n\t"
1417
1418            /* syscall
1419              r0 == __NR_clone
1420              r3 == flags
1421              r4 == child_stack
1422              r5 == parent_tidptr
1423              r6 == newtls
1424              r7 == child_tidptr */
1425            "mr 3, %7\n\t"
1426            "mr 5, %9\n\t"
1427            "mr 6, %10\n\t"
1428            "mr 7, %11\n\t"
1429            "li 0, %3\n\t"
1430            "sc\n\t"
1431
1432            /* Test if syscall was successful */
1433            "cmpdi  cr1, 3, 0\n\t"
1434            "crandc cr1*4+eq, cr1*4+eq, cr0*4+so\n\t"
1435            "bne-   cr1, 1f\n\t"
1436
1437            /* Set up stack frame */
1438            "li    29, 0\n\t"
1439            "stdu  29, -8(1)\n\t"
1440            "stdu  1, -%12(1)\n\t"
1441            /* Do the function call */
1442            "std   2, %13(1)\n\t"
1443 #if SANITIZER_PPC64V1
1444            "ld    0, 0(28)\n\t"
1445            "ld    2, 8(28)\n\t"
1446            "mtctr 0\n\t"
1447 #elif SANITIZER_PPC64V2
1448            "mr    12, 28\n\t"
1449            "mtctr 12\n\t"
1450 #else
1451 # error "Unsupported PPC64 ABI"
1452 #endif
1453            "mr    3, 27\n\t"
1454            "bctrl\n\t"
1455            "ld    2, %13(1)\n\t"
1456
1457            /* Call _exit(r3) */
1458            "li 0, %4\n\t"
1459            "sc\n\t"
1460
1461            /* Return to parent */
1462            "1:\n\t"
1463            "mr %0, 3\n\t"
1464              : "=r" (res)
1465              : "0" (-1),
1466                "i" (EINVAL),
1467                "i" (__NR_clone),
1468                "i" (__NR_exit),
1469                "r" (__fn),
1470                "r" (__cstack),
1471                "r" (__flags),
1472                "r" (__arg),
1473                "r" (__ptidptr),
1474                "r" (__newtls),
1475                "r" (__ctidptr),
1476                "i" (FRAME_SIZE),
1477                "i" (FRAME_TOC_SAVE_OFFSET)
1478              : "cr0", "cr1", "memory", "ctr", "r0", "r27", "r28", "r29");
1479   return res;
1480 }
1481 #elif defined(__i386__) && SANITIZER_LINUX
1482 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1483                     int *parent_tidptr, void *newtls, int *child_tidptr) {
1484   int res;
1485   if (!fn || !child_stack)
1486     return -EINVAL;
1487   CHECK_EQ(0, (uptr)child_stack % 16);
1488   child_stack = (char *)child_stack - 7 * sizeof(unsigned int);
1489   ((unsigned int *)child_stack)[0] = (uptr)flags;
1490   ((unsigned int *)child_stack)[1] = (uptr)0;
1491   ((unsigned int *)child_stack)[2] = (uptr)fn;
1492   ((unsigned int *)child_stack)[3] = (uptr)arg;
1493   __asm__ __volatile__(
1494                        /* %eax = syscall(%eax = SYSCALL(clone),
1495                         *                %ebx = flags,
1496                         *                %ecx = child_stack,
1497                         *                %edx = parent_tidptr,
1498                         *                %esi  = new_tls,
1499                         *                %edi = child_tidptr)
1500                         */
1501
1502                         /* Obtain flags */
1503                         "movl    (%%ecx), %%ebx\n"
1504                         /* Do the system call */
1505                         "pushl   %%ebx\n"
1506                         "pushl   %%esi\n"
1507                         "pushl   %%edi\n"
1508                         /* Remember the flag value.  */
1509                         "movl    %%ebx, (%%ecx)\n"
1510                         "int     $0x80\n"
1511                         "popl    %%edi\n"
1512                         "popl    %%esi\n"
1513                         "popl    %%ebx\n"
1514
1515                         /* if (%eax != 0)
1516                          *   return;
1517                          */
1518
1519                         "test    %%eax,%%eax\n"
1520                         "jnz    1f\n"
1521
1522                         /* terminate the stack frame */
1523                         "xorl   %%ebp,%%ebp\n"
1524                         /* Call FN. */
1525                         "call    *%%ebx\n"
1526 #ifdef PIC
1527                         "call    here\n"
1528                         "here:\n"
1529                         "popl    %%ebx\n"
1530                         "addl    $_GLOBAL_OFFSET_TABLE_+[.-here], %%ebx\n"
1531 #endif
1532                         /* Call exit */
1533                         "movl    %%eax, %%ebx\n"
1534                         "movl    %2, %%eax\n"
1535                         "int     $0x80\n"
1536                         "1:\n"
1537                        : "=a" (res)
1538                        : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
1539                          "c"(child_stack),
1540                          "d"(parent_tidptr),
1541                          "S"(newtls),
1542                          "D"(child_tidptr)
1543                        : "memory");
1544   return res;
1545 }
1546 #elif defined(__arm__) && SANITIZER_LINUX
1547 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1548                     int *parent_tidptr, void *newtls, int *child_tidptr) {
1549   unsigned int res;
1550   if (!fn || !child_stack)
1551     return -EINVAL;
1552   child_stack = (char *)child_stack - 2 * sizeof(unsigned int);
1553   ((unsigned int *)child_stack)[0] = (uptr)fn;
1554   ((unsigned int *)child_stack)[1] = (uptr)arg;
1555   register int r0 __asm__("r0") = flags;
1556   register void *r1 __asm__("r1") = child_stack;
1557   register int *r2 __asm__("r2") = parent_tidptr;
1558   register void *r3 __asm__("r3") = newtls;
1559   register int *r4 __asm__("r4") = child_tidptr;
1560   register int r7 __asm__("r7") = __NR_clone;
1561
1562 #if __ARM_ARCH > 4 || defined (__ARM_ARCH_4T__)
1563 # define ARCH_HAS_BX
1564 #endif
1565 #if __ARM_ARCH > 4
1566 # define ARCH_HAS_BLX
1567 #endif
1568
1569 #ifdef ARCH_HAS_BX
1570 # ifdef ARCH_HAS_BLX
1571 #  define BLX(R) "blx "  #R "\n"
1572 # else
1573 #  define BLX(R) "mov lr, pc; bx " #R "\n"
1574 # endif
1575 #else
1576 # define BLX(R)  "mov lr, pc; mov pc," #R "\n"
1577 #endif
1578
1579   __asm__ __volatile__(
1580                        /* %r0 = syscall(%r7 = SYSCALL(clone),
1581                         *               %r0 = flags,
1582                         *               %r1 = child_stack,
1583                         *               %r2 = parent_tidptr,
1584                         *               %r3  = new_tls,
1585                         *               %r4 = child_tidptr)
1586                         */
1587
1588                        /* Do the system call */
1589                        "swi 0x0\n"
1590
1591                        /* if (%r0 != 0)
1592                         *   return %r0;
1593                         */
1594                        "cmp r0, #0\n"
1595                        "bne 1f\n"
1596
1597                        /* In the child, now. Call "fn(arg)". */
1598                        "ldr r0, [sp, #4]\n"
1599                        "ldr ip, [sp], #8\n"
1600                        BLX(ip)
1601                        /* Call _exit(%r0). */
1602                        "mov r7, %7\n"
1603                        "swi 0x0\n"
1604                        "1:\n"
1605                        "mov %0, r0\n"
1606                        : "=r"(res)
1607                        : "r"(r0), "r"(r1), "r"(r2), "r"(r3), "r"(r4), "r"(r7),
1608                          "i"(__NR_exit)
1609                        : "memory");
1610   return res;
1611 }
1612 #endif  // defined(__x86_64__) && SANITIZER_LINUX
1613
1614 #if SANITIZER_ANDROID
1615 #if __ANDROID_API__ < 21
1616 extern "C" __attribute__((weak)) int dl_iterate_phdr(
1617     int (*)(struct dl_phdr_info *, size_t, void *), void *);
1618 #endif
1619
1620 static int dl_iterate_phdr_test_cb(struct dl_phdr_info *info, size_t size,
1621                                    void *data) {
1622   // Any name starting with "lib" indicates a bug in L where library base names
1623   // are returned instead of paths.
1624   if (info->dlpi_name && info->dlpi_name[0] == 'l' &&
1625       info->dlpi_name[1] == 'i' && info->dlpi_name[2] == 'b') {
1626     *(bool *)data = true;
1627     return 1;
1628   }
1629   return 0;
1630 }
1631
1632 static atomic_uint32_t android_api_level;
1633
1634 static AndroidApiLevel AndroidDetectApiLevel() {
1635   if (!&dl_iterate_phdr)
1636     return ANDROID_KITKAT; // K or lower
1637   bool base_name_seen = false;
1638   dl_iterate_phdr(dl_iterate_phdr_test_cb, &base_name_seen);
1639   if (base_name_seen)
1640     return ANDROID_LOLLIPOP_MR1; // L MR1
1641   return ANDROID_POST_LOLLIPOP;   // post-L
1642   // Plain L (API level 21) is completely broken wrt ASan and not very
1643   // interesting to detect.
1644 }
1645
1646 AndroidApiLevel AndroidGetApiLevel() {
1647   AndroidApiLevel level =
1648       (AndroidApiLevel)atomic_load(&android_api_level, memory_order_relaxed);
1649   if (level) return level;
1650   level = AndroidDetectApiLevel();
1651   atomic_store(&android_api_level, level, memory_order_relaxed);
1652   return level;
1653 }
1654
1655 #endif
1656
1657 static HandleSignalMode GetHandleSignalModeImpl(int signum) {
1658   switch (signum) {
1659     case SIGABRT:
1660       return common_flags()->handle_abort;
1661     case SIGILL:
1662       return common_flags()->handle_sigill;
1663     case SIGTRAP:
1664       return common_flags()->handle_sigtrap;
1665     case SIGFPE:
1666       return common_flags()->handle_sigfpe;
1667     case SIGSEGV:
1668       return common_flags()->handle_segv;
1669     case SIGBUS:
1670       return common_flags()->handle_sigbus;
1671   }
1672   return kHandleSignalNo;
1673 }
1674
1675 HandleSignalMode GetHandleSignalMode(int signum) {
1676   HandleSignalMode result = GetHandleSignalModeImpl(signum);
1677   if (result == kHandleSignalYes && !common_flags()->allow_user_segv_handler)
1678     return kHandleSignalExclusive;
1679   return result;
1680 }
1681
1682 #if !SANITIZER_GO
1683 void *internal_start_thread(void(*func)(void *arg), void *arg) {
1684   // Start the thread with signals blocked, otherwise it can steal user signals.
1685   __sanitizer_sigset_t set, old;
1686   internal_sigfillset(&set);
1687 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1688   // Glibc uses SIGSETXID signal during setuid call. If this signal is blocked
1689   // on any thread, setuid call hangs (see test/tsan/setuid.c).
1690   internal_sigdelset(&set, 33);
1691 #endif
1692   internal_sigprocmask(SIG_SETMASK, &set, &old);
1693   void *th;
1694   real_pthread_create(&th, nullptr, (void*(*)(void *arg))func, arg);
1695   internal_sigprocmask(SIG_SETMASK, &old, nullptr);
1696   return th;
1697 }
1698
1699 void internal_join_thread(void *th) {
1700   real_pthread_join(th, nullptr);
1701 }
1702 #else
1703 void *internal_start_thread(void (*func)(void *), void *arg) { return 0; }
1704
1705 void internal_join_thread(void *th) {}
1706 #endif
1707
1708 #if defined(__aarch64__)
1709 // Android headers in the older NDK releases miss this definition.
1710 struct __sanitizer_esr_context {
1711   struct _aarch64_ctx head;
1712   uint64_t esr;
1713 };
1714
1715 static bool Aarch64GetESR(ucontext_t *ucontext, u64 *esr) {
1716   static const u32 kEsrMagic = 0x45535201;
1717   u8 *aux = ucontext->uc_mcontext.__reserved;
1718   while (true) {
1719     _aarch64_ctx *ctx = (_aarch64_ctx *)aux;
1720     if (ctx->size == 0) break;
1721     if (ctx->magic == kEsrMagic) {
1722       *esr = ((__sanitizer_esr_context *)ctx)->esr;
1723       return true;
1724     }
1725     aux += ctx->size;
1726   }
1727   return false;
1728 }
1729 #endif
1730
1731 #if SANITIZER_OPENBSD
1732 using Context = sigcontext;
1733 #else
1734 using Context = ucontext_t;
1735 #endif
1736
1737 SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
1738   Context *ucontext = (Context *)context;
1739 #if defined(__x86_64__) || defined(__i386__)
1740   static const uptr PF_WRITE = 1U << 1;
1741 #if SANITIZER_FREEBSD
1742   uptr err = ucontext->uc_mcontext.mc_err;
1743 #elif SANITIZER_NETBSD
1744   uptr err = ucontext->uc_mcontext.__gregs[_REG_ERR];
1745 #elif SANITIZER_OPENBSD
1746   uptr err = ucontext->sc_err;
1747 #elif SANITIZER_SOLARIS && defined(__i386__)
1748   const int Err = 13;
1749   uptr err = ucontext->uc_mcontext.gregs[Err];
1750 #else
1751   uptr err = ucontext->uc_mcontext.gregs[REG_ERR];
1752 #endif // SANITIZER_FREEBSD
1753   return err & PF_WRITE ? WRITE : READ;
1754 #elif defined(__mips__)
1755   uint32_t *exception_source;
1756   uint32_t faulty_instruction;
1757   uint32_t op_code;
1758
1759   exception_source = (uint32_t *)ucontext->uc_mcontext.pc;
1760   faulty_instruction = (uint32_t)(*exception_source);
1761
1762   op_code = (faulty_instruction >> 26) & 0x3f;
1763
1764   // FIXME: Add support for FPU, microMIPS, DSP, MSA memory instructions.
1765   switch (op_code) {
1766     case 0x28:  // sb
1767     case 0x29:  // sh
1768     case 0x2b:  // sw
1769     case 0x3f:  // sd
1770 #if __mips_isa_rev < 6
1771     case 0x2c:  // sdl
1772     case 0x2d:  // sdr
1773     case 0x2a:  // swl
1774     case 0x2e:  // swr
1775 #endif
1776       return SignalContext::WRITE;
1777
1778     case 0x20:  // lb
1779     case 0x24:  // lbu
1780     case 0x21:  // lh
1781     case 0x25:  // lhu
1782     case 0x23:  // lw
1783     case 0x27:  // lwu
1784     case 0x37:  // ld
1785 #if __mips_isa_rev < 6
1786     case 0x1a:  // ldl
1787     case 0x1b:  // ldr
1788     case 0x22:  // lwl
1789     case 0x26:  // lwr
1790 #endif
1791       return SignalContext::READ;
1792 #if __mips_isa_rev == 6
1793     case 0x3b:  // pcrel
1794       op_code = (faulty_instruction >> 19) & 0x3;
1795       switch (op_code) {
1796         case 0x1:  // lwpc
1797         case 0x2:  // lwupc
1798           return SignalContext::READ;
1799       }
1800 #endif
1801   }
1802   return SignalContext::UNKNOWN;
1803 #elif defined(__arm__)
1804   static const uptr FSR_WRITE = 1U << 11;
1805   uptr fsr = ucontext->uc_mcontext.error_code;
1806   return fsr & FSR_WRITE ? WRITE : READ;
1807 #elif defined(__aarch64__)
1808   static const u64 ESR_ELx_WNR = 1U << 6;
1809   u64 esr;
1810   if (!Aarch64GetESR(ucontext, &esr)) return UNKNOWN;
1811   return esr & ESR_ELx_WNR ? WRITE : READ;
1812 #elif SANITIZER_SOLARIS && defined(__sparc__)
1813   // Decode the instruction to determine the access type.
1814   // From OpenSolaris $SRC/uts/sun4/os/trap.c (get_accesstype).
1815   uptr pc = ucontext->uc_mcontext.gregs[REG_PC];
1816   u32 instr = *(u32 *)pc;
1817   return (instr >> 21) & 1 ? WRITE: READ;
1818 #else
1819   (void)ucontext;
1820   return UNKNOWN;  // FIXME: Implement.
1821 #endif
1822 }
1823
1824 void SignalContext::DumpAllRegisters(void *context) {
1825   // FIXME: Implement this.
1826 }
1827
1828 static void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
1829 #if SANITIZER_NETBSD
1830   // This covers all NetBSD architectures
1831   ucontext_t *ucontext = (ucontext_t *)context;
1832   *pc = _UC_MACHINE_PC(ucontext);
1833   *bp = _UC_MACHINE_FP(ucontext);
1834   *sp = _UC_MACHINE_SP(ucontext);
1835 #elif defined(__arm__)
1836   ucontext_t *ucontext = (ucontext_t*)context;
1837   *pc = ucontext->uc_mcontext.arm_pc;
1838   *bp = ucontext->uc_mcontext.arm_fp;
1839   *sp = ucontext->uc_mcontext.arm_sp;
1840 #elif defined(__aarch64__)
1841   ucontext_t *ucontext = (ucontext_t*)context;
1842   *pc = ucontext->uc_mcontext.pc;
1843   *bp = ucontext->uc_mcontext.regs[29];
1844   *sp = ucontext->uc_mcontext.sp;
1845 #elif defined(__hppa__)
1846   ucontext_t *ucontext = (ucontext_t*)context;
1847   *pc = ucontext->uc_mcontext.sc_iaoq[0];
1848   /* GCC uses %r3 whenever a frame pointer is needed.  */
1849   *bp = ucontext->uc_mcontext.sc_gr[3];
1850   *sp = ucontext->uc_mcontext.sc_gr[30];
1851 #elif defined(__x86_64__)
1852 # if SANITIZER_FREEBSD
1853   ucontext_t *ucontext = (ucontext_t*)context;
1854   *pc = ucontext->uc_mcontext.mc_rip;
1855   *bp = ucontext->uc_mcontext.mc_rbp;
1856   *sp = ucontext->uc_mcontext.mc_rsp;
1857 #elif SANITIZER_OPENBSD
1858   sigcontext *ucontext = (sigcontext *)context;
1859   *pc = ucontext->sc_rip;
1860   *bp = ucontext->sc_rbp;
1861   *sp = ucontext->sc_rsp;
1862 # else
1863   ucontext_t *ucontext = (ucontext_t*)context;
1864   *pc = ucontext->uc_mcontext.gregs[REG_RIP];
1865   *bp = ucontext->uc_mcontext.gregs[REG_RBP];
1866   *sp = ucontext->uc_mcontext.gregs[REG_RSP];
1867 # endif
1868 #elif defined(__i386__)
1869 # if SANITIZER_FREEBSD
1870   ucontext_t *ucontext = (ucontext_t*)context;
1871   *pc = ucontext->uc_mcontext.mc_eip;
1872   *bp = ucontext->uc_mcontext.mc_ebp;
1873   *sp = ucontext->uc_mcontext.mc_esp;
1874 #elif SANITIZER_OPENBSD
1875   sigcontext *ucontext = (sigcontext *)context;
1876   *pc = ucontext->sc_eip;
1877   *bp = ucontext->sc_ebp;
1878   *sp = ucontext->sc_esp;
1879 # else
1880   ucontext_t *ucontext = (ucontext_t*)context;
1881 # if SANITIZER_SOLARIS
1882   /* Use the numeric values: the symbolic ones are undefined by llvm
1883      include/llvm/Support/Solaris.h.  */
1884 # ifndef REG_EIP
1885 #  define REG_EIP 14 // REG_PC
1886 # endif
1887 # ifndef REG_EBP
1888 #  define REG_EBP  6 // REG_FP
1889 # endif
1890 # ifndef REG_ESP
1891 #  define REG_ESP 17 // REG_SP
1892 # endif
1893 # endif
1894   *pc = ucontext->uc_mcontext.gregs[REG_EIP];
1895   *bp = ucontext->uc_mcontext.gregs[REG_EBP];
1896   *sp = ucontext->uc_mcontext.gregs[REG_ESP];
1897 # endif
1898 #elif defined(__powerpc__) || defined(__powerpc64__)
1899   ucontext_t *ucontext = (ucontext_t*)context;
1900   *pc = ucontext->uc_mcontext.regs->nip;
1901   *sp = ucontext->uc_mcontext.regs->gpr[PT_R1];
1902   // The powerpc{,64}-linux ABIs do not specify r31 as the frame
1903   // pointer, but GCC always uses r31 when we need a frame pointer.
1904   *bp = ucontext->uc_mcontext.regs->gpr[PT_R31];
1905 #elif defined(__sparc__)
1906   ucontext_t *ucontext = (ucontext_t*)context;
1907   uptr *stk_ptr;
1908 # if defined (__sparcv9)
1909 # ifndef MC_PC
1910 #  define MC_PC REG_PC
1911 # endif
1912 # ifndef MC_O6
1913 #  define MC_O6 REG_O6
1914 # endif
1915 # ifdef SANITIZER_SOLARIS
1916 #  define mc_gregs gregs
1917 # endif
1918   *pc = ucontext->uc_mcontext.mc_gregs[MC_PC];
1919   *sp = ucontext->uc_mcontext.mc_gregs[MC_O6];
1920   stk_ptr = (uptr *) (*sp + 2047);
1921   *bp = stk_ptr[15];
1922 # else
1923   *pc = ucontext->uc_mcontext.gregs[REG_PC];
1924   *sp = ucontext->uc_mcontext.gregs[REG_O6];
1925   stk_ptr = (uptr *) *sp;
1926   *bp = stk_ptr[15];
1927 # endif
1928 #elif defined(__mips__)
1929   ucontext_t *ucontext = (ucontext_t*)context;
1930   *pc = ucontext->uc_mcontext.pc;
1931   *bp = ucontext->uc_mcontext.gregs[30];
1932   *sp = ucontext->uc_mcontext.gregs[29];
1933 #elif defined(__s390__)
1934   ucontext_t *ucontext = (ucontext_t*)context;
1935 # if defined(__s390x__)
1936   *pc = ucontext->uc_mcontext.psw.addr;
1937 # else
1938   *pc = ucontext->uc_mcontext.psw.addr & 0x7fffffff;
1939 # endif
1940   *bp = ucontext->uc_mcontext.gregs[11];
1941   *sp = ucontext->uc_mcontext.gregs[15];
1942 #else
1943 # error "Unsupported arch"
1944 #endif
1945 }
1946
1947 void SignalContext::InitPcSpBp() { GetPcSpBp(context, &pc, &sp, &bp); }
1948
1949 void MaybeReexec() {
1950   // No need to re-exec on Linux.
1951 }
1952
1953 void CheckASLR() {
1954 #if SANITIZER_NETBSD
1955   int mib[3];
1956   int paxflags;
1957   size_t len = sizeof(paxflags);
1958
1959   mib[0] = CTL_PROC;
1960   mib[1] = internal_getpid();
1961   mib[2] = PROC_PID_PAXFLAGS;
1962
1963   if (UNLIKELY(sysctl(mib, 3, &paxflags, &len, NULL, 0) == -1)) {
1964     Printf("sysctl failed\n");
1965     Die();
1966   }
1967
1968   if (UNLIKELY(paxflags & CTL_PROC_PAXFLAGS_ASLR)) {
1969     Printf("This sanitizer is not compatible with enabled ASLR\n");
1970     Die();
1971   }
1972 #else
1973   // Do nothing
1974 #endif
1975 }
1976
1977 void PrintModuleMap() { }
1978
1979 void CheckNoDeepBind(const char *filename, int flag) {
1980 #ifdef RTLD_DEEPBIND
1981   if (flag & RTLD_DEEPBIND) {
1982     Report(
1983         "You are trying to dlopen a %s shared library with RTLD_DEEPBIND flag"
1984         " which is incompatibe with sanitizer runtime "
1985         "(see https://github.com/google/sanitizers/issues/611 for details"
1986         "). If you want to run %s library under sanitizers please remove "
1987         "RTLD_DEEPBIND from dlopen flags.\n",
1988         filename, filename);
1989     Die();
1990   }
1991 #endif
1992 }
1993
1994 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
1995                               uptr *largest_gap_found,
1996                               uptr *max_occupied_addr) {
1997   UNREACHABLE("FindAvailableMemoryRange is not available");
1998   return 0;
1999 }
2000
2001 bool GetRandom(void *buffer, uptr length, bool blocking) {
2002   if (!buffer || !length || length > 256)
2003     return false;
2004 #if SANITIZER_USE_GETENTROPY
2005   uptr rnd = getentropy(buffer, length);
2006   int rverrno = 0;
2007   if (internal_iserror(rnd, &rverrno) && rverrno == EFAULT)
2008     return false;
2009   else if (rnd == 0)
2010     return true;
2011 #endif // SANITIZER_USE_GETENTROPY
2012
2013 #if SANITIZER_USE_GETRANDOM
2014   static atomic_uint8_t skip_getrandom_syscall;
2015   if (!atomic_load_relaxed(&skip_getrandom_syscall)) {
2016     // Up to 256 bytes, getrandom will not be interrupted.
2017     uptr res = internal_syscall(SYSCALL(getrandom), buffer, length,
2018                                 blocking ? 0 : GRND_NONBLOCK);
2019     int rverrno = 0;
2020     if (internal_iserror(res, &rverrno) && rverrno == ENOSYS)
2021       atomic_store_relaxed(&skip_getrandom_syscall, 1);
2022     else if (res == length)
2023       return true;
2024   }
2025 #endif // SANITIZER_USE_GETRANDOM
2026   // Up to 256 bytes, a read off /dev/urandom will not be interrupted.
2027   // blocking is moot here, O_NONBLOCK has no effect when opening /dev/urandom.
2028   uptr fd = internal_open("/dev/urandom", O_RDONLY);
2029   if (internal_iserror(fd))
2030     return false;
2031   uptr res = internal_read(fd, buffer, length);
2032   if (internal_iserror(res))
2033     return false;
2034   internal_close(fd);
2035   return true;
2036 }
2037
2038 } // namespace __sanitizer
2039
2040 #endif