]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/sanitizer_common/sanitizer_linux_libcdep.cc
Merge ^/head r279759 through r279892.
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / sanitizer_common / sanitizer_linux_libcdep.cc
1 //===-- sanitizer_linux_libcdep.cc ----------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file is shared between AddressSanitizer and ThreadSanitizer
11 // run-time libraries and implements linux-specific functions from
12 // sanitizer_libc.h.
13 //===----------------------------------------------------------------------===//
14
15 #include "sanitizer_platform.h"
16 #if SANITIZER_FREEBSD || SANITIZER_LINUX
17
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"
27
28 #if SANITIZER_ANDROID || SANITIZER_FREEBSD
29 #include <dlfcn.h>  // for dlsym()
30 #endif
31
32 #include <pthread.h>
33 #include <signal.h>
34 #include <sys/resource.h>
35
36 #if SANITIZER_FREEBSD
37 #include <pthread_np.h>
38 #include <osreldate.h>
39 #define pthread_getattr_np pthread_attr_get_np
40 #endif
41
42 #if SANITIZER_LINUX
43 #include <sys/prctl.h>
44 #endif
45
46 #if !SANITIZER_ANDROID
47 #include <elf.h>
48 #include <link.h>
49 #include <unistd.h>
50 #endif
51
52 namespace __sanitizer {
53
54 // This function is defined elsewhere if we intercepted pthread_attr_getstack.
55 extern "C" {
56 SANITIZER_WEAK_ATTRIBUTE int
57 real_pthread_attr_getstack(void *attr, void **addr, size_t *size);
58 }  // extern "C"
59
60 static int my_pthread_attr_getstack(void *attr, void **addr, size_t *size) {
61 #if !SANITIZER_GO
62   if (&real_pthread_attr_getstack)
63     return real_pthread_attr_getstack((pthread_attr_t *)attr, addr, size);
64 #endif
65   return pthread_attr_getstack((pthread_attr_t *)attr, addr, size);
66 }
67
68 SANITIZER_WEAK_ATTRIBUTE int
69 real_sigaction(int signum, const void *act, void *oldact);
70
71 int internal_sigaction(int signum, const void *act, void *oldact) {
72 #if !SANITIZER_GO
73   if (&real_sigaction)
74     return real_sigaction(signum, act, oldact);
75 #endif
76   return sigaction(signum, (const struct sigaction *)act,
77                    (struct sigaction *)oldact);
78 }
79
80 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
81                                 uptr *stack_bottom) {
82   CHECK(stack_top);
83   CHECK(stack_bottom);
84   if (at_initialization) {
85     // This is the main thread. Libpthread may not be initialized yet.
86     struct rlimit rl;
87     CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
88
89     // Find the mapping that contains a stack variable.
90     MemoryMappingLayout proc_maps(/*cache_enabled*/true);
91     uptr start, end, offset;
92     uptr prev_end = 0;
93     while (proc_maps.Next(&start, &end, &offset, 0, 0, /* protection */0)) {
94       if ((uptr)&rl < end)
95         break;
96       prev_end = end;
97     }
98     CHECK((uptr)&rl >= start && (uptr)&rl < end);
99
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;
110     *stack_top = end;
111     *stack_bottom = end - stacksize;
112     return;
113   }
114   pthread_attr_t attr;
115   pthread_attr_init(&attr);
116   CHECK_EQ(pthread_getattr_np(pthread_self(), &attr), 0);
117   uptr stacksize = 0;
118   void *stackaddr = 0;
119   my_pthread_attr_getstack(&attr, &stackaddr, (size_t*)&stacksize);
120   pthread_attr_destroy(&attr);
121
122   CHECK_LE(stacksize, kMaxThreadStackSize);  // Sanity check.
123   *stack_top = (uptr)stackaddr + stacksize;
124   *stack_bottom = (uptr)stackaddr;
125 }
126
127 #if !SANITIZER_GO
128 bool SetEnv(const char *name, const char *value) {
129   void *f = dlsym(RTLD_NEXT, "setenv");
130   if (f == 0)
131     return false;
132   typedef int(*setenv_ft)(const char *name, const char *value, int overwrite);
133   setenv_ft setenv_f;
134   CHECK_EQ(sizeof(setenv_f), sizeof(f));
135   internal_memcpy(&setenv_f, &f, sizeof(f));
136   return setenv_f(name, value, 1) == 0;
137 }
138 #endif
139
140 bool SanitizerSetThreadName(const char *name) {
141 #ifdef PR_SET_NAME
142   return 0 == prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0);  // NOLINT
143 #else
144   return false;
145 #endif
146 }
147
148 bool SanitizerGetThreadName(char *name, int max_len) {
149 #ifdef PR_GET_NAME
150   char buff[17];
151   if (prctl(PR_GET_NAME, (unsigned long)buff, 0, 0, 0))  // NOLINT
152     return false;
153   internal_strncpy(name, buff, max_len);
154   name[max_len] = 0;
155   return true;
156 #else
157   return false;
158 #endif
159 }
160
161 #if !SANITIZER_FREEBSD
162 static uptr g_tls_size;
163 #endif
164
165 #ifdef __i386__
166 # define DL_INTERNAL_FUNCTION __attribute__((regparm(3), stdcall))
167 #else
168 # define DL_INTERNAL_FUNCTION
169 #endif
170
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);
179   InitTlsSize();
180   g_tls_size = (g_tls_size + kTlsPreTcbSize + kTlsAlign -1) & ~(kTlsAlign - 1);
181   return kTlsPreTcbSize;
182 }
183 #endif
184
185 void InitTlsSize() {
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);
194   size_t tls_size = 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
199 }
200
201 #if (defined(__x86_64__) || defined(__i386__) || defined(__mips__)) \
202     && SANITIZER_LINUX
203 // sizeof(struct thread) from glibc.
204 static atomic_uintptr_t kThreadDescriptorSize;
205
206 uptr ThreadDescriptorSize() {
207   uptr val = atomic_load(&kThreadDescriptorSize, memory_order_relaxed);
208   if (val)
209     return val;
210 #if defined(__x86_64__) || defined(__i386__)
211 #ifdef _CS_GNU_LIBC_VERSION
212   char buf[64];
213   uptr len = confstr(_CS_GNU_LIBC_VERSION, buf, sizeof(buf));
214   if (len < sizeof(buf) && internal_strncmp(buf, "glibc 2.", 8) == 0) {
215     char *end;
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.  */
219       if (SANITIZER_X32)
220         val = 1728;  // Assume only one particular version for x32.
221       else if (minor <= 3)
222         val = FIRST_32_SECOND_64(1104, 1696);
223       else if (minor == 4)
224         val = FIRST_32_SECOND_64(1120, 1728);
225       else if (minor == 5)
226         val = FIRST_32_SECOND_64(1136, 1728);
227       else if (minor <= 9)
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);
235       else
236         val = FIRST_32_SECOND_64(1216, 2304);
237     }
238     if (val)
239       atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
240     return val;
241   }
242 #endif
243 #elif defined(__mips__)
244   // TODO(sagarthakur): add more values as per different glibc versions.
245   val = FIRST_32_SECOND_64(1152, 1776);
246   if (val)
247     atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
248   return val;
249 #endif
250   return 0;
251 }
252
253 // The offset at which pointer to self is located in the thread descriptor.
254 const uptr kThreadSelfOffset = FIRST_32_SECOND_64(8, 16);
255
256 uptr ThreadSelfOffset() {
257   return kThreadSelfOffset;
258 }
259
260 uptr ThreadSelf() {
261   uptr descr_addr;
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;
272   uptr thread_pointer;
273   asm volatile(".set push;\
274                 .set mips64r2;\
275                 rdhwr %0,$29;\
276                 .set pop" : "=r" (thread_pointer));
277   descr_addr = thread_pointer - kTlsTcbOffset - TlsPreTcbSize();
278 # else
279 #  error "unsupported CPU arch"
280 # endif
281   return descr_addr;
282 }
283 #endif  // (x86_64 || i386 || MIPS) && SANITIZER_LINUX
284
285 #if SANITIZER_FREEBSD
286 static void **ThreadSelfSegbase() {
287   void **segbase = 0;
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));
294 # else
295 #  error "unsupported CPU arch for FreeBSD platform"
296 # endif
297   return segbase;
298 }
299
300 uptr ThreadSelf() {
301   return (uptr)ThreadSelfSegbase()[2];
302 }
303 #endif  // SANITIZER_FREEBSD
304
305 #if !SANITIZER_GO
306 static void GetTls(uptr *addr, uptr *size) {
307 #if SANITIZER_LINUX
308 # if defined(__x86_64__) || defined(__i386__)
309   *addr = ThreadSelf();
310   *size = GetTlsSize();
311   *addr -= *size;
312   *addr += ThreadDescriptorSize();
313 # elif defined(__mips__)
314   *addr = ThreadSelf();
315   *size = GetTlsSize();
316 # else
317   *addr = 0;
318   *size = 0;
319 # endif
320 #elif SANITIZER_FREEBSD
321   void** segbase = ThreadSelfSegbase();
322   *addr = 0;
323   *size = 0;
324   if (segbase != 0) {
325     // tcbalign = 16
326     // tls_size = round(tls_static_space, tcbalign);
327     // dtv = segbase[1];
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]);
332   }
333 #else
334 # error "Unknown OS"
335 #endif
336 }
337 #endif
338
339 #if !SANITIZER_GO
340 uptr GetTlsSize() {
341 #if SANITIZER_FREEBSD
342   uptr addr, size;
343   GetTls(&addr, &size);
344   return size;
345 #else
346   return g_tls_size;
347 #endif
348 }
349 #endif
350
351 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
352                           uptr *tls_addr, uptr *tls_size) {
353 #if SANITIZER_GO
354   // Stub implementation for Go.
355   *stk_addr = *stk_size = *tls_addr = *tls_size = 0;
356 #else
357   GetTls(tls_addr, tls_size);
358
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;
363
364   if (!main) {
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;
371     }
372   }
373 #endif
374 }
375
376 void AdjustStackSize(void *attr_) {
377   pthread_attr_t *attr = (pthread_attr_t *)attr_;
378   uptr stackaddr = 0;
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) {
387     if (!stack_set) {
388       if (stacksize != 0) {
389         VPrintf(1, "Sanitizer: increasing stacksize %zu->%zu\n", stacksize,
390                 minstacksize);
391         pthread_attr_setstacksize(attr, minstacksize);
392       }
393     } else {
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");
397     }
398   }
399 }
400
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);
406 }
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))
414 # endif
415
416 struct DlIteratePhdrData {
417   LoadedModule *modules;
418   uptr current_n;
419   bool first;
420   uptr max_n;
421   string_predicate_t filter;
422 };
423
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)
427     return 0;
428   InternalScopedString module_name(kMaxPathLength);
429   if (data->first) {
430     data->first = false;
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);
435   }
436   if (module_name[0] == '\0')
437     return 0;
438   if (data->filter && !data->filter(module_name.data()))
439     return 0;
440   void *mem = &data->modules[data->current_n];
441   LoadedModule *cur_module = new(mem) LoadedModule(module_name.data(),
442                                                    info->dlpi_addr);
443   data->current_n++;
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);
451     }
452   }
453   return 0;
454 }
455
456 uptr GetListOfModules(LoadedModule *modules, uptr max_modules,
457                       string_predicate_t filter) {
458   CHECK(modules);
459   DlIteratePhdrData data = {modules, 0, true, max_modules, filter};
460   dl_iterate_phdr(dl_iterate_phdr_cb, &data);
461   return data.current_n;
462 }
463 #endif  // SANITIZER_ANDROID
464
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
469   // cached mappings.
470   MemoryMappingLayout::CacheMemoryMappings();
471   // Same for /proc/self/exe in the symbolizer.
472 #if !SANITIZER_GO
473   Symbolizer::GetOrInit()->PrepareForSandboxing();
474   CovPrepareForSandboxing(args);
475 #endif
476 }
477
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() {
482   struct rusage usage;
483   if (getrusage(RUSAGE_SELF, &usage))  // Failed, probably due to a sandbox.
484     return 0;
485   return usage.ru_maxrss << 10;  // ru_maxrss is in Kb.
486 }
487
488 uptr GetRSS() {
489   if (!common_flags()->can_use_proc_maps_statm)
490     return GetRSSFromGetrusage();
491   uptr fd = OpenFile("/proc/self/statm", false);
492   if ((sptr)fd < 0)
493     return GetRSSFromGetrusage();
494   char buf[64];
495   uptr len = internal_read(fd, buf, sizeof(buf) - 1);
496   internal_close(fd);
497   if ((sptr)len <= 0)
498     return 0;
499   buf[len] = 0;
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.
503   char *pos = buf;
504   // Skip the first number.
505   while (*pos >= '0' && *pos <= '9')
506     pos++;
507   // Skip whitespaces.
508   while (!(*pos >= '0' && *pos <= '9') && *pos != 0)
509     pos++;
510   // Read the number.
511   uptr rss = 0;
512   while (*pos >= '0' && *pos <= '9')
513     rss = rss * 10 + *pos++ - '0';
514   return rss * GetPageSizeCached();
515 }
516
517 }  // namespace __sanitizer
518
519 #endif  // SANITIZER_FREEBSD || SANITIZER_LINUX