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