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 MemoryMappedSegment segment;
86 while (proc_maps.Next(&segment)) {
87 if ((uptr)&rl < segment.end) break;
88 prev_end = segment.end;
90 CHECK((uptr)&rl >= segment.start && (uptr)&rl < segment.end);
92 // Get stacksize from rlimit, but clip it so that it does not overlap
93 // with other mappings.
94 uptr stacksize = rl.rlim_cur;
95 if (stacksize > segment.end - prev_end) stacksize = segment.end - prev_end;
96 // When running with unlimited stack size, we still want to set some limit.
97 // The unlimited stack size is caused by 'ulimit -s unlimited'.
98 // Also, for some reason, GNU make spawns subprocesses with unlimited stack.
99 if (stacksize > kMaxThreadStackSize)
100 stacksize = kMaxThreadStackSize;
101 *stack_top = segment.end;
102 *stack_bottom = segment.end - stacksize;
106 pthread_attr_init(&attr);
107 CHECK_EQ(pthread_getattr_np(pthread_self(), &attr), 0);
109 void *stackaddr = nullptr;
110 my_pthread_attr_getstack(&attr, &stackaddr, &stacksize);
111 pthread_attr_destroy(&attr);
113 *stack_top = (uptr)stackaddr + stacksize;
114 *stack_bottom = (uptr)stackaddr;
118 bool SetEnv(const char *name, const char *value) {
119 void *f = dlsym(RTLD_NEXT, "setenv");
122 typedef int(*setenv_ft)(const char *name, const char *value, int overwrite);
124 CHECK_EQ(sizeof(setenv_f), sizeof(f));
125 internal_memcpy(&setenv_f, &f, sizeof(f));
126 return setenv_f(name, value, 1) == 0;
130 bool SanitizerSetThreadName(const char *name) {
132 return 0 == prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0); // NOLINT
138 bool SanitizerGetThreadName(char *name, int max_len) {
141 if (prctl(PR_GET_NAME, (unsigned long)buff, 0, 0, 0)) // NOLINT
143 internal_strncpy(name, buff, max_len);
151 #if !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO
152 static uptr g_tls_size;
155 # define DL_INTERNAL_FUNCTION __attribute__((regparm(3), stdcall))
157 # define DL_INTERNAL_FUNCTION
161 // all current supported platforms have 16 bytes stack alignment
162 const size_t kStackAlign = 16;
163 typedef void (*get_tls_func)(size_t*, size_t*) DL_INTERNAL_FUNCTION;
164 get_tls_func get_tls;
165 void *get_tls_static_info_ptr = dlsym(RTLD_NEXT, "_dl_get_tls_static_info");
166 CHECK_EQ(sizeof(get_tls), sizeof(get_tls_static_info_ptr));
167 internal_memcpy(&get_tls, &get_tls_static_info_ptr,
168 sizeof(get_tls_static_info_ptr));
169 CHECK_NE(get_tls, 0);
171 size_t tls_align = 0;
172 get_tls(&tls_size, &tls_align);
173 if (tls_align < kStackAlign)
174 tls_align = kStackAlign;
175 g_tls_size = RoundUpTo(tls_size, tls_align);
178 void InitTlsSize() { }
179 #endif // !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO
181 #if (defined(__x86_64__) || defined(__i386__) || defined(__mips__) \
182 || defined(__aarch64__) || defined(__powerpc64__) || defined(__s390__) \
183 || defined(__arm__)) && SANITIZER_LINUX && !SANITIZER_ANDROID
184 // sizeof(struct pthread) from glibc.
185 static atomic_uintptr_t kThreadDescriptorSize;
187 uptr ThreadDescriptorSize() {
188 uptr val = atomic_load(&kThreadDescriptorSize, memory_order_relaxed);
191 #if defined(__x86_64__) || defined(__i386__) || defined(__arm__)
192 #ifdef _CS_GNU_LIBC_VERSION
194 uptr len = confstr(_CS_GNU_LIBC_VERSION, buf, sizeof(buf));
195 if (len < sizeof(buf) && internal_strncmp(buf, "glibc 2.", 8) == 0) {
197 int minor = internal_simple_strtoll(buf + 8, &end, 10);
198 if (end != buf + 8 && (*end == '\0' || *end == '.' || *end == '-')) {
201 // strtoll will return 0 if no valid conversion could be performed
202 patch = internal_simple_strtoll(end + 1, nullptr, 10);
204 /* sizeof(struct pthread) values from various glibc versions. */
206 val = 1728; // Assume only one particular version for x32.
207 // For ARM sizeof(struct pthread) changed in Glibc 2.23.
208 else if (SANITIZER_ARM)
209 val = minor <= 22 ? 1120 : 1216;
211 val = FIRST_32_SECOND_64(1104, 1696);
213 val = FIRST_32_SECOND_64(1120, 1728);
215 val = FIRST_32_SECOND_64(1136, 1728);
217 val = FIRST_32_SECOND_64(1136, 1712);
218 else if (minor == 10)
219 val = FIRST_32_SECOND_64(1168, 1776);
220 else if (minor == 11 || (minor == 12 && patch == 1))
221 val = FIRST_32_SECOND_64(1168, 2288);
222 else if (minor <= 13)
223 val = FIRST_32_SECOND_64(1168, 2304);
225 val = FIRST_32_SECOND_64(1216, 2304);
228 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
232 #elif defined(__mips__)
233 // TODO(sagarthakur): add more values as per different glibc versions.
234 val = FIRST_32_SECOND_64(1152, 1776);
236 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
238 #elif defined(__aarch64__)
239 // The sizeof (struct pthread) is the same from GLIBC 2.17 to 2.22.
241 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
243 #elif defined(__powerpc64__)
244 val = 1776; // from glibc.ppc64le 2.20-8.fc21
245 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
247 #elif defined(__s390__)
248 val = FIRST_32_SECOND_64(1152, 1776); // valid for glibc 2.22
249 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
254 // The offset at which pointer to self is located in the thread descriptor.
255 const uptr kThreadSelfOffset = FIRST_32_SECOND_64(8, 16);
257 uptr ThreadSelfOffset() {
258 return kThreadSelfOffset;
261 #if defined(__mips__) || defined(__powerpc64__)
262 // TlsPreTcbSize includes size of struct pthread_descr and size of tcb
263 // head structure. It lies before the static tls blocks.
264 static uptr TlsPreTcbSize() {
265 # if defined(__mips__)
266 const uptr kTcbHead = 16; // sizeof (tcbhead_t)
267 # elif defined(__powerpc64__)
268 const uptr kTcbHead = 88; // sizeof (tcbhead_t)
270 const uptr kTlsAlign = 16;
271 const uptr kTlsPreTcbSize =
272 RoundUpTo(ThreadDescriptorSize() + kTcbHead, kTlsAlign);
273 return kTlsPreTcbSize;
279 # if defined(__i386__)
280 asm("mov %%gs:%c1,%0" : "=r"(descr_addr) : "i"(kThreadSelfOffset));
281 # elif defined(__x86_64__)
282 asm("mov %%fs:%c1,%0" : "=r"(descr_addr) : "i"(kThreadSelfOffset));
283 # elif defined(__mips__)
284 // MIPS uses TLS variant I. The thread pointer (in hardware register $29)
285 // points to the end of the TCB + 0x7000. The pthread_descr structure is
286 // immediately in front of the TCB. TlsPreTcbSize() includes the size of the
287 // TCB and the size of pthread_descr.
288 const uptr kTlsTcbOffset = 0x7000;
290 asm volatile(".set push;\
293 .set pop" : "=r" (thread_pointer));
294 descr_addr = thread_pointer - kTlsTcbOffset - TlsPreTcbSize();
295 # elif defined(__aarch64__) || defined(__arm__)
296 descr_addr = reinterpret_cast<uptr>(__builtin_thread_pointer()) -
297 ThreadDescriptorSize();
298 # elif defined(__s390__)
299 descr_addr = reinterpret_cast<uptr>(__builtin_thread_pointer());
300 # elif defined(__powerpc64__)
301 // PPC64LE uses TLS variant I. The thread pointer (in GPR 13)
302 // points to the end of the TCB + 0x7000. The pthread_descr structure is
303 // immediately in front of the TCB. TlsPreTcbSize() includes the size of the
304 // TCB and the size of pthread_descr.
305 const uptr kTlsTcbOffset = 0x7000;
307 asm("addi %0,13,%1" : "=r"(thread_pointer) : "I"(-kTlsTcbOffset));
308 descr_addr = thread_pointer - TlsPreTcbSize();
310 # error "unsupported CPU arch"
314 #endif // (x86_64 || i386 || MIPS) && SANITIZER_LINUX
316 #if SANITIZER_FREEBSD
317 static void **ThreadSelfSegbase() {
319 # if defined(__i386__)
320 // sysarch(I386_GET_GSBASE, segbase);
321 __asm __volatile("mov %%gs:0, %0" : "=r" (segbase));
322 # elif defined(__x86_64__)
323 // sysarch(AMD64_GET_FSBASE, segbase);
324 __asm __volatile("movq %%fs:0, %0" : "=r" (segbase));
326 # error "unsupported CPU arch for FreeBSD platform"
332 return (uptr)ThreadSelfSegbase()[2];
334 #endif // SANITIZER_FREEBSD
337 static void GetTls(uptr *addr, uptr *size) {
338 #if SANITIZER_LINUX && !SANITIZER_ANDROID
339 # if defined(__x86_64__) || defined(__i386__) || defined(__s390__)
340 *addr = ThreadSelf();
341 *size = GetTlsSize();
343 *addr += ThreadDescriptorSize();
344 # 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);
380 #elif defined(__mips__) || defined(__powerpc64__)
381 return RoundUpTo(g_tls_size + TlsPreTcbSize(), 16);
388 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
389 uptr *tls_addr, uptr *tls_size) {
391 // Stub implementation for Go.
392 *stk_addr = *stk_size = *tls_addr = *tls_size = 0;
394 GetTls(tls_addr, tls_size);
396 uptr stack_top, stack_bottom;
397 GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
398 *stk_addr = stack_bottom;
399 *stk_size = stack_top - stack_bottom;
402 // If stack and tls intersect, make them non-intersecting.
403 if (*tls_addr > *stk_addr && *tls_addr < *stk_addr + *stk_size) {
404 CHECK_GT(*tls_addr + *tls_size, *stk_addr);
405 CHECK_LE(*tls_addr + *tls_size, *stk_addr + *stk_size);
406 *stk_size -= *tls_size;
407 *tls_addr = *stk_addr + *stk_size;
413 # if !SANITIZER_FREEBSD
414 typedef ElfW(Phdr) Elf_Phdr;
415 # elif SANITIZER_WORDSIZE == 32 && __FreeBSD_version <= 902001 // v9.2
416 # define Elf_Phdr XElf32_Phdr
417 # define dl_phdr_info xdl_phdr_info
418 # define dl_iterate_phdr(c, b) xdl_iterate_phdr((c), (b))
421 struct DlIteratePhdrData {
422 InternalMmapVector<LoadedModule> *modules;
426 static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
427 DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
428 InternalScopedString module_name(kMaxPathLength);
431 // First module is the binary itself.
432 ReadBinaryNameCached(module_name.data(), module_name.size());
433 } else if (info->dlpi_name) {
434 module_name.append("%s", info->dlpi_name);
436 if (module_name[0] == '\0')
438 LoadedModule cur_module;
439 cur_module.set(module_name.data(), info->dlpi_addr);
440 for (int i = 0; i < info->dlpi_phnum; i++) {
441 const Elf_Phdr *phdr = &info->dlpi_phdr[i];
442 if (phdr->p_type == PT_LOAD) {
443 uptr cur_beg = info->dlpi_addr + phdr->p_vaddr;
444 uptr cur_end = cur_beg + phdr->p_memsz;
445 bool executable = phdr->p_flags & PF_X;
446 bool writable = phdr->p_flags & PF_W;
447 cur_module.addAddressRange(cur_beg, cur_end, executable,
451 data->modules->push_back(cur_module);
455 #if SANITIZER_ANDROID && __ANDROID_API__ < 21
456 extern "C" __attribute__((weak)) int dl_iterate_phdr(
457 int (*)(struct dl_phdr_info *, size_t, void *), void *);
460 void ListOfModules::init() {
462 #if SANITIZER_ANDROID && __ANDROID_API__ <= 22
463 u32 api_level = AndroidGetApiLevel();
464 // Fall back to /proc/maps if dl_iterate_phdr is unavailable or broken.
465 // The runtime check allows the same library to work with
466 // both K and L (and future) Android releases.
467 if (api_level <= ANDROID_LOLLIPOP_MR1) { // L or earlier
468 MemoryMappingLayout memory_mapping(false);
469 memory_mapping.DumpListOfModules(&modules_);
473 DlIteratePhdrData data = {&modules_, true};
474 dl_iterate_phdr(dl_iterate_phdr_cb, &data);
477 // getrusage does not give us the current RSS, only the max RSS.
478 // Still, this is better than nothing if /proc/self/statm is not available
479 // for some reason, e.g. due to a sandbox.
480 static uptr GetRSSFromGetrusage() {
482 if (getrusage(RUSAGE_SELF, &usage)) // Failed, probably due to a sandbox.
484 return usage.ru_maxrss << 10; // ru_maxrss is in Kb.
488 if (!common_flags()->can_use_proc_maps_statm)
489 return GetRSSFromGetrusage();
490 fd_t fd = OpenFile("/proc/self/statm", RdOnly);
491 if (fd == kInvalidFd)
492 return GetRSSFromGetrusage();
494 uptr len = internal_read(fd, buf, sizeof(buf) - 1);
499 // The format of the file is:
500 // 1084 89 69 11 0 79 0
501 // We need the second number which is RSS in pages.
503 // Skip the first number.
504 while (*pos >= '0' && *pos <= '9')
507 while (!(*pos >= '0' && *pos <= '9') && *pos != 0)
511 while (*pos >= '0' && *pos <= '9')
512 rss = rss * 10 + *pos++ - '0';
513 return rss * GetPageSizeCached();
516 // 64-bit Android targets don't provide the deprecated __android_log_write.
517 // Starting with the L release, syslog() works and is preferable to
518 // __android_log_write.
521 #if SANITIZER_ANDROID
522 static atomic_uint8_t android_log_initialized;
524 void AndroidLogInit() {
525 openlog(GetProcessName(), 0, LOG_USER);
526 atomic_store(&android_log_initialized, 1, memory_order_release);
529 static bool ShouldLogAfterPrintf() {
530 return atomic_load(&android_log_initialized, memory_order_acquire);
533 void AndroidLogInit() {}
535 static bool ShouldLogAfterPrintf() { return true; }
536 #endif // SANITIZER_ANDROID
538 void WriteOneLineToSyslog(const char *s) {
539 #if SANITIZER_ANDROID &&__ANDROID_API__ < 21
540 __android_log_write(ANDROID_LOG_INFO, NULL, s);
542 syslog(LOG_INFO, "%s", s);
546 void LogMessageOnPrintf(const char *str) {
547 if (common_flags()->log_to_syslog && ShouldLogAfterPrintf())
551 #if SANITIZER_ANDROID && __ANDROID_API__ >= 21
552 extern "C" void android_set_abort_message(const char *msg);
553 void SetAbortMessage(const char *str) { android_set_abort_message(str); }
555 void SetAbortMessage(const char *str) {}
558 #endif // SANITIZER_LINUX
560 } // namespace __sanitizer
562 #endif // SANITIZER_FREEBSD || SANITIZER_LINUX