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