1 //===-- sanitizer_linux_libcdep.cc ----------------------------------------===//
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
6 //===----------------------------------------------------------------------===//
8 // This file is shared between AddressSanitizer and ThreadSanitizer
9 // run-time libraries and implements linux-specific functions from
11 //===----------------------------------------------------------------------===//
13 #include "sanitizer_platform.h"
15 #if SANITIZER_FREEBSD || SANITIZER_LINUX
17 #include "sanitizer_allocator_internal.h"
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"
27 #if SANITIZER_ANDROID || SANITIZER_FREEBSD
28 #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>
47 #include <android/api-level.h>
50 #if SANITIZER_ANDROID && __ANDROID_API__ < 21
51 #include <android/log.h>
56 #if !SANITIZER_ANDROID
61 namespace __sanitizer
{
63 SANITIZER_WEAK_ATTRIBUTE
int
64 real_sigaction(int signum
, const void *act
, void *oldact
);
66 int internal_sigaction(int signum
, const void *act
, void *oldact
) {
69 return real_sigaction(signum
, act
, oldact
);
71 return sigaction(signum
, (const struct sigaction
*)act
,
72 (struct sigaction
*)oldact
);
75 void GetThreadStackTopAndBottom(bool at_initialization
, uptr
*stack_top
,
79 if (at_initialization
) {
80 // This is the main thread. Libpthread may not be initialized yet.
82 CHECK_EQ(getrlimit(RLIMIT_STACK
, &rl
), 0);
84 // Find the mapping that contains a stack variable.
85 MemoryMappingLayout
proc_maps(/*cache_enabled*/true);
86 uptr start
, end
, offset
;
88 while (proc_maps
.Next(&start
, &end
, &offset
, nullptr, 0,
89 /* protection */nullptr)) {
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);
114 void *stackaddr
= nullptr;
115 my_pthread_attr_getstack(&attr
, &stackaddr
, &stacksize
);
116 pthread_attr_destroy(&attr
);
118 CHECK_LE(stacksize
, kMaxThreadStackSize
); // Sanity check.
119 *stack_top
= (uptr
)stackaddr
+ stacksize
;
120 *stack_bottom
= (uptr
)stackaddr
;
124 bool SetEnv(const char *name
, const char *value
) {
125 void *f
= dlsym(RTLD_NEXT
, "setenv");
128 typedef int(*setenv_ft
)(const char *name
, const char *value
, int overwrite
);
130 CHECK_EQ(sizeof(setenv_f
), sizeof(f
));
131 internal_memcpy(&setenv_f
, &f
, sizeof(f
));
132 return setenv_f(name
, value
, 1) == 0;
136 bool SanitizerSetThreadName(const char *name
) {
138 return 0 == prctl(PR_SET_NAME
, (unsigned long)name
, 0, 0, 0); // NOLINT
144 bool SanitizerGetThreadName(char *name
, int max_len
) {
147 if (prctl(PR_GET_NAME
, (unsigned long)buff
, 0, 0, 0)) // NOLINT
149 internal_strncpy(name
, buff
, max_len
);
157 #if !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO
158 static uptr g_tls_size
;
162 # define DL_INTERNAL_FUNCTION __attribute__((regparm(3), stdcall))
164 # define DL_INTERNAL_FUNCTION
167 #if defined(__mips__) || defined(__powerpc64__)
168 // TlsPreTcbSize includes size of struct pthread_descr and size of tcb
169 // head structure. It lies before the static tls blocks.
170 static uptr
TlsPreTcbSize() {
171 # if defined(__mips__)
172 const uptr kTcbHead
= 16; // sizeof (tcbhead_t)
173 # elif defined(__powerpc64__)
174 const uptr kTcbHead
= 88; // sizeof (tcbhead_t)
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 // all current supported platforms have 16 bytes stack alignment
188 const size_t kStackAlign
= 16;
189 typedef void (*get_tls_func
)(size_t*, size_t*) DL_INTERNAL_FUNCTION
;
190 get_tls_func get_tls
;
191 void *get_tls_static_info_ptr
= dlsym(RTLD_NEXT
, "_dl_get_tls_static_info");
192 CHECK_EQ(sizeof(get_tls
), sizeof(get_tls_static_info_ptr
));
193 internal_memcpy(&get_tls
, &get_tls_static_info_ptr
,
194 sizeof(get_tls_static_info_ptr
));
195 CHECK_NE(get_tls
, 0);
197 size_t tls_align
= 0;
198 get_tls(&tls_size
, &tls_align
);
199 if (tls_align
< kStackAlign
)
200 tls_align
= kStackAlign
;
201 g_tls_size
= RoundUpTo(tls_size
, tls_align
);
202 #endif // !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO
205 #if (defined(__x86_64__) || defined(__i386__) || defined(__mips__) \
206 || defined(__aarch64__) || defined(__powerpc64__)) \
207 && SANITIZER_LINUX && !SANITIZER_ANDROID
208 // sizeof(struct pthread) from glibc.
209 static atomic_uintptr_t kThreadDescriptorSize
;
211 uptr
ThreadDescriptorSize() {
212 uptr val
= atomic_load(&kThreadDescriptorSize
, memory_order_relaxed
);
215 #if defined(__x86_64__) || defined(__i386__)
216 #ifdef _CS_GNU_LIBC_VERSION
218 uptr len
= confstr(_CS_GNU_LIBC_VERSION
, buf
, sizeof(buf
));
219 if (len
< sizeof(buf
) && internal_strncmp(buf
, "glibc 2.", 8) == 0) {
221 int minor
= internal_simple_strtoll(buf
+ 8, &end
, 10);
222 if (end
!= buf
+ 8 && (*end
== '\0' || *end
== '.')) {
223 /* sizeof(struct pthread) values from various glibc versions. */
225 val
= 1728; // Assume only one particular version for x32.
227 val
= FIRST_32_SECOND_64(1104, 1696);
229 val
= FIRST_32_SECOND_64(1120, 1728);
231 val
= FIRST_32_SECOND_64(1136, 1728);
233 val
= FIRST_32_SECOND_64(1136, 1712);
234 else if (minor
== 10)
235 val
= FIRST_32_SECOND_64(1168, 1776);
236 else if (minor
<= 12)
237 val
= FIRST_32_SECOND_64(1168, 2288);
238 else if (minor
== 13)
239 val
= FIRST_32_SECOND_64(1168, 2304);
241 val
= FIRST_32_SECOND_64(1216, 2304);
244 atomic_store(&kThreadDescriptorSize
, val
, memory_order_relaxed
);
248 #elif defined(__mips__)
249 // TODO(sagarthakur): add more values as per different glibc versions.
250 val
= FIRST_32_SECOND_64(1152, 1776);
252 atomic_store(&kThreadDescriptorSize
, val
, memory_order_relaxed
);
254 #elif defined(__aarch64__)
255 // The sizeof (struct pthread) is the same from GLIBC 2.17 to 2.22.
257 atomic_store(&kThreadDescriptorSize
, val
, memory_order_relaxed
);
259 #elif defined(__powerpc64__)
260 val
= 1776; // from glibc.ppc64le 2.20-8.fc21
261 atomic_store(&kThreadDescriptorSize
, val
, memory_order_relaxed
);
267 // The offset at which pointer to self is located in the thread descriptor.
268 const uptr kThreadSelfOffset
= FIRST_32_SECOND_64(8, 16);
270 uptr
ThreadSelfOffset() {
271 return kThreadSelfOffset
;
276 # if defined(__i386__)
277 asm("mov %%gs:%c1,%0" : "=r"(descr_addr
) : "i"(kThreadSelfOffset
));
278 # elif defined(__x86_64__)
279 asm("mov %%fs:%c1,%0" : "=r"(descr_addr
) : "i"(kThreadSelfOffset
));
280 # elif defined(__mips__)
281 // MIPS uses TLS variant I. The thread pointer (in hardware register $29)
282 // points to the end of the TCB + 0x7000. The pthread_descr structure is
283 // immediately in front of the TCB. TlsPreTcbSize() includes the size of the
284 // TCB and the size of pthread_descr.
285 const uptr kTlsTcbOffset
= 0x7000;
287 asm volatile(".set push;\
290 .set pop" : "=r" (thread_pointer
));
291 descr_addr
= thread_pointer
- kTlsTcbOffset
- TlsPreTcbSize();
292 # elif defined(__aarch64__)
293 descr_addr
= reinterpret_cast<uptr
>(__builtin_thread_pointer());
294 # elif defined(__powerpc64__)
295 // PPC64LE uses TLS variant I. The thread pointer (in GPR 13)
296 // points to the end of the TCB + 0x7000. The pthread_descr structure is
297 // immediately in front of the TCB. TlsPreTcbSize() includes the size of the
298 // TCB and the size of pthread_descr.
299 const uptr kTlsTcbOffset
= 0x7000;
301 asm("addi %0,13,%1" : "=r"(thread_pointer
) : "I"(-kTlsTcbOffset
));
302 descr_addr
= thread_pointer
- TlsPreTcbSize();
304 # error "unsupported CPU arch"
308 #endif // (x86_64 || i386 || MIPS) && SANITIZER_LINUX
310 #if SANITIZER_FREEBSD
311 static void **ThreadSelfSegbase() {
313 # if defined(__i386__)
314 // sysarch(I386_GET_GSBASE, segbase);
315 __asm
__volatile("mov %%gs:0, %0" : "=r" (segbase
));
316 # elif defined(__x86_64__)
317 // sysarch(AMD64_GET_FSBASE, segbase);
318 __asm
__volatile("movq %%fs:0, %0" : "=r" (segbase
));
320 # error "unsupported CPU arch for FreeBSD platform"
326 return (uptr
)ThreadSelfSegbase()[2];
328 #endif // SANITIZER_FREEBSD
331 static void GetTls(uptr
*addr
, uptr
*size
) {
332 #if SANITIZER_LINUX && !SANITIZER_ANDROID
333 # if defined(__x86_64__) || defined(__i386__)
334 *addr
= ThreadSelf();
335 *size
= GetTlsSize();
337 *addr
+= ThreadDescriptorSize();
338 # elif defined(__mips__) || defined(__aarch64__) || defined(__powerpc64__)
339 *addr
= ThreadSelf();
340 *size
= GetTlsSize();
345 #elif SANITIZER_FREEBSD
346 void** segbase
= ThreadSelfSegbase();
351 // tls_size = round(tls_static_space, tcbalign);
353 // dtv[2] = segbase - tls_static_space;
354 void **dtv
= (void**) segbase
[1];
355 *addr
= (uptr
) dtv
[2];
356 *size
= (*addr
== 0) ? 0 : ((uptr
) segbase
[0] - (uptr
) dtv
[2]);
358 #elif SANITIZER_ANDROID
369 #if SANITIZER_FREEBSD || SANITIZER_ANDROID
371 GetTls(&addr
, &size
);
379 void GetThreadStackAndTls(bool main
, uptr
*stk_addr
, uptr
*stk_size
,
380 uptr
*tls_addr
, uptr
*tls_size
) {
382 // Stub implementation for Go.
383 *stk_addr
= *stk_size
= *tls_addr
= *tls_size
= 0;
385 GetTls(tls_addr
, tls_size
);
387 uptr stack_top
, stack_bottom
;
388 GetThreadStackTopAndBottom(main
, &stack_top
, &stack_bottom
);
389 *stk_addr
= stack_bottom
;
390 *stk_size
= stack_top
- stack_bottom
;
393 // If stack and tls intersect, make them non-intersecting.
394 if (*tls_addr
> *stk_addr
&& *tls_addr
< *stk_addr
+ *stk_size
) {
395 CHECK_GT(*tls_addr
+ *tls_size
, *stk_addr
);
396 CHECK_LE(*tls_addr
+ *tls_size
, *stk_addr
+ *stk_size
);
397 *stk_size
-= *tls_size
;
398 *tls_addr
= *stk_addr
+ *stk_size
;
404 # if !SANITIZER_FREEBSD
405 typedef ElfW(Phdr
) Elf_Phdr
;
406 # elif SANITIZER_WORDSIZE == 32 && __FreeBSD_version <= 902001 // v9.2
407 # define Elf_Phdr XElf32_Phdr
408 # define dl_phdr_info xdl_phdr_info
409 # define dl_iterate_phdr(c, b) xdl_iterate_phdr((c), (b))
412 struct DlIteratePhdrData
{
413 LoadedModule
*modules
;
417 string_predicate_t filter
;
420 static int dl_iterate_phdr_cb(dl_phdr_info
*info
, size_t size
, void *arg
) {
421 DlIteratePhdrData
*data
= (DlIteratePhdrData
*)arg
;
422 if (data
->current_n
== data
->max_n
)
424 InternalScopedString
module_name(kMaxPathLength
);
427 // First module is the binary itself.
428 ReadBinaryNameCached(module_name
.data(), module_name
.size());
429 } else if (info
->dlpi_name
) {
430 module_name
.append("%s", info
->dlpi_name
);
432 if (module_name
[0] == '\0')
434 if (data
->filter
&& !data
->filter(module_name
.data()))
436 LoadedModule
*cur_module
= &data
->modules
[data
->current_n
];
437 cur_module
->set(module_name
.data(), info
->dlpi_addr
);
439 for (int i
= 0; i
< info
->dlpi_phnum
; i
++) {
440 const Elf_Phdr
*phdr
= &info
->dlpi_phdr
[i
];
441 if (phdr
->p_type
== PT_LOAD
) {
442 uptr cur_beg
= info
->dlpi_addr
+ phdr
->p_vaddr
;
443 uptr cur_end
= cur_beg
+ phdr
->p_memsz
;
444 bool executable
= phdr
->p_flags
& PF_X
;
445 cur_module
->addAddressRange(cur_beg
, cur_end
, executable
);
451 #if SANITIZER_ANDROID && __ANDROID_API__ < 21
452 extern "C" __attribute__((weak
)) int dl_iterate_phdr(
453 int (*)(struct dl_phdr_info
*, size_t, void *), void *);
456 uptr
GetListOfModules(LoadedModule
*modules
, uptr max_modules
,
457 string_predicate_t filter
) {
458 #if SANITIZER_ANDROID && __ANDROID_API__ <= 22
459 u32 api_level
= AndroidGetApiLevel();
460 // Fall back to /proc/maps if dl_iterate_phdr is unavailable or broken.
461 // The runtime check allows the same library to work with
462 // both K and L (and future) Android releases.
463 if (api_level
<= ANDROID_LOLLIPOP_MR1
) { // L or earlier
464 MemoryMappingLayout
memory_mapping(false);
465 return memory_mapping
.DumpListOfModules(modules
, max_modules
, filter
);
469 DlIteratePhdrData data
= {modules
, 0, true, max_modules
, filter
};
470 dl_iterate_phdr(dl_iterate_phdr_cb
, &data
);
471 return data
.current_n
;
474 // getrusage does not give us the current RSS, only the max RSS.
475 // Still, this is better than nothing if /proc/self/statm is not available
476 // for some reason, e.g. due to a sandbox.
477 static uptr
GetRSSFromGetrusage() {
479 if (getrusage(RUSAGE_SELF
, &usage
)) // Failed, probably due to a sandbox.
481 return usage
.ru_maxrss
<< 10; // ru_maxrss is in Kb.
485 if (!common_flags()->can_use_proc_maps_statm
)
486 return GetRSSFromGetrusage();
487 fd_t fd
= OpenFile("/proc/self/statm", RdOnly
);
488 if (fd
== kInvalidFd
)
489 return GetRSSFromGetrusage();
491 uptr len
= internal_read(fd
, buf
, sizeof(buf
) - 1);
496 // The format of the file is:
497 // 1084 89 69 11 0 79 0
498 // We need the second number which is RSS in pages.
500 // Skip the first number.
501 while (*pos
>= '0' && *pos
<= '9')
504 while (!(*pos
>= '0' && *pos
<= '9') && *pos
!= 0)
508 while (*pos
>= '0' && *pos
<= '9')
509 rss
= rss
* 10 + *pos
++ - '0';
510 return rss
* GetPageSizeCached();
513 // 64-bit Android targets don't provide the deprecated __android_log_write.
514 // Starting with the L release, syslog() works and is preferable to
515 // __android_log_write.
518 #if SANITIZER_ANDROID
519 static atomic_uint8_t android_log_initialized
;
521 void AndroidLogInit() {
522 atomic_store(&android_log_initialized
, 1, memory_order_release
);
525 static bool IsSyslogAvailable() {
526 return atomic_load(&android_log_initialized
, memory_order_acquire
);
529 void AndroidLogInit() {}
531 static bool IsSyslogAvailable() { return true; }
532 #endif // SANITIZER_ANDROID
534 static void WriteOneLineToSyslog(const char *s
) {
535 #if SANITIZER_ANDROID &&__ANDROID_API__ < 21
536 __android_log_write(ANDROID_LOG_INFO
, NULL
, s
);
538 syslog(LOG_INFO
, "%s", s
);
542 void WriteToSyslog(const char *buffer
) {
543 if (!IsSyslogAvailable())
545 char *copy
= internal_strdup(buffer
);
548 // syslog, at least on Android, has an implicit message length limit.
549 // Print one line at a time.
551 q
= internal_strchr(p
, '\n');
554 WriteOneLineToSyslog(p
);
560 #endif // SANITIZER_LINUX
562 } // namespace __sanitizer
564 #endif // SANITIZER_FREEBSD || SANITIZER_LINUX