sanitizer_linux.cc revision c1a1ed62228288155459d39194995a36aca4a8a6
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#if SANITIZER_LINUX
17
18#include "sanitizer_common.h"
19#include "sanitizer_internal_defs.h"
20#include "sanitizer_libc.h"
21#include "sanitizer_linux.h"
22#include "sanitizer_mutex.h"
23#include "sanitizer_placement_new.h"
24#include "sanitizer_procmaps.h"
25#include "sanitizer_stacktrace.h"
26#include "sanitizer_symbolizer.h"
27
28#include <asm/param.h>
29#include <dlfcn.h>
30#include <errno.h>
31#include <fcntl.h>
32#if !SANITIZER_ANDROID
33#include <link.h>
34#endif
35#include <pthread.h>
36#include <sched.h>
37#include <sys/mman.h>
38#include <sys/ptrace.h>
39#include <sys/resource.h>
40#include <sys/stat.h>
41#include <sys/syscall.h>
42#include <sys/time.h>
43#include <sys/types.h>
44#include <unistd.h>
45#include <unwind.h>
46
47#if !SANITIZER_ANDROID
48#include <sys/signal.h>
49#endif
50
51// <linux/time.h>
52struct kernel_timeval {
53  long tv_sec;
54  long tv_usec;
55};
56
57// <linux/futex.h> is broken on some linux distributions.
58const int FUTEX_WAIT = 0;
59const int FUTEX_WAKE = 1;
60
61// Are we using 32-bit or 64-bit syscalls?
62// x32 (which defines __x86_64__) has SANITIZER_WORDSIZE == 32
63// but it still needs to use 64-bit syscalls.
64#if defined(__x86_64__) || SANITIZER_WORDSIZE == 64
65# define SANITIZER_LINUX_USES_64BIT_SYSCALLS 1
66#else
67# define SANITIZER_LINUX_USES_64BIT_SYSCALLS 0
68#endif
69
70namespace __sanitizer {
71
72#ifdef __x86_64__
73#include "sanitizer_syscall_linux_x86_64.inc"
74#else
75#include "sanitizer_syscall_generic.inc"
76#endif
77
78// --------------- sanitizer_libc.h
79uptr internal_mmap(void *addr, uptr length, int prot, int flags,
80                    int fd, u64 offset) {
81#if SANITIZER_LINUX_USES_64BIT_SYSCALLS
82  return internal_syscall(__NR_mmap, addr, length, prot, flags, fd, offset);
83#else
84  return internal_syscall(__NR_mmap2, addr, length, prot, flags, fd, offset);
85#endif
86}
87
88uptr internal_munmap(void *addr, uptr length) {
89  return internal_syscall(__NR_munmap, addr, length);
90}
91
92uptr internal_close(fd_t fd) {
93  return internal_syscall(__NR_close, fd);
94}
95
96uptr internal_open(const char *filename, int flags) {
97  return internal_syscall(__NR_open, filename, flags);
98}
99
100uptr internal_open(const char *filename, int flags, u32 mode) {
101  return internal_syscall(__NR_open, filename, flags, mode);
102}
103
104uptr OpenFile(const char *filename, bool write) {
105  return internal_open(filename,
106      write ? O_WRONLY | O_CREAT /*| O_CLOEXEC*/ : O_RDONLY, 0660);
107}
108
109uptr internal_read(fd_t fd, void *buf, uptr count) {
110  sptr res;
111  HANDLE_EINTR(res, (sptr)internal_syscall(__NR_read, fd, buf, count));
112  return res;
113}
114
115uptr internal_write(fd_t fd, const void *buf, uptr count) {
116  sptr res;
117  HANDLE_EINTR(res, (sptr)internal_syscall(__NR_write, fd, buf, count));
118  return res;
119}
120
121#if !SANITIZER_LINUX_USES_64BIT_SYSCALLS
122static void stat64_to_stat(struct stat64 *in, struct stat *out) {
123  internal_memset(out, 0, sizeof(*out));
124  out->st_dev = in->st_dev;
125  out->st_ino = in->st_ino;
126  out->st_mode = in->st_mode;
127  out->st_nlink = in->st_nlink;
128  out->st_uid = in->st_uid;
129  out->st_gid = in->st_gid;
130  out->st_rdev = in->st_rdev;
131  out->st_size = in->st_size;
132  out->st_blksize = in->st_blksize;
133  out->st_blocks = in->st_blocks;
134  out->st_atime = in->st_atime;
135  out->st_mtime = in->st_mtime;
136  out->st_ctime = in->st_ctime;
137  out->st_ino = in->st_ino;
138}
139#endif
140
141uptr internal_stat(const char *path, void *buf) {
142#if SANITIZER_LINUX_USES_64BIT_SYSCALLS
143  return internal_syscall(__NR_stat, path, buf);
144#else
145  struct stat64 buf64;
146  int res = internal_syscall(__NR_stat64, path, &buf64);
147  stat64_to_stat(&buf64, (struct stat *)buf);
148  return res;
149#endif
150}
151
152uptr internal_lstat(const char *path, void *buf) {
153#if SANITIZER_LINUX_USES_64BIT_SYSCALLS
154  return internal_syscall(__NR_lstat, path, buf);
155#else
156  struct stat64 buf64;
157  int res = internal_syscall(__NR_lstat64, path, &buf64);
158  stat64_to_stat(&buf64, (struct stat *)buf);
159  return res;
160#endif
161}
162
163uptr internal_fstat(fd_t fd, void *buf) {
164#if SANITIZER_LINUX_USES_64BIT_SYSCALLS
165  return internal_syscall(__NR_fstat, fd, buf);
166#else
167  struct stat64 buf64;
168  int res = internal_syscall(__NR_fstat64, fd, &buf64);
169  stat64_to_stat(&buf64, (struct stat *)buf);
170  return res;
171#endif
172}
173
174uptr internal_filesize(fd_t fd) {
175  struct stat st;
176  if (internal_fstat(fd, &st))
177    return -1;
178  return (uptr)st.st_size;
179}
180
181uptr internal_dup2(int oldfd, int newfd) {
182  return internal_syscall(__NR_dup2, oldfd, newfd);
183}
184
185uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
186  return internal_syscall(__NR_readlink, path, buf, bufsize);
187}
188
189uptr internal_unlink(const char *path) {
190  return internal_syscall(__NR_unlink, path);
191}
192
193uptr internal_sched_yield() {
194  return internal_syscall(__NR_sched_yield);
195}
196
197void internal__exit(int exitcode) {
198  internal_syscall(__NR_exit_group, exitcode);
199  Die();  // Unreachable.
200}
201
202uptr internal_execve(const char *filename, char *const argv[],
203                     char *const envp[]) {
204  return internal_syscall(__NR_execve, filename, argv, envp);
205}
206
207// ----------------- sanitizer_common.h
208bool FileExists(const char *filename) {
209  struct stat st;
210  if (internal_stat(filename, &st))
211    return false;
212  // Sanity check: filename is a regular file.
213  return S_ISREG(st.st_mode);
214}
215
216uptr GetTid() {
217  return internal_syscall(__NR_gettid);
218}
219
220u64 NanoTime() {
221  kernel_timeval tv;
222  internal_memset(&tv, 0, sizeof(tv));
223  internal_syscall(__NR_gettimeofday, &tv, 0);
224  return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
225}
226
227// Like getenv, but reads env directly from /proc and does not use libc.
228// This function should be called first inside __asan_init.
229const char *GetEnv(const char *name) {
230  static char *environ;
231  static uptr len;
232  static bool inited;
233  if (!inited) {
234    inited = true;
235    uptr environ_size;
236    len = ReadFileToBuffer("/proc/self/environ",
237                           &environ, &environ_size, 1 << 26);
238  }
239  if (!environ || len == 0) return 0;
240  uptr namelen = internal_strlen(name);
241  const char *p = environ;
242  while (*p != '\0') {  // will happen at the \0\0 that terminates the buffer
243    // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
244    const char* endp =
245        (char*)internal_memchr(p, '\0', len - (p - environ));
246    if (endp == 0)  // this entry isn't NUL terminated
247      return 0;
248    else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=')  // Match.
249      return p + namelen + 1;  // point after =
250    p = endp + 1;
251  }
252  return 0;  // Not found.
253}
254
255extern "C" {
256  SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
257}
258
259#if !SANITIZER_GO
260static void ReadNullSepFileToArray(const char *path, char ***arr,
261                                   int arr_size) {
262  char *buff;
263  uptr buff_size = 0;
264  *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
265  ReadFileToBuffer(path, &buff, &buff_size, 1024 * 1024);
266  (*arr)[0] = buff;
267  int count, i;
268  for (count = 1, i = 1; ; i++) {
269    if (buff[i] == 0) {
270      if (buff[i+1] == 0) break;
271      (*arr)[count] = &buff[i+1];
272      CHECK_LE(count, arr_size - 1);  // FIXME: make this more flexible.
273      count++;
274    }
275  }
276  (*arr)[count] = 0;
277}
278#endif
279
280static void GetArgsAndEnv(char*** argv, char*** envp) {
281#if !SANITIZER_GO
282  if (&__libc_stack_end) {
283#endif
284    uptr* stack_end = (uptr*)__libc_stack_end;
285    int argc = *stack_end;
286    *argv = (char**)(stack_end + 1);
287    *envp = (char**)(stack_end + argc + 2);
288#if !SANITIZER_GO
289  } else {
290    static const int kMaxArgv = 2000, kMaxEnvp = 2000;
291    ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
292    ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
293  }
294#endif
295}
296
297void ReExec() {
298  char **argv, **envp;
299  GetArgsAndEnv(&argv, &envp);
300  uptr rv = internal_execve("/proc/self/exe", argv, envp);
301  int rverrno;
302  CHECK_EQ(internal_iserror(rv, &rverrno), true);
303  Printf("execve failed, errno %d\n", rverrno);
304  Die();
305}
306
307void PrepareForSandboxing() {
308  // Some kinds of sandboxes may forbid filesystem access, so we won't be able
309  // to read the file mappings from /proc/self/maps. Luckily, neither the
310  // process will be able to load additional libraries, so it's fine to use the
311  // cached mappings.
312  MemoryMappingLayout::CacheMemoryMappings();
313  // Same for /proc/self/exe in the symbolizer.
314#if !SANITIZER_GO
315  if (Symbolizer *sym = Symbolizer::GetOrNull())
316    sym->PrepareForSandboxing();
317#endif
318}
319
320// ----------------- sanitizer_procmaps.h
321// Linker initialized.
322ProcSelfMapsBuff MemoryMappingLayout::cached_proc_self_maps_;
323StaticSpinMutex MemoryMappingLayout::cache_lock_;  // Linker initialized.
324
325MemoryMappingLayout::MemoryMappingLayout(bool cache_enabled) {
326  proc_self_maps_.len =
327      ReadFileToBuffer("/proc/self/maps", &proc_self_maps_.data,
328                       &proc_self_maps_.mmaped_size, 1 << 26);
329  if (cache_enabled) {
330    if (proc_self_maps_.mmaped_size == 0) {
331      LoadFromCache();
332      CHECK_GT(proc_self_maps_.len, 0);
333    }
334  } else {
335    CHECK_GT(proc_self_maps_.mmaped_size, 0);
336  }
337  Reset();
338  // FIXME: in the future we may want to cache the mappings on demand only.
339  if (cache_enabled)
340    CacheMemoryMappings();
341}
342
343MemoryMappingLayout::~MemoryMappingLayout() {
344  // Only unmap the buffer if it is different from the cached one. Otherwise
345  // it will be unmapped when the cache is refreshed.
346  if (proc_self_maps_.data != cached_proc_self_maps_.data) {
347    UnmapOrDie(proc_self_maps_.data, proc_self_maps_.mmaped_size);
348  }
349}
350
351void MemoryMappingLayout::Reset() {
352  current_ = proc_self_maps_.data;
353}
354
355// static
356void MemoryMappingLayout::CacheMemoryMappings() {
357  SpinMutexLock l(&cache_lock_);
358  // Don't invalidate the cache if the mappings are unavailable.
359  ProcSelfMapsBuff old_proc_self_maps;
360  old_proc_self_maps = cached_proc_self_maps_;
361  cached_proc_self_maps_.len =
362      ReadFileToBuffer("/proc/self/maps", &cached_proc_self_maps_.data,
363                       &cached_proc_self_maps_.mmaped_size, 1 << 26);
364  if (cached_proc_self_maps_.mmaped_size == 0) {
365    cached_proc_self_maps_ = old_proc_self_maps;
366  } else {
367    if (old_proc_self_maps.mmaped_size) {
368      UnmapOrDie(old_proc_self_maps.data,
369                 old_proc_self_maps.mmaped_size);
370    }
371  }
372}
373
374void MemoryMappingLayout::LoadFromCache() {
375  SpinMutexLock l(&cache_lock_);
376  if (cached_proc_self_maps_.data) {
377    proc_self_maps_ = cached_proc_self_maps_;
378  }
379}
380
381// Parse a hex value in str and update str.
382static uptr ParseHex(char **str) {
383  uptr x = 0;
384  char *s;
385  for (s = *str; ; s++) {
386    char c = *s;
387    uptr v = 0;
388    if (c >= '0' && c <= '9')
389      v = c - '0';
390    else if (c >= 'a' && c <= 'f')
391      v = c - 'a' + 10;
392    else if (c >= 'A' && c <= 'F')
393      v = c - 'A' + 10;
394    else
395      break;
396    x = x * 16 + v;
397  }
398  *str = s;
399  return x;
400}
401
402static bool IsOneOf(char c, char c1, char c2) {
403  return c == c1 || c == c2;
404}
405
406static bool IsDecimal(char c) {
407  return c >= '0' && c <= '9';
408}
409
410static bool IsHex(char c) {
411  return (c >= '0' && c <= '9')
412      || (c >= 'a' && c <= 'f');
413}
414
415static uptr ReadHex(const char *p) {
416  uptr v = 0;
417  for (; IsHex(p[0]); p++) {
418    if (p[0] >= '0' && p[0] <= '9')
419      v = v * 16 + p[0] - '0';
420    else
421      v = v * 16 + p[0] - 'a' + 10;
422  }
423  return v;
424}
425
426static uptr ReadDecimal(const char *p) {
427  uptr v = 0;
428  for (; IsDecimal(p[0]); p++)
429    v = v * 10 + p[0] - '0';
430  return v;
431}
432
433
434bool MemoryMappingLayout::Next(uptr *start, uptr *end, uptr *offset,
435                               char filename[], uptr filename_size,
436                               uptr *protection) {
437  char *last = proc_self_maps_.data + proc_self_maps_.len;
438  if (current_ >= last) return false;
439  uptr dummy;
440  if (!start) start = &dummy;
441  if (!end) end = &dummy;
442  if (!offset) offset = &dummy;
443  char *next_line = (char*)internal_memchr(current_, '\n', last - current_);
444  if (next_line == 0)
445    next_line = last;
446  // Example: 08048000-08056000 r-xp 00000000 03:0c 64593   /foo/bar
447  *start = ParseHex(&current_);
448  CHECK_EQ(*current_++, '-');
449  *end = ParseHex(&current_);
450  CHECK_EQ(*current_++, ' ');
451  uptr local_protection = 0;
452  CHECK(IsOneOf(*current_, '-', 'r'));
453  if (*current_++ == 'r')
454    local_protection |= kProtectionRead;
455  CHECK(IsOneOf(*current_, '-', 'w'));
456  if (*current_++ == 'w')
457    local_protection |= kProtectionWrite;
458  CHECK(IsOneOf(*current_, '-', 'x'));
459  if (*current_++ == 'x')
460    local_protection |= kProtectionExecute;
461  CHECK(IsOneOf(*current_, 's', 'p'));
462  if (*current_++ == 's')
463    local_protection |= kProtectionShared;
464  if (protection) {
465    *protection = local_protection;
466  }
467  CHECK_EQ(*current_++, ' ');
468  *offset = ParseHex(&current_);
469  CHECK_EQ(*current_++, ' ');
470  ParseHex(&current_);
471  CHECK_EQ(*current_++, ':');
472  ParseHex(&current_);
473  CHECK_EQ(*current_++, ' ');
474  while (IsDecimal(*current_))
475    current_++;
476  // Qemu may lack the trailing space.
477  // http://code.google.com/p/address-sanitizer/issues/detail?id=160
478  // CHECK_EQ(*current_++, ' ');
479  // Skip spaces.
480  while (current_ < next_line && *current_ == ' ')
481    current_++;
482  // Fill in the filename.
483  uptr i = 0;
484  while (current_ < next_line) {
485    if (filename && i < filename_size - 1)
486      filename[i++] = *current_;
487    current_++;
488  }
489  if (filename && i < filename_size)
490    filename[i] = 0;
491  current_ = next_line + 1;
492  return true;
493}
494
495// Gets the object name and the offset by walking MemoryMappingLayout.
496bool MemoryMappingLayout::GetObjectNameAndOffset(uptr addr, uptr *offset,
497                                                 char filename[],
498                                                 uptr filename_size,
499                                                 uptr *protection) {
500  return IterateForObjectNameAndOffset(addr, offset, filename, filename_size,
501                                       protection);
502}
503
504void GetMemoryProfile(fill_profile_f cb, uptr *stats, uptr stats_size) {
505  char *smaps = 0;
506  uptr smaps_cap = 0;
507  uptr smaps_len = ReadFileToBuffer("/proc/self/smaps",
508      &smaps, &smaps_cap, 64<<20);
509  uptr start = 0;
510  bool file = false;
511  const char *pos = smaps;
512  while (pos < smaps + smaps_len) {
513    if (IsHex(pos[0])) {
514      start = ReadHex(pos);
515      for (; *pos != '/' && *pos > '\n'; pos++) {}
516      file = *pos == '/';
517    } else if (internal_strncmp(pos, "Rss:", 4) == 0) {
518      for (; *pos < '0' || *pos > '9'; pos++) {}
519      uptr rss = ReadDecimal(pos) * 1024;
520      cb(start, rss, file, stats, stats_size);
521    }
522    while (*pos++ != '\n') {}
523  }
524  UnmapOrDie(smaps, smaps_cap);
525}
526
527enum MutexState {
528  MtxUnlocked = 0,
529  MtxLocked = 1,
530  MtxSleeping = 2
531};
532
533BlockingMutex::BlockingMutex(LinkerInitialized) {
534  CHECK_EQ(owner_, 0);
535}
536
537BlockingMutex::BlockingMutex() {
538  internal_memset(this, 0, sizeof(*this));
539}
540
541void BlockingMutex::Lock() {
542  atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
543  if (atomic_exchange(m, MtxLocked, memory_order_acquire) == MtxUnlocked)
544    return;
545  while (atomic_exchange(m, MtxSleeping, memory_order_acquire) != MtxUnlocked)
546    internal_syscall(__NR_futex, m, FUTEX_WAIT, MtxSleeping, 0, 0, 0);
547}
548
549void BlockingMutex::Unlock() {
550  atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
551  u32 v = atomic_exchange(m, MtxUnlocked, memory_order_relaxed);
552  CHECK_NE(v, MtxUnlocked);
553  if (v == MtxSleeping)
554    internal_syscall(__NR_futex, m, FUTEX_WAKE, 1, 0, 0, 0);
555}
556
557void BlockingMutex::CheckLocked() {
558  atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
559  CHECK_NE(MtxUnlocked, atomic_load(m, memory_order_relaxed));
560}
561
562// ----------------- sanitizer_linux.h
563// The actual size of this structure is specified by d_reclen.
564// Note that getdents64 uses a different structure format. We only provide the
565// 32-bit syscall here.
566struct linux_dirent {
567  unsigned long      d_ino;
568  unsigned long      d_off;
569  unsigned short     d_reclen;
570  char               d_name[256];
571};
572
573// Syscall wrappers.
574uptr internal_ptrace(int request, int pid, void *addr, void *data) {
575  return internal_syscall(__NR_ptrace, request, pid, addr, data);
576}
577
578uptr internal_waitpid(int pid, int *status, int options) {
579  return internal_syscall(__NR_wait4, pid, status, options, 0 /* rusage */);
580}
581
582uptr internal_getpid() {
583  return internal_syscall(__NR_getpid);
584}
585
586uptr internal_getppid() {
587  return internal_syscall(__NR_getppid);
588}
589
590uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) {
591  return internal_syscall(__NR_getdents, fd, dirp, count);
592}
593
594uptr internal_lseek(fd_t fd, OFF_T offset, int whence) {
595  return internal_syscall(__NR_lseek, fd, offset, whence);
596}
597
598uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
599  return internal_syscall(__NR_prctl, option, arg2, arg3, arg4, arg5);
600}
601
602uptr internal_sigaltstack(const struct sigaltstack *ss,
603                         struct sigaltstack *oss) {
604  return internal_syscall(__NR_sigaltstack, ss, oss);
605}
606
607uptr internal_sigaction(int signum, const __sanitizer_kernel_sigaction_t *act,
608    __sanitizer_kernel_sigaction_t *oldact) {
609  return internal_syscall(__NR_rt_sigaction, signum, act, oldact,
610      sizeof(__sanitizer_kernel_sigset_t));
611}
612
613uptr internal_sigprocmask(int how, __sanitizer_kernel_sigset_t *set,
614    __sanitizer_kernel_sigset_t *oldset) {
615  return internal_syscall(__NR_rt_sigprocmask, (uptr)how, &set->sig[0],
616      &oldset->sig[0], sizeof(__sanitizer_kernel_sigset_t));
617}
618
619void internal_sigfillset(__sanitizer_kernel_sigset_t *set) {
620  internal_memset(set, 0xff, sizeof(*set));
621}
622
623void internal_sigdelset(__sanitizer_kernel_sigset_t *set, int signum) {
624  signum -= 1;
625  CHECK_GE(signum, 0);
626  CHECK_LT(signum, sizeof(*set) * 8);
627  const uptr idx = signum / (sizeof(set->sig[0]) * 8);
628  const uptr bit = signum % (sizeof(set->sig[0]) * 8);
629  set->sig[idx] &= ~(1 << bit);
630}
631
632// ThreadLister implementation.
633ThreadLister::ThreadLister(int pid)
634  : pid_(pid),
635    descriptor_(-1),
636    buffer_(4096),
637    error_(true),
638    entry_((struct linux_dirent *)buffer_.data()),
639    bytes_read_(0) {
640  char task_directory_path[80];
641  internal_snprintf(task_directory_path, sizeof(task_directory_path),
642                    "/proc/%d/task/", pid);
643  uptr openrv = internal_open(task_directory_path, O_RDONLY | O_DIRECTORY);
644  if (internal_iserror(openrv)) {
645    error_ = true;
646    Report("Can't open /proc/%d/task for reading.\n", pid);
647  } else {
648    error_ = false;
649    descriptor_ = openrv;
650  }
651}
652
653int ThreadLister::GetNextTID() {
654  int tid = -1;
655  do {
656    if (error_)
657      return -1;
658    if ((char *)entry_ >= &buffer_[bytes_read_] && !GetDirectoryEntries())
659      return -1;
660    if (entry_->d_ino != 0 && entry_->d_name[0] >= '0' &&
661        entry_->d_name[0] <= '9') {
662      // Found a valid tid.
663      tid = (int)internal_atoll(entry_->d_name);
664    }
665    entry_ = (struct linux_dirent *)(((char *)entry_) + entry_->d_reclen);
666  } while (tid < 0);
667  return tid;
668}
669
670void ThreadLister::Reset() {
671  if (error_ || descriptor_ < 0)
672    return;
673  internal_lseek(descriptor_, 0, SEEK_SET);
674}
675
676ThreadLister::~ThreadLister() {
677  if (descriptor_ >= 0)
678    internal_close(descriptor_);
679}
680
681bool ThreadLister::error() { return error_; }
682
683bool ThreadLister::GetDirectoryEntries() {
684  CHECK_GE(descriptor_, 0);
685  CHECK_NE(error_, true);
686  bytes_read_ = internal_getdents(descriptor_,
687                                  (struct linux_dirent *)buffer_.data(),
688                                  buffer_.size());
689  if (internal_iserror(bytes_read_)) {
690    Report("Can't read directory entries from /proc/%d/task.\n", pid_);
691    error_ = true;
692    return false;
693  } else if (bytes_read_ == 0) {
694    return false;
695  }
696  entry_ = (struct linux_dirent *)buffer_.data();
697  return true;
698}
699
700uptr GetPageSize() {
701#if defined(__x86_64__) || defined(__i386__)
702  return EXEC_PAGESIZE;
703#else
704  return sysconf(_SC_PAGESIZE);  // EXEC_PAGESIZE may not be trustworthy.
705#endif
706}
707
708static char proc_self_exe_cache_str[kMaxPathLength];
709static uptr proc_self_exe_cache_len = 0;
710
711uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
712  uptr module_name_len = internal_readlink(
713      "/proc/self/exe", buf, buf_len);
714  int readlink_error;
715  if (internal_iserror(module_name_len, &readlink_error)) {
716    if (proc_self_exe_cache_len) {
717      // If available, use the cached module name.
718      CHECK_LE(proc_self_exe_cache_len, buf_len);
719      internal_strncpy(buf, proc_self_exe_cache_str, buf_len);
720      module_name_len = internal_strlen(proc_self_exe_cache_str);
721    } else {
722      // We can't read /proc/self/exe for some reason, assume the name of the
723      // binary is unknown.
724      Report("WARNING: readlink(\"/proc/self/exe\") failed with errno %d, "
725             "some stack frames may not be symbolized\n", readlink_error);
726      module_name_len = internal_snprintf(buf, buf_len, "/proc/self/exe");
727    }
728    CHECK_LT(module_name_len, buf_len);
729    buf[module_name_len] = '\0';
730  }
731  return module_name_len;
732}
733
734void CacheBinaryName() {
735  if (!proc_self_exe_cache_len) {
736    proc_self_exe_cache_len =
737        ReadBinaryName(proc_self_exe_cache_str, kMaxPathLength);
738  }
739}
740
741// Match full names of the form /path/to/base_name{-,.}*
742bool LibraryNameIs(const char *full_name, const char *base_name) {
743  const char *name = full_name;
744  // Strip path.
745  while (*name != '\0') name++;
746  while (name > full_name && *name != '/') name--;
747  if (*name == '/') name++;
748  uptr base_name_length = internal_strlen(base_name);
749  if (internal_strncmp(name, base_name, base_name_length)) return false;
750  return (name[base_name_length] == '-' || name[base_name_length] == '.');
751}
752
753#if !SANITIZER_ANDROID
754// Call cb for each region mapped by map.
755void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr)) {
756  typedef ElfW(Phdr) Elf_Phdr;
757  typedef ElfW(Ehdr) Elf_Ehdr;
758  char *base = (char *)map->l_addr;
759  Elf_Ehdr *ehdr = (Elf_Ehdr *)base;
760  char *phdrs = base + ehdr->e_phoff;
761  char *phdrs_end = phdrs + ehdr->e_phnum * ehdr->e_phentsize;
762
763  // Find the segment with the minimum base so we can "relocate" the p_vaddr
764  // fields.  Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
765  // objects have a non-zero base.
766  uptr preferred_base = (uptr)-1;
767  for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
768    Elf_Phdr *phdr = (Elf_Phdr *)iter;
769    if (phdr->p_type == PT_LOAD && preferred_base > (uptr)phdr->p_vaddr)
770      preferred_base = (uptr)phdr->p_vaddr;
771  }
772
773  // Compute the delta from the real base to get a relocation delta.
774  sptr delta = (uptr)base - preferred_base;
775  // Now we can figure out what the loader really mapped.
776  for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
777    Elf_Phdr *phdr = (Elf_Phdr *)iter;
778    if (phdr->p_type == PT_LOAD) {
779      uptr seg_start = phdr->p_vaddr + delta;
780      uptr seg_end = seg_start + phdr->p_memsz;
781      // None of these values are aligned.  We consider the ragged edges of the
782      // load command as defined, since they are mapped from the file.
783      seg_start = RoundDownTo(seg_start, GetPageSizeCached());
784      seg_end = RoundUpTo(seg_end, GetPageSizeCached());
785      cb((void *)seg_start, seg_end - seg_start);
786    }
787  }
788}
789#endif
790
791#if defined(__x86_64__)
792// We cannot use glibc's clone wrapper, because it messes with the child
793// task's TLS. It writes the PID and TID of the child task to its thread
794// descriptor, but in our case the child task shares the thread descriptor with
795// the parent (because we don't know how to allocate a new thread
796// descriptor to keep glibc happy). So the stock version of clone(), when
797// used with CLONE_VM, would end up corrupting the parent's thread descriptor.
798uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
799                    int *parent_tidptr, void *newtls, int *child_tidptr) {
800  long long res;
801  if (!fn || !child_stack)
802    return -EINVAL;
803  CHECK_EQ(0, (uptr)child_stack % 16);
804  child_stack = (char *)child_stack - 2 * sizeof(void *);
805  ((void **)child_stack)[0] = (void *)(uptr)fn;
806  ((void **)child_stack)[1] = arg;
807  __asm__ __volatile__(
808                       /* %rax = syscall(%rax = __NR_clone,
809                        *                %rdi = flags,
810                        *                %rsi = child_stack,
811                        *                %rdx = parent_tidptr,
812                        *                %r8  = new_tls,
813                        *                %r10 = child_tidptr)
814                        */
815                       "movq   %6,%%r8\n"
816                       "movq   %7,%%r10\n"
817                       "syscall\n"
818
819                       /* if (%rax != 0)
820                        *   return;
821                        */
822                       "testq  %%rax,%%rax\n"
823                       "jnz    1f\n"
824
825                       /* In the child. Terminate unwind chain. */
826                       // XXX: We should also terminate the CFI unwind chain
827                       // here. Unfortunately clang 3.2 doesn't support the
828                       // necessary CFI directives, so we skip that part.
829                       "xorq   %%rbp,%%rbp\n"
830
831                       /* Call "fn(arg)". */
832                       "popq   %%rax\n"
833                       "popq   %%rdi\n"
834                       "call   *%%rax\n"
835
836                       /* Call _exit(%rax). */
837                       "movq   %%rax,%%rdi\n"
838                       "movq   %2,%%rax\n"
839                       "syscall\n"
840
841                       /* Return to parent. */
842                     "1:\n"
843                       : "=a" (res)
844                       : "a"(__NR_clone), "i"(__NR_exit),
845                         "S"(child_stack),
846                         "D"(flags),
847                         "d"(parent_tidptr),
848                         "r"(newtls),
849                         "r"(child_tidptr)
850                       : "rsp", "memory", "r8", "r10", "r11", "rcx");
851  return res;
852}
853#endif  // defined(__x86_64__)
854}  // namespace __sanitizer
855
856#endif  // SANITIZER_LINUX
857