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