sanitizer_linux.cc revision 5f4984db88b7b67539f62d7653b928aeadf91b16
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_syscall(__NR_gettimeofday, &tv, 0);
223  return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
224}
225
226// Like getenv, but reads env directly from /proc and does not use libc.
227// This function should be called first inside __asan_init.
228const char *GetEnv(const char *name) {
229  static char *environ;
230  static uptr len;
231  static bool inited;
232  if (!inited) {
233    inited = true;
234    uptr environ_size;
235    len = ReadFileToBuffer("/proc/self/environ",
236                           &environ, &environ_size, 1 << 26);
237  }
238  if (!environ || len == 0) return 0;
239  uptr namelen = internal_strlen(name);
240  const char *p = environ;
241  while (*p != '\0') {  // will happen at the \0\0 that terminates the buffer
242    // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
243    const char* endp =
244        (char*)internal_memchr(p, '\0', len - (p - environ));
245    if (endp == 0)  // this entry isn't NUL terminated
246      return 0;
247    else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=')  // Match.
248      return p + namelen + 1;  // point after =
249    p = endp + 1;
250  }
251  return 0;  // Not found.
252}
253
254extern "C" {
255  SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
256}
257
258#if !SANITIZER_GO
259static void ReadNullSepFileToArray(const char *path, char ***arr,
260                                   int arr_size) {
261  char *buff;
262  uptr buff_size = 0;
263  *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
264  ReadFileToBuffer(path, &buff, &buff_size, 1024 * 1024);
265  (*arr)[0] = buff;
266  int count, i;
267  for (count = 1, i = 1; ; i++) {
268    if (buff[i] == 0) {
269      if (buff[i+1] == 0) break;
270      (*arr)[count] = &buff[i+1];
271      CHECK_LE(count, arr_size - 1);  // FIXME: make this more flexible.
272      count++;
273    }
274  }
275  (*arr)[count] = 0;
276}
277#endif
278
279static void GetArgsAndEnv(char*** argv, char*** envp) {
280#if !SANITIZER_GO
281  if (&__libc_stack_end) {
282#endif
283    uptr* stack_end = (uptr*)__libc_stack_end;
284    int argc = *stack_end;
285    *argv = (char**)(stack_end + 1);
286    *envp = (char**)(stack_end + argc + 2);
287#if !SANITIZER_GO
288  } else {
289    static const int kMaxArgv = 2000, kMaxEnvp = 2000;
290    ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
291    ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
292  }
293#endif
294}
295
296void ReExec() {
297  char **argv, **envp;
298  GetArgsAndEnv(&argv, &envp);
299  uptr rv = internal_execve("/proc/self/exe", argv, envp);
300  int rverrno;
301  CHECK_EQ(internal_iserror(rv, &rverrno), true);
302  Printf("execve failed, errno %d\n", rverrno);
303  Die();
304}
305
306void PrepareForSandboxing() {
307  // Some kinds of sandboxes may forbid filesystem access, so we won't be able
308  // to read the file mappings from /proc/self/maps. Luckily, neither the
309  // process will be able to load additional libraries, so it's fine to use the
310  // cached mappings.
311  MemoryMappingLayout::CacheMemoryMappings();
312  // Same for /proc/self/exe in the symbolizer.
313#if !SANITIZER_GO
314  getSymbolizer()->PrepareForSandboxing();
315#endif
316}
317
318// ----------------- sanitizer_procmaps.h
319// Linker initialized.
320ProcSelfMapsBuff MemoryMappingLayout::cached_proc_self_maps_;
321StaticSpinMutex MemoryMappingLayout::cache_lock_;  // Linker initialized.
322
323MemoryMappingLayout::MemoryMappingLayout(bool cache_enabled) {
324  proc_self_maps_.len =
325      ReadFileToBuffer("/proc/self/maps", &proc_self_maps_.data,
326                       &proc_self_maps_.mmaped_size, 1 << 26);
327  if (cache_enabled) {
328    if (proc_self_maps_.mmaped_size == 0) {
329      LoadFromCache();
330      CHECK_GT(proc_self_maps_.len, 0);
331    }
332  } else {
333    CHECK_GT(proc_self_maps_.mmaped_size, 0);
334  }
335  Reset();
336  // FIXME: in the future we may want to cache the mappings on demand only.
337  if (cache_enabled)
338    CacheMemoryMappings();
339}
340
341MemoryMappingLayout::~MemoryMappingLayout() {
342  // Only unmap the buffer if it is different from the cached one. Otherwise
343  // it will be unmapped when the cache is refreshed.
344  if (proc_self_maps_.data != cached_proc_self_maps_.data) {
345    UnmapOrDie(proc_self_maps_.data, proc_self_maps_.mmaped_size);
346  }
347}
348
349void MemoryMappingLayout::Reset() {
350  current_ = proc_self_maps_.data;
351}
352
353// static
354void MemoryMappingLayout::CacheMemoryMappings() {
355  SpinMutexLock l(&cache_lock_);
356  // Don't invalidate the cache if the mappings are unavailable.
357  ProcSelfMapsBuff old_proc_self_maps;
358  old_proc_self_maps = cached_proc_self_maps_;
359  cached_proc_self_maps_.len =
360      ReadFileToBuffer("/proc/self/maps", &cached_proc_self_maps_.data,
361                       &cached_proc_self_maps_.mmaped_size, 1 << 26);
362  if (cached_proc_self_maps_.mmaped_size == 0) {
363    cached_proc_self_maps_ = old_proc_self_maps;
364  } else {
365    if (old_proc_self_maps.mmaped_size) {
366      UnmapOrDie(old_proc_self_maps.data,
367                 old_proc_self_maps.mmaped_size);
368    }
369  }
370}
371
372void MemoryMappingLayout::LoadFromCache() {
373  SpinMutexLock l(&cache_lock_);
374  if (cached_proc_self_maps_.data) {
375    proc_self_maps_ = cached_proc_self_maps_;
376  }
377}
378
379// Parse a hex value in str and update str.
380static uptr ParseHex(char **str) {
381  uptr x = 0;
382  char *s;
383  for (s = *str; ; s++) {
384    char c = *s;
385    uptr v = 0;
386    if (c >= '0' && c <= '9')
387      v = c - '0';
388    else if (c >= 'a' && c <= 'f')
389      v = c - 'a' + 10;
390    else if (c >= 'A' && c <= 'F')
391      v = c - 'A' + 10;
392    else
393      break;
394    x = x * 16 + v;
395  }
396  *str = s;
397  return x;
398}
399
400static bool IsOneOf(char c, char c1, char c2) {
401  return c == c1 || c == c2;
402}
403
404static bool IsDecimal(char c) {
405  return c >= '0' && c <= '9';
406}
407
408static bool IsHex(char c) {
409  return (c >= '0' && c <= '9')
410      || (c >= 'a' && c <= 'f');
411}
412
413static uptr ReadHex(const char *p) {
414  uptr v = 0;
415  for (; IsHex(p[0]); p++) {
416    if (p[0] >= '0' && p[0] <= '9')
417      v = v * 16 + p[0] - '0';
418    else
419      v = v * 16 + p[0] - 'a' + 10;
420  }
421  return v;
422}
423
424static uptr ReadDecimal(const char *p) {
425  uptr v = 0;
426  for (; IsDecimal(p[0]); p++)
427    v = v * 10 + p[0] - '0';
428  return v;
429}
430
431
432bool MemoryMappingLayout::Next(uptr *start, uptr *end, uptr *offset,
433                               char filename[], uptr filename_size,
434                               uptr *protection) {
435  char *last = proc_self_maps_.data + proc_self_maps_.len;
436  if (current_ >= last) return false;
437  uptr dummy;
438  if (!start) start = &dummy;
439  if (!end) end = &dummy;
440  if (!offset) offset = &dummy;
441  char *next_line = (char*)internal_memchr(current_, '\n', last - current_);
442  if (next_line == 0)
443    next_line = last;
444  // Example: 08048000-08056000 r-xp 00000000 03:0c 64593   /foo/bar
445  *start = ParseHex(&current_);
446  CHECK_EQ(*current_++, '-');
447  *end = ParseHex(&current_);
448  CHECK_EQ(*current_++, ' ');
449  uptr local_protection = 0;
450  CHECK(IsOneOf(*current_, '-', 'r'));
451  if (*current_++ == 'r')
452    local_protection |= kProtectionRead;
453  CHECK(IsOneOf(*current_, '-', 'w'));
454  if (*current_++ == 'w')
455    local_protection |= kProtectionWrite;
456  CHECK(IsOneOf(*current_, '-', 'x'));
457  if (*current_++ == 'x')
458    local_protection |= kProtectionExecute;
459  CHECK(IsOneOf(*current_, 's', 'p'));
460  if (*current_++ == 's')
461    local_protection |= kProtectionShared;
462  if (protection) {
463    *protection = local_protection;
464  }
465  CHECK_EQ(*current_++, ' ');
466  *offset = ParseHex(&current_);
467  CHECK_EQ(*current_++, ' ');
468  ParseHex(&current_);
469  CHECK_EQ(*current_++, ':');
470  ParseHex(&current_);
471  CHECK_EQ(*current_++, ' ');
472  while (IsDecimal(*current_))
473    current_++;
474  // Qemu may lack the trailing space.
475  // http://code.google.com/p/address-sanitizer/issues/detail?id=160
476  // CHECK_EQ(*current_++, ' ');
477  // Skip spaces.
478  while (current_ < next_line && *current_ == ' ')
479    current_++;
480  // Fill in the filename.
481  uptr i = 0;
482  while (current_ < next_line) {
483    if (filename && i < filename_size - 1)
484      filename[i++] = *current_;
485    current_++;
486  }
487  if (filename && i < filename_size)
488    filename[i] = 0;
489  current_ = next_line + 1;
490  return true;
491}
492
493// Gets the object name and the offset by walking MemoryMappingLayout.
494bool MemoryMappingLayout::GetObjectNameAndOffset(uptr addr, uptr *offset,
495                                                 char filename[],
496                                                 uptr filename_size,
497                                                 uptr *protection) {
498  return IterateForObjectNameAndOffset(addr, offset, filename, filename_size,
499                                       protection);
500}
501
502void GetMemoryProfile(fill_profile_f cb, uptr *stats, uptr stats_size) {
503  char *smaps = 0;
504  uptr smaps_cap = 0;
505  uptr smaps_len = ReadFileToBuffer("/proc/self/smaps",
506      &smaps, &smaps_cap, 64<<20);
507  uptr start = 0;
508  bool file = false;
509  const char *pos = smaps;
510  while (pos < smaps + smaps_len) {
511    if (IsHex(pos[0])) {
512      start = ReadHex(pos);
513      for (; *pos != '/' && *pos > '\n'; pos++) {}
514      file = *pos == '/';
515    } else if (internal_strncmp(pos, "Rss:", 4) == 0) {
516      for (; *pos < '0' || *pos > '9'; pos++) {}
517      uptr rss = ReadDecimal(pos) * 1024;
518      cb(start, rss, file, stats, stats_size);
519    }
520    while (*pos++ != '\n') {}
521  }
522  UnmapOrDie(smaps, smaps_cap);
523}
524
525enum MutexState {
526  MtxUnlocked = 0,
527  MtxLocked = 1,
528  MtxSleeping = 2
529};
530
531BlockingMutex::BlockingMutex(LinkerInitialized) {
532  CHECK_EQ(owner_, 0);
533}
534
535BlockingMutex::BlockingMutex() {
536  internal_memset(this, 0, sizeof(*this));
537}
538
539void BlockingMutex::Lock() {
540  atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
541  if (atomic_exchange(m, MtxLocked, memory_order_acquire) == MtxUnlocked)
542    return;
543  while (atomic_exchange(m, MtxSleeping, memory_order_acquire) != MtxUnlocked)
544    internal_syscall(__NR_futex, m, FUTEX_WAIT, MtxSleeping, 0, 0, 0);
545}
546
547void BlockingMutex::Unlock() {
548  atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
549  u32 v = atomic_exchange(m, MtxUnlocked, memory_order_relaxed);
550  CHECK_NE(v, MtxUnlocked);
551  if (v == MtxSleeping)
552    internal_syscall(__NR_futex, m, FUTEX_WAKE, 1, 0, 0, 0);
553}
554
555void BlockingMutex::CheckLocked() {
556  atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
557  CHECK_NE(MtxUnlocked, atomic_load(m, memory_order_relaxed));
558}
559
560// ----------------- sanitizer_linux.h
561// The actual size of this structure is specified by d_reclen.
562// Note that getdents64 uses a different structure format. We only provide the
563// 32-bit syscall here.
564struct linux_dirent {
565  unsigned long      d_ino;
566  unsigned long      d_off;
567  unsigned short     d_reclen;
568  char               d_name[256];
569};
570
571// Syscall wrappers.
572uptr internal_ptrace(int request, int pid, void *addr, void *data) {
573  return internal_syscall(__NR_ptrace, request, pid, addr, data);
574}
575
576uptr internal_waitpid(int pid, int *status, int options) {
577  return internal_syscall(__NR_wait4, pid, status, options, 0 /* rusage */);
578}
579
580uptr internal_getpid() {
581  return internal_syscall(__NR_getpid);
582}
583
584uptr internal_getppid() {
585  return internal_syscall(__NR_getppid);
586}
587
588uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) {
589  return internal_syscall(__NR_getdents, fd, dirp, count);
590}
591
592uptr internal_lseek(fd_t fd, OFF_T offset, int whence) {
593  return internal_syscall(__NR_lseek, fd, offset, whence);
594}
595
596uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
597  return internal_syscall(__NR_prctl, option, arg2, arg3, arg4, arg5);
598}
599
600uptr internal_sigaltstack(const struct sigaltstack *ss,
601                         struct sigaltstack *oss) {
602  return internal_syscall(__NR_sigaltstack, ss, oss);
603}
604
605uptr internal_sigaction(int signum, const __sanitizer_kernel_sigaction_t *act,
606    __sanitizer_kernel_sigaction_t *oldact) {
607  return internal_syscall(__NR_rt_sigaction, signum, act, oldact,
608      sizeof(__sanitizer_kernel_sigset_t));
609}
610
611uptr internal_sigprocmask(int how, __sanitizer_kernel_sigset_t *set,
612    __sanitizer_kernel_sigset_t *oldset) {
613  return internal_syscall(__NR_rt_sigprocmask, (uptr)how, &set->sig[0],
614      &oldset->sig[0], sizeof(__sanitizer_kernel_sigset_t));
615}
616
617void internal_sigfillset(__sanitizer_kernel_sigset_t *set) {
618  internal_memset(set, 0xff, sizeof(*set));
619}
620
621void internal_sigdelset(__sanitizer_kernel_sigset_t *set, int signum) {
622  signum -= 1;
623  CHECK_GE(signum, 0);
624  CHECK_LT(signum, sizeof(*set) * 8);
625  const uptr idx = signum / (sizeof(set->sig[0]) * 8);
626  const uptr bit = signum % (sizeof(set->sig[0]) * 8);
627  set->sig[idx] &= ~(1 << bit);
628}
629
630// ThreadLister implementation.
631ThreadLister::ThreadLister(int pid)
632  : pid_(pid),
633    descriptor_(-1),
634    buffer_(4096),
635    error_(true),
636    entry_((struct linux_dirent *)buffer_.data()),
637    bytes_read_(0) {
638  char task_directory_path[80];
639  internal_snprintf(task_directory_path, sizeof(task_directory_path),
640                    "/proc/%d/task/", pid);
641  uptr openrv = internal_open(task_directory_path, O_RDONLY | O_DIRECTORY);
642  if (internal_iserror(openrv)) {
643    error_ = true;
644    Report("Can't open /proc/%d/task for reading.\n", pid);
645  } else {
646    error_ = false;
647    descriptor_ = openrv;
648  }
649}
650
651int ThreadLister::GetNextTID() {
652  int tid = -1;
653  do {
654    if (error_)
655      return -1;
656    if ((char *)entry_ >= &buffer_[bytes_read_] && !GetDirectoryEntries())
657      return -1;
658    if (entry_->d_ino != 0 && entry_->d_name[0] >= '0' &&
659        entry_->d_name[0] <= '9') {
660      // Found a valid tid.
661      tid = (int)internal_atoll(entry_->d_name);
662    }
663    entry_ = (struct linux_dirent *)(((char *)entry_) + entry_->d_reclen);
664  } while (tid < 0);
665  return tid;
666}
667
668void ThreadLister::Reset() {
669  if (error_ || descriptor_ < 0)
670    return;
671  internal_lseek(descriptor_, 0, SEEK_SET);
672}
673
674ThreadLister::~ThreadLister() {
675  if (descriptor_ >= 0)
676    internal_close(descriptor_);
677}
678
679bool ThreadLister::error() { return error_; }
680
681bool ThreadLister::GetDirectoryEntries() {
682  CHECK_GE(descriptor_, 0);
683  CHECK_NE(error_, true);
684  bytes_read_ = internal_getdents(descriptor_,
685                                  (struct linux_dirent *)buffer_.data(),
686                                  buffer_.size());
687  if (internal_iserror(bytes_read_)) {
688    Report("Can't read directory entries from /proc/%d/task.\n", pid_);
689    error_ = true;
690    return false;
691  } else if (bytes_read_ == 0) {
692    return false;
693  }
694  entry_ = (struct linux_dirent *)buffer_.data();
695  return true;
696}
697
698uptr GetPageSize() {
699#if defined(__x86_64__) || defined(__i386__)
700  return EXEC_PAGESIZE;
701#else
702  return sysconf(_SC_PAGESIZE);  // EXEC_PAGESIZE may not be trustworthy.
703#endif
704}
705
706static char proc_self_exe_cache_str[kMaxPathLength];
707static uptr proc_self_exe_cache_len = 0;
708
709uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
710  uptr module_name_len = internal_readlink(
711      "/proc/self/exe", buf, buf_len);
712  int readlink_error;
713  if (internal_iserror(module_name_len, &readlink_error)) {
714    if (proc_self_exe_cache_len) {
715      // If available, use the cached module name.
716      CHECK_LE(proc_self_exe_cache_len, buf_len);
717      internal_strncpy(buf, proc_self_exe_cache_str, buf_len);
718      module_name_len = internal_strlen(proc_self_exe_cache_str);
719    } else {
720      // We can't read /proc/self/exe for some reason, assume the name of the
721      // binary is unknown.
722      Report("WARNING: readlink(\"/proc/self/exe\") failed with errno %d, "
723             "some stack frames may not be symbolized\n", readlink_error);
724      module_name_len = internal_snprintf(buf, buf_len, "/proc/self/exe");
725    }
726    CHECK_LT(module_name_len, buf_len);
727    buf[module_name_len] = '\0';
728  }
729  return module_name_len;
730}
731
732void CacheBinaryName() {
733  if (!proc_self_exe_cache_len) {
734    proc_self_exe_cache_len =
735        ReadBinaryName(proc_self_exe_cache_str, kMaxPathLength);
736  }
737}
738
739// Match full names of the form /path/to/base_name{-,.}*
740bool LibraryNameIs(const char *full_name, const char *base_name) {
741  const char *name = full_name;
742  // Strip path.
743  while (*name != '\0') name++;
744  while (name > full_name && *name != '/') name--;
745  if (*name == '/') name++;
746  uptr base_name_length = internal_strlen(base_name);
747  if (internal_strncmp(name, base_name, base_name_length)) return false;
748  return (name[base_name_length] == '-' || name[base_name_length] == '.');
749}
750
751#if !SANITIZER_ANDROID
752// Call cb for each region mapped by map.
753void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr)) {
754  typedef ElfW(Phdr) Elf_Phdr;
755  typedef ElfW(Ehdr) Elf_Ehdr;
756  char *base = (char *)map->l_addr;
757  Elf_Ehdr *ehdr = (Elf_Ehdr *)base;
758  char *phdrs = base + ehdr->e_phoff;
759  char *phdrs_end = phdrs + ehdr->e_phnum * ehdr->e_phentsize;
760
761  // Find the segment with the minimum base so we can "relocate" the p_vaddr
762  // fields.  Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
763  // objects have a non-zero base.
764  uptr preferred_base = (uptr)-1;
765  for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
766    Elf_Phdr *phdr = (Elf_Phdr *)iter;
767    if (phdr->p_type == PT_LOAD && preferred_base > (uptr)phdr->p_vaddr)
768      preferred_base = (uptr)phdr->p_vaddr;
769  }
770
771  // Compute the delta from the real base to get a relocation delta.
772  sptr delta = (uptr)base - preferred_base;
773  // Now we can figure out what the loader really mapped.
774  for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
775    Elf_Phdr *phdr = (Elf_Phdr *)iter;
776    if (phdr->p_type == PT_LOAD) {
777      uptr seg_start = phdr->p_vaddr + delta;
778      uptr seg_end = seg_start + phdr->p_memsz;
779      // None of these values are aligned.  We consider the ragged edges of the
780      // load command as defined, since they are mapped from the file.
781      seg_start = RoundDownTo(seg_start, GetPageSizeCached());
782      seg_end = RoundUpTo(seg_end, GetPageSizeCached());
783      cb((void *)seg_start, seg_end - seg_start);
784    }
785  }
786}
787#endif
788
789#if defined(__x86_64__)
790// We cannot use glibc's clone wrapper, because it messes with the child
791// task's TLS. It writes the PID and TID of the child task to its thread
792// descriptor, but in our case the child task shares the thread descriptor with
793// the parent (because we don't know how to allocate a new thread
794// descriptor to keep glibc happy). So the stock version of clone(), when
795// used with CLONE_VM, would end up corrupting the parent's thread descriptor.
796uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
797                    int *parent_tidptr, void *newtls, int *child_tidptr) {
798  long long res;
799  if (!fn || !child_stack)
800    return -EINVAL;
801  CHECK_EQ(0, (uptr)child_stack % 16);
802  child_stack = (char *)child_stack - 2 * sizeof(void *);
803  ((void **)child_stack)[0] = (void *)(uptr)fn;
804  ((void **)child_stack)[1] = arg;
805  __asm__ __volatile__(
806                       /* %rax = syscall(%rax = __NR_clone,
807                        *                %rdi = flags,
808                        *                %rsi = child_stack,
809                        *                %rdx = parent_tidptr,
810                        *                %r8  = new_tls,
811                        *                %r10 = child_tidptr)
812                        */
813                       "movq   %6,%%r8\n"
814                       "movq   %7,%%r10\n"
815                       "syscall\n"
816
817                       /* if (%rax != 0)
818                        *   return;
819                        */
820                       "testq  %%rax,%%rax\n"
821                       "jnz    1f\n"
822
823                       /* In the child. Terminate unwind chain. */
824                       // XXX: We should also terminate the CFI unwind chain
825                       // here. Unfortunately clang 3.2 doesn't support the
826                       // necessary CFI directives, so we skip that part.
827                       "xorq   %%rbp,%%rbp\n"
828
829                       /* Call "fn(arg)". */
830                       "popq   %%rax\n"
831                       "popq   %%rdi\n"
832                       "call   *%%rax\n"
833
834                       /* Call _exit(%rax). */
835                       "movq   %%rax,%%rdi\n"
836                       "movq   %2,%%rax\n"
837                       "syscall\n"
838
839                       /* Return to parent. */
840                     "1:\n"
841                       : "=a" (res)
842                       : "a"(__NR_clone), "i"(__NR_exit),
843                         "S"(child_stack),
844                         "D"(flags),
845                         "d"(parent_tidptr),
846                         "r"(newtls),
847                         "r"(child_tidptr)
848                       : "rsp", "memory", "r8", "r10", "r11", "rcx");
849  return res;
850}
851#endif  // defined(__x86_64__)
852}  // namespace __sanitizer
853
854#endif  // SANITIZER_LINUX
855