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_atomic.h"
19 #include "sanitizer_common.h"
20 #include "sanitizer_flags.h"
21 #include "sanitizer_freebsd.h"
22 #include "sanitizer_linux.h"
23 #include "sanitizer_placement_new.h"
24 #include "sanitizer_procmaps.h"
25 #include "sanitizer_stacktrace.h"
26 
27 #if SANITIZER_ANDROID || SANITIZER_FREEBSD
28 #include <dlfcn.h>  // for dlsym()
29 #endif
30 
31 #include <pthread.h>
32 #include <signal.h>
33 #include <sys/resource.h>
34 
35 #if SANITIZER_FREEBSD
36 #include <pthread_np.h>
37 #include <osreldate.h>
38 #define pthread_getattr_np pthread_attr_get_np
39 #endif
40 
41 #if SANITIZER_LINUX
42 #include <sys/prctl.h>
43 #endif
44 
45 #if !SANITIZER_ANDROID
46 #include <elf.h>
47 #include <link.h>
48 #include <unistd.h>
49 #endif
50 
51 namespace __sanitizer {
52 
53 // This function is defined elsewhere if we intercepted pthread_attr_getstack.
54 extern "C" {
55 SANITIZER_WEAK_ATTRIBUTE int
56 real_pthread_attr_getstack(void *attr, void **addr, size_t *size);
57 }  // extern "C"
58 
my_pthread_attr_getstack(void * attr,void ** addr,size_t * size)59 static int my_pthread_attr_getstack(void *attr, void **addr, size_t *size) {
60 #if !SANITIZER_GO
61   if (&real_pthread_attr_getstack)
62     return real_pthread_attr_getstack((pthread_attr_t *)attr, addr, size);
63 #endif
64   return pthread_attr_getstack((pthread_attr_t *)attr, addr, size);
65 }
66 
67 SANITIZER_WEAK_ATTRIBUTE int
68 real_sigaction(int signum, const void *act, void *oldact);
69 
internal_sigaction(int signum,const void * act,void * oldact)70 int internal_sigaction(int signum, const void *act, void *oldact) {
71 #if !SANITIZER_GO
72   if (&real_sigaction)
73     return real_sigaction(signum, act, oldact);
74 #endif
75   return sigaction(signum, (const struct sigaction *)act,
76                    (struct sigaction *)oldact);
77 }
78 
GetThreadStackTopAndBottom(bool at_initialization,uptr * stack_top,uptr * stack_bottom)79 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
80                                 uptr *stack_bottom) {
81   CHECK(stack_top);
82   CHECK(stack_bottom);
83   if (at_initialization) {
84     // This is the main thread. Libpthread may not be initialized yet.
85     struct rlimit rl;
86     CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
87 
88     // Find the mapping that contains a stack variable.
89     MemoryMappingLayout proc_maps(/*cache_enabled*/true);
90     uptr start, end, offset;
91     uptr prev_end = 0;
92     while (proc_maps.Next(&start, &end, &offset, 0, 0, /* protection */0)) {
93       if ((uptr)&rl < end)
94         break;
95       prev_end = end;
96     }
97     CHECK((uptr)&rl >= start && (uptr)&rl < end);
98 
99     // Get stacksize from rlimit, but clip it so that it does not overlap
100     // with other mappings.
101     uptr stacksize = rl.rlim_cur;
102     if (stacksize > end - prev_end)
103       stacksize = end - prev_end;
104     // When running with unlimited stack size, we still want to set some limit.
105     // The unlimited stack size is caused by 'ulimit -s unlimited'.
106     // Also, for some reason, GNU make spawns subprocesses with unlimited stack.
107     if (stacksize > kMaxThreadStackSize)
108       stacksize = kMaxThreadStackSize;
109     *stack_top = end;
110     *stack_bottom = end - stacksize;
111     return;
112   }
113   pthread_attr_t attr;
114   pthread_attr_init(&attr);
115   CHECK_EQ(pthread_getattr_np(pthread_self(), &attr), 0);
116   uptr stacksize = 0;
117   void *stackaddr = 0;
118   my_pthread_attr_getstack(&attr, &stackaddr, (size_t*)&stacksize);
119   pthread_attr_destroy(&attr);
120 
121   CHECK_LE(stacksize, kMaxThreadStackSize);  // Sanity check.
122   *stack_top = (uptr)stackaddr + stacksize;
123   *stack_bottom = (uptr)stackaddr;
124 }
125 
126 #if !SANITIZER_GO
SetEnv(const char * name,const char * value)127 bool SetEnv(const char *name, const char *value) {
128   void *f = dlsym(RTLD_NEXT, "setenv");
129   if (f == 0)
130     return false;
131   typedef int(*setenv_ft)(const char *name, const char *value, int overwrite);
132   setenv_ft setenv_f;
133   CHECK_EQ(sizeof(setenv_f), sizeof(f));
134   internal_memcpy(&setenv_f, &f, sizeof(f));
135   return setenv_f(name, value, 1) == 0;
136 }
137 #endif
138 
SanitizerSetThreadName(const char * name)139 bool SanitizerSetThreadName(const char *name) {
140 #ifdef PR_SET_NAME
141   return 0 == prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0);  // NOLINT
142 #else
143   return false;
144 #endif
145 }
146 
SanitizerGetThreadName(char * name,int max_len)147 bool SanitizerGetThreadName(char *name, int max_len) {
148 #ifdef PR_GET_NAME
149   char buff[17];
150   if (prctl(PR_GET_NAME, (unsigned long)buff, 0, 0, 0))  // NOLINT
151     return false;
152   internal_strncpy(name, buff, max_len);
153   name[max_len] = 0;
154   return true;
155 #else
156   return false;
157 #endif
158 }
159 
160 #if !SANITIZER_FREEBSD
161 static uptr g_tls_size;
162 #endif
163 
164 #ifdef __i386__
165 # define DL_INTERNAL_FUNCTION __attribute__((regparm(3), stdcall))
166 #else
167 # define DL_INTERNAL_FUNCTION
168 #endif
169 
170 #if defined(__mips__)
171 // TlsPreTcbSize includes size of struct pthread_descr and size of tcb
172 // head structure. It lies before the static tls blocks.
TlsPreTcbSize()173 static uptr TlsPreTcbSize() {
174   const uptr kTcbHead = 16;
175   const uptr kTlsAlign = 16;
176   const uptr kTlsPreTcbSize =
177     (ThreadDescriptorSize() + kTcbHead + kTlsAlign - 1) & ~(kTlsAlign - 1);
178   InitTlsSize();
179   g_tls_size = (g_tls_size + kTlsPreTcbSize + kTlsAlign -1) & ~(kTlsAlign - 1);
180   return kTlsPreTcbSize;
181 }
182 #endif
183 
InitTlsSize()184 void InitTlsSize() {
185 #if !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO
186   typedef void (*get_tls_func)(size_t*, size_t*) DL_INTERNAL_FUNCTION;
187   get_tls_func get_tls;
188   void *get_tls_static_info_ptr = dlsym(RTLD_NEXT, "_dl_get_tls_static_info");
189   CHECK_EQ(sizeof(get_tls), sizeof(get_tls_static_info_ptr));
190   internal_memcpy(&get_tls, &get_tls_static_info_ptr,
191                   sizeof(get_tls_static_info_ptr));
192   CHECK_NE(get_tls, 0);
193   size_t tls_size = 0;
194   size_t tls_align = 0;
195   get_tls(&tls_size, &tls_align);
196   g_tls_size = tls_size;
197 #endif  // !SANITIZER_FREEBSD && !SANITIZER_ANDROID
198 }
199 
200 #if (defined(__x86_64__) || defined(__i386__) || defined(__mips__)) \
201     && SANITIZER_LINUX
202 // sizeof(struct thread) from glibc.
203 static atomic_uintptr_t kThreadDescriptorSize;
204 
ThreadDescriptorSize()205 uptr ThreadDescriptorSize() {
206   uptr val = atomic_load(&kThreadDescriptorSize, memory_order_relaxed);
207   if (val)
208     return val;
209 #if defined(__x86_64__) || defined(__i386__)
210 #ifdef _CS_GNU_LIBC_VERSION
211   char buf[64];
212   uptr len = confstr(_CS_GNU_LIBC_VERSION, buf, sizeof(buf));
213   if (len < sizeof(buf) && internal_strncmp(buf, "glibc 2.", 8) == 0) {
214     char *end;
215     int minor = internal_simple_strtoll(buf + 8, &end, 10);
216     if (end != buf + 8 && (*end == '\0' || *end == '.')) {
217       /* sizeof(struct thread) values from various glibc versions.  */
218       if (SANITIZER_X32)
219         val = 1728;  // Assume only one particular version for x32.
220       else if (minor <= 3)
221         val = FIRST_32_SECOND_64(1104, 1696);
222       else if (minor == 4)
223         val = FIRST_32_SECOND_64(1120, 1728);
224       else if (minor == 5)
225         val = FIRST_32_SECOND_64(1136, 1728);
226       else if (minor <= 9)
227         val = FIRST_32_SECOND_64(1136, 1712);
228       else if (minor == 10)
229         val = FIRST_32_SECOND_64(1168, 1776);
230       else if (minor <= 12)
231         val = FIRST_32_SECOND_64(1168, 2288);
232       else if (minor == 13)
233         val = FIRST_32_SECOND_64(1168, 2304);
234       else
235         val = FIRST_32_SECOND_64(1216, 2304);
236     }
237     if (val)
238       atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
239     return val;
240   }
241 #endif
242 #elif defined(__mips__)
243   // TODO(sagarthakur): add more values as per different glibc versions.
244   val = FIRST_32_SECOND_64(1152, 1776);
245   if (val)
246     atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
247   return val;
248 #endif
249   return 0;
250 }
251 
252 // The offset at which pointer to self is located in the thread descriptor.
253 const uptr kThreadSelfOffset = FIRST_32_SECOND_64(8, 16);
254 
ThreadSelfOffset()255 uptr ThreadSelfOffset() {
256   return kThreadSelfOffset;
257 }
258 
ThreadSelf()259 uptr ThreadSelf() {
260   uptr descr_addr;
261 # if defined(__i386__)
262   asm("mov %%gs:%c1,%0" : "=r"(descr_addr) : "i"(kThreadSelfOffset));
263 # elif defined(__x86_64__)
264   asm("mov %%fs:%c1,%0" : "=r"(descr_addr) : "i"(kThreadSelfOffset));
265 # elif defined(__mips__)
266   // MIPS uses TLS variant I. The thread pointer (in hardware register $29)
267   // points to the end of the TCB + 0x7000. The pthread_descr structure is
268   // immediately in front of the TCB. TlsPreTcbSize() includes the size of the
269   // TCB and the size of pthread_descr.
270   const uptr kTlsTcbOffset = 0x7000;
271   uptr thread_pointer;
272   asm volatile(".set push;\
273                 .set mips64r2;\
274                 rdhwr %0,$29;\
275                 .set pop" : "=r" (thread_pointer));
276   descr_addr = thread_pointer - kTlsTcbOffset - TlsPreTcbSize();
277 # else
278 #  error "unsupported CPU arch"
279 # endif
280   return descr_addr;
281 }
282 #endif  // (x86_64 || i386 || MIPS) && SANITIZER_LINUX
283 
284 #if SANITIZER_FREEBSD
ThreadSelfSegbase()285 static void **ThreadSelfSegbase() {
286   void **segbase = 0;
287 # if defined(__i386__)
288   // sysarch(I386_GET_GSBASE, segbase);
289   __asm __volatile("mov %%gs:0, %0" : "=r" (segbase));
290 # elif defined(__x86_64__)
291   // sysarch(AMD64_GET_FSBASE, segbase);
292   __asm __volatile("movq %%fs:0, %0" : "=r" (segbase));
293 # else
294 #  error "unsupported CPU arch for FreeBSD platform"
295 # endif
296   return segbase;
297 }
298 
ThreadSelf()299 uptr ThreadSelf() {
300   return (uptr)ThreadSelfSegbase()[2];
301 }
302 #endif  // SANITIZER_FREEBSD
303 
304 #if !SANITIZER_GO
GetTls(uptr * addr,uptr * size)305 static void GetTls(uptr *addr, uptr *size) {
306 #if SANITIZER_LINUX
307 # if defined(__x86_64__) || defined(__i386__)
308   *addr = ThreadSelf();
309   *size = GetTlsSize();
310   *addr -= *size;
311   *addr += ThreadDescriptorSize();
312 # elif defined(__mips__)
313   *addr = ThreadSelf();
314   *size = GetTlsSize();
315 # else
316   *addr = 0;
317   *size = 0;
318 # endif
319 #elif SANITIZER_FREEBSD
320   void** segbase = ThreadSelfSegbase();
321   *addr = 0;
322   *size = 0;
323   if (segbase != 0) {
324     // tcbalign = 16
325     // tls_size = round(tls_static_space, tcbalign);
326     // dtv = segbase[1];
327     // dtv[2] = segbase - tls_static_space;
328     void **dtv = (void**) segbase[1];
329     *addr = (uptr) dtv[2];
330     *size = (*addr == 0) ? 0 : ((uptr) segbase[0] - (uptr) dtv[2]);
331   }
332 #else
333 # error "Unknown OS"
334 #endif
335 }
336 #endif
337 
338 #if !SANITIZER_GO
GetTlsSize()339 uptr GetTlsSize() {
340 #if SANITIZER_FREEBSD
341   uptr addr, size;
342   GetTls(&addr, &size);
343   return size;
344 #else
345   return g_tls_size;
346 #endif
347 }
348 #endif
349 
GetThreadStackAndTls(bool main,uptr * stk_addr,uptr * stk_size,uptr * tls_addr,uptr * tls_size)350 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
351                           uptr *tls_addr, uptr *tls_size) {
352 #if SANITIZER_GO
353   // Stub implementation for Go.
354   *stk_addr = *stk_size = *tls_addr = *tls_size = 0;
355 #else
356   GetTls(tls_addr, tls_size);
357 
358   uptr stack_top, stack_bottom;
359   GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
360   *stk_addr = stack_bottom;
361   *stk_size = stack_top - stack_bottom;
362 
363   if (!main) {
364     // If stack and tls intersect, make them non-intersecting.
365     if (*tls_addr > *stk_addr && *tls_addr < *stk_addr + *stk_size) {
366       CHECK_GT(*tls_addr + *tls_size, *stk_addr);
367       CHECK_LE(*tls_addr + *tls_size, *stk_addr + *stk_size);
368       *stk_size -= *tls_size;
369       *tls_addr = *stk_addr + *stk_size;
370     }
371   }
372 #endif
373 }
374 
AdjustStackSize(void * attr_)375 void AdjustStackSize(void *attr_) {
376   pthread_attr_t *attr = (pthread_attr_t *)attr_;
377   uptr stackaddr = 0;
378   size_t stacksize = 0;
379   my_pthread_attr_getstack(attr, (void**)&stackaddr, &stacksize);
380   // GLibC will return (0 - stacksize) as the stack address in the case when
381   // stacksize is set, but stackaddr is not.
382   bool stack_set = (stackaddr != 0) && (stackaddr + stacksize != 0);
383   // We place a lot of tool data into TLS, account for that.
384   const uptr minstacksize = GetTlsSize() + 128*1024;
385   if (stacksize < minstacksize) {
386     if (!stack_set) {
387       if (stacksize != 0) {
388         VPrintf(1, "Sanitizer: increasing stacksize %zu->%zu\n", stacksize,
389                 minstacksize);
390         pthread_attr_setstacksize(attr, minstacksize);
391       }
392     } else {
393       Printf("Sanitizer: pre-allocated stack size is insufficient: "
394              "%zu < %zu\n", stacksize, minstacksize);
395       Printf("Sanitizer: pthread_create is likely to fail.\n");
396     }
397   }
398 }
399 
400 #if SANITIZER_ANDROID
GetListOfModules(LoadedModule * modules,uptr max_modules,string_predicate_t filter)401 uptr GetListOfModules(LoadedModule *modules, uptr max_modules,
402                       string_predicate_t filter) {
403   MemoryMappingLayout memory_mapping(false);
404   return memory_mapping.DumpListOfModules(modules, max_modules, filter);
405 }
406 #else  // SANITIZER_ANDROID
407 # if !SANITIZER_FREEBSD
408 typedef ElfW(Phdr) Elf_Phdr;
409 # elif SANITIZER_WORDSIZE == 32 && __FreeBSD_version <= 902001  // v9.2
410 #  define Elf_Phdr XElf32_Phdr
411 #  define dl_phdr_info xdl_phdr_info
412 #  define dl_iterate_phdr(c, b) xdl_iterate_phdr((c), (b))
413 # endif
414 
415 struct DlIteratePhdrData {
416   LoadedModule *modules;
417   uptr current_n;
418   bool first;
419   uptr max_n;
420   string_predicate_t filter;
421 };
422 
dl_iterate_phdr_cb(dl_phdr_info * info,size_t size,void * arg)423 static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
424   DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
425   if (data->current_n == data->max_n)
426     return 0;
427   InternalScopedString module_name(kMaxPathLength);
428   if (data->first) {
429     data->first = false;
430     // First module is the binary itself.
431     ReadBinaryName(module_name.data(), module_name.size());
432   } else if (info->dlpi_name) {
433     module_name.append("%s", info->dlpi_name);
434   }
435   if (module_name[0] == '\0')
436     return 0;
437   if (data->filter && !data->filter(module_name.data()))
438     return 0;
439   LoadedModule *cur_module = &data->modules[data->current_n];
440   cur_module->set(module_name.data(), info->dlpi_addr);
441   data->current_n++;
442   for (int i = 0; i < info->dlpi_phnum; i++) {
443     const Elf_Phdr *phdr = &info->dlpi_phdr[i];
444     if (phdr->p_type == PT_LOAD) {
445       uptr cur_beg = info->dlpi_addr + phdr->p_vaddr;
446       uptr cur_end = cur_beg + phdr->p_memsz;
447       bool executable = phdr->p_flags & PF_X;
448       cur_module->addAddressRange(cur_beg, cur_end, executable);
449     }
450   }
451   return 0;
452 }
453 
GetListOfModules(LoadedModule * modules,uptr max_modules,string_predicate_t filter)454 uptr GetListOfModules(LoadedModule *modules, uptr max_modules,
455                       string_predicate_t filter) {
456   CHECK(modules);
457   DlIteratePhdrData data = {modules, 0, true, max_modules, filter};
458   dl_iterate_phdr(dl_iterate_phdr_cb, &data);
459   return data.current_n;
460 }
461 #endif  // SANITIZER_ANDROID
462 
463 // getrusage does not give us the current RSS, only the max RSS.
464 // Still, this is better than nothing if /proc/self/statm is not available
465 // for some reason, e.g. due to a sandbox.
GetRSSFromGetrusage()466 static uptr GetRSSFromGetrusage() {
467   struct rusage usage;
468   if (getrusage(RUSAGE_SELF, &usage))  // Failed, probably due to a sandbox.
469     return 0;
470   return usage.ru_maxrss << 10;  // ru_maxrss is in Kb.
471 }
472 
GetRSS()473 uptr GetRSS() {
474   if (!common_flags()->can_use_proc_maps_statm)
475     return GetRSSFromGetrusage();
476   fd_t fd = OpenFile("/proc/self/statm", RdOnly);
477   if (fd == kInvalidFd)
478     return GetRSSFromGetrusage();
479   char buf[64];
480   uptr len = internal_read(fd, buf, sizeof(buf) - 1);
481   internal_close(fd);
482   if ((sptr)len <= 0)
483     return 0;
484   buf[len] = 0;
485   // The format of the file is:
486   // 1084 89 69 11 0 79 0
487   // We need the second number which is RSS in pages.
488   char *pos = buf;
489   // Skip the first number.
490   while (*pos >= '0' && *pos <= '9')
491     pos++;
492   // Skip whitespaces.
493   while (!(*pos >= '0' && *pos <= '9') && *pos != 0)
494     pos++;
495   // Read the number.
496   uptr rss = 0;
497   while (*pos >= '0' && *pos <= '9')
498     rss = rss * 10 + *pos++ - '0';
499   return rss * GetPageSizeCached();
500 }
501 
502 }  // namespace __sanitizer
503 
504 #endif  // SANITIZER_FREEBSD || SANITIZER_LINUX
505