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