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