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) {
61 if (real_pthread_attr_getstack)
62 return real_pthread_attr_getstack((pthread_attr_t *)attr, addr, size);
63 return pthread_attr_getstack((pthread_attr_t *)attr, addr, size);
66 SANITIZER_WEAK_ATTRIBUTE int
67 real_sigaction(int signum, const void *act, void *oldact);
69 int internal_sigaction(int signum, const void *act, void *oldact) {
71 return real_sigaction(signum, act, oldact);
72 return sigaction(signum, (const struct sigaction *)act,
73 (struct sigaction *)oldact);
76 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
80 if (at_initialization) {
81 // This is the main thread. Libpthread may not be initialized yet.
83 CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
85 // Find the mapping that contains a stack variable.
86 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
87 uptr start, end, offset;
89 while (proc_maps.Next(&start, &end, &offset, 0, 0, /* protection */0)) {
94 CHECK((uptr)&rl >= start && (uptr)&rl < end);
96 // Get stacksize from rlimit, but clip it so that it does not overlap
97 // with other mappings.
98 uptr stacksize = rl.rlim_cur;
99 if (stacksize > end - prev_end)
100 stacksize = end - prev_end;
101 // When running with unlimited stack size, we still want to set some limit.
102 // The unlimited stack size is caused by 'ulimit -s unlimited'.
103 // Also, for some reason, GNU make spawns subprocesses with unlimited stack.
104 if (stacksize > kMaxThreadStackSize)
105 stacksize = kMaxThreadStackSize;
107 *stack_bottom = end - stacksize;
111 pthread_attr_init(&attr);
112 CHECK_EQ(pthread_getattr_np(pthread_self(), &attr), 0);
115 my_pthread_attr_getstack(&attr, &stackaddr, (size_t*)&stacksize);
116 pthread_attr_destroy(&attr);
118 CHECK_LE(stacksize, kMaxThreadStackSize); // Sanity check.
119 *stack_top = (uptr)stackaddr + stacksize;
120 *stack_bottom = (uptr)stackaddr;
123 bool SetEnv(const char *name, const char *value) {
124 void *f = dlsym(RTLD_NEXT, "setenv");
127 typedef int(*setenv_ft)(const char *name, const char *value, int overwrite);
129 CHECK_EQ(sizeof(setenv_f), sizeof(f));
130 internal_memcpy(&setenv_f, &f, sizeof(f));
131 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
156 static uptr g_tls_size;
160 # define DL_INTERNAL_FUNCTION __attribute__((regparm(3), stdcall))
162 # define DL_INTERNAL_FUNCTION
166 #if !SANITIZER_FREEBSD && !SANITIZER_ANDROID
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 g_tls_size = tls_size;
178 #endif // !SANITIZER_FREEBSD && !SANITIZER_ANDROID
181 #if (defined(__x86_64__) || defined(__i386__)) && SANITIZER_LINUX
182 // sizeof(struct thread) from glibc.
183 static atomic_uintptr_t kThreadDescriptorSize;
185 uptr ThreadDescriptorSize() {
186 uptr val = atomic_load(&kThreadDescriptorSize, memory_order_relaxed);
189 #ifdef _CS_GNU_LIBC_VERSION
191 uptr len = confstr(_CS_GNU_LIBC_VERSION, buf, sizeof(buf));
192 if (len < sizeof(buf) && internal_strncmp(buf, "glibc 2.", 8) == 0) {
194 int minor = internal_simple_strtoll(buf + 8, &end, 10);
195 if (end != buf + 8 && (*end == '\0' || *end == '.')) {
196 /* sizeof(struct thread) values from various glibc versions. */
198 val = 1728; // Assume only one particular version for x32.
200 val = FIRST_32_SECOND_64(1104, 1696);
202 val = FIRST_32_SECOND_64(1120, 1728);
204 val = FIRST_32_SECOND_64(1136, 1728);
206 val = FIRST_32_SECOND_64(1136, 1712);
207 else if (minor == 10)
208 val = FIRST_32_SECOND_64(1168, 1776);
209 else if (minor <= 12)
210 val = FIRST_32_SECOND_64(1168, 2288);
212 val = FIRST_32_SECOND_64(1216, 2304);
215 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
222 // The offset at which pointer to self is located in the thread descriptor.
223 const uptr kThreadSelfOffset = FIRST_32_SECOND_64(8, 16);
225 uptr ThreadSelfOffset() {
226 return kThreadSelfOffset;
231 # if defined(__i386__)
232 asm("mov %%gs:%c1,%0" : "=r"(descr_addr) : "i"(kThreadSelfOffset));
233 # elif defined(__x86_64__)
234 asm("mov %%fs:%c1,%0" : "=r"(descr_addr) : "i"(kThreadSelfOffset));
236 # error "unsupported CPU arch"
240 #endif // (defined(__x86_64__) || defined(__i386__)) && SANITIZER_LINUX
242 #if SANITIZER_FREEBSD
243 static void **ThreadSelfSegbase() {
245 # if defined(__i386__)
246 // sysarch(I386_GET_GSBASE, segbase);
247 __asm __volatile("mov %%gs:0, %0" : "=r" (segbase));
248 # elif defined(__x86_64__)
249 // sysarch(AMD64_GET_FSBASE, segbase);
250 __asm __volatile("movq %%fs:0, %0" : "=r" (segbase));
252 # error "unsupported CPU arch for FreeBSD platform"
258 return (uptr)ThreadSelfSegbase()[2];
260 #endif // SANITIZER_FREEBSD
262 static void GetTls(uptr *addr, uptr *size) {
264 # if defined(__x86_64__) || defined(__i386__)
265 *addr = ThreadSelf();
266 *size = GetTlsSize();
268 *addr += ThreadDescriptorSize();
273 #elif SANITIZER_FREEBSD
274 void** segbase = ThreadSelfSegbase();
279 // tls_size = round(tls_static_space, tcbalign);
281 // dtv[2] = segbase - tls_static_space;
282 void **dtv = (void**) segbase[1];
283 *addr = (uptr) dtv[2];
284 *size = (*addr == 0) ? 0 : ((uptr) segbase[0] - (uptr) dtv[2]);
292 #if SANITIZER_FREEBSD
294 GetTls(&addr, &size);
301 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
302 uptr *tls_addr, uptr *tls_size) {
303 GetTls(tls_addr, tls_size);
305 uptr stack_top, stack_bottom;
306 GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
307 *stk_addr = stack_bottom;
308 *stk_size = stack_top - stack_bottom;
311 // If stack and tls intersect, make them non-intersecting.
312 if (*tls_addr > *stk_addr && *tls_addr < *stk_addr + *stk_size) {
313 CHECK_GT(*tls_addr + *tls_size, *stk_addr);
314 CHECK_LE(*tls_addr + *tls_size, *stk_addr + *stk_size);
315 *stk_size -= *tls_size;
316 *tls_addr = *stk_addr + *stk_size;
321 void AdjustStackSize(void *attr_) {
322 pthread_attr_t *attr = (pthread_attr_t *)attr_;
324 size_t stacksize = 0;
325 my_pthread_attr_getstack(attr, (void**)&stackaddr, &stacksize);
326 // GLibC will return (0 - stacksize) as the stack address in the case when
327 // stacksize is set, but stackaddr is not.
328 bool stack_set = (stackaddr != 0) && (stackaddr + stacksize != 0);
329 // We place a lot of tool data into TLS, account for that.
330 const uptr minstacksize = GetTlsSize() + 128*1024;
331 if (stacksize < minstacksize) {
333 if (stacksize != 0) {
334 VPrintf(1, "Sanitizer: increasing stacksize %zu->%zu\n", stacksize,
336 pthread_attr_setstacksize(attr, minstacksize);
339 Printf("Sanitizer: pre-allocated stack size is insufficient: "
340 "%zu < %zu\n", stacksize, minstacksize);
341 Printf("Sanitizer: pthread_create is likely to fail.\n");
346 #if SANITIZER_ANDROID
347 uptr GetListOfModules(LoadedModule *modules, uptr max_modules,
348 string_predicate_t filter) {
349 MemoryMappingLayout memory_mapping(false);
350 return memory_mapping.DumpListOfModules(modules, max_modules, filter);
352 #else // SANITIZER_ANDROID
353 # if !SANITIZER_FREEBSD
354 typedef ElfW(Phdr) Elf_Phdr;
355 # elif SANITIZER_WORDSIZE == 32 && __FreeBSD_version <= 902001 // v9.2
356 # define Elf_Phdr XElf32_Phdr
357 # define dl_phdr_info xdl_phdr_info
358 # define dl_iterate_phdr(c, b) xdl_iterate_phdr((c), (b))
361 struct DlIteratePhdrData {
362 LoadedModule *modules;
366 string_predicate_t filter;
369 static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
370 DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
371 if (data->current_n == data->max_n)
373 InternalScopedString module_name(kMaxPathLength);
376 // First module is the binary itself.
377 ReadBinaryName(module_name.data(), module_name.size());
378 } else if (info->dlpi_name) {
379 module_name.append("%s", info->dlpi_name);
381 if (module_name[0] == '\0')
383 if (data->filter && !data->filter(module_name.data()))
385 void *mem = &data->modules[data->current_n];
386 LoadedModule *cur_module = new(mem) LoadedModule(module_name.data(),
389 for (int i = 0; i < info->dlpi_phnum; i++) {
390 const Elf_Phdr *phdr = &info->dlpi_phdr[i];
391 if (phdr->p_type == PT_LOAD) {
392 uptr cur_beg = info->dlpi_addr + phdr->p_vaddr;
393 uptr cur_end = cur_beg + phdr->p_memsz;
394 bool executable = phdr->p_flags & PF_X;
395 cur_module->addAddressRange(cur_beg, cur_end, executable);
401 uptr GetListOfModules(LoadedModule *modules, uptr max_modules,
402 string_predicate_t filter) {
404 DlIteratePhdrData data = {modules, 0, true, max_modules, filter};
405 dl_iterate_phdr(dl_iterate_phdr_cb, &data);
406 return data.current_n;
408 #endif // SANITIZER_ANDROID
410 void PrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
411 // Some kinds of sandboxes may forbid filesystem access, so we won't be able
412 // to read the file mappings from /proc/self/maps. Luckily, neither the
413 // process will be able to load additional libraries, so it's fine to use the
415 MemoryMappingLayout::CacheMemoryMappings();
416 // Same for /proc/self/exe in the symbolizer.
418 Symbolizer::GetOrInit()->PrepareForSandboxing();
419 CovPrepareForSandboxing(args);
423 } // namespace __sanitizer
425 #endif // SANITIZER_FREEBSD || SANITIZER_LINUX