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