• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
18 
19 #include "sanitizer_common.h"
20 #include "sanitizer_flags.h"
21 #include "sanitizer_internal_defs.h"
22 #include "sanitizer_libc.h"
23 #include "sanitizer_linux.h"
24 #include "sanitizer_mutex.h"
25 #include "sanitizer_placement_new.h"
26 #include "sanitizer_procmaps.h"
27 #include "sanitizer_stacktrace.h"
28 #include "sanitizer_symbolizer.h"
29 
30 #if !SANITIZER_FREEBSD
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 <sys/mman.h>
53 #include <sys/ptrace.h>
54 #include <sys/resource.h>
55 #include <sys/stat.h>
56 #include <sys/syscall.h>
57 #include <sys/time.h>
58 #include <sys/types.h>
59 #include <ucontext.h>
60 #include <unistd.h>
61 
62 #if SANITIZER_FREEBSD
63 #include <sys/exec.h>
64 #include <sys/sysctl.h>
65 #include <vm/vm_param.h>
66 #include <vm/pmap.h>
67 #include <machine/atomic.h>
68 extern "C" {
69 // <sys/umtx.h> must be included after <errno.h> and <sys/types.h> on
70 // FreeBSD 9.2 and 10.0.
71 #include <sys/umtx.h>
72 }
73 extern char **environ;  // provided by crt1
74 #endif  // SANITIZER_FREEBSD
75 
76 #if !SANITIZER_ANDROID
77 #include <sys/signal.h>
78 #endif
79 
80 #if SANITIZER_LINUX
81 // <linux/time.h>
82 struct kernel_timeval {
83   long tv_sec;
84   long tv_usec;
85 };
86 
87 // <linux/futex.h> is broken on some linux distributions.
88 const int FUTEX_WAIT = 0;
89 const int FUTEX_WAKE = 1;
90 #endif  // SANITIZER_LINUX
91 
92 // Are we using 32-bit or 64-bit Linux syscalls?
93 // x32 (which defines __x86_64__) has SANITIZER_WORDSIZE == 32
94 // but it still needs to use 64-bit syscalls.
95 #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__powerpc64__) || \
96     SANITIZER_WORDSIZE == 64)
97 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 1
98 #else
99 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 0
100 #endif
101 
102 #if defined(__x86_64__)
103 extern "C" {
104 extern void internal_sigreturn();
105 }
106 #endif
107 
108 namespace __sanitizer {
109 
110 #if SANITIZER_LINUX && defined(__x86_64__)
111 #include "sanitizer_syscall_linux_x86_64.inc"
112 #elif SANITIZER_LINUX && defined(__aarch64__)
113 #include "sanitizer_syscall_linux_aarch64.inc"
114 #else
115 #include "sanitizer_syscall_generic.inc"
116 #endif
117 
118 // --------------- sanitizer_libc.h
119 #if !SANITIZER_S390
internal_mmap(void * addr,uptr length,int prot,int flags,int fd,OFF_T offset)120 uptr internal_mmap(void *addr, uptr length, int prot, int flags, int fd,
121                    OFF_T offset) {
122 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
123   return internal_syscall(SYSCALL(mmap), (uptr)addr, length, prot, flags, fd,
124                           offset);
125 #else
126   // mmap2 specifies file offset in 4096-byte units.
127   CHECK(IsAligned(offset, 4096));
128   return internal_syscall(SYSCALL(mmap2), addr, length, prot, flags, fd,
129                           offset / 4096);
130 #endif
131 }
132 #endif // !SANITIZER_S390
133 
internal_munmap(void * addr,uptr length)134 uptr internal_munmap(void *addr, uptr length) {
135   return internal_syscall(SYSCALL(munmap), (uptr)addr, length);
136 }
137 
internal_mprotect(void * addr,uptr length,int prot)138 int internal_mprotect(void *addr, uptr length, int prot) {
139   return internal_syscall(SYSCALL(mprotect), (uptr)addr, length, prot);
140 }
141 
internal_close(fd_t fd)142 uptr internal_close(fd_t fd) {
143   return internal_syscall(SYSCALL(close), fd);
144 }
145 
internal_open(const char * filename,int flags)146 uptr internal_open(const char *filename, int flags) {
147 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
148   return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags);
149 #else
150   return internal_syscall(SYSCALL(open), (uptr)filename, flags);
151 #endif
152 }
153 
internal_open(const char * filename,int flags,u32 mode)154 uptr internal_open(const char *filename, int flags, u32 mode) {
155 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
156   return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags,
157                           mode);
158 #else
159   return internal_syscall(SYSCALL(open), (uptr)filename, flags, mode);
160 #endif
161 }
162 
internal_read(fd_t fd,void * buf,uptr count)163 uptr internal_read(fd_t fd, void *buf, uptr count) {
164   sptr res;
165   HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(read), fd, (uptr)buf,
166                count));
167   return res;
168 }
169 
internal_write(fd_t fd,const void * buf,uptr count)170 uptr internal_write(fd_t fd, const void *buf, uptr count) {
171   sptr res;
172   HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(write), fd, (uptr)buf,
173                count));
174   return res;
175 }
176 
internal_ftruncate(fd_t fd,uptr size)177 uptr internal_ftruncate(fd_t fd, uptr size) {
178   sptr res;
179   HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(ftruncate), fd,
180                (OFF_T)size));
181   return res;
182 }
183 
184 #if !SANITIZER_LINUX_USES_64BIT_SYSCALLS && !SANITIZER_FREEBSD
stat64_to_stat(struct stat64 * in,struct stat * out)185 static void stat64_to_stat(struct stat64 *in, struct stat *out) {
186   internal_memset(out, 0, sizeof(*out));
187   out->st_dev = in->st_dev;
188   out->st_ino = in->st_ino;
189   out->st_mode = in->st_mode;
190   out->st_nlink = in->st_nlink;
191   out->st_uid = in->st_uid;
192   out->st_gid = in->st_gid;
193   out->st_rdev = in->st_rdev;
194   out->st_size = in->st_size;
195   out->st_blksize = in->st_blksize;
196   out->st_blocks = in->st_blocks;
197   out->st_atime = in->st_atime;
198   out->st_mtime = in->st_mtime;
199   out->st_ctime = in->st_ctime;
200   out->st_ino = in->st_ino;
201 }
202 #endif
203 
204 #if defined(__mips64)
kernel_stat_to_stat(struct kernel_stat * in,struct stat * out)205 static void kernel_stat_to_stat(struct kernel_stat *in, struct stat *out) {
206   internal_memset(out, 0, sizeof(*out));
207   out->st_dev = in->st_dev;
208   out->st_ino = in->st_ino;
209   out->st_mode = in->st_mode;
210   out->st_nlink = in->st_nlink;
211   out->st_uid = in->st_uid;
212   out->st_gid = in->st_gid;
213   out->st_rdev = in->st_rdev;
214   out->st_size = in->st_size;
215   out->st_blksize = in->st_blksize;
216   out->st_blocks = in->st_blocks;
217   out->st_atime = in->st_atime_nsec;
218   out->st_mtime = in->st_mtime_nsec;
219   out->st_ctime = in->st_ctime_nsec;
220   out->st_ino = in->st_ino;
221 }
222 #endif
223 
internal_stat(const char * path,void * buf)224 uptr internal_stat(const char *path, void *buf) {
225 #if SANITIZER_FREEBSD
226   return internal_syscall(SYSCALL(stat), path, buf);
227 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
228   return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path,
229                           (uptr)buf, 0);
230 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
231 # if defined(__mips64)
232   // For mips64, stat syscall fills buffer in the format of kernel_stat
233   struct kernel_stat kbuf;
234   int res = internal_syscall(SYSCALL(stat), path, &kbuf);
235   kernel_stat_to_stat(&kbuf, (struct stat *)buf);
236   return res;
237 # else
238   return internal_syscall(SYSCALL(stat), (uptr)path, (uptr)buf);
239 # endif
240 #else
241   struct stat64 buf64;
242   int res = internal_syscall(SYSCALL(stat64), path, &buf64);
243   stat64_to_stat(&buf64, (struct stat *)buf);
244   return res;
245 #endif
246 }
247 
internal_lstat(const char * path,void * buf)248 uptr internal_lstat(const char *path, void *buf) {
249 #if SANITIZER_FREEBSD
250   return internal_syscall(SYSCALL(lstat), path, buf);
251 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
252   return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path,
253                          (uptr)buf, AT_SYMLINK_NOFOLLOW);
254 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
255 # if SANITIZER_MIPS64
256   // For mips64, lstat syscall fills buffer in the format of kernel_stat
257   struct kernel_stat kbuf;
258   int res = internal_syscall(SYSCALL(lstat), path, &kbuf);
259   kernel_stat_to_stat(&kbuf, (struct stat *)buf);
260   return res;
261 # else
262   return internal_syscall(SYSCALL(lstat), (uptr)path, (uptr)buf);
263 # endif
264 #else
265   struct stat64 buf64;
266   int res = internal_syscall(SYSCALL(lstat64), path, &buf64);
267   stat64_to_stat(&buf64, (struct stat *)buf);
268   return res;
269 #endif
270 }
271 
internal_fstat(fd_t fd,void * buf)272 uptr internal_fstat(fd_t fd, void *buf) {
273 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
274 # if SANITIZER_MIPS64
275   // For mips64, fstat syscall fills buffer in the format of kernel_stat
276   struct kernel_stat kbuf;
277   int res = internal_syscall(SYSCALL(fstat), fd, &kbuf);
278   kernel_stat_to_stat(&kbuf, (struct stat *)buf);
279   return res;
280 # else
281   return internal_syscall(SYSCALL(fstat), fd, (uptr)buf);
282 # endif
283 #else
284   struct stat64 buf64;
285   int res = internal_syscall(SYSCALL(fstat64), fd, &buf64);
286   stat64_to_stat(&buf64, (struct stat *)buf);
287   return res;
288 #endif
289 }
290 
internal_filesize(fd_t fd)291 uptr internal_filesize(fd_t fd) {
292   struct stat st;
293   if (internal_fstat(fd, &st))
294     return -1;
295   return (uptr)st.st_size;
296 }
297 
internal_dup2(int oldfd,int newfd)298 uptr internal_dup2(int oldfd, int newfd) {
299 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
300   return internal_syscall(SYSCALL(dup3), oldfd, newfd, 0);
301 #else
302   return internal_syscall(SYSCALL(dup2), oldfd, newfd);
303 #endif
304 }
305 
internal_readlink(const char * path,char * buf,uptr bufsize)306 uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
307 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
308   return internal_syscall(SYSCALL(readlinkat), AT_FDCWD,
309                           (uptr)path, (uptr)buf, bufsize);
310 #else
311   return internal_syscall(SYSCALL(readlink), (uptr)path, (uptr)buf, bufsize);
312 #endif
313 }
314 
internal_unlink(const char * path)315 uptr internal_unlink(const char *path) {
316 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
317   return internal_syscall(SYSCALL(unlinkat), AT_FDCWD, (uptr)path, 0);
318 #else
319   return internal_syscall(SYSCALL(unlink), (uptr)path);
320 #endif
321 }
322 
internal_rename(const char * oldpath,const char * newpath)323 uptr internal_rename(const char *oldpath, const char *newpath) {
324 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
325   return internal_syscall(SYSCALL(renameat), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
326                           (uptr)newpath);
327 #else
328   return internal_syscall(SYSCALL(rename), (uptr)oldpath, (uptr)newpath);
329 #endif
330 }
331 
internal_sched_yield()332 uptr internal_sched_yield() {
333   return internal_syscall(SYSCALL(sched_yield));
334 }
335 
internal__exit(int exitcode)336 void internal__exit(int exitcode) {
337 #if SANITIZER_FREEBSD
338   internal_syscall(SYSCALL(exit), exitcode);
339 #else
340   internal_syscall(SYSCALL(exit_group), exitcode);
341 #endif
342   Die();  // Unreachable.
343 }
344 
internal_sleep(unsigned int seconds)345 unsigned int internal_sleep(unsigned int seconds) {
346   struct timespec ts;
347   ts.tv_sec = 1;
348   ts.tv_nsec = 0;
349   int res = internal_syscall(SYSCALL(nanosleep), &ts, &ts);
350   if (res) return ts.tv_sec;
351   return 0;
352 }
353 
internal_execve(const char * filename,char * const argv[],char * const envp[])354 uptr internal_execve(const char *filename, char *const argv[],
355                      char *const envp[]) {
356   return internal_syscall(SYSCALL(execve), (uptr)filename, (uptr)argv,
357                           (uptr)envp);
358 }
359 
360 // ----------------- sanitizer_common.h
FileExists(const char * filename)361 bool FileExists(const char *filename) {
362   struct stat st;
363 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
364   if (internal_syscall(SYSCALL(newfstatat), AT_FDCWD, filename, &st, 0))
365 #else
366   if (internal_stat(filename, &st))
367 #endif
368     return false;
369   // Sanity check: filename is a regular file.
370   return S_ISREG(st.st_mode);
371 }
372 
GetTid()373 uptr GetTid() {
374 #if SANITIZER_FREEBSD
375   return (uptr)pthread_self();
376 #else
377   return internal_syscall(SYSCALL(gettid));
378 #endif
379 }
380 
NanoTime()381 u64 NanoTime() {
382 #if SANITIZER_FREEBSD
383   timeval tv;
384 #else
385   kernel_timeval tv;
386 #endif
387   internal_memset(&tv, 0, sizeof(tv));
388   internal_syscall(SYSCALL(gettimeofday), (uptr)&tv, 0);
389   return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
390 }
391 
392 // Like getenv, but reads env directly from /proc (on Linux) or parses the
393 // 'environ' array (on FreeBSD) and does not use libc. This function should be
394 // called first inside __asan_init.
GetEnv(const char * name)395 const char *GetEnv(const char *name) {
396 #if SANITIZER_FREEBSD
397   if (::environ != 0) {
398     uptr NameLen = internal_strlen(name);
399     for (char **Env = ::environ; *Env != 0; Env++) {
400       if (internal_strncmp(*Env, name, NameLen) == 0 && (*Env)[NameLen] == '=')
401         return (*Env) + NameLen + 1;
402     }
403   }
404   return 0;  // Not found.
405 #elif SANITIZER_LINUX
406   static char *environ;
407   static uptr len;
408   static bool inited;
409   if (!inited) {
410     inited = true;
411     uptr environ_size;
412     if (!ReadFileToBuffer("/proc/self/environ", &environ, &environ_size, &len))
413       environ = nullptr;
414   }
415   if (!environ || len == 0) return nullptr;
416   uptr namelen = internal_strlen(name);
417   const char *p = environ;
418   while (*p != '\0') {  // will happen at the \0\0 that terminates the buffer
419     // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
420     const char* endp =
421         (char*)internal_memchr(p, '\0', len - (p - environ));
422     if (!endp)  // this entry isn't NUL terminated
423       return nullptr;
424     else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=')  // Match.
425       return p + namelen + 1;  // point after =
426     p = endp + 1;
427   }
428   return nullptr;  // Not found.
429 #else
430 #error "Unsupported platform"
431 #endif
432 }
433 
434 #if !SANITIZER_FREEBSD
435 extern "C" {
436   SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
437 }
438 #endif
439 
440 #if !SANITIZER_GO && !SANITIZER_FREEBSD
ReadNullSepFileToArray(const char * path,char *** arr,int arr_size)441 static void ReadNullSepFileToArray(const char *path, char ***arr,
442                                    int arr_size) {
443   char *buff;
444   uptr buff_size;
445   uptr buff_len;
446   *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
447   if (!ReadFileToBuffer(path, &buff, &buff_size, &buff_len, 1024 * 1024)) {
448     (*arr)[0] = nullptr;
449     return;
450   }
451   (*arr)[0] = buff;
452   int count, i;
453   for (count = 1, i = 1; ; i++) {
454     if (buff[i] == 0) {
455       if (buff[i+1] == 0) break;
456       (*arr)[count] = &buff[i+1];
457       CHECK_LE(count, arr_size - 1);  // FIXME: make this more flexible.
458       count++;
459     }
460   }
461   (*arr)[count] = nullptr;
462 }
463 #endif
464 
GetArgsAndEnv(char *** argv,char *** envp)465 static void GetArgsAndEnv(char ***argv, char ***envp) {
466 #if !SANITIZER_FREEBSD
467 #if !SANITIZER_GO
468   if (&__libc_stack_end) {
469 #endif
470     uptr* stack_end = (uptr*)__libc_stack_end;
471     int argc = *stack_end;
472     *argv = (char**)(stack_end + 1);
473     *envp = (char**)(stack_end + argc + 2);
474 #if !SANITIZER_GO
475   } else {
476     static const int kMaxArgv = 2000, kMaxEnvp = 2000;
477     ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
478     ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
479   }
480 #endif
481 #else
482   // On FreeBSD, retrieving the argument and environment arrays is done via the
483   // kern.ps_strings sysctl, which returns a pointer to a structure containing
484   // this information. See also <sys/exec.h>.
485   ps_strings *pss;
486   size_t sz = sizeof(pss);
487   if (sysctlbyname("kern.ps_strings", &pss, &sz, NULL, 0) == -1) {
488     Printf("sysctl kern.ps_strings failed\n");
489     Die();
490   }
491   *argv = pss->ps_argvstr;
492   *envp = pss->ps_envstr;
493 #endif
494 }
495 
GetArgv()496 char **GetArgv() {
497   char **argv, **envp;
498   GetArgsAndEnv(&argv, &envp);
499   return argv;
500 }
501 
ReExec()502 void ReExec() {
503   char **argv, **envp;
504   GetArgsAndEnv(&argv, &envp);
505   uptr rv = internal_execve("/proc/self/exe", argv, envp);
506   int rverrno;
507   CHECK_EQ(internal_iserror(rv, &rverrno), true);
508   Printf("execve failed, errno %d\n", rverrno);
509   Die();
510 }
511 
512 enum MutexState {
513   MtxUnlocked = 0,
514   MtxLocked = 1,
515   MtxSleeping = 2
516 };
517 
BlockingMutex()518 BlockingMutex::BlockingMutex() {
519   internal_memset(this, 0, sizeof(*this));
520 }
521 
Lock()522 void BlockingMutex::Lock() {
523   CHECK_EQ(owner_, 0);
524   atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
525   if (atomic_exchange(m, MtxLocked, memory_order_acquire) == MtxUnlocked)
526     return;
527   while (atomic_exchange(m, MtxSleeping, memory_order_acquire) != MtxUnlocked) {
528 #if SANITIZER_FREEBSD
529     _umtx_op(m, UMTX_OP_WAIT_UINT, MtxSleeping, 0, 0);
530 #else
531     internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAIT, MtxSleeping, 0, 0, 0);
532 #endif
533   }
534 }
535 
Unlock()536 void BlockingMutex::Unlock() {
537   atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
538   u32 v = atomic_exchange(m, MtxUnlocked, memory_order_relaxed);
539   CHECK_NE(v, MtxUnlocked);
540   if (v == MtxSleeping) {
541 #if SANITIZER_FREEBSD
542     _umtx_op(m, UMTX_OP_WAKE, 1, 0, 0);
543 #else
544     internal_syscall(SYSCALL(futex), (uptr)m, FUTEX_WAKE, 1, 0, 0, 0);
545 #endif
546   }
547 }
548 
CheckLocked()549 void BlockingMutex::CheckLocked() {
550   atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
551   CHECK_NE(MtxUnlocked, atomic_load(m, memory_order_relaxed));
552 }
553 
554 // ----------------- sanitizer_linux.h
555 // The actual size of this structure is specified by d_reclen.
556 // Note that getdents64 uses a different structure format. We only provide the
557 // 32-bit syscall here.
558 struct linux_dirent {
559 #if SANITIZER_X32 || defined(__aarch64__)
560   u64 d_ino;
561   u64 d_off;
562 #else
563   unsigned long      d_ino;
564   unsigned long      d_off;
565 #endif
566   unsigned short     d_reclen;
567 #ifdef __aarch64__
568   unsigned char      d_type;
569 #endif
570   char               d_name[256];
571 };
572 
573 // Syscall wrappers.
internal_ptrace(int request,int pid,void * addr,void * data)574 uptr internal_ptrace(int request, int pid, void *addr, void *data) {
575   return internal_syscall(SYSCALL(ptrace), request, pid, (uptr)addr,
576                           (uptr)data);
577 }
578 
internal_waitpid(int pid,int * status,int options)579 uptr internal_waitpid(int pid, int *status, int options) {
580   return internal_syscall(SYSCALL(wait4), pid, (uptr)status, options,
581                           0 /* rusage */);
582 }
583 
internal_getpid()584 uptr internal_getpid() {
585   return internal_syscall(SYSCALL(getpid));
586 }
587 
internal_getppid()588 uptr internal_getppid() {
589   return internal_syscall(SYSCALL(getppid));
590 }
591 
internal_getdents(fd_t fd,struct linux_dirent * dirp,unsigned int count)592 uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) {
593 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
594   return internal_syscall(SYSCALL(getdents64), fd, (uptr)dirp, count);
595 #else
596   return internal_syscall(SYSCALL(getdents), fd, (uptr)dirp, count);
597 #endif
598 }
599 
internal_lseek(fd_t fd,OFF_T offset,int whence)600 uptr internal_lseek(fd_t fd, OFF_T offset, int whence) {
601   return internal_syscall(SYSCALL(lseek), fd, offset, whence);
602 }
603 
604 #if SANITIZER_LINUX
internal_prctl(int option,uptr arg2,uptr arg3,uptr arg4,uptr arg5)605 uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
606   return internal_syscall(SYSCALL(prctl), option, arg2, arg3, arg4, arg5);
607 }
608 #endif
609 
internal_sigaltstack(const struct sigaltstack * ss,struct sigaltstack * oss)610 uptr internal_sigaltstack(const struct sigaltstack *ss,
611                          struct sigaltstack *oss) {
612   return internal_syscall(SYSCALL(sigaltstack), (uptr)ss, (uptr)oss);
613 }
614 
internal_fork()615 int internal_fork() {
616 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
617   return internal_syscall(SYSCALL(clone), SIGCHLD, 0);
618 #else
619   return internal_syscall(SYSCALL(fork));
620 #endif
621 }
622 
623 #if SANITIZER_LINUX
624 #define SA_RESTORER 0x04000000
625 // Doesn't set sa_restorer if the caller did not set it, so use with caution
626 //(see below).
internal_sigaction_norestorer(int signum,const void * act,void * oldact)627 int internal_sigaction_norestorer(int signum, const void *act, void *oldact) {
628   __sanitizer_kernel_sigaction_t k_act, k_oldact;
629   internal_memset(&k_act, 0, sizeof(__sanitizer_kernel_sigaction_t));
630   internal_memset(&k_oldact, 0, sizeof(__sanitizer_kernel_sigaction_t));
631   const __sanitizer_sigaction *u_act = (const __sanitizer_sigaction *)act;
632   __sanitizer_sigaction *u_oldact = (__sanitizer_sigaction *)oldact;
633   if (u_act) {
634     k_act.handler = u_act->handler;
635     k_act.sigaction = u_act->sigaction;
636     internal_memcpy(&k_act.sa_mask, &u_act->sa_mask,
637                     sizeof(__sanitizer_kernel_sigset_t));
638     // Without SA_RESTORER kernel ignores the calls (probably returns EINVAL).
639     k_act.sa_flags = u_act->sa_flags | SA_RESTORER;
640     // FIXME: most often sa_restorer is unset, however the kernel requires it
641     // to point to a valid signal restorer that calls the rt_sigreturn syscall.
642     // If sa_restorer passed to the kernel is NULL, the program may crash upon
643     // signal delivery or fail to unwind the stack in the signal handler.
644     // libc implementation of sigaction() passes its own restorer to
645     // rt_sigaction, so we need to do the same (we'll need to reimplement the
646     // restorers; for x86_64 the restorer address can be obtained from
647     // oldact->sa_restorer upon a call to sigaction(xxx, NULL, oldact).
648 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
649     k_act.sa_restorer = u_act->sa_restorer;
650 #endif
651   }
652 
653   uptr result = internal_syscall(SYSCALL(rt_sigaction), (uptr)signum,
654       (uptr)(u_act ? &k_act : nullptr),
655       (uptr)(u_oldact ? &k_oldact : nullptr),
656       (uptr)sizeof(__sanitizer_kernel_sigset_t));
657 
658   if ((result == 0) && u_oldact) {
659     u_oldact->handler = k_oldact.handler;
660     u_oldact->sigaction = k_oldact.sigaction;
661     internal_memcpy(&u_oldact->sa_mask, &k_oldact.sa_mask,
662                     sizeof(__sanitizer_kernel_sigset_t));
663     u_oldact->sa_flags = k_oldact.sa_flags;
664 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
665     u_oldact->sa_restorer = k_oldact.sa_restorer;
666 #endif
667   }
668   return result;
669 }
670 
671 // Invokes sigaction via a raw syscall with a restorer, but does not support
672 // all platforms yet.
673 // We disable for Go simply because we have not yet added to buildgo.sh.
674 #if defined(__x86_64__) && !SANITIZER_GO
internal_sigaction_syscall(int signum,const void * act,void * oldact)675 int internal_sigaction_syscall(int signum, const void *act, void *oldact) {
676   if (act == nullptr)
677     return internal_sigaction_norestorer(signum, act, oldact);
678   __sanitizer_sigaction u_adjust;
679   internal_memcpy(&u_adjust, act, sizeof(u_adjust));
680 #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
681     if (u_adjust.sa_restorer == nullptr) {
682       u_adjust.sa_restorer = internal_sigreturn;
683     }
684 #endif
685     return internal_sigaction_norestorer(signum, (const void *)&u_adjust,
686                                          oldact);
687 }
688 #endif // defined(__x86_64__) && !SANITIZER_GO
689 #endif  // SANITIZER_LINUX
690 
internal_sigprocmask(int how,__sanitizer_sigset_t * set,__sanitizer_sigset_t * oldset)691 uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
692     __sanitizer_sigset_t *oldset) {
693 #if SANITIZER_FREEBSD
694   return internal_syscall(SYSCALL(sigprocmask), how, set, oldset);
695 #else
696   __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
697   __sanitizer_kernel_sigset_t *k_oldset = (__sanitizer_kernel_sigset_t *)oldset;
698   return internal_syscall(SYSCALL(rt_sigprocmask), (uptr)how,
699                           (uptr)&k_set->sig[0], (uptr)&k_oldset->sig[0],
700                           sizeof(__sanitizer_kernel_sigset_t));
701 #endif
702 }
703 
internal_sigfillset(__sanitizer_sigset_t * set)704 void internal_sigfillset(__sanitizer_sigset_t *set) {
705   internal_memset(set, 0xff, sizeof(*set));
706 }
707 
internal_sigemptyset(__sanitizer_sigset_t * set)708 void internal_sigemptyset(__sanitizer_sigset_t *set) {
709   internal_memset(set, 0, sizeof(*set));
710 }
711 
712 #if SANITIZER_LINUX
internal_sigdelset(__sanitizer_sigset_t * set,int signum)713 void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
714   signum -= 1;
715   CHECK_GE(signum, 0);
716   CHECK_LT(signum, sizeof(*set) * 8);
717   __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
718   const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
719   const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
720   k_set->sig[idx] &= ~(1 << bit);
721 }
722 
internal_sigismember(__sanitizer_sigset_t * set,int signum)723 bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
724   signum -= 1;
725   CHECK_GE(signum, 0);
726   CHECK_LT(signum, sizeof(*set) * 8);
727   __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
728   const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
729   const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
730   return k_set->sig[idx] & (1 << bit);
731 }
732 #endif  // SANITIZER_LINUX
733 
734 // ThreadLister implementation.
ThreadLister(int pid)735 ThreadLister::ThreadLister(int pid)
736   : pid_(pid),
737     descriptor_(-1),
738     buffer_(4096),
739     error_(true),
740     entry_((struct linux_dirent *)buffer_.data()),
741     bytes_read_(0) {
742   char task_directory_path[80];
743   internal_snprintf(task_directory_path, sizeof(task_directory_path),
744                     "/proc/%d/task/", pid);
745   uptr openrv = internal_open(task_directory_path, O_RDONLY | O_DIRECTORY);
746   if (internal_iserror(openrv)) {
747     error_ = true;
748     Report("Can't open /proc/%d/task for reading.\n", pid);
749   } else {
750     error_ = false;
751     descriptor_ = openrv;
752   }
753 }
754 
GetNextTID()755 int ThreadLister::GetNextTID() {
756   int tid = -1;
757   do {
758     if (error_)
759       return -1;
760     if ((char *)entry_ >= &buffer_[bytes_read_] && !GetDirectoryEntries())
761       return -1;
762     if (entry_->d_ino != 0 && entry_->d_name[0] >= '0' &&
763         entry_->d_name[0] <= '9') {
764       // Found a valid tid.
765       tid = (int)internal_atoll(entry_->d_name);
766     }
767     entry_ = (struct linux_dirent *)(((char *)entry_) + entry_->d_reclen);
768   } while (tid < 0);
769   return tid;
770 }
771 
Reset()772 void ThreadLister::Reset() {
773   if (error_ || descriptor_ < 0)
774     return;
775   internal_lseek(descriptor_, 0, SEEK_SET);
776 }
777 
~ThreadLister()778 ThreadLister::~ThreadLister() {
779   if (descriptor_ >= 0)
780     internal_close(descriptor_);
781 }
782 
error()783 bool ThreadLister::error() { return error_; }
784 
GetDirectoryEntries()785 bool ThreadLister::GetDirectoryEntries() {
786   CHECK_GE(descriptor_, 0);
787   CHECK_NE(error_, true);
788   bytes_read_ = internal_getdents(descriptor_,
789                                   (struct linux_dirent *)buffer_.data(),
790                                   buffer_.size());
791   if (internal_iserror(bytes_read_)) {
792     Report("Can't read directory entries from /proc/%d/task.\n", pid_);
793     error_ = true;
794     return false;
795   } else if (bytes_read_ == 0) {
796     return false;
797   }
798   entry_ = (struct linux_dirent *)buffer_.data();
799   return true;
800 }
801 
GetPageSize()802 uptr GetPageSize() {
803 // Android post-M sysconf(_SC_PAGESIZE) crashes if called from .preinit_array.
804 #if SANITIZER_ANDROID
805   return 4096;
806 #elif SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__))
807   return EXEC_PAGESIZE;
808 #else
809   return sysconf(_SC_PAGESIZE);  // EXEC_PAGESIZE may not be trustworthy.
810 #endif
811 }
812 
ReadBinaryName(char * buf,uptr buf_len)813 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
814 #if SANITIZER_FREEBSD
815   const int Mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
816   const char *default_module_name = "kern.proc.pathname";
817   size_t Size = buf_len;
818   bool IsErr = (sysctl(Mib, ARRAY_SIZE(Mib), buf, &Size, NULL, 0) != 0);
819   int readlink_error = IsErr ? errno : 0;
820   uptr module_name_len = Size;
821 #else
822   const char *default_module_name = "/proc/self/exe";
823   uptr module_name_len = internal_readlink(
824       default_module_name, buf, buf_len);
825   int readlink_error;
826   bool IsErr = internal_iserror(module_name_len, &readlink_error);
827 #endif
828   if (IsErr) {
829     // We can't read binary name for some reason, assume it's unknown.
830     Report("WARNING: reading executable name failed with errno %d, "
831            "some stack frames may not be symbolized\n", readlink_error);
832     module_name_len = internal_snprintf(buf, buf_len, "%s",
833                                         default_module_name);
834     CHECK_LT(module_name_len, buf_len);
835   }
836   return module_name_len;
837 }
838 
ReadLongProcessName(char * buf,uptr buf_len)839 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len) {
840 #if SANITIZER_LINUX
841   char *tmpbuf;
842   uptr tmpsize;
843   uptr tmplen;
844   if (ReadFileToBuffer("/proc/self/cmdline", &tmpbuf, &tmpsize, &tmplen,
845                        1024 * 1024)) {
846     internal_strncpy(buf, tmpbuf, buf_len);
847     UnmapOrDie(tmpbuf, tmpsize);
848     return internal_strlen(buf);
849   }
850 #endif
851   return ReadBinaryName(buf, buf_len);
852 }
853 
854 // Match full names of the form /path/to/base_name{-,.}*
LibraryNameIs(const char * full_name,const char * base_name)855 bool LibraryNameIs(const char *full_name, const char *base_name) {
856   const char *name = full_name;
857   // Strip path.
858   while (*name != '\0') name++;
859   while (name > full_name && *name != '/') name--;
860   if (*name == '/') name++;
861   uptr base_name_length = internal_strlen(base_name);
862   if (internal_strncmp(name, base_name, base_name_length)) return false;
863   return (name[base_name_length] == '-' || name[base_name_length] == '.');
864 }
865 
866 #if !SANITIZER_ANDROID
867 // Call cb for each region mapped by map.
ForEachMappedRegion(link_map * map,void (* cb)(const void *,uptr))868 void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr)) {
869   CHECK_NE(map, nullptr);
870 #if !SANITIZER_FREEBSD
871   typedef ElfW(Phdr) Elf_Phdr;
872   typedef ElfW(Ehdr) Elf_Ehdr;
873 #endif  // !SANITIZER_FREEBSD
874   char *base = (char *)map->l_addr;
875   Elf_Ehdr *ehdr = (Elf_Ehdr *)base;
876   char *phdrs = base + ehdr->e_phoff;
877   char *phdrs_end = phdrs + ehdr->e_phnum * ehdr->e_phentsize;
878 
879   // Find the segment with the minimum base so we can "relocate" the p_vaddr
880   // fields.  Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
881   // objects have a non-zero base.
882   uptr preferred_base = (uptr)-1;
883   for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
884     Elf_Phdr *phdr = (Elf_Phdr *)iter;
885     if (phdr->p_type == PT_LOAD && preferred_base > (uptr)phdr->p_vaddr)
886       preferred_base = (uptr)phdr->p_vaddr;
887   }
888 
889   // Compute the delta from the real base to get a relocation delta.
890   sptr delta = (uptr)base - preferred_base;
891   // Now we can figure out what the loader really mapped.
892   for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
893     Elf_Phdr *phdr = (Elf_Phdr *)iter;
894     if (phdr->p_type == PT_LOAD) {
895       uptr seg_start = phdr->p_vaddr + delta;
896       uptr seg_end = seg_start + phdr->p_memsz;
897       // None of these values are aligned.  We consider the ragged edges of the
898       // load command as defined, since they are mapped from the file.
899       seg_start = RoundDownTo(seg_start, GetPageSizeCached());
900       seg_end = RoundUpTo(seg_end, GetPageSizeCached());
901       cb((void *)seg_start, seg_end - seg_start);
902     }
903   }
904 }
905 #endif
906 
907 #if defined(__x86_64__) && SANITIZER_LINUX
908 // We cannot use glibc's clone wrapper, because it messes with the child
909 // task's TLS. It writes the PID and TID of the child task to its thread
910 // descriptor, but in our case the child task shares the thread descriptor with
911 // the parent (because we don't know how to allocate a new thread
912 // descriptor to keep glibc happy). So the stock version of clone(), when
913 // used with CLONE_VM, would end up corrupting the parent's thread descriptor.
internal_clone(int (* fn)(void *),void * child_stack,int flags,void * arg,int * parent_tidptr,void * newtls,int * child_tidptr)914 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
915                     int *parent_tidptr, void *newtls, int *child_tidptr) {
916   long long res;
917   if (!fn || !child_stack)
918     return -EINVAL;
919   CHECK_EQ(0, (uptr)child_stack % 16);
920   child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
921   ((unsigned long long *)child_stack)[0] = (uptr)fn;
922   ((unsigned long long *)child_stack)[1] = (uptr)arg;
923   register void *r8 __asm__("r8") = newtls;
924   register int *r10 __asm__("r10") = child_tidptr;
925   __asm__ __volatile__(
926                        /* %rax = syscall(%rax = SYSCALL(clone),
927                         *                %rdi = flags,
928                         *                %rsi = child_stack,
929                         *                %rdx = parent_tidptr,
930                         *                %r8  = new_tls,
931                         *                %r10 = child_tidptr)
932                         */
933                        "syscall\n"
934 
935                        /* if (%rax != 0)
936                         *   return;
937                         */
938                        "testq  %%rax,%%rax\n"
939                        "jnz    1f\n"
940 
941                        /* In the child. Terminate unwind chain. */
942                        // XXX: We should also terminate the CFI unwind chain
943                        // here. Unfortunately clang 3.2 doesn't support the
944                        // necessary CFI directives, so we skip that part.
945                        "xorq   %%rbp,%%rbp\n"
946 
947                        /* Call "fn(arg)". */
948                        "popq   %%rax\n"
949                        "popq   %%rdi\n"
950                        "call   *%%rax\n"
951 
952                        /* Call _exit(%rax). */
953                        "movq   %%rax,%%rdi\n"
954                        "movq   %2,%%rax\n"
955                        "syscall\n"
956 
957                        /* Return to parent. */
958                      "1:\n"
959                        : "=a" (res)
960                        : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
961                          "S"(child_stack),
962                          "D"(flags),
963                          "d"(parent_tidptr),
964                          "r"(r8),
965                          "r"(r10)
966                        : "rsp", "memory", "r11", "rcx");
967   return res;
968 }
969 #elif defined(__mips__)
internal_clone(int (* fn)(void *),void * child_stack,int flags,void * arg,int * parent_tidptr,void * newtls,int * child_tidptr)970 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
971                     int *parent_tidptr, void *newtls, int *child_tidptr) {
972   long long res;
973   if (!fn || !child_stack)
974     return -EINVAL;
975   CHECK_EQ(0, (uptr)child_stack % 16);
976   child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
977   ((unsigned long long *)child_stack)[0] = (uptr)fn;
978   ((unsigned long long *)child_stack)[1] = (uptr)arg;
979   register void *a3 __asm__("$7") = newtls;
980   register int *a4 __asm__("$8") = child_tidptr;
981   // We don't have proper CFI directives here because it requires alot of code
982   // for very marginal benefits.
983   __asm__ __volatile__(
984                        /* $v0 = syscall($v0 = __NR_clone,
985                         * $a0 = flags,
986                         * $a1 = child_stack,
987                         * $a2 = parent_tidptr,
988                         * $a3 = new_tls,
989                         * $a4 = child_tidptr)
990                         */
991                        ".cprestore 16;\n"
992                        "move $4,%1;\n"
993                        "move $5,%2;\n"
994                        "move $6,%3;\n"
995                        "move $7,%4;\n"
996                        /* Store the fifth argument on stack
997                         * if we are using 32-bit abi.
998                         */
999 #if SANITIZER_WORDSIZE == 32
1000                        "lw %5,16($29);\n"
1001 #else
1002                        "move $8,%5;\n"
1003 #endif
1004                        "li $2,%6;\n"
1005                        "syscall;\n"
1006 
1007                        /* if ($v0 != 0)
1008                         * return;
1009                         */
1010                        "bnez $2,1f;\n"
1011 
1012                        /* Call "fn(arg)". */
1013 #if SANITIZER_WORDSIZE == 32
1014 #ifdef __BIG_ENDIAN__
1015                        "lw $25,4($29);\n"
1016                        "lw $4,12($29);\n"
1017 #else
1018                        "lw $25,0($29);\n"
1019                        "lw $4,8($29);\n"
1020 #endif
1021 #else
1022                        "ld $25,0($29);\n"
1023                        "ld $4,8($29);\n"
1024 #endif
1025                        "jal $25;\n"
1026 
1027                        /* Call _exit($v0). */
1028                        "move $4,$2;\n"
1029                        "li $2,%7;\n"
1030                        "syscall;\n"
1031 
1032                        /* Return to parent. */
1033                      "1:\n"
1034                        : "=r" (res)
1035                        : "r"(flags),
1036                          "r"(child_stack),
1037                          "r"(parent_tidptr),
1038                          "r"(a3),
1039                          "r"(a4),
1040                          "i"(__NR_clone),
1041                          "i"(__NR_exit)
1042                        : "memory", "$29" );
1043   return res;
1044 }
1045 #elif defined(__aarch64__)
internal_clone(int (* fn)(void *),void * child_stack,int flags,void * arg,int * parent_tidptr,void * newtls,int * child_tidptr)1046 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1047                     int *parent_tidptr, void *newtls, int *child_tidptr) {
1048   long long res;
1049   if (!fn || !child_stack)
1050     return -EINVAL;
1051   CHECK_EQ(0, (uptr)child_stack % 16);
1052   child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1053   ((unsigned long long *)child_stack)[0] = (uptr)fn;
1054   ((unsigned long long *)child_stack)[1] = (uptr)arg;
1055 
1056   register int (*__fn)(void *)  __asm__("x0") = fn;
1057   register void *__stack __asm__("x1") = child_stack;
1058   register int   __flags __asm__("x2") = flags;
1059   register void *__arg   __asm__("x3") = arg;
1060   register int  *__ptid  __asm__("x4") = parent_tidptr;
1061   register void *__tls   __asm__("x5") = newtls;
1062   register int  *__ctid  __asm__("x6") = child_tidptr;
1063 
1064   __asm__ __volatile__(
1065                        "mov x0,x2\n" /* flags  */
1066                        "mov x2,x4\n" /* ptid  */
1067                        "mov x3,x5\n" /* tls  */
1068                        "mov x4,x6\n" /* ctid  */
1069                        "mov x8,%9\n" /* clone  */
1070 
1071                        "svc 0x0\n"
1072 
1073                        /* if (%r0 != 0)
1074                         *   return %r0;
1075                         */
1076                        "cmp x0, #0\n"
1077                        "bne 1f\n"
1078 
1079                        /* In the child, now. Call "fn(arg)". */
1080                        "ldp x1, x0, [sp], #16\n"
1081                        "blr x1\n"
1082 
1083                        /* Call _exit(%r0).  */
1084                        "mov x8, %10\n"
1085                        "svc 0x0\n"
1086                      "1:\n"
1087 
1088                        : "=r" (res)
1089                        : "i"(-EINVAL),
1090                          "r"(__fn), "r"(__stack), "r"(__flags), "r"(__arg),
1091                          "r"(__ptid), "r"(__tls), "r"(__ctid),
1092                          "i"(__NR_clone), "i"(__NR_exit)
1093                        : "x30", "memory");
1094   return res;
1095 }
1096 #elif defined(__powerpc64__)
internal_clone(int (* fn)(void *),void * child_stack,int flags,void * arg,int * parent_tidptr,void * newtls,int * child_tidptr)1097 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
1098                    int *parent_tidptr, void *newtls, int *child_tidptr) {
1099   long long res;
1100 /* Stack frame offsets.  */
1101 #if _CALL_ELF != 2
1102 #define FRAME_MIN_SIZE         112
1103 #define FRAME_TOC_SAVE         40
1104 #else
1105 #define FRAME_MIN_SIZE         32
1106 #define FRAME_TOC_SAVE         24
1107 #endif
1108   if (!fn || !child_stack)
1109     return -EINVAL;
1110   CHECK_EQ(0, (uptr)child_stack % 16);
1111   child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
1112   ((unsigned long long *)child_stack)[0] = (uptr)fn;
1113   ((unsigned long long *)child_stack)[1] = (uptr)arg;
1114 
1115   register int (*__fn)(void *) __asm__("r3") = fn;
1116   register void *__cstack      __asm__("r4") = child_stack;
1117   register int __flags         __asm__("r5") = flags;
1118   register void * __arg        __asm__("r6") = arg;
1119   register int * __ptidptr     __asm__("r7") = parent_tidptr;
1120   register void * __newtls     __asm__("r8") = newtls;
1121   register int * __ctidptr     __asm__("r9") = child_tidptr;
1122 
1123  __asm__ __volatile__(
1124            /* fn, arg, child_stack are saved acrVoss the syscall */
1125            "mr 28, %5\n\t"
1126            "mr 29, %6\n\t"
1127            "mr 27, %8\n\t"
1128 
1129            /* syscall
1130              r3 == flags
1131              r4 == child_stack
1132              r5 == parent_tidptr
1133              r6 == newtls
1134              r7 == child_tidptr */
1135            "mr 3, %7\n\t"
1136            "mr 5, %9\n\t"
1137            "mr 6, %10\n\t"
1138            "mr 7, %11\n\t"
1139            "li 0, %3\n\t"
1140            "sc\n\t"
1141 
1142            /* Test if syscall was successful */
1143            "cmpdi  cr1, 3, 0\n\t"
1144            "crandc cr1*4+eq, cr1*4+eq, cr0*4+so\n\t"
1145            "bne-   cr1, 1f\n\t"
1146 
1147            /* Do the function call */
1148            "std   2, %13(1)\n\t"
1149 #if _CALL_ELF != 2
1150            "ld    0, 0(28)\n\t"
1151            "ld    2, 8(28)\n\t"
1152            "mtctr 0\n\t"
1153 #else
1154            "mr    12, 28\n\t"
1155            "mtctr 12\n\t"
1156 #endif
1157            "mr    3, 27\n\t"
1158            "bctrl\n\t"
1159            "ld    2, %13(1)\n\t"
1160 
1161            /* Call _exit(r3) */
1162            "li 0, %4\n\t"
1163            "sc\n\t"
1164 
1165            /* Return to parent */
1166            "1:\n\t"
1167            "mr %0, 3\n\t"
1168              : "=r" (res)
1169              : "0" (-1), "i" (EINVAL),
1170                "i" (__NR_clone), "i" (__NR_exit),
1171                "r" (__fn), "r" (__cstack), "r" (__flags),
1172                "r" (__arg), "r" (__ptidptr), "r" (__newtls),
1173                "r" (__ctidptr), "i" (FRAME_MIN_SIZE), "i" (FRAME_TOC_SAVE)
1174              : "cr0", "cr1", "memory", "ctr",
1175                "r0", "r29", "r27", "r28");
1176   return res;
1177 }
1178 #endif  // defined(__x86_64__) && SANITIZER_LINUX
1179 
1180 #if SANITIZER_ANDROID
1181 #if __ANDROID_API__ < 21
1182 extern "C" __attribute__((weak)) int dl_iterate_phdr(
1183     int (*)(struct dl_phdr_info *, size_t, void *), void *);
1184 #endif
1185 
dl_iterate_phdr_test_cb(struct dl_phdr_info * info,size_t size,void * data)1186 static int dl_iterate_phdr_test_cb(struct dl_phdr_info *info, size_t size,
1187                                    void *data) {
1188   // Any name starting with "lib" indicates a bug in L where library base names
1189   // are returned instead of paths.
1190   if (info->dlpi_name && info->dlpi_name[0] == 'l' &&
1191       info->dlpi_name[1] == 'i' && info->dlpi_name[2] == 'b') {
1192     *(bool *)data = true;
1193     return 1;
1194   }
1195   return 0;
1196 }
1197 
1198 static atomic_uint32_t android_api_level;
1199 
AndroidDetectApiLevel()1200 static AndroidApiLevel AndroidDetectApiLevel() {
1201   if (!&dl_iterate_phdr)
1202     return ANDROID_KITKAT; // K or lower
1203   bool base_name_seen = false;
1204   dl_iterate_phdr(dl_iterate_phdr_test_cb, &base_name_seen);
1205   if (base_name_seen)
1206     return ANDROID_LOLLIPOP_MR1; // L MR1
1207   return ANDROID_POST_LOLLIPOP;   // post-L
1208   // Plain L (API level 21) is completely broken wrt ASan and not very
1209   // interesting to detect.
1210 }
1211 
AndroidGetApiLevel()1212 AndroidApiLevel AndroidGetApiLevel() {
1213   AndroidApiLevel level =
1214       (AndroidApiLevel)atomic_load(&android_api_level, memory_order_relaxed);
1215   if (level) return level;
1216   level = AndroidDetectApiLevel();
1217   atomic_store(&android_api_level, level, memory_order_relaxed);
1218   return level;
1219 }
1220 
1221 #endif
1222 
IsHandledDeadlySignal(int signum)1223 bool IsHandledDeadlySignal(int signum) {
1224   if (common_flags()->handle_abort && signum == SIGABRT)
1225     return true;
1226   if (common_flags()->handle_sigill && signum == SIGILL)
1227     return true;
1228   if (common_flags()->handle_sigfpe && signum == SIGFPE)
1229     return true;
1230   return (signum == SIGSEGV || signum == SIGBUS) && common_flags()->handle_segv;
1231 }
1232 
1233 #ifndef SANITIZER_GO
internal_start_thread(void (* func)(void * arg),void * arg)1234 void *internal_start_thread(void(*func)(void *arg), void *arg) {
1235   // Start the thread with signals blocked, otherwise it can steal user signals.
1236   __sanitizer_sigset_t set, old;
1237   internal_sigfillset(&set);
1238 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1239   // Glibc uses SIGSETXID signal during setuid call. If this signal is blocked
1240   // on any thread, setuid call hangs (see test/tsan/setuid.c).
1241   internal_sigdelset(&set, 33);
1242 #endif
1243   internal_sigprocmask(SIG_SETMASK, &set, &old);
1244   void *th;
1245   real_pthread_create(&th, nullptr, (void*(*)(void *arg))func, arg);
1246   internal_sigprocmask(SIG_SETMASK, &old, nullptr);
1247   return th;
1248 }
1249 
internal_join_thread(void * th)1250 void internal_join_thread(void *th) {
1251   real_pthread_join(th, nullptr);
1252 }
1253 #else
internal_start_thread(void (* func)(void *),void * arg)1254 void *internal_start_thread(void (*func)(void *), void *arg) { return 0; }
1255 
internal_join_thread(void * th)1256 void internal_join_thread(void *th) {}
1257 #endif
1258 
1259 #if defined(__aarch64__)
1260 // Android headers in the older NDK releases miss this definition.
1261 struct __sanitizer_esr_context {
1262   struct _aarch64_ctx head;
1263   uint64_t esr;
1264 };
1265 
Aarch64GetESR(ucontext_t * ucontext,u64 * esr)1266 static bool Aarch64GetESR(ucontext_t *ucontext, u64 *esr) {
1267   static const u32 kEsrMagic = 0x45535201;
1268   u8 *aux = ucontext->uc_mcontext.__reserved;
1269   while (true) {
1270     _aarch64_ctx *ctx = (_aarch64_ctx *)aux;
1271     if (ctx->size == 0) break;
1272     if (ctx->magic == kEsrMagic) {
1273       *esr = ((__sanitizer_esr_context *)ctx)->esr;
1274       return true;
1275     }
1276     aux += ctx->size;
1277   }
1278   return false;
1279 }
1280 #endif
1281 
GetWriteFlag(void * context)1282 SignalContext::WriteFlag SignalContext::GetWriteFlag(void *context) {
1283   ucontext_t *ucontext = (ucontext_t *)context;
1284 #if defined(__x86_64__) || defined(__i386__)
1285   static const uptr PF_WRITE = 1U << 1;
1286 #if SANITIZER_FREEBSD
1287   uptr err = ucontext->uc_mcontext.mc_err;
1288 #else
1289   uptr err = ucontext->uc_mcontext.gregs[REG_ERR];
1290 #endif
1291   return err & PF_WRITE ? WRITE : READ;
1292 #elif defined(__arm__)
1293   static const uptr FSR_WRITE = 1U << 11;
1294   uptr fsr = ucontext->uc_mcontext.error_code;
1295   // FSR bits 5:0 describe the abort type, and are never 0 (or so it seems).
1296   // Zero FSR indicates an older kernel that does not pass this information to
1297   // the userspace.
1298   if (fsr == 0) return UNKNOWN;
1299   return fsr & FSR_WRITE ? WRITE : READ;
1300 #elif defined(__aarch64__)
1301   static const u64 ESR_ELx_WNR = 1U << 6;
1302   u64 esr;
1303   if (!Aarch64GetESR(ucontext, &esr)) return UNKNOWN;
1304   return esr & ESR_ELx_WNR ? WRITE : READ;
1305 #else
1306   (void)ucontext;
1307   return UNKNOWN;  // FIXME: Implement.
1308 #endif
1309 }
1310 
GetPcSpBp(void * context,uptr * pc,uptr * sp,uptr * bp)1311 void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
1312 #if defined(__arm__)
1313   ucontext_t *ucontext = (ucontext_t*)context;
1314   *pc = ucontext->uc_mcontext.arm_pc;
1315   *bp = ucontext->uc_mcontext.arm_fp;
1316   *sp = ucontext->uc_mcontext.arm_sp;
1317 #elif defined(__aarch64__)
1318   ucontext_t *ucontext = (ucontext_t*)context;
1319   *pc = ucontext->uc_mcontext.pc;
1320   *bp = ucontext->uc_mcontext.regs[29];
1321   *sp = ucontext->uc_mcontext.sp;
1322 #elif defined(__hppa__)
1323   ucontext_t *ucontext = (ucontext_t*)context;
1324   *pc = ucontext->uc_mcontext.sc_iaoq[0];
1325   /* GCC uses %r3 whenever a frame pointer is needed.  */
1326   *bp = ucontext->uc_mcontext.sc_gr[3];
1327   *sp = ucontext->uc_mcontext.sc_gr[30];
1328 #elif defined(__x86_64__)
1329 # if SANITIZER_FREEBSD
1330   ucontext_t *ucontext = (ucontext_t*)context;
1331   *pc = ucontext->uc_mcontext.mc_rip;
1332   *bp = ucontext->uc_mcontext.mc_rbp;
1333   *sp = ucontext->uc_mcontext.mc_rsp;
1334 # else
1335   ucontext_t *ucontext = (ucontext_t*)context;
1336   *pc = ucontext->uc_mcontext.gregs[REG_RIP];
1337   *bp = ucontext->uc_mcontext.gregs[REG_RBP];
1338   *sp = ucontext->uc_mcontext.gregs[REG_RSP];
1339 # endif
1340 #elif defined(__i386__)
1341 # if SANITIZER_FREEBSD
1342   ucontext_t *ucontext = (ucontext_t*)context;
1343   *pc = ucontext->uc_mcontext.mc_eip;
1344   *bp = ucontext->uc_mcontext.mc_ebp;
1345   *sp = ucontext->uc_mcontext.mc_esp;
1346 # else
1347   ucontext_t *ucontext = (ucontext_t*)context;
1348   *pc = ucontext->uc_mcontext.gregs[REG_EIP];
1349   *bp = ucontext->uc_mcontext.gregs[REG_EBP];
1350   *sp = ucontext->uc_mcontext.gregs[REG_ESP];
1351 # endif
1352 #elif defined(__powerpc__) || defined(__powerpc64__)
1353   ucontext_t *ucontext = (ucontext_t*)context;
1354   *pc = ucontext->uc_mcontext.regs->nip;
1355   *sp = ucontext->uc_mcontext.regs->gpr[PT_R1];
1356   // The powerpc{,64}-linux ABIs do not specify r31 as the frame
1357   // pointer, but GCC always uses r31 when we need a frame pointer.
1358   *bp = ucontext->uc_mcontext.regs->gpr[PT_R31];
1359 #elif defined(__sparc__)
1360   ucontext_t *ucontext = (ucontext_t*)context;
1361   uptr *stk_ptr;
1362 # if defined (__arch64__)
1363   *pc = ucontext->uc_mcontext.mc_gregs[MC_PC];
1364   *sp = ucontext->uc_mcontext.mc_gregs[MC_O6];
1365   stk_ptr = (uptr *) (*sp + 2047);
1366   *bp = stk_ptr[15];
1367 # else
1368   *pc = ucontext->uc_mcontext.gregs[REG_PC];
1369   *sp = ucontext->uc_mcontext.gregs[REG_O6];
1370   stk_ptr = (uptr *) *sp;
1371   *bp = stk_ptr[15];
1372 # endif
1373 #elif defined(__mips__)
1374   ucontext_t *ucontext = (ucontext_t*)context;
1375   *pc = ucontext->uc_mcontext.pc;
1376   *bp = ucontext->uc_mcontext.gregs[30];
1377   *sp = ucontext->uc_mcontext.gregs[29];
1378 #elif defined(__s390__)
1379   ucontext_t *ucontext = (ucontext_t*)context;
1380 # if defined(__s390x__)
1381   *pc = ucontext->uc_mcontext.psw.addr;
1382 # else
1383   *pc = ucontext->uc_mcontext.psw.addr & 0x7fffffff;
1384 # endif
1385   *bp = ucontext->uc_mcontext.gregs[11];
1386   *sp = ucontext->uc_mcontext.gregs[15];
1387 #else
1388 # error "Unsupported arch"
1389 #endif
1390 }
1391 
MaybeReexec()1392 void MaybeReexec() {
1393   // No need to re-exec on Linux.
1394 }
1395 
1396 } // namespace __sanitizer
1397 
1398 #endif // SANITIZER_FREEBSD || SANITIZER_LINUX
1399