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