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