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