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