Home | History | Annotate | Download | only in sanitizer_common
      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 #include <link.h>
     33 #include <pthread.h>
     34 #include <sched.h>
     35 #include <sys/mman.h>
     36 #include <sys/ptrace.h>
     37 #include <sys/resource.h>
     38 #include <sys/stat.h>
     39 #include <sys/syscall.h>
     40 #include <sys/time.h>
     41 #include <sys/types.h>
     42 #include <unistd.h>
     43 #include <unwind.h>
     44 
     45 #if !SANITIZER_ANDROID
     46 #include <sys/signal.h>
     47 #endif
     48 
     49 // <linux/time.h>
     50 struct kernel_timeval {
     51   long tv_sec;
     52   long tv_usec;
     53 };
     54 
     55 // <linux/futex.h> is broken on some linux distributions.
     56 const int FUTEX_WAIT = 0;
     57 const int FUTEX_WAKE = 1;
     58 
     59 // Are we using 32-bit or 64-bit syscalls?
     60 // x32 (which defines __x86_64__) has SANITIZER_WORDSIZE == 32
     61 // but it still needs to use 64-bit syscalls.
     62 #if defined(__x86_64__) || SANITIZER_WORDSIZE == 64
     63 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 1
     64 #else
     65 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 0
     66 #endif
     67 
     68 namespace __sanitizer {
     69 
     70 #ifdef __x86_64__
     71 #include "sanitizer_syscall_linux_x86_64.inc"
     72 #else
     73 #include "sanitizer_syscall_generic.inc"
     74 #endif
     75 
     76 // --------------- sanitizer_libc.h
     77 uptr internal_mmap(void *addr, uptr length, int prot, int flags,
     78                     int fd, u64 offset) {
     79 #if SANITIZER_LINUX_USES_64BIT_SYSCALLS
     80   return internal_syscall(__NR_mmap, addr, length, prot, flags, fd, offset);
     81 #else
     82   return internal_syscall(__NR_mmap2, addr, length, prot, flags, fd, offset);
     83 #endif
     84 }
     85 
     86 uptr internal_munmap(void *addr, uptr length) {
     87   return internal_syscall(__NR_munmap, addr, length);
     88 }
     89 
     90 uptr internal_close(fd_t fd) {
     91   return internal_syscall(__NR_close, fd);
     92 }
     93 
     94 uptr internal_open(const char *filename, int flags) {
     95   return internal_syscall(__NR_open, filename, flags);
     96 }
     97 
     98 uptr internal_open(const char *filename, int flags, u32 mode) {
     99   return internal_syscall(__NR_open, filename, flags, mode);
    100 }
    101 
    102 uptr OpenFile(const char *filename, bool write) {
    103   return internal_open(filename,
    104       write ? O_WRONLY | O_CREAT /*| O_CLOEXEC*/ : O_RDONLY, 0660);
    105 }
    106 
    107 uptr internal_read(fd_t fd, void *buf, uptr count) {
    108   sptr res;
    109   HANDLE_EINTR(res, (sptr)internal_syscall(__NR_read, fd, buf, count));
    110   return res;
    111 }
    112 
    113 uptr internal_write(fd_t fd, const void *buf, uptr count) {
    114   sptr res;
    115   HANDLE_EINTR(res, (sptr)internal_syscall(__NR_write, fd, buf, count));
    116   return res;
    117 }
    118 
    119 #if !SANITIZER_LINUX_USES_64BIT_SYSCALLS
    120 static void stat64_to_stat(struct stat64 *in, struct stat *out) {
    121   internal_memset(out, 0, sizeof(*out));
    122   out->st_dev = in->st_dev;
    123   out->st_ino = in->st_ino;
    124   out->st_mode = in->st_mode;
    125   out->st_nlink = in->st_nlink;
    126   out->st_uid = in->st_uid;
    127   out->st_gid = in->st_gid;
    128   out->st_rdev = in->st_rdev;
    129   out->st_size = in->st_size;
    130   out->st_blksize = in->st_blksize;
    131   out->st_blocks = in->st_blocks;
    132   out->st_atime = in->st_atime;
    133   out->st_mtime = in->st_mtime;
    134   out->st_ctime = in->st_ctime;
    135   out->st_ino = in->st_ino;
    136 }
    137 #endif
    138 
    139 uptr internal_stat(const char *path, void *buf) {
    140 #if SANITIZER_LINUX_USES_64BIT_SYSCALLS
    141   return internal_syscall(__NR_stat, path, buf);
    142 #else
    143   struct stat64 buf64;
    144   int res = internal_syscall(__NR_stat64, path, &buf64);
    145   stat64_to_stat(&buf64, (struct stat *)buf);
    146   return res;
    147 #endif
    148 }
    149 
    150 uptr internal_lstat(const char *path, void *buf) {
    151 #if SANITIZER_LINUX_USES_64BIT_SYSCALLS
    152   return internal_syscall(__NR_lstat, path, buf);
    153 #else
    154   struct stat64 buf64;
    155   int res = internal_syscall(__NR_lstat64, path, &buf64);
    156   stat64_to_stat(&buf64, (struct stat *)buf);
    157   return res;
    158 #endif
    159 }
    160 
    161 uptr internal_fstat(fd_t fd, void *buf) {
    162 #if SANITIZER_LINUX_USES_64BIT_SYSCALLS
    163   return internal_syscall(__NR_fstat, fd, buf);
    164 #else
    165   struct stat64 buf64;
    166   int res = internal_syscall(__NR_fstat64, fd, &buf64);
    167   stat64_to_stat(&buf64, (struct stat *)buf);
    168   return res;
    169 #endif
    170 }
    171 
    172 uptr internal_filesize(fd_t fd) {
    173   struct stat st;
    174   if (internal_fstat(fd, &st))
    175     return -1;
    176   return (uptr)st.st_size;
    177 }
    178 
    179 uptr internal_dup2(int oldfd, int newfd) {
    180   return internal_syscall(__NR_dup2, oldfd, newfd);
    181 }
    182 
    183 uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
    184   return internal_syscall(__NR_readlink, path, buf, bufsize);
    185 }
    186 
    187 uptr internal_unlink(const char *path) {
    188   return internal_syscall(__NR_unlink, path);
    189 }
    190 
    191 uptr internal_sched_yield() {
    192   return internal_syscall(__NR_sched_yield);
    193 }
    194 
    195 void internal__exit(int exitcode) {
    196   internal_syscall(__NR_exit_group, exitcode);
    197   Die();  // Unreachable.
    198 }
    199 
    200 uptr internal_execve(const char *filename, char *const argv[],
    201                      char *const envp[]) {
    202   return internal_syscall(__NR_execve, filename, argv, envp);
    203 }
    204 
    205 // ----------------- sanitizer_common.h
    206 bool FileExists(const char *filename) {
    207   struct stat st;
    208   if (internal_stat(filename, &st))
    209     return false;
    210   // Sanity check: filename is a regular file.
    211   return S_ISREG(st.st_mode);
    212 }
    213 
    214 uptr GetTid() {
    215   return internal_syscall(__NR_gettid);
    216 }
    217 
    218 u64 NanoTime() {
    219   kernel_timeval tv = {};
    220   internal_syscall(__NR_gettimeofday, &tv, 0);
    221   return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
    222 }
    223 
    224 // Like getenv, but reads env directly from /proc and does not use libc.
    225 // This function should be called first inside __asan_init.
    226 const char *GetEnv(const char *name) {
    227   static char *environ;
    228   static uptr len;
    229   static bool inited;
    230   if (!inited) {
    231     inited = true;
    232     uptr environ_size;
    233     len = ReadFileToBuffer("/proc/self/environ",
    234                            &environ, &environ_size, 1 << 26);
    235   }
    236   if (!environ || len == 0) return 0;
    237   uptr namelen = internal_strlen(name);
    238   const char *p = environ;
    239   while (*p != '\0') {  // will happen at the \0\0 that terminates the buffer
    240     // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
    241     const char* endp =
    242         (char*)internal_memchr(p, '\0', len - (p - environ));
    243     if (endp == 0)  // this entry isn't NUL terminated
    244       return 0;
    245     else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=')  // Match.
    246       return p + namelen + 1;  // point after =
    247     p = endp + 1;
    248   }
    249   return 0;  // Not found.
    250 }
    251 
    252 extern "C" {
    253   extern void *__libc_stack_end SANITIZER_WEAK_ATTRIBUTE;
    254 }
    255 
    256 #if !SANITIZER_GO
    257 static void ReadNullSepFileToArray(const char *path, char ***arr,
    258                                    int arr_size) {
    259   char *buff;
    260   uptr buff_size = 0;
    261   *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
    262   ReadFileToBuffer(path, &buff, &buff_size, 1024 * 1024);
    263   (*arr)[0] = buff;
    264   int count, i;
    265   for (count = 1, i = 1; ; i++) {
    266     if (buff[i] == 0) {
    267       if (buff[i+1] == 0) break;
    268       (*arr)[count] = &buff[i+1];
    269       CHECK_LE(count, arr_size - 1);  // FIXME: make this more flexible.
    270       count++;
    271     }
    272   }
    273   (*arr)[count] = 0;
    274 }
    275 #endif
    276 
    277 static void GetArgsAndEnv(char*** argv, char*** envp) {
    278 #if !SANITIZER_GO
    279   if (&__libc_stack_end) {
    280 #endif
    281     uptr* stack_end = (uptr*)__libc_stack_end;
    282     int argc = *stack_end;
    283     *argv = (char**)(stack_end + 1);
    284     *envp = (char**)(stack_end + argc + 2);
    285 #if !SANITIZER_GO
    286   } else {
    287     static const int kMaxArgv = 2000, kMaxEnvp = 2000;
    288     ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
    289     ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
    290   }
    291 #endif
    292 }
    293 
    294 void ReExec() {
    295   char **argv, **envp;
    296   GetArgsAndEnv(&argv, &envp);
    297   uptr rv = internal_execve("/proc/self/exe", argv, envp);
    298   int rverrno;
    299   CHECK_EQ(internal_iserror(rv, &rverrno), true);
    300   Printf("execve failed, errno %d\n", rverrno);
    301   Die();
    302 }
    303 
    304 void PrepareForSandboxing() {
    305   // Some kinds of sandboxes may forbid filesystem access, so we won't be able
    306   // to read the file mappings from /proc/self/maps. Luckily, neither the
    307   // process will be able to load additional libraries, so it's fine to use the
    308   // cached mappings.
    309   MemoryMappingLayout::CacheMemoryMappings();
    310   // Same for /proc/self/exe in the symbolizer.
    311   SymbolizerPrepareForSandboxing();
    312 }
    313 
    314 // ----------------- sanitizer_procmaps.h
    315 // Linker initialized.
    316 ProcSelfMapsBuff MemoryMappingLayout::cached_proc_self_maps_;
    317 StaticSpinMutex MemoryMappingLayout::cache_lock_;  // Linker initialized.
    318 
    319 MemoryMappingLayout::MemoryMappingLayout(bool cache_enabled) {
    320   proc_self_maps_.len =
    321       ReadFileToBuffer("/proc/self/maps", &proc_self_maps_.data,
    322                        &proc_self_maps_.mmaped_size, 1 << 26);
    323   if (cache_enabled) {
    324     if (proc_self_maps_.mmaped_size == 0) {
    325       LoadFromCache();
    326       CHECK_GT(proc_self_maps_.len, 0);
    327     }
    328   } else {
    329     CHECK_GT(proc_self_maps_.mmaped_size, 0);
    330   }
    331   Reset();
    332   // FIXME: in the future we may want to cache the mappings on demand only.
    333   if (cache_enabled)
    334     CacheMemoryMappings();
    335 }
    336 
    337 MemoryMappingLayout::~MemoryMappingLayout() {
    338   // Only unmap the buffer if it is different from the cached one. Otherwise
    339   // it will be unmapped when the cache is refreshed.
    340   if (proc_self_maps_.data != cached_proc_self_maps_.data) {
    341     UnmapOrDie(proc_self_maps_.data, proc_self_maps_.mmaped_size);
    342   }
    343 }
    344 
    345 void MemoryMappingLayout::Reset() {
    346   current_ = proc_self_maps_.data;
    347 }
    348 
    349 // static
    350 void MemoryMappingLayout::CacheMemoryMappings() {
    351   SpinMutexLock l(&cache_lock_);
    352   // Don't invalidate the cache if the mappings are unavailable.
    353   ProcSelfMapsBuff old_proc_self_maps;
    354   old_proc_self_maps = cached_proc_self_maps_;
    355   cached_proc_self_maps_.len =
    356       ReadFileToBuffer("/proc/self/maps", &cached_proc_self_maps_.data,
    357                        &cached_proc_self_maps_.mmaped_size, 1 << 26);
    358   if (cached_proc_self_maps_.mmaped_size == 0) {
    359     cached_proc_self_maps_ = old_proc_self_maps;
    360   } else {
    361     if (old_proc_self_maps.mmaped_size) {
    362       UnmapOrDie(old_proc_self_maps.data,
    363                  old_proc_self_maps.mmaped_size);
    364     }
    365   }
    366 }
    367 
    368 void MemoryMappingLayout::LoadFromCache() {
    369   SpinMutexLock l(&cache_lock_);
    370   if (cached_proc_self_maps_.data) {
    371     proc_self_maps_ = cached_proc_self_maps_;
    372   }
    373 }
    374 
    375 // Parse a hex value in str and update str.
    376 static uptr ParseHex(char **str) {
    377   uptr x = 0;
    378   char *s;
    379   for (s = *str; ; s++) {
    380     char c = *s;
    381     uptr v = 0;
    382     if (c >= '0' && c <= '9')
    383       v = c - '0';
    384     else if (c >= 'a' && c <= 'f')
    385       v = c - 'a' + 10;
    386     else if (c >= 'A' && c <= 'F')
    387       v = c - 'A' + 10;
    388     else
    389       break;
    390     x = x * 16 + v;
    391   }
    392   *str = s;
    393   return x;
    394 }
    395 
    396 static bool IsOneOf(char c, char c1, char c2) {
    397   return c == c1 || c == c2;
    398 }
    399 
    400 static bool IsDecimal(char c) {
    401   return c >= '0' && c <= '9';
    402 }
    403 
    404 bool MemoryMappingLayout::Next(uptr *start, uptr *end, uptr *offset,
    405                                char filename[], uptr filename_size,
    406                                uptr *protection) {
    407   char *last = proc_self_maps_.data + proc_self_maps_.len;
    408   if (current_ >= last) return false;
    409   uptr dummy;
    410   if (!start) start = &dummy;
    411   if (!end) end = &dummy;
    412   if (!offset) offset = &dummy;
    413   char *next_line = (char*)internal_memchr(current_, '\n', last - current_);
    414   if (next_line == 0)
    415     next_line = last;
    416   // Example: 08048000-08056000 r-xp 00000000 03:0c 64593   /foo/bar
    417   *start = ParseHex(&current_);
    418   CHECK_EQ(*current_++, '-');
    419   *end = ParseHex(&current_);
    420   CHECK_EQ(*current_++, ' ');
    421   uptr local_protection = 0;
    422   CHECK(IsOneOf(*current_, '-', 'r'));
    423   if (*current_++ == 'r')
    424     local_protection |= kProtectionRead;
    425   CHECK(IsOneOf(*current_, '-', 'w'));
    426   if (*current_++ == 'w')
    427     local_protection |= kProtectionWrite;
    428   CHECK(IsOneOf(*current_, '-', 'x'));
    429   if (*current_++ == 'x')
    430     local_protection |= kProtectionExecute;
    431   CHECK(IsOneOf(*current_, 's', 'p'));
    432   if (*current_++ == 's')
    433     local_protection |= kProtectionShared;
    434   if (protection) {
    435     *protection = local_protection;
    436   }
    437   CHECK_EQ(*current_++, ' ');
    438   *offset = ParseHex(&current_);
    439   CHECK_EQ(*current_++, ' ');
    440   ParseHex(&current_);
    441   CHECK_EQ(*current_++, ':');
    442   ParseHex(&current_);
    443   CHECK_EQ(*current_++, ' ');
    444   while (IsDecimal(*current_))
    445     current_++;
    446   // Qemu may lack the trailing space.
    447   // http://code.google.com/p/address-sanitizer/issues/detail?id=160
    448   // CHECK_EQ(*current_++, ' ');
    449   // Skip spaces.
    450   while (current_ < next_line && *current_ == ' ')
    451     current_++;
    452   // Fill in the filename.
    453   uptr i = 0;
    454   while (current_ < next_line) {
    455     if (filename && i < filename_size - 1)
    456       filename[i++] = *current_;
    457     current_++;
    458   }
    459   if (filename && i < filename_size)
    460     filename[i] = 0;
    461   current_ = next_line + 1;
    462   return true;
    463 }
    464 
    465 // Gets the object name and the offset by walking MemoryMappingLayout.
    466 bool MemoryMappingLayout::GetObjectNameAndOffset(uptr addr, uptr *offset,
    467                                                  char filename[],
    468                                                  uptr filename_size,
    469                                                  uptr *protection) {
    470   return IterateForObjectNameAndOffset(addr, offset, filename, filename_size,
    471                                        protection);
    472 }
    473 
    474 enum MutexState {
    475   MtxUnlocked = 0,
    476   MtxLocked = 1,
    477   MtxSleeping = 2
    478 };
    479 
    480 BlockingMutex::BlockingMutex(LinkerInitialized) {
    481   CHECK_EQ(owner_, 0);
    482 }
    483 
    484 BlockingMutex::BlockingMutex() {
    485   internal_memset(this, 0, sizeof(*this));
    486 }
    487 
    488 void BlockingMutex::Lock() {
    489   atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
    490   if (atomic_exchange(m, MtxLocked, memory_order_acquire) == MtxUnlocked)
    491     return;
    492   while (atomic_exchange(m, MtxSleeping, memory_order_acquire) != MtxUnlocked)
    493     internal_syscall(__NR_futex, m, FUTEX_WAIT, MtxSleeping, 0, 0, 0);
    494 }
    495 
    496 void BlockingMutex::Unlock() {
    497   atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
    498   u32 v = atomic_exchange(m, MtxUnlocked, memory_order_relaxed);
    499   CHECK_NE(v, MtxUnlocked);
    500   if (v == MtxSleeping)
    501     internal_syscall(__NR_futex, m, FUTEX_WAKE, 1, 0, 0, 0);
    502 }
    503 
    504 void BlockingMutex::CheckLocked() {
    505   atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
    506   CHECK_NE(MtxUnlocked, atomic_load(m, memory_order_relaxed));
    507 }
    508 
    509 // ----------------- sanitizer_linux.h
    510 // The actual size of this structure is specified by d_reclen.
    511 // Note that getdents64 uses a different structure format. We only provide the
    512 // 32-bit syscall here.
    513 struct linux_dirent {
    514   unsigned long      d_ino;
    515   unsigned long      d_off;
    516   unsigned short     d_reclen;
    517   char               d_name[256];
    518 };
    519 
    520 // Syscall wrappers.
    521 uptr internal_ptrace(int request, int pid, void *addr, void *data) {
    522   return internal_syscall(__NR_ptrace, request, pid, addr, data);
    523 }
    524 
    525 uptr internal_waitpid(int pid, int *status, int options) {
    526   return internal_syscall(__NR_wait4, pid, status, options, 0 /* rusage */);
    527 }
    528 
    529 uptr internal_getpid() {
    530   return internal_syscall(__NR_getpid);
    531 }
    532 
    533 uptr internal_getppid() {
    534   return internal_syscall(__NR_getppid);
    535 }
    536 
    537 uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) {
    538   return internal_syscall(__NR_getdents, fd, dirp, count);
    539 }
    540 
    541 uptr internal_lseek(fd_t fd, OFF_T offset, int whence) {
    542   return internal_syscall(__NR_lseek, fd, offset, whence);
    543 }
    544 
    545 uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
    546   return internal_syscall(__NR_prctl, option, arg2, arg3, arg4, arg5);
    547 }
    548 
    549 uptr internal_sigaltstack(const struct sigaltstack *ss,
    550                          struct sigaltstack *oss) {
    551   return internal_syscall(__NR_sigaltstack, ss, oss);
    552 }
    553 
    554 // ThreadLister implementation.
    555 ThreadLister::ThreadLister(int pid)
    556   : pid_(pid),
    557     descriptor_(-1),
    558     buffer_(4096),
    559     error_(true),
    560     entry_((struct linux_dirent *)buffer_.data()),
    561     bytes_read_(0) {
    562   char task_directory_path[80];
    563   internal_snprintf(task_directory_path, sizeof(task_directory_path),
    564                     "/proc/%d/task/", pid);
    565   uptr openrv = internal_open(task_directory_path, O_RDONLY | O_DIRECTORY);
    566   if (internal_iserror(openrv)) {
    567     error_ = true;
    568     Report("Can't open /proc/%d/task for reading.\n", pid);
    569   } else {
    570     error_ = false;
    571     descriptor_ = openrv;
    572   }
    573 }
    574 
    575 int ThreadLister::GetNextTID() {
    576   int tid = -1;
    577   do {
    578     if (error_)
    579       return -1;
    580     if ((char *)entry_ >= &buffer_[bytes_read_] && !GetDirectoryEntries())
    581       return -1;
    582     if (entry_->d_ino != 0 && entry_->d_name[0] >= '0' &&
    583         entry_->d_name[0] <= '9') {
    584       // Found a valid tid.
    585       tid = (int)internal_atoll(entry_->d_name);
    586     }
    587     entry_ = (struct linux_dirent *)(((char *)entry_) + entry_->d_reclen);
    588   } while (tid < 0);
    589   return tid;
    590 }
    591 
    592 void ThreadLister::Reset() {
    593   if (error_ || descriptor_ < 0)
    594     return;
    595   internal_lseek(descriptor_, 0, SEEK_SET);
    596 }
    597 
    598 ThreadLister::~ThreadLister() {
    599   if (descriptor_ >= 0)
    600     internal_close(descriptor_);
    601 }
    602 
    603 bool ThreadLister::error() { return error_; }
    604 
    605 bool ThreadLister::GetDirectoryEntries() {
    606   CHECK_GE(descriptor_, 0);
    607   CHECK_NE(error_, true);
    608   bytes_read_ = internal_getdents(descriptor_,
    609                                   (struct linux_dirent *)buffer_.data(),
    610                                   buffer_.size());
    611   if (internal_iserror(bytes_read_)) {
    612     Report("Can't read directory entries from /proc/%d/task.\n", pid_);
    613     error_ = true;
    614     return false;
    615   } else if (bytes_read_ == 0) {
    616     return false;
    617   }
    618   entry_ = (struct linux_dirent *)buffer_.data();
    619   return true;
    620 }
    621 
    622 uptr GetPageSize() {
    623 #if defined(__x86_64__) || defined(__i386__)
    624   return EXEC_PAGESIZE;
    625 #else
    626   return sysconf(_SC_PAGESIZE);  // EXEC_PAGESIZE may not be trustworthy.
    627 #endif
    628 }
    629 
    630 // Match full names of the form /path/to/base_name{-,.}*
    631 bool LibraryNameIs(const char *full_name, const char *base_name) {
    632   const char *name = full_name;
    633   // Strip path.
    634   while (*name != '\0') name++;
    635   while (name > full_name && *name != '/') name--;
    636   if (*name == '/') name++;
    637   uptr base_name_length = internal_strlen(base_name);
    638   if (internal_strncmp(name, base_name, base_name_length)) return false;
    639   return (name[base_name_length] == '-' || name[base_name_length] == '.');
    640 }
    641 
    642 #if !SANITIZER_ANDROID
    643 // Call cb for each region mapped by map.
    644 void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr)) {
    645   typedef ElfW(Phdr) Elf_Phdr;
    646   typedef ElfW(Ehdr) Elf_Ehdr;
    647   char *base = (char *)map->l_addr;
    648   Elf_Ehdr *ehdr = (Elf_Ehdr *)base;
    649   char *phdrs = base + ehdr->e_phoff;
    650   char *phdrs_end = phdrs + ehdr->e_phnum * ehdr->e_phentsize;
    651 
    652   // Find the segment with the minimum base so we can "relocate" the p_vaddr
    653   // fields.  Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
    654   // objects have a non-zero base.
    655   uptr preferred_base = (uptr)-1;
    656   for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
    657     Elf_Phdr *phdr = (Elf_Phdr *)iter;
    658     if (phdr->p_type == PT_LOAD && preferred_base > (uptr)phdr->p_vaddr)
    659       preferred_base = (uptr)phdr->p_vaddr;
    660   }
    661 
    662   // Compute the delta from the real base to get a relocation delta.
    663   sptr delta = (uptr)base - preferred_base;
    664   // Now we can figure out what the loader really mapped.
    665   for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
    666     Elf_Phdr *phdr = (Elf_Phdr *)iter;
    667     if (phdr->p_type == PT_LOAD) {
    668       uptr seg_start = phdr->p_vaddr + delta;
    669       uptr seg_end = seg_start + phdr->p_memsz;
    670       // None of these values are aligned.  We consider the ragged edges of the
    671       // load command as defined, since they are mapped from the file.
    672       seg_start = RoundDownTo(seg_start, GetPageSizeCached());
    673       seg_end = RoundUpTo(seg_end, GetPageSizeCached());
    674       cb((void *)seg_start, seg_end - seg_start);
    675     }
    676   }
    677 }
    678 #endif
    679 
    680 }  // namespace __sanitizer
    681 
    682 #endif  // SANITIZER_LINUX
    683