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