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