1 //===-- sanitizer_linux_libcdep.cpp ---------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is shared between AddressSanitizer and ThreadSanitizer
10 // run-time libraries and implements linux-specific functions from
11 // sanitizer_libc.h.
12 //===----------------------------------------------------------------------===//
13 
14 #include "sanitizer_platform.h"
15 
16 #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD || \
17     SANITIZER_OPENBSD || SANITIZER_SOLARIS
18 
19 #include "sanitizer_allocator_internal.h"
20 #include "sanitizer_atomic.h"
21 #include "sanitizer_common.h"
22 #include "sanitizer_file.h"
23 #include "sanitizer_flags.h"
24 #include "sanitizer_freebsd.h"
25 #include "sanitizer_getauxval.h"
26 #include "sanitizer_glibc_version.h"
27 #include "sanitizer_linux.h"
28 #include "sanitizer_placement_new.h"
29 #include "sanitizer_procmaps.h"
30 
31 #if SANITIZER_NETBSD
32 #define _RTLD_SOURCE  // for __lwp_gettcb_fast() / __lwp_getprivate_fast()
33 #endif
34 
35 #include <dlfcn.h>  // for dlsym()
36 #include <link.h>
37 #include <pthread.h>
38 #include <signal.h>
39 #include <sys/resource.h>
40 #include <syslog.h>
41 
42 #if !defined(ElfW)
43 #define ElfW(type) Elf_##type
44 #endif
45 
46 #if SANITIZER_FREEBSD
47 #include <pthread_np.h>
48 #include <osreldate.h>
49 #include <sys/sysctl.h>
50 #define pthread_getattr_np pthread_attr_get_np
51 #endif
52 
53 #if SANITIZER_OPENBSD
54 #include <pthread_np.h>
55 #include <sys/sysctl.h>
56 #endif
57 
58 #if SANITIZER_NETBSD
59 #include <sys/sysctl.h>
60 #include <sys/tls.h>
61 #include <lwp.h>
62 #endif
63 
64 #if SANITIZER_SOLARIS
65 #include <stdlib.h>
66 #include <thread.h>
67 #endif
68 
69 #if SANITIZER_ANDROID
70 #include <android/api-level.h>
71 #if !defined(CPU_COUNT) && !defined(__aarch64__)
72 #include <dirent.h>
73 #include <fcntl.h>
74 struct __sanitizer::linux_dirent {
75   long           d_ino;
76   off_t          d_off;
77   unsigned short d_reclen;
78   char           d_name[];
79 };
80 #endif
81 #endif
82 
83 #if !SANITIZER_ANDROID
84 #include <elf.h>
85 #include <unistd.h>
86 #endif
87 
88 namespace __sanitizer {
89 
90 SANITIZER_WEAK_ATTRIBUTE int
91 real_sigaction(int signum, const void *act, void *oldact);
92 
93 int internal_sigaction(int signum, const void *act, void *oldact) {
94 #if !SANITIZER_GO
95   if (&real_sigaction)
96     return real_sigaction(signum, act, oldact);
97 #endif
98   return sigaction(signum, (const struct sigaction *)act,
99                    (struct sigaction *)oldact);
100 }
101 
102 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
103                                 uptr *stack_bottom) {
104   CHECK(stack_top);
105   CHECK(stack_bottom);
106   if (at_initialization) {
107     // This is the main thread. Libpthread may not be initialized yet.
108     struct rlimit rl;
109     CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
110 
111     // Find the mapping that contains a stack variable.
112     MemoryMappingLayout proc_maps(/*cache_enabled*/true);
113     if (proc_maps.Error()) {
114       *stack_top = *stack_bottom = 0;
115       return;
116     }
117     MemoryMappedSegment segment;
118     uptr prev_end = 0;
119     while (proc_maps.Next(&segment)) {
120       if ((uptr)&rl < segment.end) break;
121       prev_end = segment.end;
122     }
123     CHECK((uptr)&rl >= segment.start && (uptr)&rl < segment.end);
124 
125     // Get stacksize from rlimit, but clip it so that it does not overlap
126     // with other mappings.
127     uptr stacksize = rl.rlim_cur;
128     if (stacksize > segment.end - prev_end) stacksize = segment.end - prev_end;
129     // When running with unlimited stack size, we still want to set some limit.
130     // The unlimited stack size is caused by 'ulimit -s unlimited'.
131     // Also, for some reason, GNU make spawns subprocesses with unlimited stack.
132     if (stacksize > kMaxThreadStackSize)
133       stacksize = kMaxThreadStackSize;
134     *stack_top = segment.end;
135     *stack_bottom = segment.end - stacksize;
136     return;
137   }
138   uptr stacksize = 0;
139   void *stackaddr = nullptr;
140 #if SANITIZER_SOLARIS
141   stack_t ss;
142   CHECK_EQ(thr_stksegment(&ss), 0);
143   stacksize = ss.ss_size;
144   stackaddr = (char *)ss.ss_sp - stacksize;
145 #elif SANITIZER_OPENBSD
146   stack_t sattr;
147   CHECK_EQ(pthread_stackseg_np(pthread_self(), &sattr), 0);
148   stackaddr = sattr.ss_sp;
149   stacksize = sattr.ss_size;
150 #else  // !SANITIZER_SOLARIS
151   pthread_attr_t attr;
152   pthread_attr_init(&attr);
153   CHECK_EQ(pthread_getattr_np(pthread_self(), &attr), 0);
154   my_pthread_attr_getstack(&attr, &stackaddr, &stacksize);
155   pthread_attr_destroy(&attr);
156 #endif  // SANITIZER_SOLARIS
157 
158   *stack_top = (uptr)stackaddr + stacksize;
159   *stack_bottom = (uptr)stackaddr;
160 }
161 
162 #if !SANITIZER_GO
163 bool SetEnv(const char *name, const char *value) {
164   void *f = dlsym(RTLD_NEXT, "setenv");
165   if (!f)
166     return false;
167   typedef int(*setenv_ft)(const char *name, const char *value, int overwrite);
168   setenv_ft setenv_f;
169   CHECK_EQ(sizeof(setenv_f), sizeof(f));
170   internal_memcpy(&setenv_f, &f, sizeof(f));
171   return setenv_f(name, value, 1) == 0;
172 }
173 #endif
174 
175 __attribute__((unused)) static bool GetLibcVersion(int *major, int *minor,
176                                                    int *patch) {
177 #ifdef _CS_GNU_LIBC_VERSION
178   char buf[64];
179   uptr len = confstr(_CS_GNU_LIBC_VERSION, buf, sizeof(buf));
180   if (len >= sizeof(buf))
181     return false;
182   buf[len] = 0;
183   static const char kGLibC[] = "glibc ";
184   if (internal_strncmp(buf, kGLibC, sizeof(kGLibC) - 1) != 0)
185     return false;
186   const char *p = buf + sizeof(kGLibC) - 1;
187   *major = internal_simple_strtoll(p, &p, 10);
188   *minor = (*p == '.') ? internal_simple_strtoll(p + 1, &p, 10) : 0;
189   *patch = (*p == '.') ? internal_simple_strtoll(p + 1, &p, 10) : 0;
190   return true;
191 #else
192   return false;
193 #endif
194 }
195 
196 #if !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO && \
197     !SANITIZER_NETBSD && !SANITIZER_OPENBSD && !SANITIZER_SOLARIS
198 static uptr g_tls_size;
199 
200 #ifdef __i386__
201 #define CHECK_GET_TLS_STATIC_INFO_VERSION (!__GLIBC_PREREQ(2, 27))
202 #else
203 #define CHECK_GET_TLS_STATIC_INFO_VERSION 0
204 #endif
205 
206 #if CHECK_GET_TLS_STATIC_INFO_VERSION
207 #define DL_INTERNAL_FUNCTION __attribute__((regparm(3), stdcall))
208 #else
209 #define DL_INTERNAL_FUNCTION
210 #endif
211 
212 namespace {
213 struct GetTlsStaticInfoCall {
214   typedef void (*get_tls_func)(size_t*, size_t*);
215 };
216 struct GetTlsStaticInfoRegparmCall {
217   typedef void (*get_tls_func)(size_t*, size_t*) DL_INTERNAL_FUNCTION;
218 };
219 
220 template <typename T>
221 void CallGetTls(void* ptr, size_t* size, size_t* align) {
222   typename T::get_tls_func get_tls;
223   CHECK_EQ(sizeof(get_tls), sizeof(ptr));
224   internal_memcpy(&get_tls, &ptr, sizeof(ptr));
225   CHECK_NE(get_tls, 0);
226   get_tls(size, align);
227 }
228 
229 bool CmpLibcVersion(int major, int minor, int patch) {
230   int ma;
231   int mi;
232   int pa;
233   if (!GetLibcVersion(&ma, &mi, &pa))
234     return false;
235   if (ma > major)
236     return true;
237   if (ma < major)
238     return false;
239   if (mi > minor)
240     return true;
241   if (mi < minor)
242     return false;
243   return pa >= patch;
244 }
245 
246 }  // namespace
247 
248 void InitTlsSize() {
249   // all current supported platforms have 16 bytes stack alignment
250   const size_t kStackAlign = 16;
251   void *get_tls_static_info_ptr = dlsym(RTLD_NEXT, "_dl_get_tls_static_info");
252   size_t tls_size = 0;
253   size_t tls_align = 0;
254   // On i?86, _dl_get_tls_static_info used to be internal_function, i.e.
255   // __attribute__((regparm(3), stdcall)) before glibc 2.27 and is normal
256   // function in 2.27 and later.
257   if (CHECK_GET_TLS_STATIC_INFO_VERSION && !CmpLibcVersion(2, 27, 0))
258     CallGetTls<GetTlsStaticInfoRegparmCall>(get_tls_static_info_ptr,
259                                             &tls_size, &tls_align);
260   else
261     CallGetTls<GetTlsStaticInfoCall>(get_tls_static_info_ptr,
262                                      &tls_size, &tls_align);
263   if (tls_align < kStackAlign)
264     tls_align = kStackAlign;
265   g_tls_size = RoundUpTo(tls_size, tls_align);
266 }
267 #else
268 void InitTlsSize() { }
269 #endif
270 
271 #if (defined(__x86_64__) || defined(__i386__) || defined(__mips__) ||       \
272      defined(__aarch64__) || defined(__powerpc64__) || defined(__s390__) || \
273      defined(__arm__) || SANITIZER_RISCV64) &&                              \
274     SANITIZER_LINUX && !SANITIZER_ANDROID
275 // sizeof(struct pthread) from glibc.
276 static atomic_uintptr_t thread_descriptor_size;
277 
278 uptr ThreadDescriptorSize() {
279   uptr val = atomic_load_relaxed(&thread_descriptor_size);
280   if (val)
281     return val;
282 #if defined(__x86_64__) || defined(__i386__) || defined(__arm__)
283   int major;
284   int minor;
285   int patch;
286   if (GetLibcVersion(&major, &minor, &patch) && major == 2) {
287     /* sizeof(struct pthread) values from various glibc versions.  */
288     if (SANITIZER_X32)
289       val = 1728; // Assume only one particular version for x32.
290     // For ARM sizeof(struct pthread) changed in Glibc 2.23.
291     else if (SANITIZER_ARM)
292       val = minor <= 22 ? 1120 : 1216;
293     else if (minor <= 3)
294       val = FIRST_32_SECOND_64(1104, 1696);
295     else if (minor == 4)
296       val = FIRST_32_SECOND_64(1120, 1728);
297     else if (minor == 5)
298       val = FIRST_32_SECOND_64(1136, 1728);
299     else if (minor <= 9)
300       val = FIRST_32_SECOND_64(1136, 1712);
301     else if (minor == 10)
302       val = FIRST_32_SECOND_64(1168, 1776);
303     else if (minor == 11 || (minor == 12 && patch == 1))
304       val = FIRST_32_SECOND_64(1168, 2288);
305     else if (minor <= 14)
306       val = FIRST_32_SECOND_64(1168, 2304);
307     else
308       val = FIRST_32_SECOND_64(1216, 2304);
309   }
310 #elif defined(__mips__)
311   // TODO(sagarthakur): add more values as per different glibc versions.
312   val = FIRST_32_SECOND_64(1152, 1776);
313 #elif SANITIZER_RISCV64
314   int major;
315   int minor;
316   int patch;
317   if (GetLibcVersion(&major, &minor, &patch) && major == 2) {
318     // TODO: consider adding an optional runtime check for an unknown (untested)
319     // glibc version
320     if (minor <= 28)  // WARNING: the highest tested version is 2.29
321       val = 1772;     // no guarantees for this one
322     else if (minor <= 31)
323       val = 1772;  // tested against glibc 2.29, 2.31
324     else
325       val = 1936;  // tested against glibc 2.32
326   }
327 
328 #elif defined(__aarch64__)
329   // The sizeof (struct pthread) is the same from GLIBC 2.17 to 2.22.
330   val = 1776;
331 #elif defined(__powerpc64__)
332   val = 1776; // from glibc.ppc64le 2.20-8.fc21
333 #elif defined(__s390__)
334   val = FIRST_32_SECOND_64(1152, 1776); // valid for glibc 2.22
335 #endif
336   if (val)
337     atomic_store_relaxed(&thread_descriptor_size, val);
338   return val;
339 }
340 
341 // The offset at which pointer to self is located in the thread descriptor.
342 const uptr kThreadSelfOffset = FIRST_32_SECOND_64(8, 16);
343 
344 uptr ThreadSelfOffset() {
345   return kThreadSelfOffset;
346 }
347 
348 #if defined(__mips__) || defined(__powerpc64__) || SANITIZER_RISCV64
349 // TlsPreTcbSize includes size of struct pthread_descr and size of tcb
350 // head structure. It lies before the static tls blocks.
351 static uptr TlsPreTcbSize() {
352 #if defined(__mips__)
353   const uptr kTcbHead = 16; // sizeof (tcbhead_t)
354 #elif defined(__powerpc64__)
355   const uptr kTcbHead = 88; // sizeof (tcbhead_t)
356 #elif SANITIZER_RISCV64
357   const uptr kTcbHead = 16;  // sizeof (tcbhead_t)
358 #endif
359   const uptr kTlsAlign = 16;
360   const uptr kTlsPreTcbSize =
361       RoundUpTo(ThreadDescriptorSize() + kTcbHead, kTlsAlign);
362   return kTlsPreTcbSize;
363 }
364 #endif
365 
366 uptr ThreadSelf() {
367   uptr descr_addr;
368 #if defined(__i386__)
369   asm("mov %%gs:%c1,%0" : "=r"(descr_addr) : "i"(kThreadSelfOffset));
370 #elif defined(__x86_64__)
371   asm("mov %%fs:%c1,%0" : "=r"(descr_addr) : "i"(kThreadSelfOffset));
372 #elif defined(__mips__)
373   // MIPS uses TLS variant I. The thread pointer (in hardware register $29)
374   // points to the end of the TCB + 0x7000. The pthread_descr structure is
375   // immediately in front of the TCB. TlsPreTcbSize() includes the size of the
376   // TCB and the size of pthread_descr.
377   const uptr kTlsTcbOffset = 0x7000;
378   uptr thread_pointer;
379   asm volatile(".set push;\
380                 .set mips64r2;\
381                 rdhwr %0,$29;\
382                 .set pop" : "=r" (thread_pointer));
383   descr_addr = thread_pointer - kTlsTcbOffset - TlsPreTcbSize();
384 #elif defined(__aarch64__) || defined(__arm__)
385   descr_addr = reinterpret_cast<uptr>(__builtin_thread_pointer()) -
386                                       ThreadDescriptorSize();
387 #elif SANITIZER_RISCV64
388   uptr tcb_end;
389   asm volatile("mv %0, tp;\n" : "=r"(tcb_end));
390   // https://github.com/riscv/riscv-elf-psabi-doc/issues/53
391   const uptr kTlsTcbOffset = 0x800;
392   descr_addr =
393       reinterpret_cast<uptr>(tcb_end - kTlsTcbOffset - TlsPreTcbSize());
394 #elif defined(__s390__)
395   descr_addr = reinterpret_cast<uptr>(__builtin_thread_pointer());
396 #elif defined(__powerpc64__)
397   // PPC64LE uses TLS variant I. The thread pointer (in GPR 13)
398   // points to the end of the TCB + 0x7000. The pthread_descr structure is
399   // immediately in front of the TCB. TlsPreTcbSize() includes the size of the
400   // TCB and the size of pthread_descr.
401   const uptr kTlsTcbOffset = 0x7000;
402   uptr thread_pointer;
403   asm("addi %0,13,%1" : "=r"(thread_pointer) : "I"(-kTlsTcbOffset));
404   descr_addr = thread_pointer - TlsPreTcbSize();
405 #else
406 #error "unsupported CPU arch"
407 #endif
408   return descr_addr;
409 }
410 #endif  // (x86_64 || i386 || MIPS) && SANITIZER_LINUX
411 
412 #if SANITIZER_FREEBSD
413 static void **ThreadSelfSegbase() {
414   void **segbase = 0;
415 #if defined(__i386__)
416   // sysarch(I386_GET_GSBASE, segbase);
417   __asm __volatile("mov %%gs:0, %0" : "=r" (segbase));
418 #elif defined(__x86_64__)
419   // sysarch(AMD64_GET_FSBASE, segbase);
420   __asm __volatile("movq %%fs:0, %0" : "=r" (segbase));
421 #else
422 #error "unsupported CPU arch"
423 #endif
424   return segbase;
425 }
426 
427 uptr ThreadSelf() {
428   return (uptr)ThreadSelfSegbase()[2];
429 }
430 #endif  // SANITIZER_FREEBSD
431 
432 #if SANITIZER_NETBSD
433 static struct tls_tcb * ThreadSelfTlsTcb() {
434   struct tls_tcb *tcb = nullptr;
435 #ifdef __HAVE___LWP_GETTCB_FAST
436   tcb = (struct tls_tcb *)__lwp_gettcb_fast();
437 #elif defined(__HAVE___LWP_GETPRIVATE_FAST)
438   tcb = (struct tls_tcb *)__lwp_getprivate_fast();
439 #endif
440   return tcb;
441 }
442 
443 uptr ThreadSelf() {
444   return (uptr)ThreadSelfTlsTcb()->tcb_pthread;
445 }
446 
447 int GetSizeFromHdr(struct dl_phdr_info *info, size_t size, void *data) {
448   const Elf_Phdr *hdr = info->dlpi_phdr;
449   const Elf_Phdr *last_hdr = hdr + info->dlpi_phnum;
450 
451   for (; hdr != last_hdr; ++hdr) {
452     if (hdr->p_type == PT_TLS && info->dlpi_tls_modid == 1) {
453       *(uptr*)data = hdr->p_memsz;
454       break;
455     }
456   }
457   return 0;
458 }
459 #endif  // SANITIZER_NETBSD
460 
461 #if !SANITIZER_GO
462 static void GetTls(uptr *addr, uptr *size) {
463 #if SANITIZER_LINUX && !SANITIZER_ANDROID
464 #if defined(__x86_64__) || defined(__i386__) || defined(__s390__)
465   *addr = ThreadSelf();
466   *size = GetTlsSize();
467   *addr -= *size;
468   *addr += ThreadDescriptorSize();
469 #elif defined(__mips__) || defined(__aarch64__) || defined(__powerpc64__) || \
470     defined(__arm__) || SANITIZER_RISCV64
471   *addr = ThreadSelf();
472   *size = GetTlsSize();
473 #else
474   *addr = 0;
475   *size = 0;
476 #endif
477 #elif SANITIZER_FREEBSD
478   void** segbase = ThreadSelfSegbase();
479   *addr = 0;
480   *size = 0;
481   if (segbase != 0) {
482     // tcbalign = 16
483     // tls_size = round(tls_static_space, tcbalign);
484     // dtv = segbase[1];
485     // dtv[2] = segbase - tls_static_space;
486     void **dtv = (void**) segbase[1];
487     *addr = (uptr) dtv[2];
488     *size = (*addr == 0) ? 0 : ((uptr) segbase[0] - (uptr) dtv[2]);
489   }
490 #elif SANITIZER_NETBSD
491   struct tls_tcb * const tcb = ThreadSelfTlsTcb();
492   *addr = 0;
493   *size = 0;
494   if (tcb != 0) {
495     // Find size (p_memsz) of dlpi_tls_modid 1 (TLS block of the main program).
496     // ld.elf_so hardcodes the index 1.
497     dl_iterate_phdr(GetSizeFromHdr, size);
498 
499     if (*size != 0) {
500       // The block has been found and tcb_dtv[1] contains the base address
501       *addr = (uptr)tcb->tcb_dtv[1];
502     }
503   }
504 #elif SANITIZER_OPENBSD
505   *addr = 0;
506   *size = 0;
507 #elif SANITIZER_ANDROID
508   *addr = 0;
509   *size = 0;
510 #elif SANITIZER_SOLARIS
511   // FIXME
512   *addr = 0;
513   *size = 0;
514 #else
515 #error "Unknown OS"
516 #endif
517 }
518 #endif
519 
520 #if !SANITIZER_GO
521 uptr GetTlsSize() {
522 #if SANITIZER_FREEBSD || SANITIZER_ANDROID || SANITIZER_NETBSD || \
523     SANITIZER_OPENBSD || SANITIZER_SOLARIS
524   uptr addr, size;
525   GetTls(&addr, &size);
526   return size;
527 #elif defined(__mips__) || defined(__powerpc64__) || SANITIZER_RISCV64
528   return RoundUpTo(g_tls_size + TlsPreTcbSize(), 16);
529 #else
530   return g_tls_size;
531 #endif
532 }
533 #endif
534 
535 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
536                           uptr *tls_addr, uptr *tls_size) {
537 #if SANITIZER_GO
538   // Stub implementation for Go.
539   *stk_addr = *stk_size = *tls_addr = *tls_size = 0;
540 #else
541   GetTls(tls_addr, tls_size);
542 
543   uptr stack_top, stack_bottom;
544   GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
545   *stk_addr = stack_bottom;
546   *stk_size = stack_top - stack_bottom;
547 
548   if (!main) {
549     // If stack and tls intersect, make them non-intersecting.
550     if (*tls_addr > *stk_addr && *tls_addr < *stk_addr + *stk_size) {
551       CHECK_GT(*tls_addr + *tls_size, *stk_addr);
552       CHECK_LE(*tls_addr + *tls_size, *stk_addr + *stk_size);
553       *stk_size -= *tls_size;
554       *tls_addr = *stk_addr + *stk_size;
555     }
556   }
557 #endif
558 }
559 
560 #if !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
561 typedef ElfW(Phdr) Elf_Phdr;
562 #elif SANITIZER_WORDSIZE == 32 && __FreeBSD_version <= 902001  // v9.2
563 #define Elf_Phdr XElf32_Phdr
564 #define dl_phdr_info xdl_phdr_info
565 #define dl_iterate_phdr(c, b) xdl_iterate_phdr((c), (b))
566 #endif  // !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
567 
568 struct DlIteratePhdrData {
569   InternalMmapVectorNoCtor<LoadedModule> *modules;
570   bool first;
571 };
572 
573 static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
574   DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
575   InternalScopedString module_name(kMaxPathLength);
576   if (data->first) {
577     data->first = false;
578     // First module is the binary itself.
579     ReadBinaryNameCached(module_name.data(), module_name.size());
580   } else if (info->dlpi_name) {
581     module_name.append("%s", info->dlpi_name);
582   }
583   if (module_name[0] == '\0')
584     return 0;
585   LoadedModule cur_module;
586   cur_module.set(module_name.data(), info->dlpi_addr);
587   for (int i = 0; i < (int)info->dlpi_phnum; i++) {
588     const Elf_Phdr *phdr = &info->dlpi_phdr[i];
589     if (phdr->p_type == PT_LOAD) {
590       uptr cur_beg = info->dlpi_addr + phdr->p_vaddr;
591       uptr cur_end = cur_beg + phdr->p_memsz;
592       bool executable = phdr->p_flags & PF_X;
593       bool writable = phdr->p_flags & PF_W;
594       cur_module.addAddressRange(cur_beg, cur_end, executable,
595                                  writable);
596     }
597   }
598   data->modules->push_back(cur_module);
599   return 0;
600 }
601 
602 #if SANITIZER_ANDROID && __ANDROID_API__ < 21
603 extern "C" __attribute__((weak)) int dl_iterate_phdr(
604     int (*)(struct dl_phdr_info *, size_t, void *), void *);
605 #endif
606 
607 static bool requiresProcmaps() {
608 #if SANITIZER_ANDROID && __ANDROID_API__ <= 22
609   // Fall back to /proc/maps if dl_iterate_phdr is unavailable or broken.
610   // The runtime check allows the same library to work with
611   // both K and L (and future) Android releases.
612   return AndroidGetApiLevel() <= ANDROID_LOLLIPOP_MR1;
613 #else
614   return false;
615 #endif
616 }
617 
618 static void procmapsInit(InternalMmapVectorNoCtor<LoadedModule> *modules) {
619   MemoryMappingLayout memory_mapping(/*cache_enabled*/true);
620   memory_mapping.DumpListOfModules(modules);
621 }
622 
623 void ListOfModules::init() {
624   clearOrInit();
625   if (requiresProcmaps()) {
626     procmapsInit(&modules_);
627   } else {
628     DlIteratePhdrData data = {&modules_, true};
629     dl_iterate_phdr(dl_iterate_phdr_cb, &data);
630   }
631 }
632 
633 // When a custom loader is used, dl_iterate_phdr may not contain the full
634 // list of modules. Allow callers to fall back to using procmaps.
635 void ListOfModules::fallbackInit() {
636   if (!requiresProcmaps()) {
637     clearOrInit();
638     procmapsInit(&modules_);
639   } else {
640     clear();
641   }
642 }
643 
644 // getrusage does not give us the current RSS, only the max RSS.
645 // Still, this is better than nothing if /proc/self/statm is not available
646 // for some reason, e.g. due to a sandbox.
647 static uptr GetRSSFromGetrusage() {
648   struct rusage usage;
649   if (getrusage(RUSAGE_SELF, &usage))  // Failed, probably due to a sandbox.
650     return 0;
651   return usage.ru_maxrss << 10;  // ru_maxrss is in Kb.
652 }
653 
654 uptr GetRSS() {
655   if (!common_flags()->can_use_proc_maps_statm)
656     return GetRSSFromGetrusage();
657   fd_t fd = OpenFile("/proc/self/statm", RdOnly);
658   if (fd == kInvalidFd)
659     return GetRSSFromGetrusage();
660   char buf[64];
661   uptr len = internal_read(fd, buf, sizeof(buf) - 1);
662   internal_close(fd);
663   if ((sptr)len <= 0)
664     return 0;
665   buf[len] = 0;
666   // The format of the file is:
667   // 1084 89 69 11 0 79 0
668   // We need the second number which is RSS in pages.
669   char *pos = buf;
670   // Skip the first number.
671   while (*pos >= '0' && *pos <= '9')
672     pos++;
673   // Skip whitespaces.
674   while (!(*pos >= '0' && *pos <= '9') && *pos != 0)
675     pos++;
676   // Read the number.
677   uptr rss = 0;
678   while (*pos >= '0' && *pos <= '9')
679     rss = rss * 10 + *pos++ - '0';
680   return rss * GetPageSizeCached();
681 }
682 
683 // sysconf(_SC_NPROCESSORS_{CONF,ONLN}) cannot be used on most platforms as
684 // they allocate memory.
685 u32 GetNumberOfCPUs() {
686 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD
687   u32 ncpu;
688   int req[2];
689   uptr len = sizeof(ncpu);
690   req[0] = CTL_HW;
691   req[1] = HW_NCPU;
692   CHECK_EQ(internal_sysctl(req, 2, &ncpu, &len, NULL, 0), 0);
693   return ncpu;
694 #elif SANITIZER_ANDROID && !defined(CPU_COUNT) && !defined(__aarch64__)
695   // Fall back to /sys/devices/system/cpu on Android when cpu_set_t doesn't
696   // exist in sched.h. That is the case for toolchains generated with older
697   // NDKs.
698   // This code doesn't work on AArch64 because internal_getdents makes use of
699   // the 64bit getdents syscall, but cpu_set_t seems to always exist on AArch64.
700   uptr fd = internal_open("/sys/devices/system/cpu", O_RDONLY | O_DIRECTORY);
701   if (internal_iserror(fd))
702     return 0;
703   InternalMmapVector<u8> buffer(4096);
704   uptr bytes_read = buffer.size();
705   uptr n_cpus = 0;
706   u8 *d_type;
707   struct linux_dirent *entry = (struct linux_dirent *)&buffer[bytes_read];
708   while (true) {
709     if ((u8 *)entry >= &buffer[bytes_read]) {
710       bytes_read = internal_getdents(fd, (struct linux_dirent *)buffer.data(),
711                                      buffer.size());
712       if (internal_iserror(bytes_read) || !bytes_read)
713         break;
714       entry = (struct linux_dirent *)buffer.data();
715     }
716     d_type = (u8 *)entry + entry->d_reclen - 1;
717     if (d_type >= &buffer[bytes_read] ||
718         (u8 *)&entry->d_name[3] >= &buffer[bytes_read])
719       break;
720     if (entry->d_ino != 0 && *d_type == DT_DIR) {
721       if (entry->d_name[0] == 'c' && entry->d_name[1] == 'p' &&
722           entry->d_name[2] == 'u' &&
723           entry->d_name[3] >= '0' && entry->d_name[3] <= '9')
724         n_cpus++;
725     }
726     entry = (struct linux_dirent *)(((u8 *)entry) + entry->d_reclen);
727   }
728   internal_close(fd);
729   return n_cpus;
730 #elif SANITIZER_SOLARIS
731   return sysconf(_SC_NPROCESSORS_ONLN);
732 #else
733   cpu_set_t CPUs;
734   CHECK_EQ(sched_getaffinity(0, sizeof(cpu_set_t), &CPUs), 0);
735   return CPU_COUNT(&CPUs);
736 #endif
737 }
738 
739 #if SANITIZER_LINUX
740 
741 #if SANITIZER_ANDROID
742 static atomic_uint8_t android_log_initialized;
743 
744 void AndroidLogInit() {
745   openlog(GetProcessName(), 0, LOG_USER);
746   atomic_store(&android_log_initialized, 1, memory_order_release);
747 }
748 
749 static bool ShouldLogAfterPrintf() {
750   return atomic_load(&android_log_initialized, memory_order_acquire);
751 }
752 
753 extern "C" SANITIZER_WEAK_ATTRIBUTE
754 int async_safe_write_log(int pri, const char* tag, const char* msg);
755 extern "C" SANITIZER_WEAK_ATTRIBUTE
756 int __android_log_write(int prio, const char* tag, const char* msg);
757 
758 // ANDROID_LOG_INFO is 4, but can't be resolved at runtime.
759 #define SANITIZER_ANDROID_LOG_INFO 4
760 
761 // async_safe_write_log is a new public version of __libc_write_log that is
762 // used behind syslog. It is preferable to syslog as it will not do any dynamic
763 // memory allocation or formatting.
764 // If the function is not available, syslog is preferred for L+ (it was broken
765 // pre-L) as __android_log_write triggers a racey behavior with the strncpy
766 // interceptor. Fallback to __android_log_write pre-L.
767 void WriteOneLineToSyslog(const char *s) {
768   if (&async_safe_write_log) {
769     async_safe_write_log(SANITIZER_ANDROID_LOG_INFO, GetProcessName(), s);
770   } else if (AndroidGetApiLevel() > ANDROID_KITKAT) {
771     syslog(LOG_INFO, "%s", s);
772   } else {
773     CHECK(&__android_log_write);
774     __android_log_write(SANITIZER_ANDROID_LOG_INFO, nullptr, s);
775   }
776 }
777 
778 extern "C" SANITIZER_WEAK_ATTRIBUTE
779 void android_set_abort_message(const char *);
780 
781 void SetAbortMessage(const char *str) {
782   if (&android_set_abort_message)
783     android_set_abort_message(str);
784 }
785 #else
786 void AndroidLogInit() {}
787 
788 static bool ShouldLogAfterPrintf() { return true; }
789 
790 void WriteOneLineToSyslog(const char *s) { syslog(LOG_INFO, "%s", s); }
791 
792 void SetAbortMessage(const char *str) {}
793 #endif  // SANITIZER_ANDROID
794 
795 void LogMessageOnPrintf(const char *str) {
796   if (common_flags()->log_to_syslog && ShouldLogAfterPrintf())
797     WriteToSyslog(str);
798 }
799 
800 #endif  // SANITIZER_LINUX
801 
802 #if SANITIZER_LINUX && !SANITIZER_GO
803 // glibc crashes when using clock_gettime from a preinit_array function as the
804 // vDSO function pointers haven't been initialized yet. __progname is
805 // initialized after the vDSO function pointers, so if it exists, is not null
806 // and is not empty, we can use clock_gettime.
807 extern "C" SANITIZER_WEAK_ATTRIBUTE char *__progname;
808 inline bool CanUseVDSO() {
809   // Bionic is safe, it checks for the vDSO function pointers to be initialized.
810   if (SANITIZER_ANDROID)
811     return true;
812   if (&__progname && __progname && *__progname)
813     return true;
814   return false;
815 }
816 
817 // MonotonicNanoTime is a timing function that can leverage the vDSO by calling
818 // clock_gettime. real_clock_gettime only exists if clock_gettime is
819 // intercepted, so define it weakly and use it if available.
820 extern "C" SANITIZER_WEAK_ATTRIBUTE
821 int real_clock_gettime(u32 clk_id, void *tp);
822 u64 MonotonicNanoTime() {
823   timespec ts;
824   if (CanUseVDSO()) {
825     if (&real_clock_gettime)
826       real_clock_gettime(CLOCK_MONOTONIC, &ts);
827     else
828       clock_gettime(CLOCK_MONOTONIC, &ts);
829   } else {
830     internal_clock_gettime(CLOCK_MONOTONIC, &ts);
831   }
832   return (u64)ts.tv_sec * (1000ULL * 1000 * 1000) + ts.tv_nsec;
833 }
834 #else
835 // Non-Linux & Go always use the syscall.
836 u64 MonotonicNanoTime() {
837   timespec ts;
838   internal_clock_gettime(CLOCK_MONOTONIC, &ts);
839   return (u64)ts.tv_sec * (1000ULL * 1000 * 1000) + ts.tv_nsec;
840 }
841 #endif  // SANITIZER_LINUX && !SANITIZER_GO
842 
843 #if !SANITIZER_OPENBSD
844 void ReExec() {
845   const char *pathname = "/proc/self/exe";
846 
847 #if SANITIZER_NETBSD
848   static const int name[] = {
849       CTL_KERN,
850       KERN_PROC_ARGS,
851       -1,
852       KERN_PROC_PATHNAME,
853   };
854   char path[400];
855   uptr len;
856 
857   len = sizeof(path);
858   if (internal_sysctl(name, ARRAY_SIZE(name), path, &len, NULL, 0) != -1)
859     pathname = path;
860 #elif SANITIZER_SOLARIS
861   pathname = getexecname();
862   CHECK_NE(pathname, NULL);
863 #elif SANITIZER_USE_GETAUXVAL
864   // Calling execve with /proc/self/exe sets that as $EXEC_ORIGIN. Binaries that
865   // rely on that will fail to load shared libraries. Query AT_EXECFN instead.
866   pathname = reinterpret_cast<const char *>(getauxval(AT_EXECFN));
867 #endif
868 
869   uptr rv = internal_execve(pathname, GetArgv(), GetEnviron());
870   int rverrno;
871   CHECK_EQ(internal_iserror(rv, &rverrno), true);
872   Printf("execve failed, errno %d\n", rverrno);
873   Die();
874 }
875 #endif  // !SANITIZER_OPENBSD
876 
877 void UnmapFromTo(uptr from, uptr to) {
878   if (to == from)
879     return;
880   CHECK(to >= from);
881   uptr res = internal_munmap(reinterpret_cast<void *>(from), to - from);
882   if (UNLIKELY(internal_iserror(res))) {
883     Report("ERROR: %s failed to unmap 0x%zx (%zd) bytes at address %p\n",
884            SanitizerToolName, to - from, to - from, (void *)from);
885     CHECK("unable to unmap" && 0);
886   }
887 }
888 
889 uptr MapDynamicShadow(uptr shadow_size_bytes, uptr shadow_scale,
890                       uptr min_shadow_base_alignment,
891                       UNUSED uptr &high_mem_end) {
892   const uptr granularity = GetMmapGranularity();
893   const uptr alignment =
894       Max<uptr>(granularity << shadow_scale, 1ULL << min_shadow_base_alignment);
895   const uptr left_padding =
896       Max<uptr>(granularity, 1ULL << min_shadow_base_alignment);
897 
898   const uptr shadow_size = RoundUpTo(shadow_size_bytes, granularity);
899   const uptr map_size = shadow_size + left_padding + alignment;
900 
901   const uptr map_start = (uptr)MmapNoAccess(map_size);
902   CHECK_NE(map_start, ~(uptr)0);
903 
904   const uptr shadow_start = RoundUpTo(map_start + left_padding, alignment);
905 
906   UnmapFromTo(map_start, shadow_start - left_padding);
907   UnmapFromTo(shadow_start + shadow_size, map_start + map_size);
908 
909   return shadow_start;
910 }
911 
912 } // namespace __sanitizer
913 
914 #endif
915