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