xref: /freebsd/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp (revision cfd6422a5217410fbd66f7a7a8a64d9d85e61229)
1 //===-- sanitizer_linux.cpp -----------------------------------------------===//
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 && !SANITIZER_GO
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                    u64 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 defined(__riscv)
411   return internal_syscall(SYSCALL(renameat2), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
412                           (uptr)newpath, 0);
413 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS || SANITIZER_OPENBSD
414   return internal_syscall(SYSCALL(renameat), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
415                           (uptr)newpath);
416 #else
417   return internal_syscall(SYSCALL(rename), (uptr)oldpath, (uptr)newpath);
418 #endif
419 }
420 
421 uptr internal_sched_yield() {
422   return internal_syscall(SYSCALL(sched_yield));
423 }
424 
425 void internal__exit(int exitcode) {
426 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD
427   internal_syscall(SYSCALL(exit), exitcode);
428 #else
429   internal_syscall(SYSCALL(exit_group), exitcode);
430 #endif
431   Die();  // Unreachable.
432 }
433 
434 unsigned int internal_sleep(unsigned int seconds) {
435   struct timespec ts;
436   ts.tv_sec = seconds;
437   ts.tv_nsec = 0;
438   int res = internal_syscall(SYSCALL(nanosleep), &ts, &ts);
439   if (res) return ts.tv_sec;
440   return 0;
441 }
442 
443 uptr internal_execve(const char *filename, char *const argv[],
444                      char *const envp[]) {
445   return internal_syscall(SYSCALL(execve), (uptr)filename, (uptr)argv,
446                           (uptr)envp);
447 }
448 #endif  // !SANITIZER_SOLARIS && !SANITIZER_NETBSD
449 
450 // ----------------- sanitizer_common.h
451 bool FileExists(const char *filename) {
452   if (ShouldMockFailureToOpen(filename))
453     return false;
454   struct stat st;
455 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
456   if (internal_syscall(SYSCALL(newfstatat), AT_FDCWD, filename, &st, 0))
457 #else
458   if (internal_stat(filename, &st))
459 #endif
460     return false;
461   // Sanity check: filename is a regular file.
462   return S_ISREG(st.st_mode);
463 }
464 
465 #if !SANITIZER_NETBSD
466 tid_t GetTid() {
467 #if SANITIZER_FREEBSD
468   long Tid;
469   thr_self(&Tid);
470   return Tid;
471 #elif SANITIZER_OPENBSD
472   return internal_syscall(SYSCALL(getthrid));
473 #elif SANITIZER_SOLARIS
474   return thr_self();
475 #else
476   return internal_syscall(SYSCALL(gettid));
477 #endif
478 }
479 
480 int TgKill(pid_t pid, tid_t tid, int sig) {
481 #if SANITIZER_LINUX
482   return internal_syscall(SYSCALL(tgkill), pid, tid, sig);
483 #elif SANITIZER_FREEBSD
484   return internal_syscall(SYSCALL(thr_kill2), pid, tid, sig);
485 #elif SANITIZER_OPENBSD
486   (void)pid;
487   return internal_syscall(SYSCALL(thrkill), tid, sig, nullptr);
488 #elif SANITIZER_SOLARIS
489   (void)pid;
490   return thr_kill(tid, sig);
491 #endif
492 }
493 #endif
494 
495 #if !SANITIZER_SOLARIS && !SANITIZER_NETBSD
496 u64 NanoTime() {
497 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD
498   timeval tv;
499 #else
500   kernel_timeval tv;
501 #endif
502   internal_memset(&tv, 0, sizeof(tv));
503   internal_syscall(SYSCALL(gettimeofday), &tv, 0);
504   return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
505 }
506 
507 uptr internal_clock_gettime(__sanitizer_clockid_t clk_id, void *tp) {
508   return internal_syscall(SYSCALL(clock_gettime), clk_id, tp);
509 }
510 #endif  // !SANITIZER_SOLARIS && !SANITIZER_NETBSD
511 
512 // Like getenv, but reads env directly from /proc (on Linux) or parses the
513 // 'environ' array (on some others) and does not use libc. This function
514 // should be called first inside __asan_init.
515 const char *GetEnv(const char *name) {
516 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD || \
517     SANITIZER_SOLARIS
518   if (::environ != 0) {
519     uptr NameLen = internal_strlen(name);
520     for (char **Env = ::environ; *Env != 0; Env++) {
521       if (internal_strncmp(*Env, name, NameLen) == 0 && (*Env)[NameLen] == '=')
522         return (*Env) + NameLen + 1;
523     }
524   }
525   return 0;  // Not found.
526 #elif SANITIZER_LINUX
527   static char *environ;
528   static uptr len;
529   static bool inited;
530   if (!inited) {
531     inited = true;
532     uptr environ_size;
533     if (!ReadFileToBuffer("/proc/self/environ", &environ, &environ_size, &len))
534       environ = nullptr;
535   }
536   if (!environ || len == 0) return nullptr;
537   uptr namelen = internal_strlen(name);
538   const char *p = environ;
539   while (*p != '\0') {  // will happen at the \0\0 that terminates the buffer
540     // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
541     const char* endp =
542         (char*)internal_memchr(p, '\0', len - (p - environ));
543     if (!endp)  // this entry isn't NUL terminated
544       return nullptr;
545     else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=')  // Match.
546       return p + namelen + 1;  // point after =
547     p = endp + 1;
548   }
549   return nullptr;  // Not found.
550 #else
551 #error "Unsupported platform"
552 #endif
553 }
554 
555 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD && !SANITIZER_OPENBSD && \
556     !SANITIZER_GO
557 extern "C" {
558 SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
559 }
560 #endif
561 
562 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD &&                \
563     !SANITIZER_OPENBSD
564 static void ReadNullSepFileToArray(const char *path, char ***arr,
565                                    int arr_size) {
566   char *buff;
567   uptr buff_size;
568   uptr buff_len;
569   *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
570   if (!ReadFileToBuffer(path, &buff, &buff_size, &buff_len, 1024 * 1024)) {
571     (*arr)[0] = nullptr;
572     return;
573   }
574   (*arr)[0] = buff;
575   int count, i;
576   for (count = 1, i = 1; ; i++) {
577     if (buff[i] == 0) {
578       if (buff[i+1] == 0) break;
579       (*arr)[count] = &buff[i+1];
580       CHECK_LE(count, arr_size - 1);  // FIXME: make this more flexible.
581       count++;
582     }
583   }
584   (*arr)[count] = nullptr;
585 }
586 #endif
587 
588 #if !SANITIZER_OPENBSD
589 static void GetArgsAndEnv(char ***argv, char ***envp) {
590 #if SANITIZER_FREEBSD
591   // On FreeBSD, retrieving the argument and environment arrays is done via the
592   // kern.ps_strings sysctl, which returns a pointer to a structure containing
593   // this information. See also <sys/exec.h>.
594   ps_strings *pss;
595   uptr sz = sizeof(pss);
596   if (internal_sysctlbyname("kern.ps_strings", &pss, &sz, NULL, 0) == -1) {
597     Printf("sysctl kern.ps_strings failed\n");
598     Die();
599   }
600   *argv = pss->ps_argvstr;
601   *envp = pss->ps_envstr;
602 #elif SANITIZER_NETBSD
603   *argv = __ps_strings->ps_argvstr;
604   *envp = __ps_strings->ps_envstr;
605 #else // SANITIZER_FREEBSD
606 #if !SANITIZER_GO
607   if (&__libc_stack_end) {
608     uptr* stack_end = (uptr*)__libc_stack_end;
609     // Normally argc can be obtained from *stack_end, however, on ARM glibc's
610     // _start clobbers it:
611     // https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/arm/start.S;hb=refs/heads/release/2.31/master#l75
612     // Do not special-case ARM and infer argc from argv everywhere.
613     int argc = 0;
614     while (stack_end[argc + 1]) argc++;
615     *argv = (char**)(stack_end + 1);
616     *envp = (char**)(stack_end + argc + 2);
617   } else {
618 #endif // !SANITIZER_GO
619     static const int kMaxArgv = 2000, kMaxEnvp = 2000;
620     ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
621     ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
622 #if !SANITIZER_GO
623   }
624 #endif // !SANITIZER_GO
625 #endif // SANITIZER_FREEBSD
626 }
627 
628 char **GetArgv() {
629   char **argv, **envp;
630   GetArgsAndEnv(&argv, &envp);
631   return argv;
632 }
633 
634 char **GetEnviron() {
635   char **argv, **envp;
636   GetArgsAndEnv(&argv, &envp);
637   return envp;
638 }
639 
640 #endif  // !SANITIZER_OPENBSD
641 
642 #if !SANITIZER_SOLARIS
643 enum MutexState {
644   MtxUnlocked = 0,
645   MtxLocked = 1,
646   MtxSleeping = 2
647 };
648 
649 BlockingMutex::BlockingMutex() {
650   internal_memset(this, 0, sizeof(*this));
651 }
652 
653 void BlockingMutex::Lock() {
654   CHECK_EQ(owner_, 0);
655   atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
656   if (atomic_exchange(m, MtxLocked, memory_order_acquire) == MtxUnlocked)
657     return;
658   while (atomic_exchange(m, MtxSleeping, memory_order_acquire) != MtxUnlocked) {
659 #if SANITIZER_FREEBSD
660     _umtx_op(m, UMTX_OP_WAIT_UINT, MtxSleeping, 0, 0);
661 #elif SANITIZER_NETBSD
662     sched_yield(); /* No userspace futex-like synchronization */
663 #else
664     internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAIT_PRIVATE, MtxSleeping,
665                      0, 0, 0);
666 #endif
667   }
668 }
669 
670 void BlockingMutex::Unlock() {
671   atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
672   u32 v = atomic_exchange(m, MtxUnlocked, memory_order_release);
673   CHECK_NE(v, MtxUnlocked);
674   if (v == MtxSleeping) {
675 #if SANITIZER_FREEBSD
676     _umtx_op(m, UMTX_OP_WAKE, 1, 0, 0);
677 #elif SANITIZER_NETBSD
678                    /* No userspace futex-like synchronization */
679 #else
680     internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAKE_PRIVATE, 1, 0, 0, 0);
681 #endif
682   }
683 }
684 
685 void BlockingMutex::CheckLocked() {
686   atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
687   CHECK_NE(MtxUnlocked, atomic_load(m, memory_order_relaxed));
688 }
689 #endif // !SANITIZER_SOLARIS
690 
691 // ----------------- sanitizer_linux.h
692 // The actual size of this structure is specified by d_reclen.
693 // Note that getdents64 uses a different structure format. We only provide the
694 // 32-bit syscall here.
695 #if SANITIZER_NETBSD
696 // Not used
697 #elif 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 && !SANITIZER_NETBSD
725 // Syscall wrappers.
726 uptr internal_ptrace(int request, int pid, void *addr, void *data) {
727   return internal_syscall(SYSCALL(ptrace), request, pid, (uptr)addr,
728                           (uptr)data);
729 }
730 
731 uptr internal_waitpid(int pid, int *status, int options) {
732   return internal_syscall(SYSCALL(wait4), pid, (uptr)status, options,
733                           0 /* rusage */);
734 }
735 
736 uptr internal_getpid() {
737   return internal_syscall(SYSCALL(getpid));
738 }
739 
740 uptr internal_getppid() {
741   return internal_syscall(SYSCALL(getppid));
742 }
743 
744 int internal_dlinfo(void *handle, int request, void *p) {
745 #if SANITIZER_FREEBSD
746   return dlinfo(handle, request, p);
747 #else
748   UNIMPLEMENTED();
749 #endif
750 }
751 
752 uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) {
753 #if SANITIZER_FREEBSD
754   return internal_syscall(SYSCALL(getdirentries), fd, (uptr)dirp, count, NULL);
755 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
756   return internal_syscall(SYSCALL(getdents64), fd, (uptr)dirp, count);
757 #else
758   return internal_syscall(SYSCALL(getdents), fd, (uptr)dirp, count);
759 #endif
760 }
761 
762 uptr internal_lseek(fd_t fd, OFF_T offset, int whence) {
763   return internal_syscall(SYSCALL(lseek), fd, offset, whence);
764 }
765 
766 #if SANITIZER_LINUX
767 uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
768   return internal_syscall(SYSCALL(prctl), option, arg2, arg3, arg4, arg5);
769 }
770 #endif
771 
772 uptr internal_sigaltstack(const void *ss, void *oss) {
773   return internal_syscall(SYSCALL(sigaltstack), (uptr)ss, (uptr)oss);
774 }
775 
776 int internal_fork() {
777 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
778   return internal_syscall(SYSCALL(clone), SIGCHLD, 0);
779 #else
780   return internal_syscall(SYSCALL(fork));
781 #endif
782 }
783 
784 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD
785 int internal_sysctl(const int *name, unsigned int namelen, void *oldp,
786                     uptr *oldlenp, const void *newp, uptr newlen) {
787 #if SANITIZER_OPENBSD
788   return sysctl(name, namelen, oldp, (size_t *)oldlenp, (void *)newp,
789                 (size_t)newlen);
790 #else
791   return internal_syscall(SYSCALL(__sysctl), name, namelen, oldp,
792                           (size_t *)oldlenp, newp, (size_t)newlen);
793 #endif
794 }
795 
796 #if SANITIZER_FREEBSD
797 int internal_sysctlbyname(const char *sname, void *oldp, uptr *oldlenp,
798                           const void *newp, uptr newlen) {
799   static decltype(sysctlbyname) *real = nullptr;
800   if (!real)
801     real = (decltype(sysctlbyname) *)dlsym(RTLD_NEXT, "sysctlbyname");
802   CHECK(real);
803   return real(sname, oldp, (size_t *)oldlenp, newp, (size_t)newlen);
804 }
805 #endif
806 #endif
807 
808 #if SANITIZER_LINUX
809 #define SA_RESTORER 0x04000000
810 // Doesn't set sa_restorer if the caller did not set it, so use with caution
811 //(see below).
812 int internal_sigaction_norestorer(int signum, const void *act, void *oldact) {
813   __sanitizer_kernel_sigaction_t k_act, k_oldact;
814   internal_memset(&k_act, 0, sizeof(__sanitizer_kernel_sigaction_t));
815   internal_memset(&k_oldact, 0, sizeof(__sanitizer_kernel_sigaction_t));
816   const __sanitizer_sigaction *u_act = (const __sanitizer_sigaction *)act;
817   __sanitizer_sigaction *u_oldact = (__sanitizer_sigaction *)oldact;
818   if (u_act) {
819     k_act.handler = u_act->handler;
820     k_act.sigaction = u_act->sigaction;
821     internal_memcpy(&k_act.sa_mask, &u_act->sa_mask,
822                     sizeof(__sanitizer_kernel_sigset_t));
823     // Without SA_RESTORER kernel ignores the calls (probably returns EINVAL).
824     k_act.sa_flags = u_act->sa_flags | SA_RESTORER;
825     // FIXME: most often sa_restorer is unset, however the kernel requires it
826     // to point to a valid signal restorer that calls the rt_sigreturn syscall.
827     // If sa_restorer passed to the kernel is NULL, the program may crash upon
828     // signal delivery or fail to unwind the stack in the signal handler.
829     // libc implementation of sigaction() passes its own restorer to
830     // rt_sigaction, so we need to do the same (we'll need to reimplement the
831     // restorers; for x86_64 the restorer address can be obtained from
832     // oldact->sa_restorer upon a call to sigaction(xxx, NULL, oldact).
833 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
834     k_act.sa_restorer = u_act->sa_restorer;
835 #endif
836   }
837 
838   uptr result = internal_syscall(SYSCALL(rt_sigaction), (uptr)signum,
839       (uptr)(u_act ? &k_act : nullptr),
840       (uptr)(u_oldact ? &k_oldact : nullptr),
841       (uptr)sizeof(__sanitizer_kernel_sigset_t));
842 
843   if ((result == 0) && u_oldact) {
844     u_oldact->handler = k_oldact.handler;
845     u_oldact->sigaction = k_oldact.sigaction;
846     internal_memcpy(&u_oldact->sa_mask, &k_oldact.sa_mask,
847                     sizeof(__sanitizer_kernel_sigset_t));
848     u_oldact->sa_flags = k_oldact.sa_flags;
849 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
850     u_oldact->sa_restorer = k_oldact.sa_restorer;
851 #endif
852   }
853   return result;
854 }
855 #endif  // SANITIZER_LINUX
856 
857 uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
858                           __sanitizer_sigset_t *oldset) {
859 #if SANITIZER_FREEBSD || SANITIZER_OPENBSD
860   return internal_syscall(SYSCALL(sigprocmask), how, set, oldset);
861 #else
862   __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
863   __sanitizer_kernel_sigset_t *k_oldset = (__sanitizer_kernel_sigset_t *)oldset;
864   return internal_syscall(SYSCALL(rt_sigprocmask), (uptr)how, (uptr)k_set,
865                           (uptr)k_oldset, sizeof(__sanitizer_kernel_sigset_t));
866 #endif
867 }
868 
869 void internal_sigfillset(__sanitizer_sigset_t *set) {
870   internal_memset(set, 0xff, sizeof(*set));
871 }
872 
873 void internal_sigemptyset(__sanitizer_sigset_t *set) {
874   internal_memset(set, 0, sizeof(*set));
875 }
876 
877 #if SANITIZER_LINUX
878 void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
879   signum -= 1;
880   CHECK_GE(signum, 0);
881   CHECK_LT(signum, sizeof(*set) * 8);
882   __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
883   const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
884   const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
885   k_set->sig[idx] &= ~(1 << bit);
886 }
887 
888 bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
889   signum -= 1;
890   CHECK_GE(signum, 0);
891   CHECK_LT(signum, sizeof(*set) * 8);
892   __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
893   const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
894   const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
895   return k_set->sig[idx] & (1 << bit);
896 }
897 #elif SANITIZER_FREEBSD
898 void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
899   sigset_t *rset = reinterpret_cast<sigset_t *>(set);
900   sigdelset(rset, signum);
901 }
902 
903 bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
904   sigset_t *rset = reinterpret_cast<sigset_t *>(set);
905   return sigismember(rset, signum);
906 }
907 #endif
908 #endif // !SANITIZER_SOLARIS
909 
910 #if !SANITIZER_NETBSD
911 // ThreadLister implementation.
912 ThreadLister::ThreadLister(pid_t pid) : pid_(pid), buffer_(4096) {
913   char task_directory_path[80];
914   internal_snprintf(task_directory_path, sizeof(task_directory_path),
915                     "/proc/%d/task/", pid);
916   descriptor_ = internal_open(task_directory_path, O_RDONLY | O_DIRECTORY);
917   if (internal_iserror(descriptor_)) {
918     Report("Can't open /proc/%d/task for reading.\n", pid);
919   }
920 }
921 
922 ThreadLister::Result ThreadLister::ListThreads(
923     InternalMmapVector<tid_t> *threads) {
924   if (internal_iserror(descriptor_))
925     return Error;
926   internal_lseek(descriptor_, 0, SEEK_SET);
927   threads->clear();
928 
929   Result result = Ok;
930   for (bool first_read = true;; first_read = false) {
931     // Resize to max capacity if it was downsized by IsAlive.
932     buffer_.resize(buffer_.capacity());
933     CHECK_GE(buffer_.size(), 4096);
934     uptr read = internal_getdents(
935         descriptor_, (struct linux_dirent *)buffer_.data(), buffer_.size());
936     if (!read)
937       return result;
938     if (internal_iserror(read)) {
939       Report("Can't read directory entries from /proc/%d/task.\n", pid_);
940       return Error;
941     }
942 
943     for (uptr begin = (uptr)buffer_.data(), end = begin + read; begin < end;) {
944       struct linux_dirent *entry = (struct linux_dirent *)begin;
945       begin += entry->d_reclen;
946       if (entry->d_ino == 1) {
947         // Inode 1 is for bad blocks and also can be a reason for early return.
948         // Should be emitted if kernel tried to output terminating thread.
949         // See proc_task_readdir implementation in Linux.
950         result = Incomplete;
951       }
952       if (entry->d_ino && *entry->d_name >= '0' && *entry->d_name <= '9')
953         threads->push_back(internal_atoll(entry->d_name));
954     }
955 
956     // Now we are going to detect short-read or early EOF. In such cases Linux
957     // can return inconsistent list with missing alive threads.
958     // Code will just remember that the list can be incomplete but it will
959     // continue reads to return as much as possible.
960     if (!first_read) {
961       // The first one was a short-read by definition.
962       result = Incomplete;
963     } else if (read > buffer_.size() - 1024) {
964       // Read was close to the buffer size. So double the size and assume the
965       // worst.
966       buffer_.resize(buffer_.size() * 2);
967       result = Incomplete;
968     } else if (!threads->empty() && !IsAlive(threads->back())) {
969       // Maybe Linux early returned from read on terminated thread (!pid_alive)
970       // and failed to restore read position.
971       // See next_tid and proc_task_instantiate in Linux.
972       result = Incomplete;
973     }
974   }
975 }
976 
977 bool ThreadLister::IsAlive(int tid) {
978   // /proc/%d/task/%d/status uses same call to detect alive threads as
979   // proc_task_readdir. See task_state implementation in Linux.
980   char path[80];
981   internal_snprintf(path, sizeof(path), "/proc/%d/task/%d/status", pid_, tid);
982   if (!ReadFileToVector(path, &buffer_) || buffer_.empty())
983     return false;
984   buffer_.push_back(0);
985   static const char kPrefix[] = "\nPPid:";
986   const char *field = internal_strstr(buffer_.data(), kPrefix);
987   if (!field)
988     return false;
989   field += internal_strlen(kPrefix);
990   return (int)internal_atoll(field) != 0;
991 }
992 
993 ThreadLister::~ThreadLister() {
994   if (!internal_iserror(descriptor_))
995     internal_close(descriptor_);
996 }
997 #endif
998 
999 #if SANITIZER_WORDSIZE == 32
1000 // Take care of unusable kernel area in top gigabyte.
1001 static uptr GetKernelAreaSize() {
1002 #if SANITIZER_LINUX && !SANITIZER_X32
1003   const uptr gbyte = 1UL << 30;
1004 
1005   // Firstly check if there are writable segments
1006   // mapped to top gigabyte (e.g. stack).
1007   MemoryMappingLayout proc_maps(/*cache_enabled*/true);
1008   if (proc_maps.Error())
1009     return 0;
1010   MemoryMappedSegment segment;
1011   while (proc_maps.Next(&segment)) {
1012     if ((segment.end >= 3 * gbyte) && segment.IsWritable()) return 0;
1013   }
1014 
1015 #if !SANITIZER_ANDROID
1016   // Even if nothing is mapped, top Gb may still be accessible
1017   // if we are running on 64-bit kernel.
1018   // Uname may report misleading results if personality type
1019   // is modified (e.g. under schroot) so check this as well.
1020   struct utsname uname_info;
1021   int pers = personality(0xffffffffUL);
1022   if (!(pers & PER_MASK) && internal_uname(&uname_info) == 0 &&
1023       internal_strstr(uname_info.machine, "64"))
1024     return 0;
1025 #endif  // SANITIZER_ANDROID
1026 
1027   // Top gigabyte is reserved for kernel.
1028   return gbyte;
1029 #else
1030   return 0;
1031 #endif  // SANITIZER_LINUX && !SANITIZER_X32
1032 }
1033 #endif  // SANITIZER_WORDSIZE == 32
1034 
1035 uptr GetMaxVirtualAddress() {
1036 #if (SANITIZER_NETBSD || SANITIZER_OPENBSD) && defined(__x86_64__)
1037   return 0x7f7ffffff000ULL;  // (0x00007f8000000000 - PAGE_SIZE)
1038 #elif SANITIZER_WORDSIZE == 64
1039 # if defined(__powerpc64__) || defined(__aarch64__)
1040   // On PowerPC64 we have two different address space layouts: 44- and 46-bit.
1041   // We somehow need to figure out which one we are using now and choose
1042   // one of 0x00000fffffffffffUL and 0x00003fffffffffffUL.
1043   // Note that with 'ulimit -s unlimited' the stack is moved away from the top
1044   // of the address space, so simply checking the stack address is not enough.
1045   // This should (does) work for both PowerPC64 Endian modes.
1046   // Similarly, aarch64 has multiple address space layouts: 39, 42 and 47-bit.
1047   return (1ULL << (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1)) - 1;
1048 # elif defined(__mips64)
1049   return (1ULL << 40) - 1;  // 0x000000ffffffffffUL;
1050 # elif defined(__s390x__)
1051   return (1ULL << 53) - 1;  // 0x001fffffffffffffUL;
1052 #elif defined(__sparc__)
1053   return ~(uptr)0;
1054 # else
1055   return (1ULL << 47) - 1;  // 0x00007fffffffffffUL;
1056 # endif
1057 #else  // SANITIZER_WORDSIZE == 32
1058 # if defined(__s390__)
1059   return (1ULL << 31) - 1;  // 0x7fffffff;
1060 # else
1061   return (1ULL << 32) - 1;  // 0xffffffff;
1062 # endif
1063 #endif  // SANITIZER_WORDSIZE
1064 }
1065 
1066 uptr GetMaxUserVirtualAddress() {
1067   uptr addr = GetMaxVirtualAddress();
1068 #if SANITIZER_WORDSIZE == 32 && !defined(__s390__)
1069   if (!common_flags()->full_address_space)
1070     addr -= GetKernelAreaSize();
1071   CHECK_LT(reinterpret_cast<uptr>(&addr), addr);
1072 #endif
1073   return addr;
1074 }
1075 
1076 #if !SANITIZER_ANDROID
1077 uptr GetPageSize() {
1078 #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__)) && \
1079     defined(EXEC_PAGESIZE)
1080   return EXEC_PAGESIZE;
1081 #elif SANITIZER_FREEBSD || SANITIZER_NETBSD
1082 // Use sysctl as sysconf can trigger interceptors internally.
1083   int pz = 0;
1084   uptr pzl = sizeof(pz);
1085   int mib[2] = {CTL_HW, HW_PAGESIZE};
1086   int rv = internal_sysctl(mib, 2, &pz, &pzl, nullptr, 0);
1087   CHECK_EQ(rv, 0);
1088   return (uptr)pz;
1089 #elif SANITIZER_USE_GETAUXVAL
1090   return getauxval(AT_PAGESZ);
1091 #else
1092   return sysconf(_SC_PAGESIZE);  // EXEC_PAGESIZE may not be trustworthy.
1093 #endif
1094 }
1095 #endif // !SANITIZER_ANDROID
1096 
1097 #if !SANITIZER_OPENBSD
1098 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
1099 #if SANITIZER_SOLARIS
1100   const char *default_module_name = getexecname();
1101   CHECK_NE(default_module_name, NULL);
1102   return internal_snprintf(buf, buf_len, "%s", default_module_name);
1103 #else
1104 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
1105 #if SANITIZER_FREEBSD
1106   const int Mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
1107 #else
1108   const int Mib[4] = {CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME};
1109 #endif
1110   const char *default_module_name = "kern.proc.pathname";
1111   uptr Size = buf_len;
1112   bool IsErr =
1113       (internal_sysctl(Mib, ARRAY_SIZE(Mib), buf, &Size, NULL, 0) != 0);
1114   int readlink_error = IsErr ? errno : 0;
1115   uptr module_name_len = Size;
1116 #else
1117   const char *default_module_name = "/proc/self/exe";
1118   uptr module_name_len = internal_readlink(
1119       default_module_name, buf, buf_len);
1120   int readlink_error;
1121   bool IsErr = internal_iserror(module_name_len, &readlink_error);
1122 #endif  // SANITIZER_SOLARIS
1123   if (IsErr) {
1124     // We can't read binary name for some reason, assume it's unknown.
1125     Report("WARNING: reading executable name failed with errno %d, "
1126            "some stack frames may not be symbolized\n", readlink_error);
1127     module_name_len = internal_snprintf(buf, buf_len, "%s",
1128                                         default_module_name);
1129     CHECK_LT(module_name_len, buf_len);
1130   }
1131   return module_name_len;
1132 #endif
1133 }
1134 #endif // !SANITIZER_OPENBSD
1135 
1136 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len) {
1137 #if SANITIZER_LINUX
1138   char *tmpbuf;
1139   uptr tmpsize;
1140   uptr tmplen;
1141   if (ReadFileToBuffer("/proc/self/cmdline", &tmpbuf, &tmpsize, &tmplen,
1142                        1024 * 1024)) {
1143     internal_strncpy(buf, tmpbuf, buf_len);
1144     UnmapOrDie(tmpbuf, tmpsize);
1145     return internal_strlen(buf);
1146   }
1147 #endif
1148   return ReadBinaryName(buf, buf_len);
1149 }
1150 
1151 // Match full names of the form /path/to/base_name{-,.}*
1152 bool LibraryNameIs(const char *full_name, const char *base_name) {
1153   const char *name = full_name;
1154   // Strip path.
1155   while (*name != '\0') name++;
1156   while (name > full_name && *name != '/') name--;
1157   if (*name == '/') name++;
1158   uptr base_name_length = internal_strlen(base_name);
1159   if (internal_strncmp(name, base_name, base_name_length)) return false;
1160   return (name[base_name_length] == '-' || name[base_name_length] == '.');
1161 }
1162 
1163 #if !SANITIZER_ANDROID
1164 // Call cb for each region mapped by map.
1165 void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr)) {
1166   CHECK_NE(map, nullptr);
1167 #if !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
1168   typedef ElfW(Phdr) Elf_Phdr;
1169   typedef ElfW(Ehdr) Elf_Ehdr;
1170 #endif // !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
1171   char *base = (char *)map->l_addr;
1172   Elf_Ehdr *ehdr = (Elf_Ehdr *)base;
1173   char *phdrs = base + ehdr->e_phoff;
1174   char *phdrs_end = phdrs + ehdr->e_phnum * ehdr->e_phentsize;
1175 
1176   // Find the segment with the minimum base so we can "relocate" the p_vaddr
1177   // fields.  Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
1178   // objects have a non-zero base.
1179   uptr preferred_base = (uptr)-1;
1180   for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
1181     Elf_Phdr *phdr = (Elf_Phdr *)iter;
1182     if (phdr->p_type == PT_LOAD && preferred_base > (uptr)phdr->p_vaddr)
1183       preferred_base = (uptr)phdr->p_vaddr;
1184   }
1185 
1186   // Compute the delta from the real base to get a relocation delta.
1187   sptr delta = (uptr)base - preferred_base;
1188   // Now we can figure out what the loader really mapped.
1189   for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
1190     Elf_Phdr *phdr = (Elf_Phdr *)iter;
1191     if (phdr->p_type == PT_LOAD) {
1192       uptr seg_start = phdr->p_vaddr + delta;
1193       uptr seg_end = seg_start + phdr->p_memsz;
1194       // None of these values are aligned.  We consider the ragged edges of the
1195       // load command as defined, since they are mapped from the file.
1196       seg_start = RoundDownTo(seg_start, GetPageSizeCached());
1197       seg_end = RoundUpTo(seg_end, GetPageSizeCached());
1198       cb((void *)seg_start, seg_end - seg_start);
1199     }
1200   }
1201 }
1202 #endif
1203 
1204 #if defined(__x86_64__) && SANITIZER_LINUX
1205 // We cannot use glibc's clone wrapper, because it messes with the child
1206 // task's TLS. It writes the PID and TID of the child task to its thread
1207 // descriptor, but in our case the child task shares the thread descriptor with
1208 // the parent (because we don't know how to allocate a new thread
1209 // descriptor to keep glibc happy). So the stock version of clone(), when
1210 // used with CLONE_VM, would end up corrupting the parent's thread descriptor.
1211 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1212                     int *parent_tidptr, void *newtls, int *child_tidptr) {
1213   long long res;
1214   if (!fn || !child_stack)
1215     return -EINVAL;
1216   CHECK_EQ(0, (uptr)child_stack % 16);
1217   child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1218   ((unsigned long long *)child_stack)[0] = (uptr)fn;
1219   ((unsigned long long *)child_stack)[1] = (uptr)arg;
1220   register void *r8 __asm__("r8") = newtls;
1221   register int *r10 __asm__("r10") = child_tidptr;
1222   __asm__ __volatile__(
1223                        /* %rax = syscall(%rax = SYSCALL(clone),
1224                         *                %rdi = flags,
1225                         *                %rsi = child_stack,
1226                         *                %rdx = parent_tidptr,
1227                         *                %r8  = new_tls,
1228                         *                %r10 = child_tidptr)
1229                         */
1230                        "syscall\n"
1231 
1232                        /* if (%rax != 0)
1233                         *   return;
1234                         */
1235                        "testq  %%rax,%%rax\n"
1236                        "jnz    1f\n"
1237 
1238                        /* In the child. Terminate unwind chain. */
1239                        // XXX: We should also terminate the CFI unwind chain
1240                        // here. Unfortunately clang 3.2 doesn't support the
1241                        // necessary CFI directives, so we skip that part.
1242                        "xorq   %%rbp,%%rbp\n"
1243 
1244                        /* Call "fn(arg)". */
1245                        "popq   %%rax\n"
1246                        "popq   %%rdi\n"
1247                        "call   *%%rax\n"
1248 
1249                        /* Call _exit(%rax). */
1250                        "movq   %%rax,%%rdi\n"
1251                        "movq   %2,%%rax\n"
1252                        "syscall\n"
1253 
1254                        /* Return to parent. */
1255                      "1:\n"
1256                        : "=a" (res)
1257                        : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
1258                          "S"(child_stack),
1259                          "D"(flags),
1260                          "d"(parent_tidptr),
1261                          "r"(r8),
1262                          "r"(r10)
1263                        : "memory", "r11", "rcx");
1264   return res;
1265 }
1266 #elif defined(__mips__)
1267 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1268                     int *parent_tidptr, void *newtls, int *child_tidptr) {
1269   long long res;
1270   if (!fn || !child_stack)
1271     return -EINVAL;
1272   CHECK_EQ(0, (uptr)child_stack % 16);
1273   child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1274   ((unsigned long long *)child_stack)[0] = (uptr)fn;
1275   ((unsigned long long *)child_stack)[1] = (uptr)arg;
1276   register void *a3 __asm__("$7") = newtls;
1277   register int *a4 __asm__("$8") = child_tidptr;
1278   // We don't have proper CFI directives here because it requires alot of code
1279   // for very marginal benefits.
1280   __asm__ __volatile__(
1281                        /* $v0 = syscall($v0 = __NR_clone,
1282                         * $a0 = flags,
1283                         * $a1 = child_stack,
1284                         * $a2 = parent_tidptr,
1285                         * $a3 = new_tls,
1286                         * $a4 = child_tidptr)
1287                         */
1288                        ".cprestore 16;\n"
1289                        "move $4,%1;\n"
1290                        "move $5,%2;\n"
1291                        "move $6,%3;\n"
1292                        "move $7,%4;\n"
1293                        /* Store the fifth argument on stack
1294                         * if we are using 32-bit abi.
1295                         */
1296 #if SANITIZER_WORDSIZE == 32
1297                        "lw %5,16($29);\n"
1298 #else
1299                        "move $8,%5;\n"
1300 #endif
1301                        "li $2,%6;\n"
1302                        "syscall;\n"
1303 
1304                        /* if ($v0 != 0)
1305                         * return;
1306                         */
1307                        "bnez $2,1f;\n"
1308 
1309                        /* Call "fn(arg)". */
1310 #if SANITIZER_WORDSIZE == 32
1311 #ifdef __BIG_ENDIAN__
1312                        "lw $25,4($29);\n"
1313                        "lw $4,12($29);\n"
1314 #else
1315                        "lw $25,0($29);\n"
1316                        "lw $4,8($29);\n"
1317 #endif
1318 #else
1319                        "ld $25,0($29);\n"
1320                        "ld $4,8($29);\n"
1321 #endif
1322                        "jal $25;\n"
1323 
1324                        /* Call _exit($v0). */
1325                        "move $4,$2;\n"
1326                        "li $2,%7;\n"
1327                        "syscall;\n"
1328 
1329                        /* Return to parent. */
1330                      "1:\n"
1331                        : "=r" (res)
1332                        : "r"(flags),
1333                          "r"(child_stack),
1334                          "r"(parent_tidptr),
1335                          "r"(a3),
1336                          "r"(a4),
1337                          "i"(__NR_clone),
1338                          "i"(__NR_exit)
1339                        : "memory", "$29" );
1340   return res;
1341 }
1342 #elif defined(__aarch64__)
1343 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1344                     int *parent_tidptr, void *newtls, int *child_tidptr) {
1345   long long res;
1346   if (!fn || !child_stack)
1347     return -EINVAL;
1348   CHECK_EQ(0, (uptr)child_stack % 16);
1349   child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1350   ((unsigned long long *)child_stack)[0] = (uptr)fn;
1351   ((unsigned long long *)child_stack)[1] = (uptr)arg;
1352 
1353   register int (*__fn)(void *)  __asm__("x0") = fn;
1354   register void *__stack __asm__("x1") = child_stack;
1355   register int   __flags __asm__("x2") = flags;
1356   register void *__arg   __asm__("x3") = arg;
1357   register int  *__ptid  __asm__("x4") = parent_tidptr;
1358   register void *__tls   __asm__("x5") = newtls;
1359   register int  *__ctid  __asm__("x6") = child_tidptr;
1360 
1361   __asm__ __volatile__(
1362                        "mov x0,x2\n" /* flags  */
1363                        "mov x2,x4\n" /* ptid  */
1364                        "mov x3,x5\n" /* tls  */
1365                        "mov x4,x6\n" /* ctid  */
1366                        "mov x8,%9\n" /* clone  */
1367 
1368                        "svc 0x0\n"
1369 
1370                        /* if (%r0 != 0)
1371                         *   return %r0;
1372                         */
1373                        "cmp x0, #0\n"
1374                        "bne 1f\n"
1375 
1376                        /* In the child, now. Call "fn(arg)". */
1377                        "ldp x1, x0, [sp], #16\n"
1378                        "blr x1\n"
1379 
1380                        /* Call _exit(%r0).  */
1381                        "mov x8, %10\n"
1382                        "svc 0x0\n"
1383                      "1:\n"
1384 
1385                        : "=r" (res)
1386                        : "i"(-EINVAL),
1387                          "r"(__fn), "r"(__stack), "r"(__flags), "r"(__arg),
1388                          "r"(__ptid), "r"(__tls), "r"(__ctid),
1389                          "i"(__NR_clone), "i"(__NR_exit)
1390                        : "x30", "memory");
1391   return res;
1392 }
1393 #elif defined(__powerpc64__)
1394 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1395                    int *parent_tidptr, void *newtls, int *child_tidptr) {
1396   long long res;
1397 // Stack frame structure.
1398 #if SANITIZER_PPC64V1
1399 //   Back chain == 0        (SP + 112)
1400 // Frame (112 bytes):
1401 //   Parameter save area    (SP + 48), 8 doublewords
1402 //   TOC save area          (SP + 40)
1403 //   Link editor doubleword (SP + 32)
1404 //   Compiler doubleword    (SP + 24)
1405 //   LR save area           (SP + 16)
1406 //   CR save area           (SP + 8)
1407 //   Back chain             (SP + 0)
1408 # define FRAME_SIZE 112
1409 # define FRAME_TOC_SAVE_OFFSET 40
1410 #elif SANITIZER_PPC64V2
1411 //   Back chain == 0        (SP + 32)
1412 // Frame (32 bytes):
1413 //   TOC save area          (SP + 24)
1414 //   LR save area           (SP + 16)
1415 //   CR save area           (SP + 8)
1416 //   Back chain             (SP + 0)
1417 # define FRAME_SIZE 32
1418 # define FRAME_TOC_SAVE_OFFSET 24
1419 #else
1420 # error "Unsupported PPC64 ABI"
1421 #endif
1422   if (!fn || !child_stack)
1423     return -EINVAL;
1424   CHECK_EQ(0, (uptr)child_stack % 16);
1425 
1426   register int (*__fn)(void *) __asm__("r3") = fn;
1427   register void *__cstack      __asm__("r4") = child_stack;
1428   register int __flags         __asm__("r5") = flags;
1429   register void *__arg         __asm__("r6") = arg;
1430   register int *__ptidptr      __asm__("r7") = parent_tidptr;
1431   register void *__newtls      __asm__("r8") = newtls;
1432   register int *__ctidptr      __asm__("r9") = child_tidptr;
1433 
1434  __asm__ __volatile__(
1435            /* fn and arg are saved across the syscall */
1436            "mr 28, %5\n\t"
1437            "mr 27, %8\n\t"
1438 
1439            /* syscall
1440              r0 == __NR_clone
1441              r3 == flags
1442              r4 == child_stack
1443              r5 == parent_tidptr
1444              r6 == newtls
1445              r7 == child_tidptr */
1446            "mr 3, %7\n\t"
1447            "mr 5, %9\n\t"
1448            "mr 6, %10\n\t"
1449            "mr 7, %11\n\t"
1450            "li 0, %3\n\t"
1451            "sc\n\t"
1452 
1453            /* Test if syscall was successful */
1454            "cmpdi  cr1, 3, 0\n\t"
1455            "crandc cr1*4+eq, cr1*4+eq, cr0*4+so\n\t"
1456            "bne-   cr1, 1f\n\t"
1457 
1458            /* Set up stack frame */
1459            "li    29, 0\n\t"
1460            "stdu  29, -8(1)\n\t"
1461            "stdu  1, -%12(1)\n\t"
1462            /* Do the function call */
1463            "std   2, %13(1)\n\t"
1464 #if SANITIZER_PPC64V1
1465            "ld    0, 0(28)\n\t"
1466            "ld    2, 8(28)\n\t"
1467            "mtctr 0\n\t"
1468 #elif SANITIZER_PPC64V2
1469            "mr    12, 28\n\t"
1470            "mtctr 12\n\t"
1471 #else
1472 # error "Unsupported PPC64 ABI"
1473 #endif
1474            "mr    3, 27\n\t"
1475            "bctrl\n\t"
1476            "ld    2, %13(1)\n\t"
1477 
1478            /* Call _exit(r3) */
1479            "li 0, %4\n\t"
1480            "sc\n\t"
1481 
1482            /* Return to parent */
1483            "1:\n\t"
1484            "mr %0, 3\n\t"
1485              : "=r" (res)
1486              : "0" (-1),
1487                "i" (EINVAL),
1488                "i" (__NR_clone),
1489                "i" (__NR_exit),
1490                "r" (__fn),
1491                "r" (__cstack),
1492                "r" (__flags),
1493                "r" (__arg),
1494                "r" (__ptidptr),
1495                "r" (__newtls),
1496                "r" (__ctidptr),
1497                "i" (FRAME_SIZE),
1498                "i" (FRAME_TOC_SAVE_OFFSET)
1499              : "cr0", "cr1", "memory", "ctr", "r0", "r27", "r28", "r29");
1500   return res;
1501 }
1502 #elif defined(__i386__) && SANITIZER_LINUX
1503 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1504                     int *parent_tidptr, void *newtls, int *child_tidptr) {
1505   int res;
1506   if (!fn || !child_stack)
1507     return -EINVAL;
1508   CHECK_EQ(0, (uptr)child_stack % 16);
1509   child_stack = (char *)child_stack - 7 * sizeof(unsigned int);
1510   ((unsigned int *)child_stack)[0] = (uptr)flags;
1511   ((unsigned int *)child_stack)[1] = (uptr)0;
1512   ((unsigned int *)child_stack)[2] = (uptr)fn;
1513   ((unsigned int *)child_stack)[3] = (uptr)arg;
1514   __asm__ __volatile__(
1515                        /* %eax = syscall(%eax = SYSCALL(clone),
1516                         *                %ebx = flags,
1517                         *                %ecx = child_stack,
1518                         *                %edx = parent_tidptr,
1519                         *                %esi  = new_tls,
1520                         *                %edi = child_tidptr)
1521                         */
1522 
1523                         /* Obtain flags */
1524                         "movl    (%%ecx), %%ebx\n"
1525                         /* Do the system call */
1526                         "pushl   %%ebx\n"
1527                         "pushl   %%esi\n"
1528                         "pushl   %%edi\n"
1529                         /* Remember the flag value.  */
1530                         "movl    %%ebx, (%%ecx)\n"
1531                         "int     $0x80\n"
1532                         "popl    %%edi\n"
1533                         "popl    %%esi\n"
1534                         "popl    %%ebx\n"
1535 
1536                         /* if (%eax != 0)
1537                          *   return;
1538                          */
1539 
1540                         "test    %%eax,%%eax\n"
1541                         "jnz    1f\n"
1542 
1543                         /* terminate the stack frame */
1544                         "xorl   %%ebp,%%ebp\n"
1545                         /* Call FN. */
1546                         "call    *%%ebx\n"
1547 #ifdef PIC
1548                         "call    here\n"
1549                         "here:\n"
1550                         "popl    %%ebx\n"
1551                         "addl    $_GLOBAL_OFFSET_TABLE_+[.-here], %%ebx\n"
1552 #endif
1553                         /* Call exit */
1554                         "movl    %%eax, %%ebx\n"
1555                         "movl    %2, %%eax\n"
1556                         "int     $0x80\n"
1557                         "1:\n"
1558                        : "=a" (res)
1559                        : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
1560                          "c"(child_stack),
1561                          "d"(parent_tidptr),
1562                          "S"(newtls),
1563                          "D"(child_tidptr)
1564                        : "memory");
1565   return res;
1566 }
1567 #elif defined(__arm__) && SANITIZER_LINUX
1568 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1569                     int *parent_tidptr, void *newtls, int *child_tidptr) {
1570   unsigned int res;
1571   if (!fn || !child_stack)
1572     return -EINVAL;
1573   child_stack = (char *)child_stack - 2 * sizeof(unsigned int);
1574   ((unsigned int *)child_stack)[0] = (uptr)fn;
1575   ((unsigned int *)child_stack)[1] = (uptr)arg;
1576   register int r0 __asm__("r0") = flags;
1577   register void *r1 __asm__("r1") = child_stack;
1578   register int *r2 __asm__("r2") = parent_tidptr;
1579   register void *r3 __asm__("r3") = newtls;
1580   register int *r4 __asm__("r4") = child_tidptr;
1581   register int r7 __asm__("r7") = __NR_clone;
1582 
1583 #if __ARM_ARCH > 4 || defined (__ARM_ARCH_4T__)
1584 # define ARCH_HAS_BX
1585 #endif
1586 #if __ARM_ARCH > 4
1587 # define ARCH_HAS_BLX
1588 #endif
1589 
1590 #ifdef ARCH_HAS_BX
1591 # ifdef ARCH_HAS_BLX
1592 #  define BLX(R) "blx "  #R "\n"
1593 # else
1594 #  define BLX(R) "mov lr, pc; bx " #R "\n"
1595 # endif
1596 #else
1597 # define BLX(R)  "mov lr, pc; mov pc," #R "\n"
1598 #endif
1599 
1600   __asm__ __volatile__(
1601                        /* %r0 = syscall(%r7 = SYSCALL(clone),
1602                         *               %r0 = flags,
1603                         *               %r1 = child_stack,
1604                         *               %r2 = parent_tidptr,
1605                         *               %r3  = new_tls,
1606                         *               %r4 = child_tidptr)
1607                         */
1608 
1609                        /* Do the system call */
1610                        "swi 0x0\n"
1611 
1612                        /* if (%r0 != 0)
1613                         *   return %r0;
1614                         */
1615                        "cmp r0, #0\n"
1616                        "bne 1f\n"
1617 
1618                        /* In the child, now. Call "fn(arg)". */
1619                        "ldr r0, [sp, #4]\n"
1620                        "ldr ip, [sp], #8\n"
1621                        BLX(ip)
1622                        /* Call _exit(%r0). */
1623                        "mov r7, %7\n"
1624                        "swi 0x0\n"
1625                        "1:\n"
1626                        "mov %0, r0\n"
1627                        : "=r"(res)
1628                        : "r"(r0), "r"(r1), "r"(r2), "r"(r3), "r"(r4), "r"(r7),
1629                          "i"(__NR_exit)
1630                        : "memory");
1631   return res;
1632 }
1633 #endif  // defined(__x86_64__) && SANITIZER_LINUX
1634 
1635 #if SANITIZER_LINUX
1636 int internal_uname(struct utsname *buf) {
1637   return internal_syscall(SYSCALL(uname), buf);
1638 }
1639 #endif
1640 
1641 #if SANITIZER_ANDROID
1642 #if __ANDROID_API__ < 21
1643 extern "C" __attribute__((weak)) int dl_iterate_phdr(
1644     int (*)(struct dl_phdr_info *, size_t, void *), void *);
1645 #endif
1646 
1647 static int dl_iterate_phdr_test_cb(struct dl_phdr_info *info, size_t size,
1648                                    void *data) {
1649   // Any name starting with "lib" indicates a bug in L where library base names
1650   // are returned instead of paths.
1651   if (info->dlpi_name && info->dlpi_name[0] == 'l' &&
1652       info->dlpi_name[1] == 'i' && info->dlpi_name[2] == 'b') {
1653     *(bool *)data = true;
1654     return 1;
1655   }
1656   return 0;
1657 }
1658 
1659 static atomic_uint32_t android_api_level;
1660 
1661 static AndroidApiLevel AndroidDetectApiLevelStatic() {
1662 #if __ANDROID_API__ <= 19
1663   return ANDROID_KITKAT;
1664 #elif __ANDROID_API__ <= 22
1665   return ANDROID_LOLLIPOP_MR1;
1666 #else
1667   return ANDROID_POST_LOLLIPOP;
1668 #endif
1669 }
1670 
1671 static AndroidApiLevel AndroidDetectApiLevel() {
1672   if (!&dl_iterate_phdr)
1673     return ANDROID_KITKAT; // K or lower
1674   bool base_name_seen = false;
1675   dl_iterate_phdr(dl_iterate_phdr_test_cb, &base_name_seen);
1676   if (base_name_seen)
1677     return ANDROID_LOLLIPOP_MR1; // L MR1
1678   return ANDROID_POST_LOLLIPOP;   // post-L
1679   // Plain L (API level 21) is completely broken wrt ASan and not very
1680   // interesting to detect.
1681 }
1682 
1683 extern "C" __attribute__((weak)) void* _DYNAMIC;
1684 
1685 AndroidApiLevel AndroidGetApiLevel() {
1686   AndroidApiLevel level =
1687       (AndroidApiLevel)atomic_load(&android_api_level, memory_order_relaxed);
1688   if (level) return level;
1689   level = &_DYNAMIC == nullptr ? AndroidDetectApiLevelStatic()
1690                                : AndroidDetectApiLevel();
1691   atomic_store(&android_api_level, level, memory_order_relaxed);
1692   return level;
1693 }
1694 
1695 #endif
1696 
1697 static HandleSignalMode GetHandleSignalModeImpl(int signum) {
1698   switch (signum) {
1699     case SIGABRT:
1700       return common_flags()->handle_abort;
1701     case SIGILL:
1702       return common_flags()->handle_sigill;
1703     case SIGTRAP:
1704       return common_flags()->handle_sigtrap;
1705     case SIGFPE:
1706       return common_flags()->handle_sigfpe;
1707     case SIGSEGV:
1708       return common_flags()->handle_segv;
1709     case SIGBUS:
1710       return common_flags()->handle_sigbus;
1711   }
1712   return kHandleSignalNo;
1713 }
1714 
1715 HandleSignalMode GetHandleSignalMode(int signum) {
1716   HandleSignalMode result = GetHandleSignalModeImpl(signum);
1717   if (result == kHandleSignalYes && !common_flags()->allow_user_segv_handler)
1718     return kHandleSignalExclusive;
1719   return result;
1720 }
1721 
1722 #if !SANITIZER_GO
1723 void *internal_start_thread(void *(*func)(void *arg), void *arg) {
1724   // Start the thread with signals blocked, otherwise it can steal user signals.
1725   __sanitizer_sigset_t set, old;
1726   internal_sigfillset(&set);
1727 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1728   // Glibc uses SIGSETXID signal during setuid call. If this signal is blocked
1729   // on any thread, setuid call hangs (see test/tsan/setuid.c).
1730   internal_sigdelset(&set, 33);
1731 #endif
1732   internal_sigprocmask(SIG_SETMASK, &set, &old);
1733   void *th;
1734   real_pthread_create(&th, nullptr, func, arg);
1735   internal_sigprocmask(SIG_SETMASK, &old, nullptr);
1736   return th;
1737 }
1738 
1739 void internal_join_thread(void *th) {
1740   real_pthread_join(th, nullptr);
1741 }
1742 #else
1743 void *internal_start_thread(void *(*func)(void *), void *arg) { return 0; }
1744 
1745 void internal_join_thread(void *th) {}
1746 #endif
1747 
1748 #if defined(__aarch64__)
1749 // Android headers in the older NDK releases miss this definition.
1750 struct __sanitizer_esr_context {
1751   struct _aarch64_ctx head;
1752   uint64_t esr;
1753 };
1754 
1755 static bool Aarch64GetESR(ucontext_t *ucontext, u64 *esr) {
1756   static const u32 kEsrMagic = 0x45535201;
1757   u8 *aux = ucontext->uc_mcontext.__reserved;
1758   while (true) {
1759     _aarch64_ctx *ctx = (_aarch64_ctx *)aux;
1760     if (ctx->size == 0) break;
1761     if (ctx->magic == kEsrMagic) {
1762       *esr = ((__sanitizer_esr_context *)ctx)->esr;
1763       return true;
1764     }
1765     aux += ctx->size;
1766   }
1767   return false;
1768 }
1769 #endif
1770 
1771 #if SANITIZER_OPENBSD
1772 using Context = sigcontext;
1773 #else
1774 using Context = ucontext_t;
1775 #endif
1776 
1777 SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
1778   Context *ucontext = (Context *)context;
1779 #if defined(__x86_64__) || defined(__i386__)
1780   static const uptr PF_WRITE = 1U << 1;
1781 #if SANITIZER_FREEBSD
1782   uptr err = ucontext->uc_mcontext.mc_err;
1783 #elif SANITIZER_NETBSD
1784   uptr err = ucontext->uc_mcontext.__gregs[_REG_ERR];
1785 #elif SANITIZER_OPENBSD
1786   uptr err = ucontext->sc_err;
1787 #elif SANITIZER_SOLARIS && defined(__i386__)
1788   const int Err = 13;
1789   uptr err = ucontext->uc_mcontext.gregs[Err];
1790 #else
1791   uptr err = ucontext->uc_mcontext.gregs[REG_ERR];
1792 #endif // SANITIZER_FREEBSD
1793   return err & PF_WRITE ? WRITE : READ;
1794 #elif defined(__mips__)
1795   uint32_t *exception_source;
1796   uint32_t faulty_instruction;
1797   uint32_t op_code;
1798 
1799   exception_source = (uint32_t *)ucontext->uc_mcontext.pc;
1800   faulty_instruction = (uint32_t)(*exception_source);
1801 
1802   op_code = (faulty_instruction >> 26) & 0x3f;
1803 
1804   // FIXME: Add support for FPU, microMIPS, DSP, MSA memory instructions.
1805   switch (op_code) {
1806     case 0x28:  // sb
1807     case 0x29:  // sh
1808     case 0x2b:  // sw
1809     case 0x3f:  // sd
1810 #if __mips_isa_rev < 6
1811     case 0x2c:  // sdl
1812     case 0x2d:  // sdr
1813     case 0x2a:  // swl
1814     case 0x2e:  // swr
1815 #endif
1816       return SignalContext::WRITE;
1817 
1818     case 0x20:  // lb
1819     case 0x24:  // lbu
1820     case 0x21:  // lh
1821     case 0x25:  // lhu
1822     case 0x23:  // lw
1823     case 0x27:  // lwu
1824     case 0x37:  // ld
1825 #if __mips_isa_rev < 6
1826     case 0x1a:  // ldl
1827     case 0x1b:  // ldr
1828     case 0x22:  // lwl
1829     case 0x26:  // lwr
1830 #endif
1831       return SignalContext::READ;
1832 #if __mips_isa_rev == 6
1833     case 0x3b:  // pcrel
1834       op_code = (faulty_instruction >> 19) & 0x3;
1835       switch (op_code) {
1836         case 0x1:  // lwpc
1837         case 0x2:  // lwupc
1838           return SignalContext::READ;
1839       }
1840 #endif
1841   }
1842   return SignalContext::UNKNOWN;
1843 #elif defined(__arm__)
1844   static const uptr FSR_WRITE = 1U << 11;
1845   uptr fsr = ucontext->uc_mcontext.error_code;
1846   return fsr & FSR_WRITE ? WRITE : READ;
1847 #elif defined(__aarch64__)
1848   static const u64 ESR_ELx_WNR = 1U << 6;
1849   u64 esr;
1850   if (!Aarch64GetESR(ucontext, &esr)) return UNKNOWN;
1851   return esr & ESR_ELx_WNR ? WRITE : READ;
1852 #elif defined(__sparc__)
1853   // Decode the instruction to determine the access type.
1854   // From OpenSolaris $SRC/uts/sun4/os/trap.c (get_accesstype).
1855 #if SANITIZER_SOLARIS
1856   uptr pc = ucontext->uc_mcontext.gregs[REG_PC];
1857 #else
1858   // Historical BSDism here.
1859   struct sigcontext *scontext = (struct sigcontext *)context;
1860 #if defined(__arch64__)
1861   uptr pc = scontext->sigc_regs.tpc;
1862 #else
1863   uptr pc = scontext->si_regs.pc;
1864 #endif
1865 #endif
1866   u32 instr = *(u32 *)pc;
1867   return (instr >> 21) & 1 ? WRITE: READ;
1868 #elif defined(__riscv)
1869   unsigned long pc = ucontext->uc_mcontext.__gregs[REG_PC];
1870   unsigned faulty_instruction = *(uint16_t *)pc;
1871 
1872 #if defined(__riscv_compressed)
1873   if ((faulty_instruction & 0x3) != 0x3) {  // it's a compressed instruction
1874     // set op_bits to the instruction bits [1, 0, 15, 14, 13]
1875     unsigned op_bits =
1876         ((faulty_instruction & 0x3) << 3) | (faulty_instruction >> 13);
1877     unsigned rd = faulty_instruction & 0xF80;  // bits 7-11, inclusive
1878     switch (op_bits) {
1879       case 0b10'010:  // c.lwsp (rd != x0)
1880 #if __riscv_xlen == 64
1881       case 0b10'011:  // c.ldsp (rd != x0)
1882 #endif
1883         return rd ? SignalContext::READ : SignalContext::UNKNOWN;
1884       case 0b00'010:  // c.lw
1885 #if __riscv_flen >= 32 && __riscv_xlen == 32
1886       case 0b10'011:  // c.flwsp
1887 #endif
1888 #if __riscv_flen >= 32 || __riscv_xlen == 64
1889       case 0b00'011:  // c.flw / c.ld
1890 #endif
1891 #if __riscv_flen == 64
1892       case 0b00'001:  // c.fld
1893       case 0b10'001:  // c.fldsp
1894 #endif
1895         return SignalContext::READ;
1896       case 0b00'110:  // c.sw
1897       case 0b10'110:  // c.swsp
1898 #if __riscv_flen >= 32 || __riscv_xlen == 64
1899       case 0b00'111:  // c.fsw / c.sd
1900       case 0b10'111:  // c.fswsp / c.sdsp
1901 #endif
1902 #if __riscv_flen == 64
1903       case 0b00'101:  // c.fsd
1904       case 0b10'101:  // c.fsdsp
1905 #endif
1906         return SignalContext::WRITE;
1907       default:
1908         return SignalContext::UNKNOWN;
1909     }
1910   }
1911 #endif
1912 
1913   unsigned opcode = faulty_instruction & 0x7f;         // lower 7 bits
1914   unsigned funct3 = (faulty_instruction >> 12) & 0x7;  // bits 12-14, inclusive
1915   switch (opcode) {
1916     case 0b0000011:  // loads
1917       switch (funct3) {
1918         case 0b000:  // lb
1919         case 0b001:  // lh
1920         case 0b010:  // lw
1921 #if __riscv_xlen == 64
1922         case 0b011:  // ld
1923 #endif
1924         case 0b100:  // lbu
1925         case 0b101:  // lhu
1926           return SignalContext::READ;
1927         default:
1928           return SignalContext::UNKNOWN;
1929       }
1930     case 0b0100011:  // stores
1931       switch (funct3) {
1932         case 0b000:  // sb
1933         case 0b001:  // sh
1934         case 0b010:  // sw
1935 #if __riscv_xlen == 64
1936         case 0b011:  // sd
1937 #endif
1938           return SignalContext::WRITE;
1939         default:
1940           return SignalContext::UNKNOWN;
1941       }
1942 #if __riscv_flen >= 32
1943     case 0b0000111:  // floating-point loads
1944       switch (funct3) {
1945         case 0b010:  // flw
1946 #if __riscv_flen == 64
1947         case 0b011:  // fld
1948 #endif
1949           return SignalContext::READ;
1950         default:
1951           return SignalContext::UNKNOWN;
1952       }
1953     case 0b0100111:  // floating-point stores
1954       switch (funct3) {
1955         case 0b010:  // fsw
1956 #if __riscv_flen == 64
1957         case 0b011:  // fsd
1958 #endif
1959           return SignalContext::WRITE;
1960         default:
1961           return SignalContext::UNKNOWN;
1962       }
1963 #endif
1964     default:
1965       return SignalContext::UNKNOWN;
1966   }
1967 #else
1968   (void)ucontext;
1969   return UNKNOWN;  // FIXME: Implement.
1970 #endif
1971 }
1972 
1973 bool SignalContext::IsTrueFaultingAddress() const {
1974   auto si = static_cast<const siginfo_t *>(siginfo);
1975   // SIGSEGV signals without a true fault address have si_code set to 128.
1976   return si->si_signo == SIGSEGV && si->si_code != 128;
1977 }
1978 
1979 void SignalContext::DumpAllRegisters(void *context) {
1980   // FIXME: Implement this.
1981 }
1982 
1983 static void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
1984 #if SANITIZER_NETBSD
1985   // This covers all NetBSD architectures
1986   ucontext_t *ucontext = (ucontext_t *)context;
1987   *pc = _UC_MACHINE_PC(ucontext);
1988   *bp = _UC_MACHINE_FP(ucontext);
1989   *sp = _UC_MACHINE_SP(ucontext);
1990 #elif defined(__arm__)
1991   ucontext_t *ucontext = (ucontext_t*)context;
1992   *pc = ucontext->uc_mcontext.arm_pc;
1993   *bp = ucontext->uc_mcontext.arm_fp;
1994   *sp = ucontext->uc_mcontext.arm_sp;
1995 #elif defined(__aarch64__)
1996   ucontext_t *ucontext = (ucontext_t*)context;
1997   *pc = ucontext->uc_mcontext.pc;
1998   *bp = ucontext->uc_mcontext.regs[29];
1999   *sp = ucontext->uc_mcontext.sp;
2000 #elif defined(__hppa__)
2001   ucontext_t *ucontext = (ucontext_t*)context;
2002   *pc = ucontext->uc_mcontext.sc_iaoq[0];
2003   /* GCC uses %r3 whenever a frame pointer is needed.  */
2004   *bp = ucontext->uc_mcontext.sc_gr[3];
2005   *sp = ucontext->uc_mcontext.sc_gr[30];
2006 #elif defined(__x86_64__)
2007 # if SANITIZER_FREEBSD
2008   ucontext_t *ucontext = (ucontext_t*)context;
2009   *pc = ucontext->uc_mcontext.mc_rip;
2010   *bp = ucontext->uc_mcontext.mc_rbp;
2011   *sp = ucontext->uc_mcontext.mc_rsp;
2012 #elif SANITIZER_OPENBSD
2013   sigcontext *ucontext = (sigcontext *)context;
2014   *pc = ucontext->sc_rip;
2015   *bp = ucontext->sc_rbp;
2016   *sp = ucontext->sc_rsp;
2017 # else
2018   ucontext_t *ucontext = (ucontext_t*)context;
2019   *pc = ucontext->uc_mcontext.gregs[REG_RIP];
2020   *bp = ucontext->uc_mcontext.gregs[REG_RBP];
2021   *sp = ucontext->uc_mcontext.gregs[REG_RSP];
2022 # endif
2023 #elif defined(__i386__)
2024 # if SANITIZER_FREEBSD
2025   ucontext_t *ucontext = (ucontext_t*)context;
2026   *pc = ucontext->uc_mcontext.mc_eip;
2027   *bp = ucontext->uc_mcontext.mc_ebp;
2028   *sp = ucontext->uc_mcontext.mc_esp;
2029 #elif SANITIZER_OPENBSD
2030   sigcontext *ucontext = (sigcontext *)context;
2031   *pc = ucontext->sc_eip;
2032   *bp = ucontext->sc_ebp;
2033   *sp = ucontext->sc_esp;
2034 # else
2035   ucontext_t *ucontext = (ucontext_t*)context;
2036 # if SANITIZER_SOLARIS
2037   /* Use the numeric values: the symbolic ones are undefined by llvm
2038      include/llvm/Support/Solaris.h.  */
2039 # ifndef REG_EIP
2040 #  define REG_EIP 14 // REG_PC
2041 # endif
2042 # ifndef REG_EBP
2043 #  define REG_EBP  6 // REG_FP
2044 # endif
2045 # ifndef REG_UESP
2046 #  define REG_UESP 17 // REG_SP
2047 # endif
2048 # endif
2049   *pc = ucontext->uc_mcontext.gregs[REG_EIP];
2050   *bp = ucontext->uc_mcontext.gregs[REG_EBP];
2051   *sp = ucontext->uc_mcontext.gregs[REG_UESP];
2052 # endif
2053 #elif defined(__powerpc__) || defined(__powerpc64__)
2054   ucontext_t *ucontext = (ucontext_t*)context;
2055   *pc = ucontext->uc_mcontext.regs->nip;
2056   *sp = ucontext->uc_mcontext.regs->gpr[PT_R1];
2057   // The powerpc{,64}-linux ABIs do not specify r31 as the frame
2058   // pointer, but GCC always uses r31 when we need a frame pointer.
2059   *bp = ucontext->uc_mcontext.regs->gpr[PT_R31];
2060 #elif defined(__sparc__)
2061 #if defined(__arch64__) || defined(__sparcv9)
2062 #define STACK_BIAS 2047
2063 #else
2064 #define STACK_BIAS 0
2065 # endif
2066 # if SANITIZER_SOLARIS
2067   ucontext_t *ucontext = (ucontext_t *)context;
2068   *pc = ucontext->uc_mcontext.gregs[REG_PC];
2069   *sp = ucontext->uc_mcontext.gregs[REG_O6] + STACK_BIAS;
2070 #else
2071   // Historical BSDism here.
2072   struct sigcontext *scontext = (struct sigcontext *)context;
2073 #if defined(__arch64__)
2074   *pc = scontext->sigc_regs.tpc;
2075   *sp = scontext->sigc_regs.u_regs[14] + STACK_BIAS;
2076 #else
2077   *pc = scontext->si_regs.pc;
2078   *sp = scontext->si_regs.u_regs[14];
2079 #endif
2080 # endif
2081   *bp = (uptr)((uhwptr *)*sp)[14] + STACK_BIAS;
2082 #elif defined(__mips__)
2083   ucontext_t *ucontext = (ucontext_t*)context;
2084   *pc = ucontext->uc_mcontext.pc;
2085   *bp = ucontext->uc_mcontext.gregs[30];
2086   *sp = ucontext->uc_mcontext.gregs[29];
2087 #elif defined(__s390__)
2088   ucontext_t *ucontext = (ucontext_t*)context;
2089 # if defined(__s390x__)
2090   *pc = ucontext->uc_mcontext.psw.addr;
2091 # else
2092   *pc = ucontext->uc_mcontext.psw.addr & 0x7fffffff;
2093 # endif
2094   *bp = ucontext->uc_mcontext.gregs[11];
2095   *sp = ucontext->uc_mcontext.gregs[15];
2096 #elif defined(__riscv)
2097   ucontext_t *ucontext = (ucontext_t*)context;
2098   *pc = ucontext->uc_mcontext.__gregs[REG_PC];
2099   *bp = ucontext->uc_mcontext.__gregs[REG_S0];
2100   *sp = ucontext->uc_mcontext.__gregs[REG_SP];
2101 #else
2102 # error "Unsupported arch"
2103 #endif
2104 }
2105 
2106 void SignalContext::InitPcSpBp() { GetPcSpBp(context, &pc, &sp, &bp); }
2107 
2108 void InitializePlatformEarly() {
2109   // Do nothing.
2110 }
2111 
2112 void MaybeReexec() {
2113   // No need to re-exec on Linux.
2114 }
2115 
2116 void CheckASLR() {
2117 #if SANITIZER_NETBSD
2118   int mib[3];
2119   int paxflags;
2120   uptr len = sizeof(paxflags);
2121 
2122   mib[0] = CTL_PROC;
2123   mib[1] = internal_getpid();
2124   mib[2] = PROC_PID_PAXFLAGS;
2125 
2126   if (UNLIKELY(internal_sysctl(mib, 3, &paxflags, &len, NULL, 0) == -1)) {
2127     Printf("sysctl failed\n");
2128     Die();
2129   }
2130 
2131   if (UNLIKELY(paxflags & CTL_PROC_PAXFLAGS_ASLR)) {
2132     Printf("This sanitizer is not compatible with enabled ASLR.\n"
2133            "To disable ASLR, please run \"paxctl +a %s\" and try again.\n",
2134            GetArgv()[0]);
2135     Die();
2136   }
2137 #elif SANITIZER_PPC64V2
2138   // Disable ASLR for Linux PPC64LE.
2139   int old_personality = personality(0xffffffff);
2140   if (old_personality != -1 && (old_personality & ADDR_NO_RANDOMIZE) == 0) {
2141     VReport(1, "WARNING: Program is being run with address space layout "
2142                "randomization (ASLR) enabled which prevents the thread and "
2143                "memory sanitizers from working on powerpc64le.\n"
2144                "ASLR will be disabled and the program re-executed.\n");
2145     CHECK_NE(personality(old_personality | ADDR_NO_RANDOMIZE), -1);
2146     ReExec();
2147   }
2148 #elif SANITIZER_FREEBSD
2149   int aslr_pie;
2150   uptr len = sizeof(aslr_pie);
2151 #if SANITIZER_WORDSIZE == 64
2152   if (UNLIKELY(internal_sysctlbyname("kern.elf64.aslr.pie_enable",
2153       &aslr_pie, &len, NULL, 0) == -1)) {
2154     // We're making things less 'dramatic' here since
2155     // the OID is not necessarily guaranteed to be here
2156     // just yet regarding FreeBSD release
2157     return;
2158   }
2159 
2160   if (aslr_pie > 0) {
2161     Printf("This sanitizer is not compatible with enabled ASLR "
2162            "and binaries compiled with PIE\n");
2163     Die();
2164   }
2165 #endif
2166   // there might be 32 bits compat for 64 bits
2167   if (UNLIKELY(internal_sysctlbyname("kern.elf32.aslr.pie_enable",
2168       &aslr_pie, &len, NULL, 0) == -1)) {
2169     return;
2170   }
2171 
2172   if (aslr_pie > 0) {
2173     Printf("This sanitizer is not compatible with enabled ASLR "
2174            "and binaries compiled with PIE\n");
2175     Die();
2176   }
2177 #else
2178   // Do nothing
2179 #endif
2180 }
2181 
2182 void CheckMPROTECT() {
2183 #if SANITIZER_NETBSD
2184   int mib[3];
2185   int paxflags;
2186   uptr len = sizeof(paxflags);
2187 
2188   mib[0] = CTL_PROC;
2189   mib[1] = internal_getpid();
2190   mib[2] = PROC_PID_PAXFLAGS;
2191 
2192   if (UNLIKELY(internal_sysctl(mib, 3, &paxflags, &len, NULL, 0) == -1)) {
2193     Printf("sysctl failed\n");
2194     Die();
2195   }
2196 
2197   if (UNLIKELY(paxflags & CTL_PROC_PAXFLAGS_MPROTECT)) {
2198     Printf("This sanitizer is not compatible with enabled MPROTECT\n");
2199     Die();
2200   }
2201 #else
2202   // Do nothing
2203 #endif
2204 }
2205 
2206 void PrintModuleMap() { }
2207 
2208 void CheckNoDeepBind(const char *filename, int flag) {
2209 #ifdef RTLD_DEEPBIND
2210   if (flag & RTLD_DEEPBIND) {
2211     Report(
2212         "You are trying to dlopen a %s shared library with RTLD_DEEPBIND flag"
2213         " which is incompatible with sanitizer runtime "
2214         "(see https://github.com/google/sanitizers/issues/611 for details"
2215         "). If you want to run %s library under sanitizers please remove "
2216         "RTLD_DEEPBIND from dlopen flags.\n",
2217         filename, filename);
2218     Die();
2219   }
2220 #endif
2221 }
2222 
2223 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
2224                               uptr *largest_gap_found,
2225                               uptr *max_occupied_addr) {
2226   UNREACHABLE("FindAvailableMemoryRange is not available");
2227   return 0;
2228 }
2229 
2230 bool GetRandom(void *buffer, uptr length, bool blocking) {
2231   if (!buffer || !length || length > 256)
2232     return false;
2233 #if SANITIZER_USE_GETENTROPY
2234   uptr rnd = getentropy(buffer, length);
2235   int rverrno = 0;
2236   if (internal_iserror(rnd, &rverrno) && rverrno == EFAULT)
2237     return false;
2238   else if (rnd == 0)
2239     return true;
2240 #endif // SANITIZER_USE_GETENTROPY
2241 
2242 #if SANITIZER_USE_GETRANDOM
2243   static atomic_uint8_t skip_getrandom_syscall;
2244   if (!atomic_load_relaxed(&skip_getrandom_syscall)) {
2245     // Up to 256 bytes, getrandom will not be interrupted.
2246     uptr res = internal_syscall(SYSCALL(getrandom), buffer, length,
2247                                 blocking ? 0 : GRND_NONBLOCK);
2248     int rverrno = 0;
2249     if (internal_iserror(res, &rverrno) && rverrno == ENOSYS)
2250       atomic_store_relaxed(&skip_getrandom_syscall, 1);
2251     else if (res == length)
2252       return true;
2253   }
2254 #endif // SANITIZER_USE_GETRANDOM
2255   // Up to 256 bytes, a read off /dev/urandom will not be interrupted.
2256   // blocking is moot here, O_NONBLOCK has no effect when opening /dev/urandom.
2257   uptr fd = internal_open("/dev/urandom", O_RDONLY);
2258   if (internal_iserror(fd))
2259     return false;
2260   uptr res = internal_read(fd, buffer, length);
2261   if (internal_iserror(res))
2262     return false;
2263   internal_close(fd);
2264   return true;
2265 }
2266 
2267 } // namespace __sanitizer
2268 
2269 #endif
2270