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