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