1 //===-- sanitizer_linux_libcdep.cc ----------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is shared between AddressSanitizer and ThreadSanitizer
11 // run-time libraries and implements linux-specific functions from
13 //===----------------------------------------------------------------------===//
15 #include "sanitizer_platform.h"
17 #if SANITIZER_FREEBSD || SANITIZER_LINUX
19 #include "sanitizer_allocator_internal.h"
20 #include "sanitizer_atomic.h"
21 #include "sanitizer_common.h"
22 #include "sanitizer_flags.h"
23 #include "sanitizer_freebsd.h"
24 #include "sanitizer_linux.h"
25 #include "sanitizer_placement_new.h"
26 #include "sanitizer_procmaps.h"
27 #include "sanitizer_stacktrace.h"
29 #if SANITIZER_ANDROID || SANITIZER_FREEBSD
30 #include <dlfcn.h> // for dlsym()
36 #include <sys/resource.h>
39 #include <pthread_np.h>
40 #include <osreldate.h>
41 #define pthread_getattr_np pthread_attr_get_np
45 #include <sys/prctl.h>
49 #include <android/api-level.h>
52 #if SANITIZER_ANDROID && __ANDROID_API__ < 21
53 #include <android/log.h>
58 #if !SANITIZER_ANDROID
63 namespace __sanitizer {
65 SANITIZER_WEAK_ATTRIBUTE int
66 real_sigaction(int signum, const void *act, void *oldact);
68 int internal_sigaction(int signum, const void *act, void *oldact) {
71 return real_sigaction(signum, act, oldact);
73 return sigaction(signum, (const struct sigaction *)act,
74 (struct sigaction *)oldact);
77 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
81 if (at_initialization) {
82 // This is the main thread. Libpthread may not be initialized yet.
84 CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
86 // Find the mapping that contains a stack variable.
87 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
88 uptr start, end, offset;
90 while (proc_maps.Next(&start, &end, &offset, nullptr, 0,
91 /* protection */nullptr)) {
96 CHECK((uptr)&rl >= start && (uptr)&rl < end);
98 // Get stacksize from rlimit, but clip it so that it does not overlap
99 // with other mappings.
100 uptr stacksize = rl.rlim_cur;
101 if (stacksize > end - prev_end)
102 stacksize = end - prev_end;
103 // When running with unlimited stack size, we still want to set some limit.
104 // The unlimited stack size is caused by 'ulimit -s unlimited'.
105 // Also, for some reason, GNU make spawns subprocesses with unlimited stack.
106 if (stacksize > kMaxThreadStackSize)
107 stacksize = kMaxThreadStackSize;
109 *stack_bottom = end - stacksize;
113 pthread_attr_init(&attr);
114 CHECK_EQ(pthread_getattr_np(pthread_self(), &attr), 0);
116 void *stackaddr = nullptr;
117 my_pthread_attr_getstack(&attr, &stackaddr, &stacksize);
118 pthread_attr_destroy(&attr);
120 CHECK_LE(stacksize, kMaxThreadStackSize); // Sanity check.
121 *stack_top = (uptr)stackaddr + stacksize;
122 *stack_bottom = (uptr)stackaddr;
126 bool SetEnv(const char *name, const char *value) {
127 void *f = dlsym(RTLD_NEXT, "setenv");
130 typedef int(*setenv_ft)(const char *name, const char *value, int overwrite);
132 CHECK_EQ(sizeof(setenv_f), sizeof(f));
133 internal_memcpy(&setenv_f, &f, sizeof(f));
134 return setenv_f(name, value, 1) == 0;
138 bool SanitizerSetThreadName(const char *name) {
140 return 0 == prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0); // NOLINT
146 bool SanitizerGetThreadName(char *name, int max_len) {
149 if (prctl(PR_GET_NAME, (unsigned long)buff, 0, 0, 0)) // NOLINT
151 internal_strncpy(name, buff, max_len);
159 #if !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO
160 static uptr g_tls_size;
164 # define DL_INTERNAL_FUNCTION __attribute__((regparm(3), stdcall))
166 # define DL_INTERNAL_FUNCTION
169 #if defined(__mips__) || defined(__powerpc64__)
170 // TlsPreTcbSize includes size of struct pthread_descr and size of tcb
171 // head structure. It lies before the static tls blocks.
172 static uptr TlsPreTcbSize() {
173 # if defined(__mips__)
174 const uptr kTcbHead = 16; // sizeof (tcbhead_t)
175 # elif defined(__powerpc64__)
176 const uptr kTcbHead = 88; // sizeof (tcbhead_t)
178 const uptr kTlsAlign = 16;
179 const uptr kTlsPreTcbSize =
180 (ThreadDescriptorSize() + kTcbHead + kTlsAlign - 1) & ~(kTlsAlign - 1);
182 g_tls_size = (g_tls_size + kTlsPreTcbSize + kTlsAlign -1) & ~(kTlsAlign - 1);
183 return kTlsPreTcbSize;
188 #if !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO
189 // all current supported platforms have 16 bytes stack alignment
190 const size_t kStackAlign = 16;
191 typedef void (*get_tls_func)(size_t*, size_t*) DL_INTERNAL_FUNCTION;
192 get_tls_func get_tls;
193 void *get_tls_static_info_ptr = dlsym(RTLD_NEXT, "_dl_get_tls_static_info");
194 CHECK_EQ(sizeof(get_tls), sizeof(get_tls_static_info_ptr));
195 internal_memcpy(&get_tls, &get_tls_static_info_ptr,
196 sizeof(get_tls_static_info_ptr));
197 CHECK_NE(get_tls, 0);
199 size_t tls_align = 0;
200 get_tls(&tls_size, &tls_align);
201 if (tls_align < kStackAlign)
202 tls_align = kStackAlign;
203 g_tls_size = RoundUpTo(tls_size, tls_align);
204 #endif // !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO
207 #if (defined(__x86_64__) || defined(__i386__) || defined(__mips__) \
208 || defined(__aarch64__) || defined(__powerpc64__)) \
209 && SANITIZER_LINUX && !SANITIZER_ANDROID
210 // sizeof(struct pthread) from glibc.
211 static atomic_uintptr_t kThreadDescriptorSize;
213 uptr ThreadDescriptorSize() {
214 uptr val = atomic_load(&kThreadDescriptorSize, memory_order_relaxed);
217 #if defined(__x86_64__) || defined(__i386__)
218 #ifdef _CS_GNU_LIBC_VERSION
220 uptr len = confstr(_CS_GNU_LIBC_VERSION, buf, sizeof(buf));
221 if (len < sizeof(buf) && internal_strncmp(buf, "glibc 2.", 8) == 0) {
223 int minor = internal_simple_strtoll(buf + 8, &end, 10);
224 if (end != buf + 8 && (*end == '\0' || *end == '.')) {
227 // strtoll will return 0 if no valid conversion could be performed
228 patch = internal_simple_strtoll(end + 1, nullptr, 10);
230 /* sizeof(struct pthread) values from various glibc versions. */
232 val = 1728; // Assume only one particular version for x32.
234 val = FIRST_32_SECOND_64(1104, 1696);
236 val = FIRST_32_SECOND_64(1120, 1728);
238 val = FIRST_32_SECOND_64(1136, 1728);
240 val = FIRST_32_SECOND_64(1136, 1712);
241 else if (minor == 10)
242 val = FIRST_32_SECOND_64(1168, 1776);
243 else if (minor == 11 || (minor == 12 && patch == 1))
244 val = FIRST_32_SECOND_64(1168, 2288);
245 else if (minor <= 13)
246 val = FIRST_32_SECOND_64(1168, 2304);
248 val = FIRST_32_SECOND_64(1216, 2304);
251 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
255 #elif defined(__mips__)
256 // TODO(sagarthakur): add more values as per different glibc versions.
257 val = FIRST_32_SECOND_64(1152, 1776);
259 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
261 #elif defined(__aarch64__)
262 // The sizeof (struct pthread) is the same from GLIBC 2.17 to 2.22.
264 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
266 #elif defined(__powerpc64__)
267 val = 1776; // from glibc.ppc64le 2.20-8.fc21
268 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
274 // The offset at which pointer to self is located in the thread descriptor.
275 const uptr kThreadSelfOffset = FIRST_32_SECOND_64(8, 16);
277 uptr ThreadSelfOffset() {
278 return kThreadSelfOffset;
283 # if defined(__i386__)
284 asm("mov %%gs:%c1,%0" : "=r"(descr_addr) : "i"(kThreadSelfOffset));
285 # elif defined(__x86_64__)
286 asm("mov %%fs:%c1,%0" : "=r"(descr_addr) : "i"(kThreadSelfOffset));
287 # elif defined(__mips__)
288 // MIPS uses TLS variant I. The thread pointer (in hardware register $29)
289 // points to the end of the TCB + 0x7000. The pthread_descr structure is
290 // immediately in front of the TCB. TlsPreTcbSize() includes the size of the
291 // TCB and the size of pthread_descr.
292 const uptr kTlsTcbOffset = 0x7000;
294 asm volatile(".set push;\
297 .set pop" : "=r" (thread_pointer));
298 descr_addr = thread_pointer - kTlsTcbOffset - TlsPreTcbSize();
299 # elif defined(__aarch64__)
300 descr_addr = reinterpret_cast<uptr>(__builtin_thread_pointer());
301 # elif defined(__powerpc64__)
302 // PPC64LE uses TLS variant I. The thread pointer (in GPR 13)
303 // points to the end of the TCB + 0x7000. The pthread_descr structure is
304 // immediately in front of the TCB. TlsPreTcbSize() includes the size of the
305 // TCB and the size of pthread_descr.
306 const uptr kTlsTcbOffset = 0x7000;
308 asm("addi %0,13,%1" : "=r"(thread_pointer) : "I"(-kTlsTcbOffset));
309 descr_addr = thread_pointer - TlsPreTcbSize();
311 # error "unsupported CPU arch"
315 #endif // (x86_64 || i386 || MIPS) && SANITIZER_LINUX
317 #if SANITIZER_FREEBSD
318 static void **ThreadSelfSegbase() {
320 # if defined(__i386__)
321 // sysarch(I386_GET_GSBASE, segbase);
322 __asm __volatile("mov %%gs:0, %0" : "=r" (segbase));
323 # elif defined(__x86_64__)
324 // sysarch(AMD64_GET_FSBASE, segbase);
325 __asm __volatile("movq %%fs:0, %0" : "=r" (segbase));
327 # error "unsupported CPU arch for FreeBSD platform"
333 return (uptr)ThreadSelfSegbase()[2];
335 #endif // SANITIZER_FREEBSD
338 static void GetTls(uptr *addr, uptr *size) {
339 #if SANITIZER_LINUX && !SANITIZER_ANDROID
340 # if defined(__x86_64__) || defined(__i386__)
341 *addr = ThreadSelf();
342 *size = GetTlsSize();
344 *addr += ThreadDescriptorSize();
345 # elif defined(__mips__) || defined(__aarch64__) || defined(__powerpc64__)
346 *addr = ThreadSelf();
347 *size = GetTlsSize();
352 #elif SANITIZER_FREEBSD
353 void** segbase = ThreadSelfSegbase();
358 // tls_size = round(tls_static_space, tcbalign);
360 // dtv[2] = segbase - tls_static_space;
361 void **dtv = (void**) segbase[1];
362 *addr = (uptr) dtv[2];
363 *size = (*addr == 0) ? 0 : ((uptr) segbase[0] - (uptr) dtv[2]);
365 #elif SANITIZER_ANDROID
376 #if SANITIZER_FREEBSD || SANITIZER_ANDROID
378 GetTls(&addr, &size);
386 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
387 uptr *tls_addr, uptr *tls_size) {
389 // Stub implementation for Go.
390 *stk_addr = *stk_size = *tls_addr = *tls_size = 0;
392 GetTls(tls_addr, tls_size);
394 uptr stack_top, stack_bottom;
395 GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
396 *stk_addr = stack_bottom;
397 *stk_size = stack_top - stack_bottom;
400 // If stack and tls intersect, make them non-intersecting.
401 if (*tls_addr > *stk_addr && *tls_addr < *stk_addr + *stk_size) {
402 CHECK_GT(*tls_addr + *tls_size, *stk_addr);
403 CHECK_LE(*tls_addr + *tls_size, *stk_addr + *stk_size);
404 *stk_size -= *tls_size;
405 *tls_addr = *stk_addr + *stk_size;
411 # if !SANITIZER_FREEBSD
412 typedef ElfW(Phdr) Elf_Phdr;
413 # elif SANITIZER_WORDSIZE == 32 && __FreeBSD_version <= 902001 // v9.2
414 # define Elf_Phdr XElf32_Phdr
415 # define dl_phdr_info xdl_phdr_info
416 # define dl_iterate_phdr(c, b) xdl_iterate_phdr((c), (b))
419 struct DlIteratePhdrData {
420 LoadedModule *modules;
424 string_predicate_t filter;
427 static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
428 DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
429 if (data->current_n == data->max_n)
431 InternalScopedString module_name(kMaxPathLength);
434 // First module is the binary itself.
435 ReadBinaryNameCached(module_name.data(), module_name.size());
436 } else if (info->dlpi_name) {
437 module_name.append("%s", info->dlpi_name);
439 if (module_name[0] == '\0')
441 if (data->filter && !data->filter(module_name.data()))
443 LoadedModule *cur_module = &data->modules[data->current_n];
444 cur_module->set(module_name.data(), info->dlpi_addr);
446 for (int i = 0; i < info->dlpi_phnum; i++) {
447 const Elf_Phdr *phdr = &info->dlpi_phdr[i];
448 if (phdr->p_type == PT_LOAD) {
449 uptr cur_beg = info->dlpi_addr + phdr->p_vaddr;
450 uptr cur_end = cur_beg + phdr->p_memsz;
451 bool executable = phdr->p_flags & PF_X;
452 cur_module->addAddressRange(cur_beg, cur_end, executable);
458 #if SANITIZER_ANDROID && __ANDROID_API__ < 21
459 extern "C" __attribute__((weak)) int dl_iterate_phdr(
460 int (*)(struct dl_phdr_info *, size_t, void *), void *);
463 uptr GetListOfModules(LoadedModule *modules, uptr max_modules,
464 string_predicate_t filter) {
465 #if SANITIZER_ANDROID && __ANDROID_API__ <= 22
466 u32 api_level = AndroidGetApiLevel();
467 // Fall back to /proc/maps if dl_iterate_phdr is unavailable or broken.
468 // The runtime check allows the same library to work with
469 // both K and L (and future) Android releases.
470 if (api_level <= ANDROID_LOLLIPOP_MR1) { // L or earlier
471 MemoryMappingLayout memory_mapping(false);
472 return memory_mapping.DumpListOfModules(modules, max_modules, filter);
476 DlIteratePhdrData data = {modules, 0, true, max_modules, filter};
477 dl_iterate_phdr(dl_iterate_phdr_cb, &data);
478 return data.current_n;
481 // getrusage does not give us the current RSS, only the max RSS.
482 // Still, this is better than nothing if /proc/self/statm is not available
483 // for some reason, e.g. due to a sandbox.
484 static uptr GetRSSFromGetrusage() {
486 if (getrusage(RUSAGE_SELF, &usage)) // Failed, probably due to a sandbox.
488 return usage.ru_maxrss << 10; // ru_maxrss is in Kb.
492 if (!common_flags()->can_use_proc_maps_statm)
493 return GetRSSFromGetrusage();
494 fd_t fd = OpenFile("/proc/self/statm", RdOnly);
495 if (fd == kInvalidFd)
496 return GetRSSFromGetrusage();
498 uptr len = internal_read(fd, buf, sizeof(buf) - 1);
503 // The format of the file is:
504 // 1084 89 69 11 0 79 0
505 // We need the second number which is RSS in pages.
507 // Skip the first number.
508 while (*pos >= '0' && *pos <= '9')
511 while (!(*pos >= '0' && *pos <= '9') && *pos != 0)
515 while (*pos >= '0' && *pos <= '9')
516 rss = rss * 10 + *pos++ - '0';
517 return rss * GetPageSizeCached();
520 // 64-bit Android targets don't provide the deprecated __android_log_write.
521 // Starting with the L release, syslog() works and is preferable to
522 // __android_log_write.
525 #if SANITIZER_ANDROID
526 static atomic_uint8_t android_log_initialized;
528 void AndroidLogInit() {
529 atomic_store(&android_log_initialized, 1, memory_order_release);
532 static bool ShouldLogAfterPrintf() {
533 return atomic_load(&android_log_initialized, memory_order_acquire);
536 void AndroidLogInit() {}
538 static bool ShouldLogAfterPrintf() { return true; }
539 #endif // SANITIZER_ANDROID
541 void WriteOneLineToSyslog(const char *s) {
542 #if SANITIZER_ANDROID &&__ANDROID_API__ < 21
543 __android_log_write(ANDROID_LOG_INFO, NULL, s);
545 syslog(LOG_INFO, "%s", s);
549 void LogMessageOnPrintf(const char *str) {
550 if (common_flags()->log_to_syslog && ShouldLogAfterPrintf())
554 #endif // SANITIZER_LINUX
556 } // namespace __sanitizer
558 #endif // SANITIZER_FREEBSD || SANITIZER_LINUX