]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/sanitizer_common/sanitizer_linux_libcdep.cc
Update svn-1.9.7 to 1.10.0.
[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
17 #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD || \
18     SANITIZER_SOLARIS
19
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"
30
31 #include <dlfcn.h>  // for dlsym()
32 #include <link.h>
33 #include <pthread.h>
34 #include <signal.h>
35 #include <sys/resource.h>
36 #include <syslog.h>
37
38 #if SANITIZER_FREEBSD
39 #include <pthread_np.h>
40 #include <osreldate.h>
41 #include <sys/sysctl.h>
42 #define pthread_getattr_np pthread_attr_get_np
43 #endif
44
45 #if SANITIZER_NETBSD
46 #include <sys/sysctl.h>
47 #include <sys/tls.h>
48 #endif
49
50 #if SANITIZER_SOLARIS
51 #include <thread.h>
52 #endif
53
54 #if SANITIZER_LINUX
55 #include <sys/prctl.h>
56 #endif
57
58 #if SANITIZER_ANDROID
59 #include <android/api-level.h>
60 #if !defined(CPU_COUNT) && !defined(__aarch64__)
61 #include <dirent.h>
62 #include <fcntl.h>
63 struct __sanitizer::linux_dirent {
64   long           d_ino;
65   off_t          d_off;
66   unsigned short d_reclen;
67   char           d_name[];
68 };
69 #endif
70 #endif
71
72 #if !SANITIZER_ANDROID
73 #include <elf.h>
74 #include <unistd.h>
75 #endif
76
77 namespace __sanitizer {
78
79 SANITIZER_WEAK_ATTRIBUTE int
80 real_sigaction(int signum, const void *act, void *oldact);
81
82 int internal_sigaction(int signum, const void *act, void *oldact) {
83 #if !SANITIZER_GO
84   if (&real_sigaction)
85     return real_sigaction(signum, act, oldact);
86 #endif
87   return sigaction(signum, (const struct sigaction *)act,
88                    (struct sigaction *)oldact);
89 }
90
91 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
92                                 uptr *stack_bottom) {
93   CHECK(stack_top);
94   CHECK(stack_bottom);
95   if (at_initialization) {
96     // This is the main thread. Libpthread may not be initialized yet.
97     struct rlimit rl;
98     CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
99
100     // Find the mapping that contains a stack variable.
101     MemoryMappingLayout proc_maps(/*cache_enabled*/true);
102     MemoryMappedSegment segment;
103     uptr prev_end = 0;
104     while (proc_maps.Next(&segment)) {
105       if ((uptr)&rl < segment.end) break;
106       prev_end = segment.end;
107     }
108     CHECK((uptr)&rl >= segment.start && (uptr)&rl < segment.end);
109
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;
121     return;
122   }
123   uptr stacksize = 0;
124   void *stackaddr = nullptr;
125 #if SANITIZER_SOLARIS
126   stack_t ss;
127   CHECK_EQ(thr_stksegment(&ss), 0);
128   stacksize = ss.ss_size;
129   stackaddr = (char *)ss.ss_sp - stacksize;
130 #else // !SANITIZER_SOLARIS
131   pthread_attr_t attr;
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
137
138   *stack_top = (uptr)stackaddr + stacksize;
139   *stack_bottom = (uptr)stackaddr;
140 }
141
142 #if !SANITIZER_GO
143 bool SetEnv(const char *name, const char *value) {
144   void *f = dlsym(RTLD_NEXT, "setenv");
145   if (!f)
146     return false;
147   typedef int(*setenv_ft)(const char *name, const char *value, int overwrite);
148   setenv_ft setenv_f;
149   CHECK_EQ(sizeof(setenv_f), sizeof(f));
150   internal_memcpy(&setenv_f, &f, sizeof(f));
151   return setenv_f(name, value, 1) == 0;
152 }
153 #endif
154
155 bool SanitizerSetThreadName(const char *name) {
156 #ifdef PR_SET_NAME
157   return 0 == prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0);  // NOLINT
158 #else
159   return false;
160 #endif
161 }
162
163 bool SanitizerGetThreadName(char *name, int max_len) {
164 #ifdef PR_GET_NAME
165   char buff[17];
166   if (prctl(PR_GET_NAME, (unsigned long)buff, 0, 0, 0))  // NOLINT
167     return false;
168   internal_strncpy(name, buff, max_len);
169   name[max_len] = 0;
170   return true;
171 #else
172   return false;
173 #endif
174 }
175
176 #if !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO && \
177     !SANITIZER_NETBSD && !SANITIZER_SOLARIS
178 static uptr g_tls_size;
179
180 #ifdef __i386__
181 # define DL_INTERNAL_FUNCTION __attribute__((regparm(3), stdcall))
182 #else
183 # define DL_INTERNAL_FUNCTION
184 #endif
185
186 void InitTlsSize() {
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);
196   size_t tls_size = 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 }
203 #else
204 void InitTlsSize() { }
205 #endif  // !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO &&
206         // !SANITIZER_NETBSD && !SANITIZER_SOLARIS
207
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;
213
214 uptr ThreadDescriptorSize() {
215   uptr val = atomic_load(&kThreadDescriptorSize, memory_order_relaxed);
216   if (val)
217     return val;
218 #if defined(__x86_64__) || defined(__i386__) || defined(__arm__)
219 #ifdef _CS_GNU_LIBC_VERSION
220   char buf[64];
221   uptr len = confstr(_CS_GNU_LIBC_VERSION, buf, sizeof(buf));
222   if (len < sizeof(buf) && internal_strncmp(buf, "glibc 2.", 8) == 0) {
223     char *end;
224     int minor = internal_simple_strtoll(buf + 8, &end, 10);
225     if (end != buf + 8 && (*end == '\0' || *end == '.' || *end == '-')) {
226       int patch = 0;
227       if (*end == '.')
228         // strtoll will return 0 if no valid conversion could be performed
229         patch = internal_simple_strtoll(end + 1, nullptr, 10);
230
231       /* sizeof(struct pthread) values from various glibc versions.  */
232       if (SANITIZER_X32)
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;
237       else if (minor <= 3)
238         val = FIRST_32_SECOND_64(1104, 1696);
239       else if (minor == 4)
240         val = FIRST_32_SECOND_64(1120, 1728);
241       else if (minor == 5)
242         val = FIRST_32_SECOND_64(1136, 1728);
243       else if (minor <= 9)
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);
251       else
252         val = FIRST_32_SECOND_64(1216, 2304);
253     }
254     if (val)
255       atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
256     return val;
257   }
258 #endif
259 #elif defined(__mips__)
260   // TODO(sagarthakur): add more values as per different glibc versions.
261   val = FIRST_32_SECOND_64(1152, 1776);
262   if (val)
263     atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
264   return val;
265 #elif defined(__aarch64__)
266   // The sizeof (struct pthread) is the same from GLIBC 2.17 to 2.22.
267   val = 1776;
268   atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
269   return val;
270 #elif defined(__powerpc64__)
271   val = 1776; // from glibc.ppc64le 2.20-8.fc21
272   atomic_store(&kThreadDescriptorSize, val, memory_order_relaxed);
273   return val;
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);
277 #endif
278   return 0;
279 }
280
281 // The offset at which pointer to self is located in the thread descriptor.
282 const uptr kThreadSelfOffset = FIRST_32_SECOND_64(8, 16);
283
284 uptr ThreadSelfOffset() {
285   return kThreadSelfOffset;
286 }
287
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)
296 # endif
297   const uptr kTlsAlign = 16;
298   const uptr kTlsPreTcbSize =
299       RoundUpTo(ThreadDescriptorSize() + kTcbHead, kTlsAlign);
300   return kTlsPreTcbSize;
301 }
302 #endif
303
304 uptr ThreadSelf() {
305   uptr descr_addr;
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;
316   uptr thread_pointer;
317   asm volatile(".set push;\
318                 .set mips64r2;\
319                 rdhwr %0,$29;\
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;
333   uptr thread_pointer;
334   asm("addi %0,13,%1" : "=r"(thread_pointer) : "I"(-kTlsTcbOffset));
335   descr_addr = thread_pointer - TlsPreTcbSize();
336 # else
337 #  error "unsupported CPU arch"
338 # endif
339   return descr_addr;
340 }
341 #endif  // (x86_64 || i386 || MIPS) && SANITIZER_LINUX
342
343 #if SANITIZER_FREEBSD
344 static void **ThreadSelfSegbase() {
345   void **segbase = 0;
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));
352 # else
353 #  error "unsupported CPU arch"
354 # endif
355   return segbase;
356 }
357
358 uptr ThreadSelf() {
359   return (uptr)ThreadSelfSegbase()[2];
360 }
361 #endif  // SANITIZER_FREEBSD
362
363 #if SANITIZER_NETBSD
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();
370 # endif
371   return tcb;
372 }
373
374 uptr ThreadSelf() {
375   return (uptr)ThreadSelfTlsTcb()->tcb_pthread;
376 }
377
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;
381
382   for (; hdr != last_hdr; ++hdr) {
383     if (hdr->p_type == PT_TLS && info->dlpi_tls_modid == 1) {
384       *(uptr*)data = hdr->p_memsz;
385       break;
386     }
387   }
388   return 0;
389 }
390 #endif  // SANITIZER_NETBSD
391
392 #if !SANITIZER_GO
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();
398   *addr -= *size;
399   *addr += ThreadDescriptorSize();
400 # elif defined(__mips__) || defined(__aarch64__) || defined(__powerpc64__) \
401     || defined(__arm__)
402   *addr = ThreadSelf();
403   *size = GetTlsSize();
404 # else
405   *addr = 0;
406   *size = 0;
407 # endif
408 #elif SANITIZER_FREEBSD
409   void** segbase = ThreadSelfSegbase();
410   *addr = 0;
411   *size = 0;
412   if (segbase != 0) {
413     // tcbalign = 16
414     // tls_size = round(tls_static_space, tcbalign);
415     // dtv = segbase[1];
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]);
420   }
421 #elif SANITIZER_NETBSD
422   struct tls_tcb * const tcb = ThreadSelfTlsTcb();
423   *addr = 0;
424   *size = 0;
425   if (tcb != 0) {
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);
429
430     if (*size != 0) {
431       // The block has been found and tcb_dtv[1] contains the base address
432       *addr = (uptr)tcb->tcb_dtv[1];
433     }
434   }
435 #elif SANITIZER_ANDROID
436   *addr = 0;
437   *size = 0;
438 #elif SANITIZER_SOLARIS
439   // FIXME
440   *addr = 0;
441   *size = 0;
442 #else
443 # error "Unknown OS"
444 #endif
445 }
446 #endif
447
448 #if !SANITIZER_GO
449 uptr GetTlsSize() {
450 #if SANITIZER_FREEBSD || SANITIZER_ANDROID || SANITIZER_NETBSD || \
451     SANITIZER_SOLARIS
452   uptr addr, size;
453   GetTls(&addr, &size);
454   return size;
455 #elif defined(__mips__) || defined(__powerpc64__)
456   return RoundUpTo(g_tls_size + TlsPreTcbSize(), 16);
457 #else
458   return g_tls_size;
459 #endif
460 }
461 #endif
462
463 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
464                           uptr *tls_addr, uptr *tls_size) {
465 #if SANITIZER_GO
466   // Stub implementation for Go.
467   *stk_addr = *stk_size = *tls_addr = *tls_size = 0;
468 #else
469   GetTls(tls_addr, tls_size);
470
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;
475
476   if (!main) {
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;
483     }
484   }
485 #endif
486 }
487
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))
494 # endif
495
496 struct DlIteratePhdrData {
497   InternalMmapVectorNoCtor<LoadedModule> *modules;
498   bool first;
499 };
500
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);
504   if (data->first) {
505     data->first = false;
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);
510   }
511   if (module_name[0] == '\0')
512     return 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,
523                                  writable);
524     }
525   }
526   data->modules->push_back(cur_module);
527   return 0;
528 }
529
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 *);
533 #endif
534
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;
541 #else
542   return false;
543 #endif
544 }
545
546 static void procmapsInit(InternalMmapVectorNoCtor<LoadedModule> *modules) {
547   MemoryMappingLayout memory_mapping(/*cache_enabled*/true);
548   memory_mapping.DumpListOfModules(modules);
549 }
550
551 void ListOfModules::init() {
552   clearOrInit();
553   if (requiresProcmaps()) {
554     procmapsInit(&modules_);
555   } else {
556     DlIteratePhdrData data = {&modules_, true};
557     dl_iterate_phdr(dl_iterate_phdr_cb, &data);
558   }
559 }
560
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()) {
565     clearOrInit();
566     procmapsInit(&modules_);
567   } else {
568     clear();
569   }
570 }
571
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() {
576   struct rusage usage;
577   if (getrusage(RUSAGE_SELF, &usage))  // Failed, probably due to a sandbox.
578     return 0;
579   return usage.ru_maxrss << 10;  // ru_maxrss is in Kb.
580 }
581
582 uptr GetRSS() {
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();
588   char buf[64];
589   uptr len = internal_read(fd, buf, sizeof(buf) - 1);
590   internal_close(fd);
591   if ((sptr)len <= 0)
592     return 0;
593   buf[len] = 0;
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.
597   char *pos = buf;
598   // Skip the first number.
599   while (*pos >= '0' && *pos <= '9')
600     pos++;
601   // Skip whitespaces.
602   while (!(*pos >= '0' && *pos <= '9') && *pos != 0)
603     pos++;
604   // Read the number.
605   uptr rss = 0;
606   while (*pos >= '0' && *pos <= '9')
607     rss = rss * 10 + *pos++ - '0';
608   return rss * GetPageSizeCached();
609 }
610
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
615   u32 ncpu;
616   int req[2];
617   size_t len = sizeof(ncpu);
618   req[0] = CTL_HW;
619   req[1] = HW_NCPU;
620   CHECK_EQ(sysctl(req, 2, &ncpu, &len, NULL, 0), 0);
621   return ncpu;
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
625   // NDKs.
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))
630     return 0;
631   InternalScopedBuffer<u8> buffer(4096);
632   uptr bytes_read = buffer.size();
633   uptr n_cpus = 0;
634   u8 *d_type;
635   struct linux_dirent *entry = (struct linux_dirent *)&buffer[bytes_read];
636   while (true) {
637     if ((u8 *)entry >= &buffer[bytes_read]) {
638       bytes_read = internal_getdents(fd, (struct linux_dirent *)buffer.data(),
639                                      buffer.size());
640       if (internal_iserror(bytes_read) || !bytes_read)
641         break;
642       entry = (struct linux_dirent *)buffer.data();
643     }
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])
647       break;
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')
652         n_cpus++;
653     }
654     entry = (struct linux_dirent *)(((u8 *)entry) + entry->d_reclen);
655   }
656   internal_close(fd);
657   return n_cpus;
658 #elif SANITIZER_SOLARIS
659   return sysconf(_SC_NPROCESSORS_ONLN);
660 #else
661   cpu_set_t CPUs;
662   CHECK_EQ(sched_getaffinity(0, sizeof(cpu_set_t), &CPUs), 0);
663   return CPU_COUNT(&CPUs);
664 #endif
665 }
666
667 #if SANITIZER_LINUX
668
669 # if SANITIZER_ANDROID
670 static atomic_uint8_t android_log_initialized;
671
672 void AndroidLogInit() {
673   openlog(GetProcessName(), 0, LOG_USER);
674   atomic_store(&android_log_initialized, 1, memory_order_release);
675 }
676
677 static bool ShouldLogAfterPrintf() {
678   return atomic_load(&android_log_initialized, memory_order_acquire);
679 }
680
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);
685
686 // ANDROID_LOG_INFO is 4, but can't be resolved at runtime.
687 #define SANITIZER_ANDROID_LOG_INFO 4
688
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);
700   } else {
701     CHECK(&__android_log_write);
702     __android_log_write(SANITIZER_ANDROID_LOG_INFO, nullptr, s);
703   }
704 }
705
706 extern "C" SANITIZER_WEAK_ATTRIBUTE
707 void android_set_abort_message(const char *);
708
709 void SetAbortMessage(const char *str) {
710   if (&android_set_abort_message)
711     android_set_abort_message(str);
712 }
713 # else
714 void AndroidLogInit() {}
715
716 static bool ShouldLogAfterPrintf() { return true; }
717
718 void WriteOneLineToSyslog(const char *s) { syslog(LOG_INFO, "%s", s); }
719
720 void SetAbortMessage(const char *str) {}
721 # endif  // SANITIZER_ANDROID
722
723 void LogMessageOnPrintf(const char *str) {
724   if (common_flags()->log_to_syslog && ShouldLogAfterPrintf())
725     WriteToSyslog(str);
726 }
727
728 #endif  // SANITIZER_LINUX
729
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)
739     return true;
740   if (&__progname && __progname && *__progname)
741     return true;
742   return false;
743 }
744
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() {
751   timespec ts;
752   if (CanUseVDSO()) {
753     if (&real_clock_gettime)
754       real_clock_gettime(CLOCK_MONOTONIC, &ts);
755     else
756       clock_gettime(CLOCK_MONOTONIC, &ts);
757   } else {
758     internal_clock_gettime(CLOCK_MONOTONIC, &ts);
759   }
760   return (u64)ts.tv_sec * (1000ULL * 1000 * 1000) + ts.tv_nsec;
761 }
762 #else
763 // Non-Linux & Go always use the syscall.
764 u64 MonotonicNanoTime() {
765   timespec ts;
766   internal_clock_gettime(CLOCK_MONOTONIC, &ts);
767   return (u64)ts.tv_sec * (1000ULL * 1000 * 1000) + ts.tv_nsec;
768 }
769 #endif  // SANITIZER_LINUX && !SANITIZER_GO
770
771 } // namespace __sanitizer
772
773 #endif  // SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD