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"
17 #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD || \
20 #include "sanitizer_allocator_internal.h"
21 #include "sanitizer_atomic.h"
22 #include "sanitizer_common.h"
23 #include "sanitizer_file.h"
24 #include "sanitizer_flags.h"
25 #include "sanitizer_freebsd.h"
26 #include "sanitizer_linux.h"
27 #include "sanitizer_placement_new.h"
28 #include "sanitizer_procmaps.h"
29 #include "sanitizer_stacktrace.h"
31 #include <dlfcn.h> // for dlsym()
35 #include <sys/resource.h>
39 #include <pthread_np.h>
40 #include <osreldate.h>
41 #include <sys/sysctl.h>
42 #define pthread_getattr_np pthread_attr_get_np
46 #include <sys/sysctl.h>
55 #include <sys/prctl.h>
59 #include <android/api-level.h>
60 #if !defined(CPU_COUNT) && !defined(__aarch64__)
63 struct __sanitizer::linux_dirent {
66 unsigned short d_reclen;
72 #if !SANITIZER_ANDROID
77 namespace __sanitizer {
79 SANITIZER_WEAK_ATTRIBUTE int
80 real_sigaction(int signum, const void *act, void *oldact);
82 int internal_sigaction(int signum, const void *act, void *oldact) {
85 return real_sigaction(signum, act, oldact);
87 return sigaction(signum, (const struct sigaction *)act,
88 (struct sigaction *)oldact);
91 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
95 if (at_initialization) {
96 // This is the main thread. Libpthread may not be initialized yet.
98 CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
100 // Find the mapping that contains a stack variable.
101 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
102 MemoryMappedSegment segment;
104 while (proc_maps.Next(&segment)) {
105 if ((uptr)&rl < segment.end) break;
106 prev_end = segment.end;
108 CHECK((uptr)&rl >= segment.start && (uptr)&rl < segment.end);
110 // Get stacksize from rlimit, but clip it so that it does not overlap
111 // with other mappings.
112 uptr stacksize = rl.rlim_cur;
113 if (stacksize > segment.end - prev_end) stacksize = segment.end - prev_end;
114 // When running with unlimited stack size, we still want to set some limit.
115 // The unlimited stack size is caused by 'ulimit -s unlimited'.
116 // Also, for some reason, GNU make spawns subprocesses with unlimited stack.
117 if (stacksize > kMaxThreadStackSize)
118 stacksize = kMaxThreadStackSize;
119 *stack_top = segment.end;
120 *stack_bottom = segment.end - stacksize;
124 void *stackaddr = nullptr;
125 #if SANITIZER_SOLARIS
127 CHECK_EQ(thr_stksegment(&ss), 0);
128 stacksize = ss.ss_size;
129 stackaddr = (char *)ss.ss_sp - stacksize;
130 #else // !SANITIZER_SOLARIS
132 pthread_attr_init(&attr);
133 CHECK_EQ(pthread_getattr_np(pthread_self(), &attr), 0);
134 my_pthread_attr_getstack(&attr, &stackaddr, &stacksize);
135 pthread_attr_destroy(&attr);
136 #endif // SANITIZER_SOLARIS
138 *stack_top = (uptr)stackaddr + stacksize;
139 *stack_bottom = (uptr)stackaddr;
143 bool SetEnv(const char *name, const char *value) {
144 void *f = dlsym(RTLD_NEXT, "setenv");
147 typedef int(*setenv_ft)(const char *name, const char *value, int overwrite);
149 CHECK_EQ(sizeof(setenv_f), sizeof(f));
150 internal_memcpy(&setenv_f, &f, sizeof(f));
151 return setenv_f(name, value, 1) == 0;
155 bool SanitizerSetThreadName(const char *name) {
157 return 0 == prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0); // NOLINT
163 bool SanitizerGetThreadName(char *name, int max_len) {
166 if (prctl(PR_GET_NAME, (unsigned long)buff, 0, 0, 0)) // NOLINT
168 internal_strncpy(name, buff, max_len);
176 #if !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO && \
177 !SANITIZER_NETBSD && !SANITIZER_SOLARIS
178 static uptr g_tls_size;
181 # define DL_INTERNAL_FUNCTION __attribute__((regparm(3), stdcall))
183 # define DL_INTERNAL_FUNCTION
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);
204 void InitTlsSize() { }
205 #endif // !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO &&
206 // !SANITIZER_NETBSD && !SANITIZER_SOLARIS
208 #if (defined(__x86_64__) || defined(__i386__) || defined(__mips__) \
209 || defined(__aarch64__) || defined(__powerpc64__) || defined(__s390__) \
210 || defined(__arm__)) && SANITIZER_LINUX && !SANITIZER_ANDROID
211 // sizeof(struct pthread) from glibc.
212 static atomic_uintptr_t kThreadDescriptorSize;
214 uptr ThreadDescriptorSize() {
215 uptr val = atomic_load(&kThreadDescriptorSize, memory_order_relaxed);
218 #if defined(__x86_64__) || defined(__i386__) || defined(__arm__)
219 #ifdef _CS_GNU_LIBC_VERSION
221 uptr len = confstr(_CS_GNU_LIBC_VERSION, buf, sizeof(buf));
222 if (len < sizeof(buf) && internal_strncmp(buf, "glibc 2.", 8) == 0) {
224 int minor = internal_simple_strtoll(buf + 8, &end, 10);
225 if (end != buf + 8 && (*end == '\0' || *end == '.' || *end == '-')) {
228 // strtoll will return 0 if no valid conversion could be performed
229 patch = internal_simple_strtoll(end + 1, nullptr, 10);
231 /* sizeof(struct pthread) values from various glibc versions. */
233 val = 1728; // Assume only one particular version for x32.
234 // For ARM sizeof(struct pthread) changed in Glibc 2.23.
235 else if (SANITIZER_ARM)
236 val = minor <= 22 ? 1120 : 1216;
238 val = FIRST_32_SECOND_64(1104, 1696);
240 val = FIRST_32_SECOND_64(1120, 1728);
242 val = FIRST_32_SECOND_64(1136, 1728);
244 val = FIRST_32_SECOND_64(1136, 1712);
245 else if (minor == 10)
246 val = FIRST_32_SECOND_64(1168, 1776);
247 else if (minor == 11 || (minor == 12 && patch == 1))
248 val = FIRST_32_SECOND_64(1168, 2288);
249 else if (minor <= 13)
250 val = FIRST_32_SECOND_64(1168, 2304);
252 val = FIRST_32_SECOND_64(1216, 2304);
255 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
259 #elif defined(__mips__)
260 // TODO(sagarthakur): add more values as per different glibc versions.
261 val = FIRST_32_SECOND_64(1152, 1776);
263 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
265 #elif defined(__aarch64__)
266 // The sizeof (struct pthread) is the same from GLIBC 2.17 to 2.22.
268 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
270 #elif defined(__powerpc64__)
271 val = 1776; // from glibc.ppc64le 2.20-8.fc21
272 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
274 #elif defined(__s390__)
275 val = FIRST_32_SECOND_64(1152, 1776); // valid for glibc 2.22
276 atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
281 // The offset at which pointer to self is located in the thread descriptor.
282 const uptr kThreadSelfOffset = FIRST_32_SECOND_64(8, 16);
284 uptr ThreadSelfOffset() {
285 return kThreadSelfOffset;
288 #if defined(__mips__) || defined(__powerpc64__)
289 // TlsPreTcbSize includes size of struct pthread_descr and size of tcb
290 // head structure. It lies before the static tls blocks.
291 static uptr TlsPreTcbSize() {
292 # if defined(__mips__)
293 const uptr kTcbHead = 16; // sizeof (tcbhead_t)
294 # elif defined(__powerpc64__)
295 const uptr kTcbHead = 88; // sizeof (tcbhead_t)
297 const uptr kTlsAlign = 16;
298 const uptr kTlsPreTcbSize =
299 RoundUpTo(ThreadDescriptorSize() + kTcbHead, kTlsAlign);
300 return kTlsPreTcbSize;
306 # if defined(__i386__)
307 asm("mov %%gs:%c1,%0" : "=r"(descr_addr) : "i"(kThreadSelfOffset));
308 # elif defined(__x86_64__)
309 asm("mov %%fs:%c1,%0" : "=r"(descr_addr) : "i"(kThreadSelfOffset));
310 # elif defined(__mips__)
311 // MIPS uses TLS variant I. The thread pointer (in hardware register $29)
312 // points to the end of the TCB + 0x7000. The pthread_descr structure is
313 // immediately in front of the TCB. TlsPreTcbSize() includes the size of the
314 // TCB and the size of pthread_descr.
315 const uptr kTlsTcbOffset = 0x7000;
317 asm volatile(".set push;\
320 .set pop" : "=r" (thread_pointer));
321 descr_addr = thread_pointer - kTlsTcbOffset - TlsPreTcbSize();
322 # elif defined(__aarch64__) || defined(__arm__)
323 descr_addr = reinterpret_cast<uptr>(__builtin_thread_pointer()) -
324 ThreadDescriptorSize();
325 # elif defined(__s390__)
326 descr_addr = reinterpret_cast<uptr>(__builtin_thread_pointer());
327 # elif defined(__powerpc64__)
328 // PPC64LE uses TLS variant I. The thread pointer (in GPR 13)
329 // points to the end of the TCB + 0x7000. The pthread_descr structure is
330 // immediately in front of the TCB. TlsPreTcbSize() includes the size of the
331 // TCB and the size of pthread_descr.
332 const uptr kTlsTcbOffset = 0x7000;
334 asm("addi %0,13,%1" : "=r"(thread_pointer) : "I"(-kTlsTcbOffset));
335 descr_addr = thread_pointer - TlsPreTcbSize();
337 # error "unsupported CPU arch"
341 #endif // (x86_64 || i386 || MIPS) && SANITIZER_LINUX
343 #if SANITIZER_FREEBSD
344 static void **ThreadSelfSegbase() {
346 # if defined(__i386__)
347 // sysarch(I386_GET_GSBASE, segbase);
348 __asm __volatile("mov %%gs:0, %0" : "=r" (segbase));
349 # elif defined(__x86_64__)
350 // sysarch(AMD64_GET_FSBASE, segbase);
351 __asm __volatile("movq %%fs:0, %0" : "=r" (segbase));
353 # error "unsupported CPU arch"
359 return (uptr)ThreadSelfSegbase()[2];
361 #endif // SANITIZER_FREEBSD
364 static struct tls_tcb * ThreadSelfTlsTcb() {
365 struct tls_tcb * tcb;
366 # ifdef __HAVE___LWP_GETTCB_FAST
367 tcb = (struct tls_tcb *)__lwp_gettcb_fast();
368 # elif defined(__HAVE___LWP_GETPRIVATE_FAST)
369 tcb = (struct tls_tcb *)__lwp_getprivate_fast();
375 return (uptr)ThreadSelfTlsTcb()->tcb_pthread;
378 int GetSizeFromHdr(struct dl_phdr_info *info, size_t size, void *data) {
379 const Elf_Phdr *hdr = info->dlpi_phdr;
380 const Elf_Phdr *last_hdr = hdr + info->dlpi_phnum;
382 for (; hdr != last_hdr; ++hdr) {
383 if (hdr->p_type == PT_TLS && info->dlpi_tls_modid == 1) {
384 *(uptr*)data = hdr->p_memsz;
390 #endif // SANITIZER_NETBSD
393 static void GetTls(uptr *addr, uptr *size) {
394 #if SANITIZER_LINUX && !SANITIZER_ANDROID
395 # if defined(__x86_64__) || defined(__i386__) || defined(__s390__)
396 *addr = ThreadSelf();
397 *size = GetTlsSize();
399 *addr += ThreadDescriptorSize();
400 # elif defined(__mips__) || defined(__aarch64__) || defined(__powerpc64__) \
402 *addr = ThreadSelf();
403 *size = GetTlsSize();
408 #elif SANITIZER_FREEBSD
409 void** segbase = ThreadSelfSegbase();
414 // tls_size = round(tls_static_space, tcbalign);
416 // dtv[2] = segbase - tls_static_space;
417 void **dtv = (void**) segbase[1];
418 *addr = (uptr) dtv[2];
419 *size = (*addr == 0) ? 0 : ((uptr) segbase[0] - (uptr) dtv[2]);
421 #elif SANITIZER_NETBSD
422 struct tls_tcb * const tcb = ThreadSelfTlsTcb();
426 // Find size (p_memsz) of dlpi_tls_modid 1 (TLS block of the main program).
427 // ld.elf_so hardcodes the index 1.
428 dl_iterate_phdr(GetSizeFromHdr, size);
431 // The block has been found and tcb_dtv[1] contains the base address
432 *addr = (uptr)tcb->tcb_dtv[1];
435 #elif SANITIZER_ANDROID
438 #elif SANITIZER_SOLARIS
450 #if SANITIZER_FREEBSD || SANITIZER_ANDROID || SANITIZER_NETBSD || \
453 GetTls(&addr, &size);
455 #elif defined(__mips__) || defined(__powerpc64__)
456 return RoundUpTo(g_tls_size + TlsPreTcbSize(), 16);
463 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
464 uptr *tls_addr, uptr *tls_size) {
466 // Stub implementation for Go.
467 *stk_addr = *stk_size = *tls_addr = *tls_size = 0;
469 GetTls(tls_addr, tls_size);
471 uptr stack_top, stack_bottom;
472 GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
473 *stk_addr = stack_bottom;
474 *stk_size = stack_top - stack_bottom;
477 // If stack and tls intersect, make them non-intersecting.
478 if (*tls_addr > *stk_addr && *tls_addr < *stk_addr + *stk_size) {
479 CHECK_GT(*tls_addr + *tls_size, *stk_addr);
480 CHECK_LE(*tls_addr + *tls_size, *stk_addr + *stk_size);
481 *stk_size -= *tls_size;
482 *tls_addr = *stk_addr + *stk_size;
488 # if !SANITIZER_FREEBSD
489 typedef ElfW(Phdr) Elf_Phdr;
490 # elif SANITIZER_WORDSIZE == 32 && __FreeBSD_version <= 902001 // v9.2
491 # define Elf_Phdr XElf32_Phdr
492 # define dl_phdr_info xdl_phdr_info
493 # define dl_iterate_phdr(c, b) xdl_iterate_phdr((c), (b))
496 struct DlIteratePhdrData {
497 InternalMmapVectorNoCtor<LoadedModule> *modules;
501 static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
502 DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
503 InternalScopedString module_name(kMaxPathLength);
506 // First module is the binary itself.
507 ReadBinaryNameCached(module_name.data(), module_name.size());
508 } else if (info->dlpi_name) {
509 module_name.append("%s", info->dlpi_name);
511 if (module_name[0] == '\0')
513 LoadedModule cur_module;
514 cur_module.set(module_name.data(), info->dlpi_addr);
515 for (int i = 0; i < info->dlpi_phnum; i++) {
516 const Elf_Phdr *phdr = &info->dlpi_phdr[i];
517 if (phdr->p_type == PT_LOAD) {
518 uptr cur_beg = info->dlpi_addr + phdr->p_vaddr;
519 uptr cur_end = cur_beg + phdr->p_memsz;
520 bool executable = phdr->p_flags & PF_X;
521 bool writable = phdr->p_flags & PF_W;
522 cur_module.addAddressRange(cur_beg, cur_end, executable,
526 data->modules->push_back(cur_module);
530 #if SANITIZER_ANDROID && __ANDROID_API__ < 21
531 extern "C" __attribute__((weak)) int dl_iterate_phdr(
532 int (*)(struct dl_phdr_info *, size_t, void *), void *);
535 static bool requiresProcmaps() {
536 #if SANITIZER_ANDROID && __ANDROID_API__ <= 22
537 // Fall back to /proc/maps if dl_iterate_phdr is unavailable or broken.
538 // The runtime check allows the same library to work with
539 // both K and L (and future) Android releases.
540 return AndroidGetApiLevel() <= ANDROID_LOLLIPOP_MR1;
546 static void procmapsInit(InternalMmapVectorNoCtor<LoadedModule> *modules) {
547 MemoryMappingLayout memory_mapping(/*cache_enabled*/true);
548 memory_mapping.DumpListOfModules(modules);
551 void ListOfModules::init() {
553 if (requiresProcmaps()) {
554 procmapsInit(&modules_);
556 DlIteratePhdrData data = {&modules_, true};
557 dl_iterate_phdr(dl_iterate_phdr_cb, &data);
561 // When a custom loader is used, dl_iterate_phdr may not contain the full
562 // list of modules. Allow callers to fall back to using procmaps.
563 void ListOfModules::fallbackInit() {
564 if (!requiresProcmaps()) {
566 procmapsInit(&modules_);
572 // getrusage does not give us the current RSS, only the max RSS.
573 // Still, this is better than nothing if /proc/self/statm is not available
574 // for some reason, e.g. due to a sandbox.
575 static uptr GetRSSFromGetrusage() {
577 if (getrusage(RUSAGE_SELF, &usage)) // Failed, probably due to a sandbox.
579 return usage.ru_maxrss << 10; // ru_maxrss is in Kb.
583 if (!common_flags()->can_use_proc_maps_statm)
584 return GetRSSFromGetrusage();
585 fd_t fd = OpenFile("/proc/self/statm", RdOnly);
586 if (fd == kInvalidFd)
587 return GetRSSFromGetrusage();
589 uptr len = internal_read(fd, buf, sizeof(buf) - 1);
594 // The format of the file is:
595 // 1084 89 69 11 0 79 0
596 // We need the second number which is RSS in pages.
598 // Skip the first number.
599 while (*pos >= '0' && *pos <= '9')
602 while (!(*pos >= '0' && *pos <= '9') && *pos != 0)
606 while (*pos >= '0' && *pos <= '9')
607 rss = rss * 10 + *pos++ - '0';
608 return rss * GetPageSizeCached();
611 // sysconf(_SC_NPROCESSORS_{CONF,ONLN}) cannot be used on most platforms as
612 // they allocate memory.
613 u32 GetNumberOfCPUs() {
614 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
617 size_t len = sizeof(ncpu);
620 CHECK_EQ(sysctl(req, 2, &ncpu, &len, NULL, 0), 0);
622 #elif SANITIZER_ANDROID && !defined(CPU_COUNT) && !defined(__aarch64__)
623 // Fall back to /sys/devices/system/cpu on Android when cpu_set_t doesn't
624 // exist in sched.h. That is the case for toolchains generated with older
626 // This code doesn't work on AArch64 because internal_getdents makes use of
627 // the 64bit getdents syscall, but cpu_set_t seems to always exist on AArch64.
628 uptr fd = internal_open("/sys/devices/system/cpu", O_RDONLY | O_DIRECTORY);
629 if (internal_iserror(fd))
631 InternalScopedBuffer<u8> buffer(4096);
632 uptr bytes_read = buffer.size();
635 struct linux_dirent *entry = (struct linux_dirent *)&buffer[bytes_read];
637 if ((u8 *)entry >= &buffer[bytes_read]) {
638 bytes_read = internal_getdents(fd, (struct linux_dirent *)buffer.data(),
640 if (internal_iserror(bytes_read) || !bytes_read)
642 entry = (struct linux_dirent *)buffer.data();
644 d_type = (u8 *)entry + entry->d_reclen - 1;
645 if (d_type >= &buffer[bytes_read] ||
646 (u8 *)&entry->d_name[3] >= &buffer[bytes_read])
648 if (entry->d_ino != 0 && *d_type == DT_DIR) {
649 if (entry->d_name[0] == 'c' && entry->d_name[1] == 'p' &&
650 entry->d_name[2] == 'u' &&
651 entry->d_name[3] >= '0' && entry->d_name[3] <= '9')
654 entry = (struct linux_dirent *)(((u8 *)entry) + entry->d_reclen);
658 #elif SANITIZER_SOLARIS
659 return sysconf(_SC_NPROCESSORS_ONLN);
662 CHECK_EQ(sched_getaffinity(0, sizeof(cpu_set_t), &CPUs), 0);
663 return CPU_COUNT(&CPUs);
669 # if SANITIZER_ANDROID
670 static atomic_uint8_t android_log_initialized;
672 void AndroidLogInit() {
673 openlog(GetProcessName(), 0, LOG_USER);
674 atomic_store(&android_log_initialized, 1, memory_order_release);
677 static bool ShouldLogAfterPrintf() {
678 return atomic_load(&android_log_initialized, memory_order_acquire);
681 extern "C" SANITIZER_WEAK_ATTRIBUTE
682 int async_safe_write_log(int pri, const char* tag, const char* msg);
683 extern "C" SANITIZER_WEAK_ATTRIBUTE
684 int __android_log_write(int prio, const char* tag, const char* msg);
686 // ANDROID_LOG_INFO is 4, but can't be resolved at runtime.
687 #define SANITIZER_ANDROID_LOG_INFO 4
689 // async_safe_write_log is a new public version of __libc_write_log that is
690 // used behind syslog. It is preferable to syslog as it will not do any dynamic
691 // memory allocation or formatting.
692 // If the function is not available, syslog is preferred for L+ (it was broken
693 // pre-L) as __android_log_write triggers a racey behavior with the strncpy
694 // interceptor. Fallback to __android_log_write pre-L.
695 void WriteOneLineToSyslog(const char *s) {
696 if (&async_safe_write_log) {
697 async_safe_write_log(SANITIZER_ANDROID_LOG_INFO, GetProcessName(), s);
698 } else if (AndroidGetApiLevel() > ANDROID_KITKAT) {
699 syslog(LOG_INFO, "%s", s);
701 CHECK(&__android_log_write);
702 __android_log_write(SANITIZER_ANDROID_LOG_INFO, nullptr, s);
706 extern "C" SANITIZER_WEAK_ATTRIBUTE
707 void android_set_abort_message(const char *);
709 void SetAbortMessage(const char *str) {
710 if (&android_set_abort_message)
711 android_set_abort_message(str);
714 void AndroidLogInit() {}
716 static bool ShouldLogAfterPrintf() { return true; }
718 void WriteOneLineToSyslog(const char *s) { syslog(LOG_INFO, "%s", s); }
720 void SetAbortMessage(const char *str) {}
721 # endif // SANITIZER_ANDROID
723 void LogMessageOnPrintf(const char *str) {
724 if (common_flags()->log_to_syslog && ShouldLogAfterPrintf())
728 #endif // SANITIZER_LINUX
730 #if SANITIZER_LINUX && !SANITIZER_GO
731 // glibc crashes when using clock_gettime from a preinit_array function as the
732 // vDSO function pointers haven't been initialized yet. __progname is
733 // initialized after the vDSO function pointers, so if it exists, is not null
734 // and is not empty, we can use clock_gettime.
735 extern "C" SANITIZER_WEAK_ATTRIBUTE char *__progname;
736 INLINE bool CanUseVDSO() {
737 // Bionic is safe, it checks for the vDSO function pointers to be initialized.
738 if (SANITIZER_ANDROID)
740 if (&__progname && __progname && *__progname)
745 // MonotonicNanoTime is a timing function that can leverage the vDSO by calling
746 // clock_gettime. real_clock_gettime only exists if clock_gettime is
747 // intercepted, so define it weakly and use it if available.
748 extern "C" SANITIZER_WEAK_ATTRIBUTE
749 int real_clock_gettime(u32 clk_id, void *tp);
750 u64 MonotonicNanoTime() {
753 if (&real_clock_gettime)
754 real_clock_gettime(CLOCK_MONOTONIC, &ts);
756 clock_gettime(CLOCK_MONOTONIC, &ts);
758 internal_clock_gettime(CLOCK_MONOTONIC, &ts);
760 return (u64)ts.tv_sec * (1000ULL * 1000 * 1000) + ts.tv_nsec;
763 // Non-Linux & Go always use the syscall.
764 u64 MonotonicNanoTime() {
766 internal_clock_gettime(CLOCK_MONOTONIC, &ts);
767 return (u64)ts.tv_sec * (1000ULL * 1000 * 1000) + ts.tv_nsec;
769 #endif // SANITIZER_LINUX && !SANITIZER_GO
771 } // namespace __sanitizer
773 #endif // SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD