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_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 #if SANITIZER_NETBSD
32 #define _RTLD_SOURCE  // for __lwp_gettcb_fast() / __lwp_getprivate_fast()
33 #endif
34 
35 #include <dlfcn.h>  // for dlsym()
36 #include <link.h>
37 #include <pthread.h>
38 #include <signal.h>
39 #include <sys/mman.h>
40 #include <sys/resource.h>
41 #include <syslog.h>
42 
43 #if !defined(ElfW)
44 #define ElfW(type) Elf_##type
45 #endif
46 
47 #if SANITIZER_FREEBSD
48 #include <pthread_np.h>
49 #include <osreldate.h>
50 #include <sys/sysctl.h>
51 #define pthread_getattr_np pthread_attr_get_np
52 // The MAP_NORESERVE define has been removed in FreeBSD 11.x, and even before
53 // that, it was never implemented. So just define it to zero.
54 #undef MAP_NORESERVE
55 #define MAP_NORESERVE 0
56 #endif
57 
58 #if SANITIZER_NETBSD
59 #include <sys/sysctl.h>
60 #include <sys/tls.h>
61 #include <lwp.h>
62 #endif
63 
64 #if SANITIZER_SOLARIS
65 #include <stdlib.h>
66 #include <thread.h>
67 #endif
68 
69 #if SANITIZER_ANDROID
70 #include <android/api-level.h>
71 #if !defined(CPU_COUNT) && !defined(__aarch64__)
72 #include <dirent.h>
73 #include <fcntl.h>
74 struct __sanitizer::linux_dirent {
75   long           d_ino;
76   off_t          d_off;
77   unsigned short d_reclen;
78   char           d_name[];
79 };
80 #endif
81 #endif
82 
83 #if !SANITIZER_ANDROID
84 #include <elf.h>
85 #include <unistd.h>
86 #endif
87 
88 namespace __sanitizer {
89 
90 SANITIZER_WEAK_ATTRIBUTE int
91 real_sigaction(int signum, const void *act, void *oldact);
92 
93 int internal_sigaction(int signum, const void *act, void *oldact) {
94 #if !SANITIZER_GO
95   if (&real_sigaction)
96     return real_sigaction(signum, act, oldact);
97 #endif
98   return sigaction(signum, (const struct sigaction *)act,
99                    (struct sigaction *)oldact);
100 }
101 
102 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
103                                 uptr *stack_bottom) {
104   CHECK(stack_top);
105   CHECK(stack_bottom);
106   if (at_initialization) {
107     // This is the main thread. Libpthread may not be initialized yet.
108     struct rlimit rl;
109     CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
110 
111     // Find the mapping that contains a stack variable.
112     MemoryMappingLayout proc_maps(/*cache_enabled*/true);
113     if (proc_maps.Error()) {
114       *stack_top = *stack_bottom = 0;
115       return;
116     }
117     MemoryMappedSegment segment;
118     uptr prev_end = 0;
119     while (proc_maps.Next(&segment)) {
120       if ((uptr)&rl < segment.end) break;
121       prev_end = segment.end;
122     }
123     CHECK((uptr)&rl >= segment.start && (uptr)&rl < segment.end);
124 
125     // Get stacksize from rlimit, but clip it so that it does not overlap
126     // with other mappings.
127     uptr stacksize = rl.rlim_cur;
128     if (stacksize > segment.end - prev_end) stacksize = segment.end - prev_end;
129     // When running with unlimited stack size, we still want to set some limit.
130     // The unlimited stack size is caused by 'ulimit -s unlimited'.
131     // Also, for some reason, GNU make spawns subprocesses with unlimited stack.
132     if (stacksize > kMaxThreadStackSize)
133       stacksize = kMaxThreadStackSize;
134     *stack_top = segment.end;
135     *stack_bottom = segment.end - stacksize;
136     return;
137   }
138   uptr stacksize = 0;
139   void *stackaddr = nullptr;
140 #if SANITIZER_SOLARIS
141   stack_t ss;
142   CHECK_EQ(thr_stksegment(&ss), 0);
143   stacksize = ss.ss_size;
144   stackaddr = (char *)ss.ss_sp - stacksize;
145 #else  // !SANITIZER_SOLARIS
146   pthread_attr_t attr;
147   pthread_attr_init(&attr);
148   CHECK_EQ(pthread_getattr_np(pthread_self(), &attr), 0);
149   my_pthread_attr_getstack(&attr, &stackaddr, &stacksize);
150   pthread_attr_destroy(&attr);
151 #endif  // SANITIZER_SOLARIS
152 
153   *stack_top = (uptr)stackaddr + stacksize;
154   *stack_bottom = (uptr)stackaddr;
155 }
156 
157 #if !SANITIZER_GO
158 bool SetEnv(const char *name, const char *value) {
159   void *f = dlsym(RTLD_NEXT, "setenv");
160   if (!f)
161     return false;
162   typedef int(*setenv_ft)(const char *name, const char *value, int overwrite);
163   setenv_ft setenv_f;
164   CHECK_EQ(sizeof(setenv_f), sizeof(f));
165   internal_memcpy(&setenv_f, &f, sizeof(f));
166   return setenv_f(name, value, 1) == 0;
167 }
168 #endif
169 
170 __attribute__((unused)) static bool GetLibcVersion(int *major, int *minor,
171                                                    int *patch) {
172 #ifdef _CS_GNU_LIBC_VERSION
173   char buf[64];
174   uptr len = confstr(_CS_GNU_LIBC_VERSION, buf, sizeof(buf));
175   if (len >= sizeof(buf))
176     return false;
177   buf[len] = 0;
178   static const char kGLibC[] = "glibc ";
179   if (internal_strncmp(buf, kGLibC, sizeof(kGLibC) - 1) != 0)
180     return false;
181   const char *p = buf + sizeof(kGLibC) - 1;
182   *major = internal_simple_strtoll(p, &p, 10);
183   *minor = (*p == '.') ? internal_simple_strtoll(p + 1, &p, 10) : 0;
184   *patch = (*p == '.') ? internal_simple_strtoll(p + 1, &p, 10) : 0;
185   return true;
186 #else
187   return false;
188 #endif
189 }
190 
191 // ThreadDescriptorSize() is only used by lsan to get the pointer to
192 // thread-specific data keys in the thread control block.
193 #if (defined(__x86_64__) || defined(__i386__) || defined(__mips__) ||       \
194      defined(__aarch64__) || defined(__powerpc64__) || defined(__s390__) || \
195      defined(__arm__) || SANITIZER_RISCV64) &&                              \
196     SANITIZER_LINUX && !SANITIZER_ANDROID
197 // sizeof(struct pthread) from glibc.
198 static atomic_uintptr_t thread_descriptor_size;
199 
200 uptr ThreadDescriptorSize() {
201   uptr val = atomic_load_relaxed(&thread_descriptor_size);
202   if (val)
203     return val;
204 #if defined(__x86_64__) || defined(__i386__) || defined(__arm__)
205   int major;
206   int minor;
207   int patch;
208   if (GetLibcVersion(&major, &minor, &patch) && major == 2) {
209     /* sizeof(struct pthread) values from various glibc versions.  */
210     if (SANITIZER_X32)
211       val = 1728; // Assume only one particular version for x32.
212     // For ARM sizeof(struct pthread) changed in Glibc 2.23.
213     else if (SANITIZER_ARM)
214       val = minor <= 22 ? 1120 : 1216;
215     else if (minor <= 3)
216       val = FIRST_32_SECOND_64(1104, 1696);
217     else if (minor == 4)
218       val = FIRST_32_SECOND_64(1120, 1728);
219     else if (minor == 5)
220       val = FIRST_32_SECOND_64(1136, 1728);
221     else if (minor <= 9)
222       val = FIRST_32_SECOND_64(1136, 1712);
223     else if (minor == 10)
224       val = FIRST_32_SECOND_64(1168, 1776);
225     else if (minor == 11 || (minor == 12 && patch == 1))
226       val = FIRST_32_SECOND_64(1168, 2288);
227     else if (minor <= 14)
228       val = FIRST_32_SECOND_64(1168, 2304);
229     else if (minor < 32)  // Unknown version
230       val = FIRST_32_SECOND_64(1216, 2304);
231     else  // minor == 32
232       val = FIRST_32_SECOND_64(1344, 2496);
233   }
234 #elif defined(__mips__)
235   // TODO(sagarthakur): add more values as per different glibc versions.
236   val = FIRST_32_SECOND_64(1152, 1776);
237 #elif SANITIZER_RISCV64
238   int major;
239   int minor;
240   int patch;
241   if (GetLibcVersion(&major, &minor, &patch) && major == 2) {
242     // TODO: consider adding an optional runtime check for an unknown (untested)
243     // glibc version
244     if (minor <= 28)  // WARNING: the highest tested version is 2.29
245       val = 1772;     // no guarantees for this one
246     else if (minor <= 31)
247       val = 1772;  // tested against glibc 2.29, 2.31
248     else
249       val = 1936;  // tested against glibc 2.32
250   }
251 
252 #elif defined(__aarch64__)
253   // The sizeof (struct pthread) is the same from GLIBC 2.17 to 2.22.
254   val = 1776;
255 #elif defined(__powerpc64__)
256   val = 1776; // from glibc.ppc64le 2.20-8.fc21
257 #elif defined(__s390__)
258   val = FIRST_32_SECOND_64(1152, 1776); // valid for glibc 2.22
259 #endif
260   if (val)
261     atomic_store_relaxed(&thread_descriptor_size, val);
262   return val;
263 }
264 
265 #if defined(__mips__) || defined(__powerpc64__) || SANITIZER_RISCV64
266 // TlsPreTcbSize includes size of struct pthread_descr and size of tcb
267 // head structure. It lies before the static tls blocks.
268 static uptr TlsPreTcbSize() {
269 #if defined(__mips__)
270   const uptr kTcbHead = 16; // sizeof (tcbhead_t)
271 #elif defined(__powerpc64__)
272   const uptr kTcbHead = 88; // sizeof (tcbhead_t)
273 #elif SANITIZER_RISCV64
274   const uptr kTcbHead = 16;  // sizeof (tcbhead_t)
275 #endif
276   const uptr kTlsAlign = 16;
277   const uptr kTlsPreTcbSize =
278       RoundUpTo(ThreadDescriptorSize() + kTcbHead, kTlsAlign);
279   return kTlsPreTcbSize;
280 }
281 #endif
282 
283 #if !SANITIZER_GO
284 namespace {
285 struct TlsRange {
286   uptr begin, end, align;
287   size_t tls_modid;
288   bool operator<(const TlsRange &rhs) const { return begin < rhs.begin; }
289 };
290 }  // namespace
291 
292 static int CollectStaticTlsRanges(struct dl_phdr_info *info, size_t size,
293                                   void *data) {
294   if (!info->dlpi_tls_data)
295     return 0;
296   const uptr begin = (uptr)info->dlpi_tls_data;
297   for (unsigned i = 0; i != info->dlpi_phnum; ++i)
298     if (info->dlpi_phdr[i].p_type == PT_TLS) {
299       static_cast<InternalMmapVector<TlsRange> *>(data)->push_back(
300           TlsRange{begin, begin + info->dlpi_phdr[i].p_memsz,
301                    info->dlpi_phdr[i].p_align, info->dlpi_tls_modid});
302       break;
303     }
304   return 0;
305 }
306 
307 static void GetStaticTlsRange(uptr *addr, uptr *size, uptr *align) {
308   InternalMmapVector<TlsRange> ranges;
309   dl_iterate_phdr(CollectStaticTlsRanges, &ranges);
310   uptr len = ranges.size();
311   Sort(ranges.begin(), len);
312   // Find the range with tls_modid=1. For glibc, because libc.so uses PT_TLS,
313   // this module is guaranteed to exist and is one of the initially loaded
314   // modules.
315   uptr one = 0;
316   while (one != len && ranges[one].tls_modid != 1) ++one;
317   if (one == len) {
318     // This may happen with musl if no module uses PT_TLS.
319     *addr = 0;
320     *size = 0;
321     *align = 1;
322     return;
323   }
324   // Find the maximum consecutive ranges. We consider two modules consecutive if
325   // the gap is smaller than the alignment. The dynamic loader places static TLS
326   // blocks this way not to waste space.
327   uptr l = one;
328   *align = ranges[l].align;
329   while (l != 0 && ranges[l].begin < ranges[l - 1].end + ranges[l - 1].align)
330     *align = Max(*align, ranges[--l].align);
331   uptr r = one + 1;
332   while (r != len && ranges[r].begin < ranges[r - 1].end + ranges[r - 1].align)
333     *align = Max(*align, ranges[r++].align);
334   *addr = ranges[l].begin;
335   *size = ranges[r - 1].end - ranges[l].begin;
336 }
337 #endif  // !SANITIZER_GO
338 #endif  // (x86_64 || i386 || mips || ...) && SANITIZER_LINUX &&
339         // !SANITIZER_ANDROID
340 
341 #if SANITIZER_FREEBSD
342 static void **ThreadSelfSegbase() {
343   void **segbase = 0;
344 #if defined(__i386__)
345   // sysarch(I386_GET_GSBASE, segbase);
346   __asm __volatile("mov %%gs:0, %0" : "=r" (segbase));
347 #elif defined(__x86_64__)
348   // sysarch(AMD64_GET_FSBASE, segbase);
349   __asm __volatile("movq %%fs:0, %0" : "=r" (segbase));
350 #else
351 #error "unsupported CPU arch"
352 #endif
353   return segbase;
354 }
355 
356 uptr ThreadSelf() {
357   return (uptr)ThreadSelfSegbase()[2];
358 }
359 #endif  // SANITIZER_FREEBSD
360 
361 #if SANITIZER_NETBSD
362 static struct tls_tcb * ThreadSelfTlsTcb() {
363   struct tls_tcb *tcb = nullptr;
364 #ifdef __HAVE___LWP_GETTCB_FAST
365   tcb = (struct tls_tcb *)__lwp_gettcb_fast();
366 #elif defined(__HAVE___LWP_GETPRIVATE_FAST)
367   tcb = (struct tls_tcb *)__lwp_getprivate_fast();
368 #endif
369   return tcb;
370 }
371 
372 uptr ThreadSelf() {
373   return (uptr)ThreadSelfTlsTcb()->tcb_pthread;
374 }
375 
376 int GetSizeFromHdr(struct dl_phdr_info *info, size_t size, void *data) {
377   const Elf_Phdr *hdr = info->dlpi_phdr;
378   const Elf_Phdr *last_hdr = hdr + info->dlpi_phnum;
379 
380   for (; hdr != last_hdr; ++hdr) {
381     if (hdr->p_type == PT_TLS && info->dlpi_tls_modid == 1) {
382       *(uptr*)data = hdr->p_memsz;
383       break;
384     }
385   }
386   return 0;
387 }
388 #endif  // SANITIZER_NETBSD
389 
390 #if SANITIZER_ANDROID
391 // Bionic provides this API since S.
392 extern "C" SANITIZER_WEAK_ATTRIBUTE void __libc_get_static_tls_bounds(void **,
393                                                                       void **);
394 #endif
395 
396 #if !SANITIZER_GO
397 static void GetTls(uptr *addr, uptr *size) {
398 #if SANITIZER_ANDROID
399   if (&__libc_get_static_tls_bounds) {
400     void *start_addr;
401     void *end_addr;
402     __libc_get_static_tls_bounds(&start_addr, &end_addr);
403     *addr = reinterpret_cast<uptr>(start_addr);
404     *size =
405         reinterpret_cast<uptr>(end_addr) - reinterpret_cast<uptr>(start_addr);
406   } else {
407     *addr = 0;
408     *size = 0;
409   }
410 #elif SANITIZER_LINUX
411   uptr align;
412   GetStaticTlsRange(addr, size, &align);
413 #if defined(__x86_64__) || defined(__i386__) || defined(__s390__)
414   if (SANITIZER_GLIBC) {
415 #if defined(__s390__)
416     align = Max<uptr>(align, 16);
417 #else
418     align = Max<uptr>(align, 64);
419 #endif
420   }
421   const uptr tp = RoundUpTo(*addr + *size, align);
422 
423   // lsan requires the range to additionally cover the static TLS surplus
424   // (elf/dl-tls.c defines 1664). Otherwise there may be false positives for
425   // allocations only referenced by tls in dynamically loaded modules.
426   if (SANITIZER_GLIBC)
427     *size += 1644;
428 
429   // Extend the range to include the thread control block. On glibc, lsan needs
430   // the range to include pthread::{specific_1stblock,specific} so that
431   // allocations only referenced by pthread_setspecific can be scanned. This may
432   // underestimate by at most TLS_TCB_ALIGN-1 bytes but it should be fine
433   // because the number of bytes after pthread::specific is larger.
434   *addr = tp - RoundUpTo(*size, align);
435   *size = tp - *addr + ThreadDescriptorSize();
436 #else
437   if (SANITIZER_GLIBC)
438     *size += 1664;
439 #if defined(__powerpc64__)
440   // TODO Figure out why *addr may be zero and use TlsPreTcbSize.
441   void *ptr = dlsym(RTLD_NEXT, "_dl_get_tls_static_info");
442   uptr tls_size, tls_align;
443   ((void (*)(size_t *, size_t *))ptr)(&tls_size, &tls_align);
444   asm("addi %0,13,-0x7000" : "=r"(*addr));
445   *addr -= TlsPreTcbSize();
446   *size = RoundUpTo(tls_size + TlsPreTcbSize(), 16);
447 #elif defined(__mips__) || SANITIZER_RISCV64
448   const uptr pre_tcb_size = TlsPreTcbSize();
449   *addr -= pre_tcb_size;
450   *size += pre_tcb_size;
451 #else
452   // arm and aarch64 reserve two words at TP, so this underestimates the range.
453   // However, this is sufficient for the purpose of finding the pointers to
454   // thread-specific data keys.
455   const uptr tcb_size = ThreadDescriptorSize();
456   *addr -= tcb_size;
457   *size += tcb_size;
458 #endif
459 #endif
460 #elif SANITIZER_FREEBSD
461   void** segbase = ThreadSelfSegbase();
462   *addr = 0;
463   *size = 0;
464   if (segbase != 0) {
465     // tcbalign = 16
466     // tls_size = round(tls_static_space, tcbalign);
467     // dtv = segbase[1];
468     // dtv[2] = segbase - tls_static_space;
469     void **dtv = (void**) segbase[1];
470     *addr = (uptr) dtv[2];
471     *size = (*addr == 0) ? 0 : ((uptr) segbase[0] - (uptr) dtv[2]);
472   }
473 #elif SANITIZER_NETBSD
474   struct tls_tcb * const tcb = ThreadSelfTlsTcb();
475   *addr = 0;
476   *size = 0;
477   if (tcb != 0) {
478     // Find size (p_memsz) of dlpi_tls_modid 1 (TLS block of the main program).
479     // ld.elf_so hardcodes the index 1.
480     dl_iterate_phdr(GetSizeFromHdr, size);
481 
482     if (*size != 0) {
483       // The block has been found and tcb_dtv[1] contains the base address
484       *addr = (uptr)tcb->tcb_dtv[1];
485     }
486   }
487 #elif SANITIZER_SOLARIS
488   // FIXME
489   *addr = 0;
490   *size = 0;
491 #else
492 #error "Unknown OS"
493 #endif
494 }
495 #endif
496 
497 #if !SANITIZER_GO
498 uptr GetTlsSize() {
499 #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD || \
500     SANITIZER_SOLARIS
501   uptr addr, size;
502   GetTls(&addr, &size);
503   return size;
504 #else
505   return 0;
506 #endif
507 }
508 #endif
509 
510 void 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       if (*stk_addr + *stk_size < *tls_addr + *tls_size)
527         *tls_size = *stk_addr + *stk_size - *tls_addr;
528       *stk_size = *tls_addr - *stk_addr;
529     }
530   }
531 #endif
532 }
533 
534 #if !SANITIZER_FREEBSD
535 typedef ElfW(Phdr) Elf_Phdr;
536 #elif SANITIZER_WORDSIZE == 32 && __FreeBSD_version <= 902001  // v9.2
537 #define Elf_Phdr XElf32_Phdr
538 #define dl_phdr_info xdl_phdr_info
539 #define dl_iterate_phdr(c, b) xdl_iterate_phdr((c), (b))
540 #endif  // !SANITIZER_FREEBSD
541 
542 struct DlIteratePhdrData {
543   InternalMmapVectorNoCtor<LoadedModule> *modules;
544   bool first;
545 };
546 
547 static int AddModuleSegments(const char *module_name, dl_phdr_info *info,
548                              InternalMmapVectorNoCtor<LoadedModule> *modules) {
549   if (module_name[0] == '\0')
550     return 0;
551   LoadedModule cur_module;
552   cur_module.set(module_name, 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   modules->push_back(cur_module);
565   return 0;
566 }
567 
568 static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
569   DlIteratePhdrData *data = (DlIteratePhdrData *)arg;
570   if (data->first) {
571     InternalMmapVector<char> module_name(kMaxPathLength);
572     data->first = false;
573     // First module is the binary itself.
574     ReadBinaryNameCached(module_name.data(), module_name.size());
575     return AddModuleSegments(module_name.data(), info, data->modules);
576   }
577 
578   if (info->dlpi_name) {
579     InternalScopedString module_name;
580     module_name.append("%s", info->dlpi_name);
581     return AddModuleSegments(module_name.data(), info, data->modules);
582   }
583 
584   return 0;
585 }
586 
587 #if SANITIZER_ANDROID && __ANDROID_API__ < 21
588 extern "C" __attribute__((weak)) int dl_iterate_phdr(
589     int (*)(struct dl_phdr_info *, size_t, void *), void *);
590 #endif
591 
592 static bool requiresProcmaps() {
593 #if SANITIZER_ANDROID && __ANDROID_API__ <= 22
594   // Fall back to /proc/maps if dl_iterate_phdr is unavailable or broken.
595   // The runtime check allows the same library to work with
596   // both K and L (and future) Android releases.
597   return AndroidGetApiLevel() <= ANDROID_LOLLIPOP_MR1;
598 #else
599   return false;
600 #endif
601 }
602 
603 static void procmapsInit(InternalMmapVectorNoCtor<LoadedModule> *modules) {
604   MemoryMappingLayout memory_mapping(/*cache_enabled*/true);
605   memory_mapping.DumpListOfModules(modules);
606 }
607 
608 void ListOfModules::init() {
609   clearOrInit();
610   if (requiresProcmaps()) {
611     procmapsInit(&modules_);
612   } else {
613     DlIteratePhdrData data = {&modules_, true};
614     dl_iterate_phdr(dl_iterate_phdr_cb, &data);
615   }
616 }
617 
618 // When a custom loader is used, dl_iterate_phdr may not contain the full
619 // list of modules. Allow callers to fall back to using procmaps.
620 void ListOfModules::fallbackInit() {
621   if (!requiresProcmaps()) {
622     clearOrInit();
623     procmapsInit(&modules_);
624   } else {
625     clear();
626   }
627 }
628 
629 // getrusage does not give us the current RSS, only the max RSS.
630 // Still, this is better than nothing if /proc/self/statm is not available
631 // for some reason, e.g. due to a sandbox.
632 static uptr GetRSSFromGetrusage() {
633   struct rusage usage;
634   if (getrusage(RUSAGE_SELF, &usage))  // Failed, probably due to a sandbox.
635     return 0;
636   return usage.ru_maxrss << 10;  // ru_maxrss is in Kb.
637 }
638 
639 uptr GetRSS() {
640   if (!common_flags()->can_use_proc_maps_statm)
641     return GetRSSFromGetrusage();
642   fd_t fd = OpenFile("/proc/self/statm", RdOnly);
643   if (fd == kInvalidFd)
644     return GetRSSFromGetrusage();
645   char buf[64];
646   uptr len = internal_read(fd, buf, sizeof(buf) - 1);
647   internal_close(fd);
648   if ((sptr)len <= 0)
649     return 0;
650   buf[len] = 0;
651   // The format of the file is:
652   // 1084 89 69 11 0 79 0
653   // We need the second number which is RSS in pages.
654   char *pos = buf;
655   // Skip the first number.
656   while (*pos >= '0' && *pos <= '9')
657     pos++;
658   // Skip whitespaces.
659   while (!(*pos >= '0' && *pos <= '9') && *pos != 0)
660     pos++;
661   // Read the number.
662   uptr rss = 0;
663   while (*pos >= '0' && *pos <= '9')
664     rss = rss * 10 + *pos++ - '0';
665   return rss * GetPageSizeCached();
666 }
667 
668 // sysconf(_SC_NPROCESSORS_{CONF,ONLN}) cannot be used on most platforms as
669 // they allocate memory.
670 u32 GetNumberOfCPUs() {
671 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
672   u32 ncpu;
673   int req[2];
674   uptr len = sizeof(ncpu);
675   req[0] = CTL_HW;
676   req[1] = HW_NCPU;
677   CHECK_EQ(internal_sysctl(req, 2, &ncpu, &len, NULL, 0), 0);
678   return ncpu;
679 #elif SANITIZER_ANDROID && !defined(CPU_COUNT) && !defined(__aarch64__)
680   // Fall back to /sys/devices/system/cpu on Android when cpu_set_t doesn't
681   // exist in sched.h. That is the case for toolchains generated with older
682   // NDKs.
683   // This code doesn't work on AArch64 because internal_getdents makes use of
684   // the 64bit getdents syscall, but cpu_set_t seems to always exist on AArch64.
685   uptr fd = internal_open("/sys/devices/system/cpu", O_RDONLY | O_DIRECTORY);
686   if (internal_iserror(fd))
687     return 0;
688   InternalMmapVector<u8> buffer(4096);
689   uptr bytes_read = buffer.size();
690   uptr n_cpus = 0;
691   u8 *d_type;
692   struct linux_dirent *entry = (struct linux_dirent *)&buffer[bytes_read];
693   while (true) {
694     if ((u8 *)entry >= &buffer[bytes_read]) {
695       bytes_read = internal_getdents(fd, (struct linux_dirent *)buffer.data(),
696                                      buffer.size());
697       if (internal_iserror(bytes_read) || !bytes_read)
698         break;
699       entry = (struct linux_dirent *)buffer.data();
700     }
701     d_type = (u8 *)entry + entry->d_reclen - 1;
702     if (d_type >= &buffer[bytes_read] ||
703         (u8 *)&entry->d_name[3] >= &buffer[bytes_read])
704       break;
705     if (entry->d_ino != 0 && *d_type == DT_DIR) {
706       if (entry->d_name[0] == 'c' && entry->d_name[1] == 'p' &&
707           entry->d_name[2] == 'u' &&
708           entry->d_name[3] >= '0' && entry->d_name[3] <= '9')
709         n_cpus++;
710     }
711     entry = (struct linux_dirent *)(((u8 *)entry) + entry->d_reclen);
712   }
713   internal_close(fd);
714   return n_cpus;
715 #elif SANITIZER_SOLARIS
716   return sysconf(_SC_NPROCESSORS_ONLN);
717 #else
718   cpu_set_t CPUs;
719   CHECK_EQ(sched_getaffinity(0, sizeof(cpu_set_t), &CPUs), 0);
720   return CPU_COUNT(&CPUs);
721 #endif
722 }
723 
724 #if SANITIZER_LINUX
725 
726 #if SANITIZER_ANDROID
727 static atomic_uint8_t android_log_initialized;
728 
729 void AndroidLogInit() {
730   openlog(GetProcessName(), 0, LOG_USER);
731   atomic_store(&android_log_initialized, 1, memory_order_release);
732 }
733 
734 static bool ShouldLogAfterPrintf() {
735   return atomic_load(&android_log_initialized, memory_order_acquire);
736 }
737 
738 extern "C" SANITIZER_WEAK_ATTRIBUTE
739 int async_safe_write_log(int pri, const char* tag, const char* msg);
740 extern "C" SANITIZER_WEAK_ATTRIBUTE
741 int __android_log_write(int prio, const char* tag, const char* msg);
742 
743 // ANDROID_LOG_INFO is 4, but can't be resolved at runtime.
744 #define SANITIZER_ANDROID_LOG_INFO 4
745 
746 // async_safe_write_log is a new public version of __libc_write_log that is
747 // used behind syslog. It is preferable to syslog as it will not do any dynamic
748 // memory allocation or formatting.
749 // If the function is not available, syslog is preferred for L+ (it was broken
750 // pre-L) as __android_log_write triggers a racey behavior with the strncpy
751 // interceptor. Fallback to __android_log_write pre-L.
752 void WriteOneLineToSyslog(const char *s) {
753   if (&async_safe_write_log) {
754     async_safe_write_log(SANITIZER_ANDROID_LOG_INFO, GetProcessName(), s);
755   } else if (AndroidGetApiLevel() > ANDROID_KITKAT) {
756     syslog(LOG_INFO, "%s", s);
757   } else {
758     CHECK(&__android_log_write);
759     __android_log_write(SANITIZER_ANDROID_LOG_INFO, nullptr, s);
760   }
761 }
762 
763 extern "C" SANITIZER_WEAK_ATTRIBUTE
764 void android_set_abort_message(const char *);
765 
766 void SetAbortMessage(const char *str) {
767   if (&android_set_abort_message)
768     android_set_abort_message(str);
769 }
770 #else
771 void AndroidLogInit() {}
772 
773 static bool ShouldLogAfterPrintf() { return true; }
774 
775 void WriteOneLineToSyslog(const char *s) { syslog(LOG_INFO, "%s", s); }
776 
777 void SetAbortMessage(const char *str) {}
778 #endif  // SANITIZER_ANDROID
779 
780 void LogMessageOnPrintf(const char *str) {
781   if (common_flags()->log_to_syslog && ShouldLogAfterPrintf())
782     WriteToSyslog(str);
783 }
784 
785 #endif  // SANITIZER_LINUX
786 
787 #if SANITIZER_GLIBC && !SANITIZER_GO
788 // glibc crashes when using clock_gettime from a preinit_array function as the
789 // vDSO function pointers haven't been initialized yet. __progname is
790 // initialized after the vDSO function pointers, so if it exists, is not null
791 // and is not empty, we can use clock_gettime.
792 extern "C" SANITIZER_WEAK_ATTRIBUTE char *__progname;
793 inline bool CanUseVDSO() { return &__progname && __progname && *__progname; }
794 
795 // MonotonicNanoTime is a timing function that can leverage the vDSO by calling
796 // clock_gettime. real_clock_gettime only exists if clock_gettime is
797 // intercepted, so define it weakly and use it if available.
798 extern "C" SANITIZER_WEAK_ATTRIBUTE
799 int real_clock_gettime(u32 clk_id, void *tp);
800 u64 MonotonicNanoTime() {
801   timespec ts;
802   if (CanUseVDSO()) {
803     if (&real_clock_gettime)
804       real_clock_gettime(CLOCK_MONOTONIC, &ts);
805     else
806       clock_gettime(CLOCK_MONOTONIC, &ts);
807   } else {
808     internal_clock_gettime(CLOCK_MONOTONIC, &ts);
809   }
810   return (u64)ts.tv_sec * (1000ULL * 1000 * 1000) + ts.tv_nsec;
811 }
812 #else
813 // Non-glibc & Go always use the regular function.
814 u64 MonotonicNanoTime() {
815   timespec ts;
816   clock_gettime(CLOCK_MONOTONIC, &ts);
817   return (u64)ts.tv_sec * (1000ULL * 1000 * 1000) + ts.tv_nsec;
818 }
819 #endif  // SANITIZER_GLIBC && !SANITIZER_GO
820 
821 void ReExec() {
822   const char *pathname = "/proc/self/exe";
823 
824 #if SANITIZER_NETBSD
825   static const int name[] = {
826       CTL_KERN,
827       KERN_PROC_ARGS,
828       -1,
829       KERN_PROC_PATHNAME,
830   };
831   char path[400];
832   uptr len;
833 
834   len = sizeof(path);
835   if (internal_sysctl(name, ARRAY_SIZE(name), path, &len, NULL, 0) != -1)
836     pathname = path;
837 #elif SANITIZER_SOLARIS
838   pathname = getexecname();
839   CHECK_NE(pathname, NULL);
840 #elif SANITIZER_USE_GETAUXVAL
841   // Calling execve with /proc/self/exe sets that as $EXEC_ORIGIN. Binaries that
842   // rely on that will fail to load shared libraries. Query AT_EXECFN instead.
843   pathname = reinterpret_cast<const char *>(getauxval(AT_EXECFN));
844 #endif
845 
846   uptr rv = internal_execve(pathname, GetArgv(), GetEnviron());
847   int rverrno;
848   CHECK_EQ(internal_iserror(rv, &rverrno), true);
849   Printf("execve failed, errno %d\n", rverrno);
850   Die();
851 }
852 
853 void UnmapFromTo(uptr from, uptr to) {
854   if (to == from)
855     return;
856   CHECK(to >= from);
857   uptr res = internal_munmap(reinterpret_cast<void *>(from), to - from);
858   if (UNLIKELY(internal_iserror(res))) {
859     Report("ERROR: %s failed to unmap 0x%zx (%zd) bytes at address %p\n",
860            SanitizerToolName, to - from, to - from, (void *)from);
861     CHECK("unable to unmap" && 0);
862   }
863 }
864 
865 uptr MapDynamicShadow(uptr shadow_size_bytes, uptr shadow_scale,
866                       uptr min_shadow_base_alignment,
867                       UNUSED uptr &high_mem_end) {
868   const uptr granularity = GetMmapGranularity();
869   const uptr alignment =
870       Max<uptr>(granularity << shadow_scale, 1ULL << min_shadow_base_alignment);
871   const uptr left_padding =
872       Max<uptr>(granularity, 1ULL << min_shadow_base_alignment);
873 
874   const uptr shadow_size = RoundUpTo(shadow_size_bytes, granularity);
875   const uptr map_size = shadow_size + left_padding + alignment;
876 
877   const uptr map_start = (uptr)MmapNoAccess(map_size);
878   CHECK_NE(map_start, ~(uptr)0);
879 
880   const uptr shadow_start = RoundUpTo(map_start + left_padding, alignment);
881 
882   UnmapFromTo(map_start, shadow_start - left_padding);
883   UnmapFromTo(shadow_start + shadow_size, map_start + map_size);
884 
885   return shadow_start;
886 }
887 
888 static uptr MmapSharedNoReserve(uptr addr, uptr size) {
889   return internal_mmap(
890       reinterpret_cast<void *>(addr), size, PROT_READ | PROT_WRITE,
891       MAP_FIXED | MAP_SHARED | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
892 }
893 
894 static uptr MremapCreateAlias(uptr base_addr, uptr alias_addr,
895                               uptr alias_size) {
896 #if SANITIZER_LINUX
897   return internal_mremap(reinterpret_cast<void *>(base_addr), 0, alias_size,
898                          MREMAP_MAYMOVE | MREMAP_FIXED,
899                          reinterpret_cast<void *>(alias_addr));
900 #else
901   CHECK(false && "mremap is not supported outside of Linux");
902   return 0;
903 #endif
904 }
905 
906 static void CreateAliases(uptr start_addr, uptr alias_size, uptr num_aliases) {
907   uptr total_size = alias_size * num_aliases;
908   uptr mapped = MmapSharedNoReserve(start_addr, total_size);
909   CHECK_EQ(mapped, start_addr);
910 
911   for (uptr i = 1; i < num_aliases; ++i) {
912     uptr alias_addr = start_addr + i * alias_size;
913     CHECK_EQ(MremapCreateAlias(start_addr, alias_addr, alias_size), alias_addr);
914   }
915 }
916 
917 uptr MapDynamicShadowAndAliases(uptr shadow_size, uptr alias_size,
918                                 uptr num_aliases, uptr ring_buffer_size) {
919   CHECK_EQ(alias_size & (alias_size - 1), 0);
920   CHECK_EQ(num_aliases & (num_aliases - 1), 0);
921   CHECK_EQ(ring_buffer_size & (ring_buffer_size - 1), 0);
922 
923   const uptr granularity = GetMmapGranularity();
924   shadow_size = RoundUpTo(shadow_size, granularity);
925   CHECK_EQ(shadow_size & (shadow_size - 1), 0);
926 
927   const uptr alias_region_size = alias_size * num_aliases;
928   const uptr alignment =
929       2 * Max(Max(shadow_size, alias_region_size), ring_buffer_size);
930   const uptr left_padding = ring_buffer_size;
931 
932   const uptr right_size = alignment;
933   const uptr map_size = left_padding + 2 * alignment;
934 
935   const uptr map_start = reinterpret_cast<uptr>(MmapNoAccess(map_size));
936   CHECK_NE(map_start, static_cast<uptr>(-1));
937   const uptr right_start = RoundUpTo(map_start + left_padding, alignment);
938 
939   UnmapFromTo(map_start, right_start - left_padding);
940   UnmapFromTo(right_start + right_size, map_start + map_size);
941 
942   CreateAliases(right_start + right_size / 2, alias_size, num_aliases);
943 
944   return right_start;
945 }
946 
947 void InitializePlatformCommonFlags(CommonFlags *cf) {
948 #if SANITIZER_ANDROID
949   if (&__libc_get_static_tls_bounds == nullptr)
950     cf->detect_leaks = false;
951 #endif
952 }
953 
954 } // namespace __sanitizer
955 
956 #endif
957