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"
16 #if SANITIZER_FREEBSD || SANITIZER_LINUX
18 #include "sanitizer_common.h"
19 #include "sanitizer_flags.h"
20 #include "sanitizer_freebsd.h"
21 #include "sanitizer_linux.h"
22 #include "sanitizer_placement_new.h"
23 #include "sanitizer_procmaps.h"
24 #include "sanitizer_stacktrace.h"
25 #include "sanitizer_atomic.h"
26 #include "sanitizer_symbolizer.h"
28 #if SANITIZER_ANDROID || SANITIZER_FREEBSD
29 #include <dlfcn.h> // for dlsym()
34 #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>
46 #if !SANITIZER_ANDROID
52 namespace __sanitizer {
54 // This function is defined elsewhere if we intercepted pthread_attr_getstack.
56 SANITIZER_WEAK_ATTRIBUTE int
57 real_pthread_attr_getstack(void *attr, void **addr, size_t *size);
60 static int my_pthread_attr_getstack(void *attr, void **addr, size_t *size) {
62 if (&real_pthread_attr_getstack)
63 return real_pthread_attr_getstack((pthread_attr_t *)attr, addr, size);
65 return pthread_attr_getstack((pthread_attr_t *)attr, addr, size);
68 SANITIZER_WEAK_ATTRIBUTE int
69 real_sigaction(int signum, const void *act, void *oldact);
71 int internal_sigaction(int signum, const void *act, void *oldact) {
74 return real_sigaction(signum, act, oldact);
76 return sigaction(signum, (const struct sigaction *)act,
77 (struct sigaction *)oldact);
80 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
84 if (at_initialization) {
85 // This is the main thread. Libpthread may not be initialized yet.
87 CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
89 // Find the mapping that contains a stack variable.
90 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
91 uptr start, end, offset;
93 while (proc_maps.Next(&start, &end, &offset, 0, 0, /* protection */0)) {
98 CHECK((uptr)&rl >= start && (uptr)&rl < end);
100 // Get stacksize from rlimit, but clip it so that it does not overlap
101 // with other mappings.
102 uptr stacksize = rl.rlim_cur;
103 if (stacksize > end - prev_end)
104 stacksize = end - prev_end;
105 // When running with unlimited stack size, we still want to set some limit.
106 // The unlimited stack size is caused by 'ulimit -s unlimited'.
107 // Also, for some reason, GNU make spawns subprocesses with unlimited stack.
108 if (stacksize > kMaxThreadStackSize)
109 stacksize = kMaxThreadStackSize;
111 *stack_bottom = end - stacksize;
115 pthread_attr_init(&attr);
116 CHECK_EQ(pthread_getattr_np(pthread_self(), &attr), 0);
119 my_pthread_attr_getstack(&attr, &stackaddr, (size_t*)&stacksize);
120 pthread_attr_destroy(&attr);
122 CHECK_LE(stacksize, kMaxThreadStackSize); // Sanity check.
123 *stack_top = (uptr)stackaddr + stacksize;
124 *stack_bottom = (uptr)stackaddr;
128 bool SetEnv(const char *name, const char *value) {
129 void *f = dlsym(RTLD_NEXT, "setenv");
132 typedef int(*setenv_ft)(const char *name, const char *value, int overwrite);
134 CHECK_EQ(sizeof(setenv_f), sizeof(f));
135 internal_memcpy(&setenv_f, &f, sizeof(f));
136 return setenv_f(name, value, 1) == 0;
140 bool SanitizerSetThreadName(const char *name) {
142 return 0 == prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0); // NOLINT
148 bool SanitizerGetThreadName(char *name, int max_len) {
151 if (prctl(PR_GET_NAME, (unsigned long)buff, 0, 0, 0)) // NOLINT
153 internal_strncpy(name, buff, max_len);
161 #if !SANITIZER_FREEBSD
162 static uptr g_tls_size;
166 # define DL_INTERNAL_FUNCTION __attribute__((regparm(3), stdcall))
168 # define DL_INTERNAL_FUNCTION
171 #if defined(__mips__)
172 // TlsPreTcbSize includes size of struct pthread_descr and size of tcb
173 // head structure. It lies before the static tls blocks.
174 static uptr TlsPreTcbSize() {
175 const uptr kTcbHead = 16;
176 const uptr kTlsAlign = 16;
177 const uptr kTlsPreTcbSize =
178 (ThreadDescriptorSize() + kTcbHead + kTlsAlign - 1) & ~(kTlsAlign - 1);
180 g_tls_size = (g_tls_size + kTlsPreTcbSize + kTlsAlign -1) & ~(kTlsAlign - 1);
181 return kTlsPreTcbSize;
186 #if !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO
187 typedef void (*get_tls_func)(size_t*, size_t*) DL_INTERNAL_FUNCTION;
188 get_tls_func get_tls;
189 void *get_tls_static_info_ptr = dlsym(RTLD_NEXT, "_dl_get_tls_static_info");
190 CHECK_EQ(sizeof(get_tls), sizeof(get_tls_static_info_ptr));
191 internal_memcpy(&get_tls, &get_tls_static_info_ptr,
192 sizeof(get_tls_static_info_ptr));
193 CHECK_NE(get_tls, 0);
195 size_t tls_align = 0;
196 get_tls(&tls_size, &tls_align);
197 g_tls_size = tls_size;
198 #endif // !SANITIZER_FREEBSD && !SANITIZER_ANDROID
201 #if (defined(__x86_64__) || defined(__i386__) || defined(__mips__)) \
203 // sizeof(struct thread) from glibc.
204 static atomic_uintptr_t kThreadDescriptorSize;
206 uptr ThreadDescriptorSize() {
207 uptr val = atomic_load(&kThreadDescriptorSize, memory_order_relaxed);
210 #if defined(__x86_64__) || defined(__i386__)
211 #ifdef _CS_GNU_LIBC_VERSION
213 uptr len = confstr(_CS_GNU_LIBC_VERSION, buf, sizeof(buf));
214 if (len < sizeof(buf) && internal_strncmp(buf, "glibc 2.", 8) == 0) {
216 int minor = internal_simple_strtoll(buf + 8, &end, 10);
217 if (end != buf + 8 && (*end == '\0' || *end == '.')) {
218 /* sizeof(struct thread) values from various glibc versions. */
220 val = 1728; // Assume only one particular version for x32.
222 val = FIRST_32_SECOND_64(1104, 1696);
224 val = FIRST_32_SECOND_64(1120, 1728);
226 val = FIRST_32_SECOND_64(1136, 1728);
228 val = FIRST_32_SECOND_64(1136, 1712);
229 else if (minor == 10)
230 val = FIRST_32_SECOND_64(1168, 1776);
231 else if (minor <= 12)
232 val = FIRST_32_SECOND_64(1168, 2288);
233 else if (minor == 13)
234 val = FIRST_32_SECOND_64(1168, 2304);
236 val = FIRST_32_SECOND_64(1216, 2304);
239 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
243 #elif defined(__mips__)
244 // TODO(sagarthakur): add more values as per different glibc versions.
245 val = FIRST_32_SECOND_64(1152, 1776);
247 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
253 // The offset at which pointer to self is located in the thread descriptor.
254 const uptr kThreadSelfOffset = FIRST_32_SECOND_64(8, 16);
256 uptr ThreadSelfOffset() {
257 return kThreadSelfOffset;
262 # if defined(__i386__)
263 asm("mov %%gs:%c1,%0" : "=r"(descr_addr) : "i"(kThreadSelfOffset));
264 # elif defined(__x86_64__)
265 asm("mov %%fs:%c1,%0" : "=r"(descr_addr) : "i"(kThreadSelfOffset));
266 # elif defined(__mips__)
267 // MIPS uses TLS variant I. The thread pointer (in hardware register $29)
268 // points to the end of the TCB + 0x7000. The pthread_descr structure is
269 // immediately in front of the TCB. TlsPreTcbSize() includes the size of the
270 // TCB and the size of pthread_descr.
271 const uptr kTlsTcbOffset = 0x7000;
273 asm volatile(".set push;\
276 .set pop" : "=r" (thread_pointer));
277 descr_addr = thread_pointer - kTlsTcbOffset - TlsPreTcbSize();
279 # error "unsupported CPU arch"
283 #endif // (x86_64 || i386 || MIPS) && SANITIZER_LINUX
285 #if SANITIZER_FREEBSD
286 static void **ThreadSelfSegbase() {
288 # if defined(__i386__)
289 // sysarch(I386_GET_GSBASE, segbase);
290 __asm __volatile("mov %%gs:0, %0" : "=r" (segbase));
291 # elif defined(__x86_64__)
292 // sysarch(AMD64_GET_FSBASE, segbase);
293 __asm __volatile("movq %%fs:0, %0" : "=r" (segbase));
295 # error "unsupported CPU arch for FreeBSD platform"
301 return (uptr)ThreadSelfSegbase()[2];
303 #endif // SANITIZER_FREEBSD
306 static void GetTls(uptr *addr, uptr *size) {
308 # if defined(__x86_64__) || defined(__i386__)
309 *addr = ThreadSelf();
310 *size = GetTlsSize();
312 *addr += ThreadDescriptorSize();
313 # elif defined(__mips__)
314 *addr = ThreadSelf();
315 *size = GetTlsSize();
320 #elif SANITIZER_FREEBSD
321 void** segbase = ThreadSelfSegbase();
326 // tls_size = round(tls_static_space, tcbalign);
328 // dtv[2] = segbase - tls_static_space;
329 void **dtv = (void**) segbase[1];
330 *addr = (uptr) dtv[2];
331 *size = (*addr == 0) ? 0 : ((uptr) segbase[0] - (uptr) dtv[2]);
341 #if SANITIZER_FREEBSD
343 GetTls(&addr, &size);
351 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
352 uptr *tls_addr, uptr *tls_size) {
354 // Stub implementation for Go.
355 *stk_addr = *stk_size = *tls_addr = *tls_size = 0;
357 GetTls(tls_addr, tls_size);
359 uptr stack_top, stack_bottom;
360 GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
361 *stk_addr = stack_bottom;
362 *stk_size = stack_top - stack_bottom;
365 // If stack and tls intersect, make them non-intersecting.
366 if (*tls_addr > *stk_addr && *tls_addr < *stk_addr + *stk_size) {
367 CHECK_GT(*tls_addr + *tls_size, *stk_addr);
368 CHECK_LE(*tls_addr + *tls_size, *stk_addr + *stk_size);
369 *stk_size -= *tls_size;
370 *tls_addr = *stk_addr + *stk_size;
376 void AdjustStackSize(void *attr_) {
377 pthread_attr_t *attr = (pthread_attr_t *)attr_;
379 size_t stacksize = 0;
380 my_pthread_attr_getstack(attr, (void**)&stackaddr, &stacksize);
381 // GLibC will return (0 - stacksize) as the stack address in the case when
382 // stacksize is set, but stackaddr is not.
383 bool stack_set = (stackaddr != 0) && (stackaddr + stacksize != 0);
384 // We place a lot of tool data into TLS, account for that.
385 const uptr minstacksize = GetTlsSize() + 128*1024;
386 if (stacksize < minstacksize) {
388 if (stacksize != 0) {
389 VPrintf(1, "Sanitizer: increasing stacksize %zu->%zu\n", stacksize,
391 pthread_attr_setstacksize(attr, minstacksize);
394 Printf("Sanitizer: pre-allocated stack size is insufficient: "
395 "%zu < %zu\n", stacksize, minstacksize);
396 Printf("Sanitizer: pthread_create is likely to fail.\n");
401 #if SANITIZER_ANDROID
402 uptr GetListOfModules(LoadedModule *modules, uptr max_modules,
403 string_predicate_t filter) {
404 MemoryMappingLayout memory_mapping(false);
405 return memory_mapping.DumpListOfModules(modules, max_modules, filter);
407 #else // SANITIZER_ANDROID
408 # if !SANITIZER_FREEBSD
409 typedef ElfW(Phdr) Elf_Phdr;
410 # elif SANITIZER_WORDSIZE == 32 && __FreeBSD_version <= 902001 // v9.2
411 # define Elf_Phdr XElf32_Phdr
412 # define dl_phdr_info xdl_phdr_info
413 # define dl_iterate_phdr(c, b) xdl_iterate_phdr((c), (b))
416 struct DlIteratePhdrData {
417 LoadedModule *modules;
421 string_predicate_t filter;
424 static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
425 DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
426 if (data->current_n == data->max_n)
428 InternalScopedString module_name(kMaxPathLength);
431 // First module is the binary itself.
432 ReadBinaryName(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 if (data->filter && !data->filter(module_name.data()))
440 void *mem = &data->modules[data->current_n];
441 LoadedModule *cur_module = new(mem) LoadedModule(module_name.data(),
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 cur_module->addAddressRange(cur_beg, cur_end, executable);
456 uptr GetListOfModules(LoadedModule *modules, uptr max_modules,
457 string_predicate_t filter) {
459 DlIteratePhdrData data = {modules, 0, true, max_modules, filter};
460 dl_iterate_phdr(dl_iterate_phdr_cb, &data);
461 return data.current_n;
463 #endif // SANITIZER_ANDROID
465 void PrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
466 // Some kinds of sandboxes may forbid filesystem access, so we won't be able
467 // to read the file mappings from /proc/self/maps. Luckily, neither the
468 // process will be able to load additional libraries, so it's fine to use the
470 MemoryMappingLayout::CacheMemoryMappings();
471 // Same for /proc/self/exe in the symbolizer.
473 Symbolizer::GetOrInit()->PrepareForSandboxing();
474 CovPrepareForSandboxing(args);
478 // getrusage does not give us the current RSS, only the max RSS.
479 // Still, this is better than nothing if /proc/self/statm is not available
480 // for some reason, e.g. due to a sandbox.
481 static uptr GetRSSFromGetrusage() {
483 if (getrusage(RUSAGE_SELF, &usage)) // Failed, probably due to a sandbox.
485 return usage.ru_maxrss << 10; // ru_maxrss is in Kb.
489 if (!common_flags()->can_use_proc_maps_statm)
490 return GetRSSFromGetrusage();
491 uptr fd = OpenFile("/proc/self/statm", false);
493 return GetRSSFromGetrusage();
495 uptr len = internal_read(fd, buf, sizeof(buf) - 1);
500 // The format of the file is:
501 // 1084 89 69 11 0 79 0
502 // We need the second number which is RSS in pages.
504 // Skip the first number.
505 while (*pos >= '0' && *pos <= '9')
508 while (!(*pos >= '0' && *pos <= '9') && *pos != 0)
512 while (*pos >= '0' && *pos <= '9')
513 rss = rss * 10 + *pos++ - '0';
514 return rss * GetPageSizeCached();
517 } // namespace __sanitizer
519 #endif // SANITIZER_FREEBSD || SANITIZER_LINUX