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