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