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 #include <dlfcn.h> // for dlsym()
33 #include <sys/resource.h>
37 #include <pthread_np.h>
38 #include <osreldate.h>
39 #define pthread_getattr_np pthread_attr_get_np
43 #include <sys/prctl.h>
47 #include <android/api-level.h>
50 #if SANITIZER_ANDROID && __ANDROID_API__ < 21
51 #include <android/log.h>
54 #if !SANITIZER_ANDROID
59 namespace __sanitizer {
61 SANITIZER_WEAK_ATTRIBUTE int
62 real_sigaction(int signum, const void *act, void *oldact);
64 int internal_sigaction(int signum, const void *act, void *oldact) {
67 return real_sigaction(signum, act, oldact);
69 return sigaction(signum, (const struct sigaction *)act,
70 (struct sigaction *)oldact);
73 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
77 if (at_initialization) {
78 // This is the main thread. Libpthread may not be initialized yet.
80 CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
82 // Find the mapping that contains a stack variable.
83 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
84 uptr start, end, offset;
86 while (proc_maps.Next(&start, &end, &offset, nullptr, 0,
87 /* protection */nullptr)) {
92 CHECK((uptr)&rl >= start && (uptr)&rl < end);
94 // Get stacksize from rlimit, but clip it so that it does not overlap
95 // with other mappings.
96 uptr stacksize = rl.rlim_cur;
97 if (stacksize > end - prev_end)
98 stacksize = end - prev_end;
99 // When running with unlimited stack size, we still want to set some limit.
100 // The unlimited stack size is caused by 'ulimit -s unlimited'.
101 // Also, for some reason, GNU make spawns subprocesses with unlimited stack.
102 if (stacksize > kMaxThreadStackSize)
103 stacksize = kMaxThreadStackSize;
105 *stack_bottom = end - stacksize;
109 pthread_attr_init(&attr);
110 CHECK_EQ(pthread_getattr_np(pthread_self(), &attr), 0);
112 void *stackaddr = nullptr;
113 my_pthread_attr_getstack(&attr, &stackaddr, &stacksize);
114 pthread_attr_destroy(&attr);
116 CHECK_LE(stacksize, kMaxThreadStackSize); // Sanity check.
117 *stack_top = (uptr)stackaddr + stacksize;
118 *stack_bottom = (uptr)stackaddr;
122 bool SetEnv(const char *name, const char *value) {
123 void *f = dlsym(RTLD_NEXT, "setenv");
126 typedef int(*setenv_ft)(const char *name, const char *value, int overwrite);
128 CHECK_EQ(sizeof(setenv_f), sizeof(f));
129 internal_memcpy(&setenv_f, &f, sizeof(f));
130 return setenv_f(name, value, 1) == 0;
134 bool SanitizerSetThreadName(const char *name) {
136 return 0 == prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0); // NOLINT
142 bool SanitizerGetThreadName(char *name, int max_len) {
145 if (prctl(PR_GET_NAME, (unsigned long)buff, 0, 0, 0)) // NOLINT
147 internal_strncpy(name, buff, max_len);
155 #if !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO
156 static uptr g_tls_size;
159 # define DL_INTERNAL_FUNCTION __attribute__((regparm(3), stdcall))
161 # define DL_INTERNAL_FUNCTION
165 // all current supported platforms have 16 bytes stack alignment
166 const size_t kStackAlign = 16;
167 typedef void (*get_tls_func)(size_t*, size_t*) DL_INTERNAL_FUNCTION;
168 get_tls_func get_tls;
169 void *get_tls_static_info_ptr = dlsym(RTLD_NEXT, "_dl_get_tls_static_info");
170 CHECK_EQ(sizeof(get_tls), sizeof(get_tls_static_info_ptr));
171 internal_memcpy(&get_tls, &get_tls_static_info_ptr,
172 sizeof(get_tls_static_info_ptr));
173 CHECK_NE(get_tls, 0);
175 size_t tls_align = 0;
176 get_tls(&tls_size, &tls_align);
177 if (tls_align < kStackAlign)
178 tls_align = kStackAlign;
179 g_tls_size = RoundUpTo(tls_size, tls_align);
182 void InitTlsSize() { }
183 #endif // !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO
185 #if (defined(__x86_64__) || defined(__i386__) || defined(__mips__) \
186 || defined(__aarch64__) || defined(__powerpc64__) || defined(__s390__) \
187 || defined(__arm__)) && SANITIZER_LINUX && !SANITIZER_ANDROID
188 // sizeof(struct pthread) from glibc.
189 static atomic_uintptr_t kThreadDescriptorSize;
191 uptr ThreadDescriptorSize() {
192 uptr val = atomic_load(&kThreadDescriptorSize, memory_order_relaxed);
195 #if defined(__x86_64__) || defined(__i386__) || defined(__arm__)
196 #ifdef _CS_GNU_LIBC_VERSION
198 uptr len = confstr(_CS_GNU_LIBC_VERSION, buf, sizeof(buf));
199 if (len < sizeof(buf) && internal_strncmp(buf, "glibc 2.", 8) == 0) {
201 int minor = internal_simple_strtoll(buf + 8, &end, 10);
202 if (end != buf + 8 && (*end == '\0' || *end == '.' || *end == '-')) {
205 // strtoll will return 0 if no valid conversion could be performed
206 patch = internal_simple_strtoll(end + 1, nullptr, 10);
208 /* sizeof(struct pthread) values from various glibc versions. */
210 val = 1728; // Assume only one particular version for x32.
211 // For ARM sizeof(struct pthread) changed in Glibc 2.23.
212 else if (SANITIZER_ARM)
213 val = minor <= 22 ? 1120 : 1216;
215 val = FIRST_32_SECOND_64(1104, 1696);
217 val = FIRST_32_SECOND_64(1120, 1728);
219 val = FIRST_32_SECOND_64(1136, 1728);
221 val = FIRST_32_SECOND_64(1136, 1712);
222 else if (minor == 10)
223 val = FIRST_32_SECOND_64(1168, 1776);
224 else if (minor == 11 || (minor == 12 && patch == 1))
225 val = FIRST_32_SECOND_64(1168, 2288);
226 else if (minor <= 13)
227 val = FIRST_32_SECOND_64(1168, 2304);
229 val = FIRST_32_SECOND_64(1216, 2304);
232 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
236 #elif defined(__mips__)
237 // TODO(sagarthakur): add more values as per different glibc versions.
238 val = FIRST_32_SECOND_64(1152, 1776);
240 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
242 #elif defined(__aarch64__)
243 // The sizeof (struct pthread) is the same from GLIBC 2.17 to 2.22.
245 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
247 #elif defined(__powerpc64__)
248 val = 1776; // from glibc.ppc64le 2.20-8.fc21
249 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
251 #elif defined(__s390__)
252 val = FIRST_32_SECOND_64(1152, 1776); // valid for glibc 2.22
253 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
258 // The offset at which pointer to self is located in the thread descriptor.
259 const uptr kThreadSelfOffset = FIRST_32_SECOND_64(8, 16);
261 uptr ThreadSelfOffset() {
262 return kThreadSelfOffset;
265 #if defined(__mips__) || defined(__powerpc64__)
266 // TlsPreTcbSize includes size of struct pthread_descr and size of tcb
267 // head structure. It lies before the static tls blocks.
268 static uptr TlsPreTcbSize() {
269 # if defined(__mips__)
270 const uptr kTcbHead = 16; // sizeof (tcbhead_t)
271 # elif defined(__powerpc64__)
272 const uptr kTcbHead = 88; // sizeof (tcbhead_t)
274 const uptr kTlsAlign = 16;
275 const uptr kTlsPreTcbSize =
276 RoundUpTo(ThreadDescriptorSize() + kTcbHead, kTlsAlign);
277 return kTlsPreTcbSize;
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__) || defined(__arm__)
300 descr_addr = reinterpret_cast<uptr>(__builtin_thread_pointer()) -
301 ThreadDescriptorSize();
302 # elif defined(__s390__)
303 descr_addr = reinterpret_cast<uptr>(__builtin_thread_pointer());
304 # elif defined(__powerpc64__)
305 // PPC64LE uses TLS variant I. The thread pointer (in GPR 13)
306 // points to the end of the TCB + 0x7000. The pthread_descr structure is
307 // immediately in front of the TCB. TlsPreTcbSize() includes the size of the
308 // TCB and the size of pthread_descr.
309 const uptr kTlsTcbOffset = 0x7000;
311 asm("addi %0,13,%1" : "=r"(thread_pointer) : "I"(-kTlsTcbOffset));
312 descr_addr = thread_pointer - TlsPreTcbSize();
314 # error "unsupported CPU arch"
318 #endif // (x86_64 || i386 || MIPS) && SANITIZER_LINUX
320 #if SANITIZER_FREEBSD
321 static void **ThreadSelfSegbase() {
323 # if defined(__i386__)
324 // sysarch(I386_GET_GSBASE, segbase);
325 __asm __volatile("mov %%gs:0, %0" : "=r" (segbase));
326 # elif defined(__x86_64__)
327 // sysarch(AMD64_GET_FSBASE, segbase);
328 __asm __volatile("movq %%fs:0, %0" : "=r" (segbase));
330 # error "unsupported CPU arch for FreeBSD platform"
336 return (uptr)ThreadSelfSegbase()[2];
338 #endif // SANITIZER_FREEBSD
341 static void GetTls(uptr *addr, uptr *size) {
342 #if SANITIZER_LINUX && !SANITIZER_ANDROID
343 # if defined(__x86_64__) || defined(__i386__) || defined(__s390__)
344 *addr = ThreadSelf();
345 *size = GetTlsSize();
347 *addr += ThreadDescriptorSize();
348 # elif defined(__mips__) || defined(__aarch64__) || defined(__powerpc64__) \
350 *addr = ThreadSelf();
351 *size = GetTlsSize();
356 #elif SANITIZER_FREEBSD
357 void** segbase = ThreadSelfSegbase();
362 // tls_size = round(tls_static_space, tcbalign);
364 // dtv[2] = segbase - tls_static_space;
365 void **dtv = (void**) segbase[1];
366 *addr = (uptr) dtv[2];
367 *size = (*addr == 0) ? 0 : ((uptr) segbase[0] - (uptr) dtv[2]);
369 #elif SANITIZER_ANDROID
380 #if SANITIZER_FREEBSD || SANITIZER_ANDROID
382 GetTls(&addr, &size);
384 #elif defined(__mips__) || defined(__powerpc64__)
385 return RoundUpTo(g_tls_size + TlsPreTcbSize(), 16);
392 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
393 uptr *tls_addr, uptr *tls_size) {
395 // Stub implementation for Go.
396 *stk_addr = *stk_size = *tls_addr = *tls_size = 0;
398 GetTls(tls_addr, tls_size);
400 uptr stack_top, stack_bottom;
401 GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
402 *stk_addr = stack_bottom;
403 *stk_size = stack_top - stack_bottom;
406 // If stack and tls intersect, make them non-intersecting.
407 if (*tls_addr > *stk_addr && *tls_addr < *stk_addr + *stk_size) {
408 CHECK_GT(*tls_addr + *tls_size, *stk_addr);
409 CHECK_LE(*tls_addr + *tls_size, *stk_addr + *stk_size);
410 *stk_size -= *tls_size;
411 *tls_addr = *stk_addr + *stk_size;
417 # if !SANITIZER_FREEBSD
418 typedef ElfW(Phdr) Elf_Phdr;
419 # elif SANITIZER_WORDSIZE == 32 && __FreeBSD_version <= 902001 // v9.2
420 # define Elf_Phdr XElf32_Phdr
421 # define dl_phdr_info xdl_phdr_info
422 # define dl_iterate_phdr(c, b) xdl_iterate_phdr((c), (b))
425 struct DlIteratePhdrData {
426 InternalMmapVector<LoadedModule> *modules;
430 static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
431 DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
432 InternalScopedString module_name(kMaxPathLength);
435 // First module is the binary itself.
436 ReadBinaryNameCached(module_name.data(), module_name.size());
437 } else if (info->dlpi_name) {
438 module_name.append("%s", info->dlpi_name);
440 if (module_name[0] == '\0')
442 LoadedModule cur_module;
443 cur_module.set(module_name.data(), info->dlpi_addr);
444 for (int i = 0; i < info->dlpi_phnum; i++) {
445 const Elf_Phdr *phdr = &info->dlpi_phdr[i];
446 if (phdr->p_type == PT_LOAD) {
447 uptr cur_beg = info->dlpi_addr + phdr->p_vaddr;
448 uptr cur_end = cur_beg + phdr->p_memsz;
449 bool executable = phdr->p_flags & PF_X;
450 bool readable = phdr->p_flags & PF_R;
451 cur_module.addAddressRange(cur_beg, cur_end, executable,
455 data->modules->push_back(cur_module);
459 #if SANITIZER_ANDROID && __ANDROID_API__ < 21
460 extern "C" __attribute__((weak)) int dl_iterate_phdr(
461 int (*)(struct dl_phdr_info *, size_t, void *), void *);
464 void ListOfModules::init() {
466 #if SANITIZER_ANDROID && __ANDROID_API__ <= 22
467 u32 api_level = AndroidGetApiLevel();
468 // Fall back to /proc/maps if dl_iterate_phdr is unavailable or broken.
469 // The runtime check allows the same library to work with
470 // both K and L (and future) Android releases.
471 if (api_level <= ANDROID_LOLLIPOP_MR1) { // L or earlier
472 MemoryMappingLayout memory_mapping(false);
473 memory_mapping.DumpListOfModules(&modules_);
477 DlIteratePhdrData data = {&modules_, true};
478 dl_iterate_phdr(dl_iterate_phdr_cb, &data);
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 openlog(GetProcessName(), 0, LOG_USER);
530 atomic_store(&android_log_initialized, 1, memory_order_release);
533 static bool ShouldLogAfterPrintf() {
534 return atomic_load(&android_log_initialized, memory_order_acquire);
537 void AndroidLogInit() {}
539 static bool ShouldLogAfterPrintf() { return true; }
540 #endif // SANITIZER_ANDROID
542 void WriteOneLineToSyslog(const char *s) {
543 #if SANITIZER_ANDROID &&__ANDROID_API__ < 21
544 __android_log_write(ANDROID_LOG_INFO, NULL, s);
546 syslog(LOG_INFO, "%s", s);
550 void LogMessageOnPrintf(const char *str) {
551 if (common_flags()->log_to_syslog && ShouldLogAfterPrintf())
555 #endif // SANITIZER_LINUX
557 } // namespace __sanitizer
559 #endif // SANITIZER_FREEBSD || SANITIZER_LINUX