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