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