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   // https://github.com/riscv/riscv-elf-psabi-doc/issues/53
389   uptr thread_pointer = reinterpret_cast<uptr>(__builtin_thread_pointer());
390   descr_addr = thread_pointer - TlsPreTcbSize();
391 #elif defined(__s390__)
392   descr_addr = reinterpret_cast<uptr>(__builtin_thread_pointer());
393 #elif defined(__powerpc64__)
394   // PPC64LE uses TLS variant I. The thread pointer (in GPR 13)
395   // points to the end of the TCB + 0x7000. The pthread_descr structure is
396   // immediately in front of the TCB. TlsPreTcbSize() includes the size of the
397   // TCB and the size of pthread_descr.
398   const uptr kTlsTcbOffset = 0x7000;
399   uptr thread_pointer;
400   asm("addi %0,13,%1" : "=r"(thread_pointer) : "I"(-kTlsTcbOffset));
401   descr_addr = thread_pointer - TlsPreTcbSize();
402 #else
403 #error "unsupported CPU arch"
404 #endif
405   return descr_addr;
406 }
407 #endif  // (x86_64 || i386 || MIPS) && SANITIZER_LINUX
408 
409 #if SANITIZER_FREEBSD
410 static void **ThreadSelfSegbase() {
411   void **segbase = 0;
412 #if defined(__i386__)
413   // sysarch(I386_GET_GSBASE, segbase);
414   __asm __volatile("mov %%gs:0, %0" : "=r" (segbase));
415 #elif defined(__x86_64__)
416   // sysarch(AMD64_GET_FSBASE, segbase);
417   __asm __volatile("movq %%fs:0, %0" : "=r" (segbase));
418 #else
419 #error "unsupported CPU arch"
420 #endif
421   return segbase;
422 }
423 
424 uptr ThreadSelf() {
425   return (uptr)ThreadSelfSegbase()[2];
426 }
427 #endif  // SANITIZER_FREEBSD
428 
429 #if SANITIZER_NETBSD
430 static struct tls_tcb * ThreadSelfTlsTcb() {
431   struct tls_tcb *tcb = nullptr;
432 #ifdef __HAVE___LWP_GETTCB_FAST
433   tcb = (struct tls_tcb *)__lwp_gettcb_fast();
434 #elif defined(__HAVE___LWP_GETPRIVATE_FAST)
435   tcb = (struct tls_tcb *)__lwp_getprivate_fast();
436 #endif
437   return tcb;
438 }
439 
440 uptr ThreadSelf() {
441   return (uptr)ThreadSelfTlsTcb()->tcb_pthread;
442 }
443 
444 int GetSizeFromHdr(struct dl_phdr_info *info, size_t size, void *data) {
445   const Elf_Phdr *hdr = info->dlpi_phdr;
446   const Elf_Phdr *last_hdr = hdr + info->dlpi_phnum;
447 
448   for (; hdr != last_hdr; ++hdr) {
449     if (hdr->p_type == PT_TLS && info->dlpi_tls_modid == 1) {
450       *(uptr*)data = hdr->p_memsz;
451       break;
452     }
453   }
454   return 0;
455 }
456 #endif  // SANITIZER_NETBSD
457 
458 #if !SANITIZER_GO
459 static void GetTls(uptr *addr, uptr *size) {
460 #if SANITIZER_LINUX && !SANITIZER_ANDROID
461 #if defined(__x86_64__) || defined(__i386__) || defined(__s390__)
462   *addr = ThreadSelf();
463   *size = GetTlsSize();
464   *addr -= *size;
465   *addr += ThreadDescriptorSize();
466 #elif defined(__mips__) || defined(__aarch64__) || defined(__powerpc64__) || \
467     defined(__arm__) || SANITIZER_RISCV64
468   *addr = ThreadSelf();
469   *size = GetTlsSize();
470 #else
471   *addr = 0;
472   *size = 0;
473 #endif
474 #elif SANITIZER_FREEBSD
475   void** segbase = ThreadSelfSegbase();
476   *addr = 0;
477   *size = 0;
478   if (segbase != 0) {
479     // tcbalign = 16
480     // tls_size = round(tls_static_space, tcbalign);
481     // dtv = segbase[1];
482     // dtv[2] = segbase - tls_static_space;
483     void **dtv = (void**) segbase[1];
484     *addr = (uptr) dtv[2];
485     *size = (*addr == 0) ? 0 : ((uptr) segbase[0] - (uptr) dtv[2]);
486   }
487 #elif SANITIZER_NETBSD
488   struct tls_tcb * const tcb = ThreadSelfTlsTcb();
489   *addr = 0;
490   *size = 0;
491   if (tcb != 0) {
492     // Find size (p_memsz) of dlpi_tls_modid 1 (TLS block of the main program).
493     // ld.elf_so hardcodes the index 1.
494     dl_iterate_phdr(GetSizeFromHdr, size);
495 
496     if (*size != 0) {
497       // The block has been found and tcb_dtv[1] contains the base address
498       *addr = (uptr)tcb->tcb_dtv[1];
499     }
500   }
501 #elif SANITIZER_OPENBSD
502   *addr = 0;
503   *size = 0;
504 #elif SANITIZER_ANDROID
505   *addr = 0;
506   *size = 0;
507 #elif SANITIZER_SOLARIS
508   // FIXME
509   *addr = 0;
510   *size = 0;
511 #else
512 #error "Unknown OS"
513 #endif
514 }
515 #endif
516 
517 #if !SANITIZER_GO
518 uptr GetTlsSize() {
519 #if SANITIZER_FREEBSD || SANITIZER_ANDROID || SANITIZER_NETBSD || \
520     SANITIZER_OPENBSD || SANITIZER_SOLARIS
521   uptr addr, size;
522   GetTls(&addr, &size);
523   return size;
524 #elif defined(__mips__) || defined(__powerpc64__) || SANITIZER_RISCV64
525   return RoundUpTo(g_tls_size + TlsPreTcbSize(), 16);
526 #else
527   return g_tls_size;
528 #endif
529 }
530 #endif
531 
532 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
533                           uptr *tls_addr, uptr *tls_size) {
534 #if SANITIZER_GO
535   // Stub implementation for Go.
536   *stk_addr = *stk_size = *tls_addr = *tls_size = 0;
537 #else
538   GetTls(tls_addr, tls_size);
539 
540   uptr stack_top, stack_bottom;
541   GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
542   *stk_addr = stack_bottom;
543   *stk_size = stack_top - stack_bottom;
544 
545   if (!main) {
546     // If stack and tls intersect, make them non-intersecting.
547     if (*tls_addr > *stk_addr && *tls_addr < *stk_addr + *stk_size) {
548       CHECK_GT(*tls_addr + *tls_size, *stk_addr);
549       CHECK_LE(*tls_addr + *tls_size, *stk_addr + *stk_size);
550       *stk_size -= *tls_size;
551       *tls_addr = *stk_addr + *stk_size;
552     }
553   }
554 #endif
555 }
556 
557 #if !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
558 typedef ElfW(Phdr) Elf_Phdr;
559 #elif SANITIZER_WORDSIZE == 32 && __FreeBSD_version <= 902001  // v9.2
560 #define Elf_Phdr XElf32_Phdr
561 #define dl_phdr_info xdl_phdr_info
562 #define dl_iterate_phdr(c, b) xdl_iterate_phdr((c), (b))
563 #endif  // !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
564 
565 struct DlIteratePhdrData {
566   InternalMmapVectorNoCtor<LoadedModule> *modules;
567   bool first;
568 };
569 
570 static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
571   DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
572   InternalScopedString module_name(kMaxPathLength);
573   if (data->first) {
574     data->first = false;
575     // First module is the binary itself.
576     ReadBinaryNameCached(module_name.data(), module_name.size());
577   } else if (info->dlpi_name) {
578     module_name.append("%s", info->dlpi_name);
579   }
580   if (module_name[0] == '\0')
581     return 0;
582   LoadedModule cur_module;
583   cur_module.set(module_name.data(), info->dlpi_addr);
584   for (int i = 0; i < (int)info->dlpi_phnum; i++) {
585     const Elf_Phdr *phdr = &info->dlpi_phdr[i];
586     if (phdr->p_type == PT_LOAD) {
587       uptr cur_beg = info->dlpi_addr + phdr->p_vaddr;
588       uptr cur_end = cur_beg + phdr->p_memsz;
589       bool executable = phdr->p_flags & PF_X;
590       bool writable = phdr->p_flags & PF_W;
591       cur_module.addAddressRange(cur_beg, cur_end, executable,
592                                  writable);
593     }
594   }
595   data->modules->push_back(cur_module);
596   return 0;
597 }
598 
599 #if SANITIZER_ANDROID && __ANDROID_API__ < 21
600 extern "C" __attribute__((weak)) int dl_iterate_phdr(
601     int (*)(struct dl_phdr_info *, size_t, void *), void *);
602 #endif
603 
604 static bool requiresProcmaps() {
605 #if SANITIZER_ANDROID && __ANDROID_API__ <= 22
606   // Fall back to /proc/maps if dl_iterate_phdr is unavailable or broken.
607   // The runtime check allows the same library to work with
608   // both K and L (and future) Android releases.
609   return AndroidGetApiLevel() <= ANDROID_LOLLIPOP_MR1;
610 #else
611   return false;
612 #endif
613 }
614 
615 static void procmapsInit(InternalMmapVectorNoCtor<LoadedModule> *modules) {
616   MemoryMappingLayout memory_mapping(/*cache_enabled*/true);
617   memory_mapping.DumpListOfModules(modules);
618 }
619 
620 void ListOfModules::init() {
621   clearOrInit();
622   if (requiresProcmaps()) {
623     procmapsInit(&modules_);
624   } else {
625     DlIteratePhdrData data = {&modules_, true};
626     dl_iterate_phdr(dl_iterate_phdr_cb, &data);
627   }
628 }
629 
630 // When a custom loader is used, dl_iterate_phdr may not contain the full
631 // list of modules. Allow callers to fall back to using procmaps.
632 void ListOfModules::fallbackInit() {
633   if (!requiresProcmaps()) {
634     clearOrInit();
635     procmapsInit(&modules_);
636   } else {
637     clear();
638   }
639 }
640 
641 // getrusage does not give us the current RSS, only the max RSS.
642 // Still, this is better than nothing if /proc/self/statm is not available
643 // for some reason, e.g. due to a sandbox.
644 static uptr GetRSSFromGetrusage() {
645   struct rusage usage;
646   if (getrusage(RUSAGE_SELF, &usage))  // Failed, probably due to a sandbox.
647     return 0;
648   return usage.ru_maxrss << 10;  // ru_maxrss is in Kb.
649 }
650 
651 uptr GetRSS() {
652   if (!common_flags()->can_use_proc_maps_statm)
653     return GetRSSFromGetrusage();
654   fd_t fd = OpenFile("/proc/self/statm", RdOnly);
655   if (fd == kInvalidFd)
656     return GetRSSFromGetrusage();
657   char buf[64];
658   uptr len = internal_read(fd, buf, sizeof(buf) - 1);
659   internal_close(fd);
660   if ((sptr)len <= 0)
661     return 0;
662   buf[len] = 0;
663   // The format of the file is:
664   // 1084 89 69 11 0 79 0
665   // We need the second number which is RSS in pages.
666   char *pos = buf;
667   // Skip the first number.
668   while (*pos >= '0' && *pos <= '9')
669     pos++;
670   // Skip whitespaces.
671   while (!(*pos >= '0' && *pos <= '9') && *pos != 0)
672     pos++;
673   // Read the number.
674   uptr rss = 0;
675   while (*pos >= '0' && *pos <= '9')
676     rss = rss * 10 + *pos++ - '0';
677   return rss * GetPageSizeCached();
678 }
679 
680 // sysconf(_SC_NPROCESSORS_{CONF,ONLN}) cannot be used on most platforms as
681 // they allocate memory.
682 u32 GetNumberOfCPUs() {
683 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD
684   u32 ncpu;
685   int req[2];
686   uptr len = sizeof(ncpu);
687   req[0] = CTL_HW;
688   req[1] = HW_NCPU;
689   CHECK_EQ(internal_sysctl(req, 2, &ncpu, &len, NULL, 0), 0);
690   return ncpu;
691 #elif SANITIZER_ANDROID && !defined(CPU_COUNT) && !defined(__aarch64__)
692   // Fall back to /sys/devices/system/cpu on Android when cpu_set_t doesn't
693   // exist in sched.h. That is the case for toolchains generated with older
694   // NDKs.
695   // This code doesn't work on AArch64 because internal_getdents makes use of
696   // the 64bit getdents syscall, but cpu_set_t seems to always exist on AArch64.
697   uptr fd = internal_open("/sys/devices/system/cpu", O_RDONLY | O_DIRECTORY);
698   if (internal_iserror(fd))
699     return 0;
700   InternalMmapVector<u8> buffer(4096);
701   uptr bytes_read = buffer.size();
702   uptr n_cpus = 0;
703   u8 *d_type;
704   struct linux_dirent *entry = (struct linux_dirent *)&buffer[bytes_read];
705   while (true) {
706     if ((u8 *)entry >= &buffer[bytes_read]) {
707       bytes_read = internal_getdents(fd, (struct linux_dirent *)buffer.data(),
708                                      buffer.size());
709       if (internal_iserror(bytes_read) || !bytes_read)
710         break;
711       entry = (struct linux_dirent *)buffer.data();
712     }
713     d_type = (u8 *)entry + entry->d_reclen - 1;
714     if (d_type >= &buffer[bytes_read] ||
715         (u8 *)&entry->d_name[3] >= &buffer[bytes_read])
716       break;
717     if (entry->d_ino != 0 && *d_type == DT_DIR) {
718       if (entry->d_name[0] == 'c' && entry->d_name[1] == 'p' &&
719           entry->d_name[2] == 'u' &&
720           entry->d_name[3] >= '0' && entry->d_name[3] <= '9')
721         n_cpus++;
722     }
723     entry = (struct linux_dirent *)(((u8 *)entry) + entry->d_reclen);
724   }
725   internal_close(fd);
726   return n_cpus;
727 #elif SANITIZER_SOLARIS
728   return sysconf(_SC_NPROCESSORS_ONLN);
729 #else
730   cpu_set_t CPUs;
731   CHECK_EQ(sched_getaffinity(0, sizeof(cpu_set_t), &CPUs), 0);
732   return CPU_COUNT(&CPUs);
733 #endif
734 }
735 
736 #if SANITIZER_LINUX
737 
738 #if SANITIZER_ANDROID
739 static atomic_uint8_t android_log_initialized;
740 
741 void AndroidLogInit() {
742   openlog(GetProcessName(), 0, LOG_USER);
743   atomic_store(&android_log_initialized, 1, memory_order_release);
744 }
745 
746 static bool ShouldLogAfterPrintf() {
747   return atomic_load(&android_log_initialized, memory_order_acquire);
748 }
749 
750 extern "C" SANITIZER_WEAK_ATTRIBUTE
751 int async_safe_write_log(int pri, const char* tag, const char* msg);
752 extern "C" SANITIZER_WEAK_ATTRIBUTE
753 int __android_log_write(int prio, const char* tag, const char* msg);
754 
755 // ANDROID_LOG_INFO is 4, but can't be resolved at runtime.
756 #define SANITIZER_ANDROID_LOG_INFO 4
757 
758 // async_safe_write_log is a new public version of __libc_write_log that is
759 // used behind syslog. It is preferable to syslog as it will not do any dynamic
760 // memory allocation or formatting.
761 // If the function is not available, syslog is preferred for L+ (it was broken
762 // pre-L) as __android_log_write triggers a racey behavior with the strncpy
763 // interceptor. Fallback to __android_log_write pre-L.
764 void WriteOneLineToSyslog(const char *s) {
765   if (&async_safe_write_log) {
766     async_safe_write_log(SANITIZER_ANDROID_LOG_INFO, GetProcessName(), s);
767   } else if (AndroidGetApiLevel() > ANDROID_KITKAT) {
768     syslog(LOG_INFO, "%s", s);
769   } else {
770     CHECK(&__android_log_write);
771     __android_log_write(SANITIZER_ANDROID_LOG_INFO, nullptr, s);
772   }
773 }
774 
775 extern "C" SANITIZER_WEAK_ATTRIBUTE
776 void android_set_abort_message(const char *);
777 
778 void SetAbortMessage(const char *str) {
779   if (&android_set_abort_message)
780     android_set_abort_message(str);
781 }
782 #else
783 void AndroidLogInit() {}
784 
785 static bool ShouldLogAfterPrintf() { return true; }
786 
787 void WriteOneLineToSyslog(const char *s) { syslog(LOG_INFO, "%s", s); }
788 
789 void SetAbortMessage(const char *str) {}
790 #endif  // SANITIZER_ANDROID
791 
792 void LogMessageOnPrintf(const char *str) {
793   if (common_flags()->log_to_syslog && ShouldLogAfterPrintf())
794     WriteToSyslog(str);
795 }
796 
797 #endif  // SANITIZER_LINUX
798 
799 #if SANITIZER_LINUX && !SANITIZER_GO
800 // glibc crashes when using clock_gettime from a preinit_array function as the
801 // vDSO function pointers haven't been initialized yet. __progname is
802 // initialized after the vDSO function pointers, so if it exists, is not null
803 // and is not empty, we can use clock_gettime.
804 extern "C" SANITIZER_WEAK_ATTRIBUTE char *__progname;
805 inline bool CanUseVDSO() {
806   // Bionic is safe, it checks for the vDSO function pointers to be initialized.
807   if (SANITIZER_ANDROID)
808     return true;
809   if (&__progname && __progname && *__progname)
810     return true;
811   return false;
812 }
813 
814 // MonotonicNanoTime is a timing function that can leverage the vDSO by calling
815 // clock_gettime. real_clock_gettime only exists if clock_gettime is
816 // intercepted, so define it weakly and use it if available.
817 extern "C" SANITIZER_WEAK_ATTRIBUTE
818 int real_clock_gettime(u32 clk_id, void *tp);
819 u64 MonotonicNanoTime() {
820   timespec ts;
821   if (CanUseVDSO()) {
822     if (&real_clock_gettime)
823       real_clock_gettime(CLOCK_MONOTONIC, &ts);
824     else
825       clock_gettime(CLOCK_MONOTONIC, &ts);
826   } else {
827     internal_clock_gettime(CLOCK_MONOTONIC, &ts);
828   }
829   return (u64)ts.tv_sec * (1000ULL * 1000 * 1000) + ts.tv_nsec;
830 }
831 #else
832 // Non-Linux & Go always use the syscall.
833 u64 MonotonicNanoTime() {
834   timespec ts;
835   internal_clock_gettime(CLOCK_MONOTONIC, &ts);
836   return (u64)ts.tv_sec * (1000ULL * 1000 * 1000) + ts.tv_nsec;
837 }
838 #endif  // SANITIZER_LINUX && !SANITIZER_GO
839 
840 #if !SANITIZER_OPENBSD
841 void ReExec() {
842   const char *pathname = "/proc/self/exe";
843 
844 #if SANITIZER_NETBSD
845   static const int name[] = {
846       CTL_KERN,
847       KERN_PROC_ARGS,
848       -1,
849       KERN_PROC_PATHNAME,
850   };
851   char path[400];
852   uptr len;
853 
854   len = sizeof(path);
855   if (internal_sysctl(name, ARRAY_SIZE(name), path, &len, NULL, 0) != -1)
856     pathname = path;
857 #elif SANITIZER_SOLARIS
858   pathname = getexecname();
859   CHECK_NE(pathname, NULL);
860 #elif SANITIZER_USE_GETAUXVAL
861   // Calling execve with /proc/self/exe sets that as $EXEC_ORIGIN. Binaries that
862   // rely on that will fail to load shared libraries. Query AT_EXECFN instead.
863   pathname = reinterpret_cast<const char *>(getauxval(AT_EXECFN));
864 #endif
865 
866   uptr rv = internal_execve(pathname, GetArgv(), GetEnviron());
867   int rverrno;
868   CHECK_EQ(internal_iserror(rv, &rverrno), true);
869   Printf("execve failed, errno %d\n", rverrno);
870   Die();
871 }
872 #endif  // !SANITIZER_OPENBSD
873 
874 void UnmapFromTo(uptr from, uptr to) {
875   if (to == from)
876     return;
877   CHECK(to >= from);
878   uptr res = internal_munmap(reinterpret_cast<void *>(from), to - from);
879   if (UNLIKELY(internal_iserror(res))) {
880     Report("ERROR: %s failed to unmap 0x%zx (%zd) bytes at address %p\n",
881            SanitizerToolName, to - from, to - from, (void *)from);
882     CHECK("unable to unmap" && 0);
883   }
884 }
885 
886 uptr MapDynamicShadow(uptr shadow_size_bytes, uptr shadow_scale,
887                       uptr min_shadow_base_alignment,
888                       UNUSED uptr &high_mem_end) {
889   const uptr granularity = GetMmapGranularity();
890   const uptr alignment =
891       Max<uptr>(granularity << shadow_scale, 1ULL << min_shadow_base_alignment);
892   const uptr left_padding =
893       Max<uptr>(granularity, 1ULL << min_shadow_base_alignment);
894 
895   const uptr shadow_size = RoundUpTo(shadow_size_bytes, granularity);
896   const uptr map_size = shadow_size + left_padding + alignment;
897 
898   const uptr map_start = (uptr)MmapNoAccess(map_size);
899   CHECK_NE(map_start, ~(uptr)0);
900 
901   const uptr shadow_start = RoundUpTo(map_start + left_padding, alignment);
902 
903   UnmapFromTo(map_start, shadow_start - left_padding);
904   UnmapFromTo(shadow_start + shadow_size, map_start + map_size);
905 
906   return shadow_start;
907 }
908 
909 } // namespace __sanitizer
910 
911 #endif
912