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