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