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