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