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