1//===-- sanitizer_linux_libcdep.cc ----------------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is shared between AddressSanitizer and ThreadSanitizer
11// run-time libraries and implements linux-specific functions from
12// sanitizer_libc.h.
13//===----------------------------------------------------------------------===//
14
15#include "sanitizer_platform.h"
16
17#if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD ||                \
18    SANITIZER_OPENBSD || SANITIZER_SOLARIS
19
20#include "sanitizer_allocator_internal.h"
21#include "sanitizer_atomic.h"
22#include "sanitizer_common.h"
23#include "sanitizer_file.h"
24#include "sanitizer_flags.h"
25#include "sanitizer_freebsd.h"
26#include "sanitizer_getauxval.h"
27#include "sanitizer_linux.h"
28#include "sanitizer_placement_new.h"
29#include "sanitizer_procmaps.h"
30
31#if SANITIZER_NETBSD
32#define _RTLD_SOURCE  // Fast LWP private pointer getters in ThreadSelfTlsTcb().
33#endif
34
35#include <dlfcn.h>  // for dlsym()
36#include <link.h>
37#include <pthread.h>
38#include <signal.h>
39#include <sys/resource.h>
40#include <syslog.h>
41
42#if SANITIZER_FREEBSD
43#include <pthread_np.h>
44#include <osreldate.h>
45#include <sys/sysctl.h>
46#define pthread_getattr_np pthread_attr_get_np
47#endif
48
49#if SANITIZER_OPENBSD
50#include <pthread_np.h>
51#include <sys/sysctl.h>
52#endif
53
54#if SANITIZER_NETBSD
55#include <sys/sysctl.h>
56#include <sys/tls.h>
57#endif
58
59#if SANITIZER_SOLARIS
60#include <thread.h>
61#endif
62
63#if SANITIZER_ANDROID
64#include <android/api-level.h>
65#if !defined(CPU_COUNT) && !defined(__aarch64__)
66#include <dirent.h>
67#include <fcntl.h>
68struct __sanitizer::linux_dirent {
69  long           d_ino;
70  off_t          d_off;
71  unsigned short d_reclen;
72  char           d_name[];
73};
74#endif
75#endif
76
77#if !SANITIZER_ANDROID
78#include <elf.h>
79#include <unistd.h>
80#endif
81
82namespace __sanitizer {
83
84SANITIZER_WEAK_ATTRIBUTE int
85real_sigaction(int signum, const void *act, void *oldact);
86
87int internal_sigaction(int signum, const void *act, void *oldact) {
88#if !SANITIZER_GO
89  if (&real_sigaction)
90    return real_sigaction(signum, act, oldact);
91#endif
92  return sigaction(signum, (const struct sigaction *)act,
93                   (struct sigaction *)oldact);
94}
95
96void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
97                                uptr *stack_bottom) {
98  CHECK(stack_top);
99  CHECK(stack_bottom);
100  if (at_initialization) {
101    // This is the main thread. Libpthread may not be initialized yet.
102    struct rlimit rl;
103    CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
104
105    // Find the mapping that contains a stack variable.
106    MemoryMappingLayout proc_maps(/*cache_enabled*/true);
107    if (proc_maps.Error()) {
108      *stack_top = *stack_bottom = 0;
109      return;
110    }
111    MemoryMappedSegment segment;
112    uptr prev_end = 0;
113    while (proc_maps.Next(&segment)) {
114      if ((uptr)&rl < segment.end) break;
115      prev_end = segment.end;
116    }
117    CHECK((uptr)&rl >= segment.start && (uptr)&rl < segment.end);
118
119    // Get stacksize from rlimit, but clip it so that it does not overlap
120    // with other mappings.
121    uptr stacksize = rl.rlim_cur;
122    if (stacksize > segment.end - prev_end) stacksize = segment.end - prev_end;
123    // When running with unlimited stack size, we still want to set some limit.
124    // The unlimited stack size is caused by 'ulimit -s unlimited'.
125    // Also, for some reason, GNU make spawns subprocesses with unlimited stack.
126    if (stacksize > kMaxThreadStackSize)
127      stacksize = kMaxThreadStackSize;
128    *stack_top = segment.end;
129    *stack_bottom = segment.end - stacksize;
130    return;
131  }
132  uptr stacksize = 0;
133  void *stackaddr = nullptr;
134#if SANITIZER_SOLARIS
135  stack_t ss;
136  CHECK_EQ(thr_stksegment(&ss), 0);
137  stacksize = ss.ss_size;
138  stackaddr = (char *)ss.ss_sp - stacksize;
139#elif SANITIZER_OPENBSD
140  stack_t sattr;
141  CHECK_EQ(pthread_stackseg_np(pthread_self(), &sattr), 0);
142  stackaddr = sattr.ss_sp;
143  stacksize = sattr.ss_size;
144#else  // !SANITIZER_SOLARIS
145  pthread_attr_t attr;
146  pthread_attr_init(&attr);
147  CHECK_EQ(pthread_getattr_np(pthread_self(), &attr), 0);
148  my_pthread_attr_getstack(&attr, &stackaddr, &stacksize);
149  pthread_attr_destroy(&attr);
150#endif // SANITIZER_SOLARIS
151
152  *stack_top = (uptr)stackaddr + stacksize;
153  *stack_bottom = (uptr)stackaddr;
154}
155
156#if !SANITIZER_GO
157bool SetEnv(const char *name, const char *value) {
158  void *f = dlsym(RTLD_NEXT, "setenv");
159  if (!f)
160    return false;
161  typedef int(*setenv_ft)(const char *name, const char *value, int overwrite);
162  setenv_ft setenv_f;
163  CHECK_EQ(sizeof(setenv_f), sizeof(f));
164  internal_memcpy(&setenv_f, &f, sizeof(f));
165  return setenv_f(name, value, 1) == 0;
166}
167#endif
168
169__attribute__((unused)) static bool GetLibcVersion(int *major, int *minor,
170                                                   int *patch) {
171#ifdef _CS_GNU_LIBC_VERSION
172  char buf[64];
173  uptr len = confstr(_CS_GNU_LIBC_VERSION, buf, sizeof(buf));
174  if (len >= sizeof(buf))
175    return false;
176  buf[len] = 0;
177  static const char kGLibC[] = "glibc ";
178  if (internal_strncmp(buf, kGLibC, sizeof(kGLibC) - 1) != 0)
179    return false;
180  const char *p = buf + sizeof(kGLibC) - 1;
181  *major = internal_simple_strtoll(p, &p, 10);
182  *minor = (*p == '.') ? internal_simple_strtoll(p + 1, &p, 10) : 0;
183  *patch = (*p == '.') ? internal_simple_strtoll(p + 1, &p, 10) : 0;
184  return true;
185#else
186  return false;
187#endif
188}
189
190#if !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO &&               \
191    !SANITIZER_NETBSD && !SANITIZER_OPENBSD && !SANITIZER_SOLARIS
192static uptr g_tls_size;
193
194#ifdef __i386__
195# ifndef __GLIBC_PREREQ
196#  define CHECK_GET_TLS_STATIC_INFO_VERSION 1
197# else
198#  define CHECK_GET_TLS_STATIC_INFO_VERSION (!__GLIBC_PREREQ(2, 27))
199# endif
200#else
201# define CHECK_GET_TLS_STATIC_INFO_VERSION 0
202#endif
203
204#if CHECK_GET_TLS_STATIC_INFO_VERSION
205# define DL_INTERNAL_FUNCTION __attribute__((regparm(3), stdcall))
206#else
207# define DL_INTERNAL_FUNCTION
208#endif
209
210namespace {
211struct GetTlsStaticInfoCall {
212  typedef void (*get_tls_func)(size_t*, size_t*);
213};
214struct GetTlsStaticInfoRegparmCall {
215  typedef void (*get_tls_func)(size_t*, size_t*) DL_INTERNAL_FUNCTION;
216};
217
218template <typename T>
219void CallGetTls(void* ptr, size_t* size, size_t* align) {
220  typename T::get_tls_func get_tls;
221  CHECK_EQ(sizeof(get_tls), sizeof(ptr));
222  internal_memcpy(&get_tls, &ptr, sizeof(ptr));
223  CHECK_NE(get_tls, 0);
224  get_tls(size, align);
225}
226
227bool CmpLibcVersion(int major, int minor, int patch) {
228  int ma;
229  int mi;
230  int pa;
231  if (!GetLibcVersion(&ma, &mi, &pa))
232    return false;
233  if (ma > major)
234    return true;
235  if (ma < major)
236    return false;
237  if (mi > minor)
238    return true;
239  if (mi < minor)
240    return false;
241  return pa >= patch;
242}
243
244}  // namespace
245
246void InitTlsSize() {
247  // all current supported platforms have 16 bytes stack alignment
248  const size_t kStackAlign = 16;
249  void *get_tls_static_info_ptr = dlsym(RTLD_NEXT, "_dl_get_tls_static_info");
250  size_t tls_size = 0;
251  size_t tls_align = 0;
252  // On i?86, _dl_get_tls_static_info used to be internal_function, i.e.
253  // __attribute__((regparm(3), stdcall)) before glibc 2.27 and is normal
254  // function in 2.27 and later.
255  if (CHECK_GET_TLS_STATIC_INFO_VERSION && !CmpLibcVersion(2, 27, 0))
256    CallGetTls<GetTlsStaticInfoRegparmCall>(get_tls_static_info_ptr,
257                                            &tls_size, &tls_align);
258  else
259    CallGetTls<GetTlsStaticInfoCall>(get_tls_static_info_ptr,
260                                     &tls_size, &tls_align);
261  if (tls_align < kStackAlign)
262    tls_align = kStackAlign;
263  g_tls_size = RoundUpTo(tls_size, tls_align);
264}
265#else
266void InitTlsSize() { }
267#endif  // !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO &&
268        // !SANITIZER_NETBSD && !SANITIZER_SOLARIS
269
270#if (defined(__x86_64__) || defined(__i386__) || defined(__mips__) ||          \
271     defined(__aarch64__) || defined(__powerpc64__) || defined(__s390__) ||    \
272     defined(__arm__)) &&                                                      \
273    SANITIZER_LINUX && !SANITIZER_ANDROID
274// sizeof(struct pthread) from glibc.
275static atomic_uintptr_t thread_descriptor_size;
276
277uptr ThreadDescriptorSize() {
278  uptr val = atomic_load_relaxed(&thread_descriptor_size);
279  if (val)
280    return val;
281#if defined(__x86_64__) || defined(__i386__) || defined(__arm__)
282  int major;
283  int minor;
284  int patch;
285  if (GetLibcVersion(&major, &minor, &patch) && major == 2) {
286    /* sizeof(struct pthread) values from various glibc versions.  */
287    if (SANITIZER_X32)
288      val = 1728; // Assume only one particular version for x32.
289    // For ARM sizeof(struct pthread) changed in Glibc 2.23.
290    else if (SANITIZER_ARM)
291      val = minor <= 22 ? 1120 : 1216;
292    else if (minor <= 3)
293      val = FIRST_32_SECOND_64(1104, 1696);
294    else if (minor == 4)
295      val = FIRST_32_SECOND_64(1120, 1728);
296    else if (minor == 5)
297      val = FIRST_32_SECOND_64(1136, 1728);
298    else if (minor <= 9)
299      val = FIRST_32_SECOND_64(1136, 1712);
300    else if (minor == 10)
301      val = FIRST_32_SECOND_64(1168, 1776);
302    else if (minor == 11 || (minor == 12 && patch == 1))
303      val = FIRST_32_SECOND_64(1168, 2288);
304    else if (minor <= 14)
305      val = FIRST_32_SECOND_64(1168, 2304);
306    else
307      val = FIRST_32_SECOND_64(1216, 2304);
308  }
309#elif defined(__mips__)
310  // TODO(sagarthakur): add more values as per different glibc versions.
311  val = FIRST_32_SECOND_64(1152, 1776);
312#elif defined(__aarch64__)
313  // The sizeof (struct pthread) is the same from GLIBC 2.17 to 2.22.
314  val = 1776;
315#elif defined(__powerpc64__)
316  val = 1776; // from glibc.ppc64le 2.20-8.fc21
317#elif defined(__s390__)
318  val = FIRST_32_SECOND_64(1152, 1776); // valid for glibc 2.22
319#endif
320  if (val)
321    atomic_store_relaxed(&thread_descriptor_size, val);
322  return val;
323}
324
325// The offset at which pointer to self is located in the thread descriptor.
326const uptr kThreadSelfOffset = FIRST_32_SECOND_64(8, 16);
327
328uptr ThreadSelfOffset() {
329  return kThreadSelfOffset;
330}
331
332#if defined(__mips__) || defined(__powerpc64__)
333// TlsPreTcbSize includes size of struct pthread_descr and size of tcb
334// head structure. It lies before the static tls blocks.
335static uptr TlsPreTcbSize() {
336# if defined(__mips__)
337  const uptr kTcbHead = 16; // sizeof (tcbhead_t)
338# elif defined(__powerpc64__)
339  const uptr kTcbHead = 88; // sizeof (tcbhead_t)
340# endif
341  const uptr kTlsAlign = 16;
342  const uptr kTlsPreTcbSize =
343      RoundUpTo(ThreadDescriptorSize() + kTcbHead, kTlsAlign);
344  return kTlsPreTcbSize;
345}
346#endif
347
348uptr ThreadSelf() {
349  uptr descr_addr;
350# if defined(__i386__)
351  asm("mov %%gs:%c1,%0" : "=r"(descr_addr) : "i"(kThreadSelfOffset));
352# elif defined(__x86_64__)
353  asm("mov %%fs:%c1,%0" : "=r"(descr_addr) : "i"(kThreadSelfOffset));
354# elif defined(__mips__)
355  // MIPS uses TLS variant I. The thread pointer (in hardware register $29)
356  // points to the end of the TCB + 0x7000. The pthread_descr structure is
357  // immediately in front of the TCB. TlsPreTcbSize() includes the size of the
358  // TCB and the size of pthread_descr.
359  const uptr kTlsTcbOffset = 0x7000;
360  uptr thread_pointer;
361  asm volatile(".set push;\
362                .set mips64r2;\
363                rdhwr %0,$29;\
364                .set pop" : "=r" (thread_pointer));
365  descr_addr = thread_pointer - kTlsTcbOffset - TlsPreTcbSize();
366# elif defined(__aarch64__) || defined(__arm__)
367  descr_addr = reinterpret_cast<uptr>(__builtin_thread_pointer()) -
368                                      ThreadDescriptorSize();
369# elif defined(__s390__)
370  descr_addr = reinterpret_cast<uptr>(__builtin_thread_pointer());
371# elif defined(__powerpc64__)
372  // PPC64LE uses TLS variant I. The thread pointer (in GPR 13)
373  // points to the end of the TCB + 0x7000. The pthread_descr structure is
374  // immediately in front of the TCB. TlsPreTcbSize() includes the size of the
375  // TCB and the size of pthread_descr.
376  const uptr kTlsTcbOffset = 0x7000;
377  uptr thread_pointer;
378  asm("addi %0,13,%1" : "=r"(thread_pointer) : "I"(-kTlsTcbOffset));
379  descr_addr = thread_pointer - TlsPreTcbSize();
380# else
381#  error "unsupported CPU arch"
382# endif
383  return descr_addr;
384}
385#endif  // (x86_64 || i386 || MIPS) && SANITIZER_LINUX
386
387#if SANITIZER_FREEBSD
388static void **ThreadSelfSegbase() {
389  void **segbase = 0;
390# if defined(__i386__)
391  // sysarch(I386_GET_GSBASE, segbase);
392  __asm __volatile("mov %%gs:0, %0" : "=r" (segbase));
393# elif defined(__x86_64__)
394  // sysarch(AMD64_GET_FSBASE, segbase);
395  __asm __volatile("movq %%fs:0, %0" : "=r" (segbase));
396# else
397#  error "unsupported CPU arch"
398# endif
399  return segbase;
400}
401
402uptr ThreadSelf() {
403  return (uptr)ThreadSelfSegbase()[2];
404}
405#endif  // SANITIZER_FREEBSD
406
407#if SANITIZER_NETBSD
408static struct tls_tcb * ThreadSelfTlsTcb() {
409  struct tls_tcb * tcb;
410# ifdef __HAVE___LWP_GETTCB_FAST
411  tcb = (struct tls_tcb *)__lwp_gettcb_fast();
412# elif defined(__HAVE___LWP_GETPRIVATE_FAST)
413  tcb = (struct tls_tcb *)__lwp_getprivate_fast();
414# endif
415  return tcb;
416}
417
418uptr ThreadSelf() {
419  return (uptr)ThreadSelfTlsTcb()->tcb_pthread;
420}
421
422int GetSizeFromHdr(struct dl_phdr_info *info, size_t size, void *data) {
423  const Elf_Phdr *hdr = info->dlpi_phdr;
424  const Elf_Phdr *last_hdr = hdr + info->dlpi_phnum;
425
426  for (; hdr != last_hdr; ++hdr) {
427    if (hdr->p_type == PT_TLS && info->dlpi_tls_modid == 1) {
428      *(uptr*)data = hdr->p_memsz;
429      break;
430    }
431  }
432  return 0;
433}
434#endif  // SANITIZER_NETBSD
435
436#if !SANITIZER_GO
437static void GetTls(uptr *addr, uptr *size) {
438#if SANITIZER_LINUX && !SANITIZER_ANDROID
439# if defined(__x86_64__) || defined(__i386__) || defined(__s390__)
440  *addr = ThreadSelf();
441  *size = GetTlsSize();
442  *addr -= *size;
443  *addr += ThreadDescriptorSize();
444# elif defined(__mips__) || defined(__aarch64__) || defined(__powerpc64__) \
445    || defined(__arm__)
446  *addr = ThreadSelf();
447  *size = GetTlsSize();
448# else
449  *addr = 0;
450  *size = 0;
451# endif
452#elif SANITIZER_FREEBSD
453  void** segbase = ThreadSelfSegbase();
454  *addr = 0;
455  *size = 0;
456  if (segbase != 0) {
457    // tcbalign = 16
458    // tls_size = round(tls_static_space, tcbalign);
459    // dtv = segbase[1];
460    // dtv[2] = segbase - tls_static_space;
461    void **dtv = (void**) segbase[1];
462    *addr = (uptr) dtv[2];
463    *size = (*addr == 0) ? 0 : ((uptr) segbase[0] - (uptr) dtv[2]);
464  }
465#elif SANITIZER_NETBSD
466  struct tls_tcb * const tcb = ThreadSelfTlsTcb();
467  *addr = 0;
468  *size = 0;
469  if (tcb != 0) {
470    // Find size (p_memsz) of dlpi_tls_modid 1 (TLS block of the main program).
471    // ld.elf_so hardcodes the index 1.
472    dl_iterate_phdr(GetSizeFromHdr, size);
473
474    if (*size != 0) {
475      // The block has been found and tcb_dtv[1] contains the base address
476      *addr = (uptr)tcb->tcb_dtv[1];
477    }
478  }
479#elif SANITIZER_OPENBSD
480  *addr = 0;
481  *size = 0;
482#elif SANITIZER_ANDROID
483  *addr = 0;
484  *size = 0;
485#elif SANITIZER_SOLARIS
486  // FIXME
487  *addr = 0;
488  *size = 0;
489#else
490# error "Unknown OS"
491#endif
492}
493#endif
494
495#if !SANITIZER_GO
496uptr GetTlsSize() {
497#if SANITIZER_FREEBSD || SANITIZER_ANDROID || SANITIZER_NETBSD ||              \
498    SANITIZER_OPENBSD || SANITIZER_SOLARIS
499  uptr addr, size;
500  GetTls(&addr, &size);
501  return size;
502#elif defined(__mips__) || defined(__powerpc64__)
503  return RoundUpTo(g_tls_size + TlsPreTcbSize(), 16);
504#else
505  return g_tls_size;
506#endif
507}
508#endif
509
510void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
511                          uptr *tls_addr, uptr *tls_size) {
512#if SANITIZER_GO
513  // Stub implementation for Go.
514  *stk_addr = *stk_size = *tls_addr = *tls_size = 0;
515#else
516  GetTls(tls_addr, tls_size);
517
518  uptr stack_top, stack_bottom;
519  GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
520  *stk_addr = stack_bottom;
521  *stk_size = stack_top - stack_bottom;
522
523  if (!main) {
524    // If stack and tls intersect, make them non-intersecting.
525    if (*tls_addr > *stk_addr && *tls_addr < *stk_addr + *stk_size) {
526      CHECK_GT(*tls_addr + *tls_size, *stk_addr);
527      CHECK_LE(*tls_addr + *tls_size, *stk_addr + *stk_size);
528      *stk_size -= *tls_size;
529      *tls_addr = *stk_addr + *stk_size;
530    }
531  }
532#endif
533}
534
535#if !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
536typedef ElfW(Phdr) Elf_Phdr;
537#elif SANITIZER_WORDSIZE == 32 && __FreeBSD_version <= 902001 // v9.2
538#define Elf_Phdr XElf32_Phdr
539#define dl_phdr_info xdl_phdr_info
540#define dl_iterate_phdr(c, b) xdl_iterate_phdr((c), (b))
541#endif // !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
542
543struct DlIteratePhdrData {
544  InternalMmapVectorNoCtor<LoadedModule> *modules;
545  bool first;
546};
547
548static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
549  DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
550  InternalScopedString module_name(kMaxPathLength);
551  if (data->first) {
552    data->first = false;
553    // First module is the binary itself.
554    ReadBinaryNameCached(module_name.data(), module_name.size());
555  } else if (info->dlpi_name) {
556    module_name.append("%s", info->dlpi_name);
557  }
558  if (module_name[0] == '\0')
559    return 0;
560  LoadedModule cur_module;
561  cur_module.set(module_name.data(), info->dlpi_addr);
562  for (int i = 0; i < (int)info->dlpi_phnum; i++) {
563    const Elf_Phdr *phdr = &info->dlpi_phdr[i];
564    if (phdr->p_type == PT_LOAD) {
565      uptr cur_beg = info->dlpi_addr + phdr->p_vaddr;
566      uptr cur_end = cur_beg + phdr->p_memsz;
567      bool executable = phdr->p_flags & PF_X;
568      bool writable = phdr->p_flags & PF_W;
569      cur_module.addAddressRange(cur_beg, cur_end, executable,
570                                 writable);
571    }
572  }
573  data->modules->push_back(cur_module);
574  return 0;
575}
576
577#if SANITIZER_ANDROID && __ANDROID_API__ < 21
578extern "C" __attribute__((weak)) int dl_iterate_phdr(
579    int (*)(struct dl_phdr_info *, size_t, void *), void *);
580#endif
581
582static bool requiresProcmaps() {
583#if SANITIZER_ANDROID && __ANDROID_API__ <= 22
584  // Fall back to /proc/maps if dl_iterate_phdr is unavailable or broken.
585  // The runtime check allows the same library to work with
586  // both K and L (and future) Android releases.
587  return AndroidGetApiLevel() <= ANDROID_LOLLIPOP_MR1;
588#else
589  return false;
590#endif
591}
592
593static void procmapsInit(InternalMmapVectorNoCtor<LoadedModule> *modules) {
594  MemoryMappingLayout memory_mapping(/*cache_enabled*/true);
595  memory_mapping.DumpListOfModules(modules);
596}
597
598void ListOfModules::init() {
599  clearOrInit();
600  if (requiresProcmaps()) {
601    procmapsInit(&modules_);
602  } else {
603    DlIteratePhdrData data = {&modules_, true};
604    dl_iterate_phdr(dl_iterate_phdr_cb, &data);
605  }
606}
607
608// When a custom loader is used, dl_iterate_phdr may not contain the full
609// list of modules. Allow callers to fall back to using procmaps.
610void ListOfModules::fallbackInit() {
611  if (!requiresProcmaps()) {
612    clearOrInit();
613    procmapsInit(&modules_);
614  } else {
615    clear();
616  }
617}
618
619// getrusage does not give us the current RSS, only the max RSS.
620// Still, this is better than nothing if /proc/self/statm is not available
621// for some reason, e.g. due to a sandbox.
622static uptr GetRSSFromGetrusage() {
623  struct rusage usage;
624  if (getrusage(RUSAGE_SELF, &usage))  // Failed, probably due to a sandbox.
625    return 0;
626  return usage.ru_maxrss << 10;  // ru_maxrss is in Kb.
627}
628
629uptr GetRSS() {
630  if (!common_flags()->can_use_proc_maps_statm)
631    return GetRSSFromGetrusage();
632  fd_t fd = OpenFile("/proc/self/statm", RdOnly);
633  if (fd == kInvalidFd)
634    return GetRSSFromGetrusage();
635  char buf[64];
636  uptr len = internal_read(fd, buf, sizeof(buf) - 1);
637  internal_close(fd);
638  if ((sptr)len <= 0)
639    return 0;
640  buf[len] = 0;
641  // The format of the file is:
642  // 1084 89 69 11 0 79 0
643  // We need the second number which is RSS in pages.
644  char *pos = buf;
645  // Skip the first number.
646  while (*pos >= '0' && *pos <= '9')
647    pos++;
648  // Skip whitespaces.
649  while (!(*pos >= '0' && *pos <= '9') && *pos != 0)
650    pos++;
651  // Read the number.
652  uptr rss = 0;
653  while (*pos >= '0' && *pos <= '9')
654    rss = rss * 10 + *pos++ - '0';
655  return rss * GetPageSizeCached();
656}
657
658// sysconf(_SC_NPROCESSORS_{CONF,ONLN}) cannot be used on most platforms as
659// they allocate memory.
660u32 GetNumberOfCPUs() {
661#if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD
662  u32 ncpu;
663  int req[2];
664  uptr len = sizeof(ncpu);
665  req[0] = CTL_HW;
666  req[1] = HW_NCPU;
667  CHECK_EQ(internal_sysctl(req, 2, &ncpu, &len, NULL, 0), 0);
668  return ncpu;
669#elif SANITIZER_ANDROID && !defined(CPU_COUNT) && !defined(__aarch64__)
670  // Fall back to /sys/devices/system/cpu on Android when cpu_set_t doesn't
671  // exist in sched.h. That is the case for toolchains generated with older
672  // NDKs.
673  // This code doesn't work on AArch64 because internal_getdents makes use of
674  // the 64bit getdents syscall, but cpu_set_t seems to always exist on AArch64.
675  uptr fd = internal_open("/sys/devices/system/cpu", O_RDONLY | O_DIRECTORY);
676  if (internal_iserror(fd))
677    return 0;
678  InternalMmapVector<u8> buffer(4096);
679  uptr bytes_read = buffer.size();
680  uptr n_cpus = 0;
681  u8 *d_type;
682  struct linux_dirent *entry = (struct linux_dirent *)&buffer[bytes_read];
683  while (true) {
684    if ((u8 *)entry >= &buffer[bytes_read]) {
685      bytes_read = internal_getdents(fd, (struct linux_dirent *)buffer.data(),
686                                     buffer.size());
687      if (internal_iserror(bytes_read) || !bytes_read)
688        break;
689      entry = (struct linux_dirent *)buffer.data();
690    }
691    d_type = (u8 *)entry + entry->d_reclen - 1;
692    if (d_type >= &buffer[bytes_read] ||
693        (u8 *)&entry->d_name[3] >= &buffer[bytes_read])
694      break;
695    if (entry->d_ino != 0 && *d_type == DT_DIR) {
696      if (entry->d_name[0] == 'c' && entry->d_name[1] == 'p' &&
697          entry->d_name[2] == 'u' &&
698          entry->d_name[3] >= '0' && entry->d_name[3] <= '9')
699        n_cpus++;
700    }
701    entry = (struct linux_dirent *)(((u8 *)entry) + entry->d_reclen);
702  }
703  internal_close(fd);
704  return n_cpus;
705#elif SANITIZER_SOLARIS
706  return sysconf(_SC_NPROCESSORS_ONLN);
707#else
708  cpu_set_t CPUs;
709  CHECK_EQ(sched_getaffinity(0, sizeof(cpu_set_t), &CPUs), 0);
710  return CPU_COUNT(&CPUs);
711#endif
712}
713
714#if SANITIZER_LINUX
715
716# if SANITIZER_ANDROID
717static atomic_uint8_t android_log_initialized;
718
719void AndroidLogInit() {
720  openlog(GetProcessName(), 0, LOG_USER);
721  atomic_store(&android_log_initialized, 1, memory_order_release);
722}
723
724static bool ShouldLogAfterPrintf() {
725  return atomic_load(&android_log_initialized, memory_order_acquire);
726}
727
728extern "C" SANITIZER_WEAK_ATTRIBUTE
729int async_safe_write_log(int pri, const char* tag, const char* msg);
730extern "C" SANITIZER_WEAK_ATTRIBUTE
731int __android_log_write(int prio, const char* tag, const char* msg);
732
733// ANDROID_LOG_INFO is 4, but can't be resolved at runtime.
734#define SANITIZER_ANDROID_LOG_INFO 4
735
736// async_safe_write_log is a new public version of __libc_write_log that is
737// used behind syslog. It is preferable to syslog as it will not do any dynamic
738// memory allocation or formatting.
739// If the function is not available, syslog is preferred for L+ (it was broken
740// pre-L) as __android_log_write triggers a racey behavior with the strncpy
741// interceptor. Fallback to __android_log_write pre-L.
742void WriteOneLineToSyslog(const char *s) {
743  if (&async_safe_write_log) {
744    async_safe_write_log(SANITIZER_ANDROID_LOG_INFO, GetProcessName(), s);
745  } else if (AndroidGetApiLevel() > ANDROID_KITKAT) {
746    syslog(LOG_INFO, "%s", s);
747  } else {
748    CHECK(&__android_log_write);
749    __android_log_write(SANITIZER_ANDROID_LOG_INFO, nullptr, s);
750  }
751}
752
753extern "C" SANITIZER_WEAK_ATTRIBUTE
754void android_set_abort_message(const char *);
755
756void SetAbortMessage(const char *str) {
757  if (&android_set_abort_message)
758    android_set_abort_message(str);
759}
760# else
761void AndroidLogInit() {}
762
763static bool ShouldLogAfterPrintf() { return true; }
764
765void WriteOneLineToSyslog(const char *s) { syslog(LOG_INFO, "%s", s); }
766
767void SetAbortMessage(const char *str) {}
768# endif  // SANITIZER_ANDROID
769
770void LogMessageOnPrintf(const char *str) {
771  if (common_flags()->log_to_syslog && ShouldLogAfterPrintf())
772    WriteToSyslog(str);
773}
774
775#endif  // SANITIZER_LINUX
776
777#if SANITIZER_LINUX && !SANITIZER_GO
778// glibc crashes when using clock_gettime from a preinit_array function as the
779// vDSO function pointers haven't been initialized yet. __progname is
780// initialized after the vDSO function pointers, so if it exists, is not null
781// and is not empty, we can use clock_gettime.
782extern "C" SANITIZER_WEAK_ATTRIBUTE char *__progname;
783INLINE bool CanUseVDSO() {
784  // Bionic is safe, it checks for the vDSO function pointers to be initialized.
785  if (SANITIZER_ANDROID)
786    return true;
787  if (&__progname && __progname && *__progname)
788    return true;
789  return false;
790}
791
792// MonotonicNanoTime is a timing function that can leverage the vDSO by calling
793// clock_gettime. real_clock_gettime only exists if clock_gettime is
794// intercepted, so define it weakly and use it if available.
795extern "C" SANITIZER_WEAK_ATTRIBUTE
796int real_clock_gettime(u32 clk_id, void *tp);
797u64 MonotonicNanoTime() {
798  timespec ts;
799  if (CanUseVDSO()) {
800    if (&real_clock_gettime)
801      real_clock_gettime(CLOCK_MONOTONIC, &ts);
802    else
803      clock_gettime(CLOCK_MONOTONIC, &ts);
804  } else {
805    internal_clock_gettime(CLOCK_MONOTONIC, &ts);
806  }
807  return (u64)ts.tv_sec * (1000ULL * 1000 * 1000) + ts.tv_nsec;
808}
809#else
810// Non-Linux & Go always use the syscall.
811u64 MonotonicNanoTime() {
812  timespec ts;
813  internal_clock_gettime(CLOCK_MONOTONIC, &ts);
814  return (u64)ts.tv_sec * (1000ULL * 1000 * 1000) + ts.tv_nsec;
815}
816#endif  // SANITIZER_LINUX && !SANITIZER_GO
817
818#if !SANITIZER_OPENBSD
819void ReExec() {
820  const char *pathname = "/proc/self/exe";
821
822#if SANITIZER_NETBSD
823  static const int name[] = {
824      CTL_KERN,
825      KERN_PROC_ARGS,
826      -1,
827      KERN_PROC_PATHNAME,
828  };
829  char path[400];
830  uptr len;
831
832  len = sizeof(path);
833  if (internal_sysctl(name, ARRAY_SIZE(name), path, &len, NULL, 0) != -1)
834    pathname = path;
835#elif SANITIZER_SOLARIS
836  pathname = getexecname();
837  CHECK_NE(pathname, NULL);
838#elif SANITIZER_USE_GETAUXVAL
839  // Calling execve with /proc/self/exe sets that as $EXEC_ORIGIN. Binaries that
840  // rely on that will fail to load shared libraries. Query AT_EXECFN instead.
841  pathname = reinterpret_cast<const char *>(getauxval(AT_EXECFN));
842#endif
843
844  uptr rv = internal_execve(pathname, GetArgv(), GetEnviron());
845  int rverrno;
846  CHECK_EQ(internal_iserror(rv, &rverrno), true);
847  Printf("execve failed, errno %d\n", rverrno);
848  Die();
849}
850#endif  // !SANITIZER_OPENBSD
851
852} // namespace __sanitizer
853
854#endif
855