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