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 #include "sanitizer_solaris.h"
31 
32 #if SANITIZER_NETBSD
33 #define _RTLD_SOURCE  // for __lwp_gettcb_fast() / __lwp_getprivate_fast()
34 #endif
35 
36 #include <dlfcn.h>  // for dlsym()
37 #include <link.h>
38 #include <pthread.h>
39 #include <signal.h>
40 #include <sys/mman.h>
41 #include <sys/resource.h>
42 #include <syslog.h>
43 
44 #if !defined(ElfW)
45 #define ElfW(type) Elf_##type
46 #endif
47 
48 #if SANITIZER_FREEBSD
49 #include <pthread_np.h>
50 #include <osreldate.h>
51 #include <sys/sysctl.h>
52 #define pthread_getattr_np pthread_attr_get_np
53 // The MAP_NORESERVE define has been removed in FreeBSD 11.x, and even before
54 // that, it was never implemented. So just define it to zero.
55 #undef MAP_NORESERVE
56 #define MAP_NORESERVE 0
57 #endif
58 
59 #if SANITIZER_NETBSD
60 #include <sys/sysctl.h>
61 #include <sys/tls.h>
62 #include <lwp.h>
63 #endif
64 
65 #if SANITIZER_SOLARIS
66 #include <stddef.h>
67 #include <stdlib.h>
68 #include <thread.h>
69 #endif
70 
71 #if SANITIZER_ANDROID
72 #include <android/api-level.h>
73 #if !defined(CPU_COUNT) && !defined(__aarch64__)
74 #include <dirent.h>
75 #include <fcntl.h>
76 struct __sanitizer::linux_dirent {
77   long           d_ino;
78   off_t          d_off;
79   unsigned short d_reclen;
80   char           d_name[];
81 };
82 #endif
83 #endif
84 
85 #if !SANITIZER_ANDROID
86 #include <elf.h>
87 #include <unistd.h>
88 #endif
89 
90 namespace __sanitizer {
91 
92 SANITIZER_WEAK_ATTRIBUTE int
93 real_sigaction(int signum, const void *act, void *oldact);
94 
internal_sigaction(int signum,const void * act,void * oldact)95 int internal_sigaction(int signum, const void *act, void *oldact) {
96 #if !SANITIZER_GO
97   if (&real_sigaction)
98     return real_sigaction(signum, act, oldact);
99 #endif
100   return sigaction(signum, (const struct sigaction *)act,
101                    (struct sigaction *)oldact);
102 }
103 
GetThreadStackTopAndBottom(bool at_initialization,uptr * stack_top,uptr * stack_bottom)104 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
105                                 uptr *stack_bottom) {
106   CHECK(stack_top);
107   CHECK(stack_bottom);
108   if (at_initialization) {
109     // This is the main thread. Libpthread may not be initialized yet.
110     struct rlimit rl;
111     CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
112 
113     // Find the mapping that contains a stack variable.
114     MemoryMappingLayout proc_maps(/*cache_enabled*/true);
115     if (proc_maps.Error()) {
116       *stack_top = *stack_bottom = 0;
117       return;
118     }
119     MemoryMappedSegment segment;
120     uptr prev_end = 0;
121     while (proc_maps.Next(&segment)) {
122       if ((uptr)&rl < segment.end) break;
123       prev_end = segment.end;
124     }
125     CHECK((uptr)&rl >= segment.start && (uptr)&rl < segment.end);
126 
127     // Get stacksize from rlimit, but clip it so that it does not overlap
128     // with other mappings.
129     uptr stacksize = rl.rlim_cur;
130     if (stacksize > segment.end - prev_end) stacksize = segment.end - prev_end;
131     // When running with unlimited stack size, we still want to set some limit.
132     // The unlimited stack size is caused by 'ulimit -s unlimited'.
133     // Also, for some reason, GNU make spawns subprocesses with unlimited stack.
134     if (stacksize > kMaxThreadStackSize)
135       stacksize = kMaxThreadStackSize;
136     *stack_top = segment.end;
137     *stack_bottom = segment.end - stacksize;
138     return;
139   }
140   uptr stacksize = 0;
141   void *stackaddr = nullptr;
142 #if SANITIZER_SOLARIS
143   stack_t ss;
144   CHECK_EQ(thr_stksegment(&ss), 0);
145   stacksize = ss.ss_size;
146   stackaddr = (char *)ss.ss_sp - stacksize;
147 #else  // !SANITIZER_SOLARIS
148   pthread_attr_t attr;
149   pthread_attr_init(&attr);
150   CHECK_EQ(pthread_getattr_np(pthread_self(), &attr), 0);
151   my_pthread_attr_getstack(&attr, &stackaddr, &stacksize);
152   pthread_attr_destroy(&attr);
153 #endif  // SANITIZER_SOLARIS
154 
155   *stack_top = (uptr)stackaddr + stacksize;
156   *stack_bottom = (uptr)stackaddr;
157 }
158 
159 #if !SANITIZER_GO
SetEnv(const char * name,const char * value)160 bool SetEnv(const char *name, const char *value) {
161   void *f = dlsym(RTLD_NEXT, "setenv");
162   if (!f)
163     return false;
164   typedef int(*setenv_ft)(const char *name, const char *value, int overwrite);
165   setenv_ft setenv_f;
166   CHECK_EQ(sizeof(setenv_f), sizeof(f));
167   internal_memcpy(&setenv_f, &f, sizeof(f));
168   return setenv_f(name, value, 1) == 0;
169 }
170 #endif
171 
GetLibcVersion(int * major,int * minor,int * patch)172 __attribute__((unused)) static bool GetLibcVersion(int *major, int *minor,
173                                                    int *patch) {
174 #ifdef _CS_GNU_LIBC_VERSION
175   char buf[64];
176   uptr len = confstr(_CS_GNU_LIBC_VERSION, buf, sizeof(buf));
177   if (len >= sizeof(buf))
178     return false;
179   buf[len] = 0;
180   static const char kGLibC[] = "glibc ";
181   if (internal_strncmp(buf, kGLibC, sizeof(kGLibC) - 1) != 0)
182     return false;
183   const char *p = buf + sizeof(kGLibC) - 1;
184   *major = internal_simple_strtoll(p, &p, 10);
185   *minor = (*p == '.') ? internal_simple_strtoll(p + 1, &p, 10) : 0;
186   *patch = (*p == '.') ? internal_simple_strtoll(p + 1, &p, 10) : 0;
187   return true;
188 #else
189   return false;
190 #endif
191 }
192 
193 // True if we can use dlpi_tls_data. glibc before 2.25 may leave NULL (BZ
194 // #19826) so dlpi_tls_data cannot be used.
195 //
196 // musl before 1.2.3 and FreeBSD as of 12.2 incorrectly set dlpi_tls_data to
197 // the TLS initialization image
198 // https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=254774
199 __attribute__((unused)) static int g_use_dlpi_tls_data;
200 
201 #if SANITIZER_GLIBC && !SANITIZER_GO
202 __attribute__((unused)) static size_t g_tls_size;
InitTlsSize()203 void InitTlsSize() {
204   int major, minor, patch;
205   g_use_dlpi_tls_data =
206       GetLibcVersion(&major, &minor, &patch) && major == 2 && minor >= 25;
207 
208 #if defined(__aarch64__) || defined(__x86_64__) || defined(__powerpc64__)
209   void *get_tls_static_info = dlsym(RTLD_NEXT, "_dl_get_tls_static_info");
210   size_t tls_align;
211   ((void (*)(size_t *, size_t *))get_tls_static_info)(&g_tls_size, &tls_align);
212 #endif
213 }
214 #else
InitTlsSize()215 void InitTlsSize() { }
216 #endif  // SANITIZER_GLIBC && !SANITIZER_GO
217 
218 // On glibc x86_64, ThreadDescriptorSize() needs to be precise due to the usage
219 // of g_tls_size. On other targets, ThreadDescriptorSize() is only used by lsan
220 // to get the pointer to thread-specific data keys in the thread control block.
221 #if (SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_SOLARIS) && \
222     !SANITIZER_ANDROID && !SANITIZER_GO
223 // sizeof(struct pthread) from glibc.
224 static atomic_uintptr_t thread_descriptor_size;
225 
ThreadDescriptorSizeFallback()226 static uptr ThreadDescriptorSizeFallback() {
227   uptr val = 0;
228 #if defined(__x86_64__) || defined(__i386__) || defined(__arm__)
229   int major;
230   int minor;
231   int patch;
232   if (GetLibcVersion(&major, &minor, &patch) && major == 2) {
233     /* sizeof(struct pthread) values from various glibc versions.  */
234     if (SANITIZER_X32)
235       val = 1728; // Assume only one particular version for x32.
236     // For ARM sizeof(struct pthread) changed in Glibc 2.23.
237     else if (SANITIZER_ARM)
238       val = minor <= 22 ? 1120 : 1216;
239     else if (minor <= 3)
240       val = FIRST_32_SECOND_64(1104, 1696);
241     else if (minor == 4)
242       val = FIRST_32_SECOND_64(1120, 1728);
243     else if (minor == 5)
244       val = FIRST_32_SECOND_64(1136, 1728);
245     else if (minor <= 9)
246       val = FIRST_32_SECOND_64(1136, 1712);
247     else if (minor == 10)
248       val = FIRST_32_SECOND_64(1168, 1776);
249     else if (minor == 11 || (minor == 12 && patch == 1))
250       val = FIRST_32_SECOND_64(1168, 2288);
251     else if (minor <= 14)
252       val = FIRST_32_SECOND_64(1168, 2304);
253     else if (minor < 32)  // Unknown version
254       val = FIRST_32_SECOND_64(1216, 2304);
255     else  // minor == 32
256       val = FIRST_32_SECOND_64(1344, 2496);
257   }
258 #elif defined(__s390__) || defined(__sparc__)
259   // The size of a prefix of TCB including pthread::{specific_1stblock,specific}
260   // suffices. Just return offsetof(struct pthread, specific_used), which hasn't
261   // changed since 2007-05. Technically this applies to i386/x86_64 as well but
262   // we call _dl_get_tls_static_info and need the precise size of struct
263   // pthread.
264   return FIRST_32_SECOND_64(524, 1552);
265 #elif defined(__mips__)
266   // TODO(sagarthakur): add more values as per different glibc versions.
267   val = FIRST_32_SECOND_64(1152, 1776);
268 #elif SANITIZER_RISCV64
269   int major;
270   int minor;
271   int patch;
272   if (GetLibcVersion(&major, &minor, &patch) && major == 2) {
273     // TODO: consider adding an optional runtime check for an unknown (untested)
274     // glibc version
275     if (minor <= 28)  // WARNING: the highest tested version is 2.29
276       val = 1772;     // no guarantees for this one
277     else if (minor <= 31)
278       val = 1772;  // tested against glibc 2.29, 2.31
279     else
280       val = 1936;  // tested against glibc 2.32
281   }
282 
283 #elif defined(__aarch64__)
284   // The sizeof (struct pthread) is the same from GLIBC 2.17 to 2.22.
285   val = 1776;
286 #elif defined(__powerpc64__)
287   val = 1776; // from glibc.ppc64le 2.20-8.fc21
288 #endif
289   return val;
290 }
291 
ThreadDescriptorSize()292 uptr ThreadDescriptorSize() {
293   uptr val = atomic_load_relaxed(&thread_descriptor_size);
294   if (val)
295     return val;
296   // _thread_db_sizeof_pthread is a GLIBC_PRIVATE symbol that is exported in
297   // glibc 2.34 and later.
298   if (unsigned *psizeof = static_cast<unsigned *>(
299           dlsym(RTLD_DEFAULT, "_thread_db_sizeof_pthread")))
300     val = *psizeof;
301   if (!val)
302     val = ThreadDescriptorSizeFallback();
303   atomic_store_relaxed(&thread_descriptor_size, val);
304   return val;
305 }
306 
307 #if defined(__mips__) || defined(__powerpc64__) || SANITIZER_RISCV64
308 // TlsPreTcbSize includes size of struct pthread_descr and size of tcb
309 // head structure. It lies before the static tls blocks.
TlsPreTcbSize()310 static uptr TlsPreTcbSize() {
311 #if defined(__mips__)
312   const uptr kTcbHead = 16; // sizeof (tcbhead_t)
313 #elif defined(__powerpc64__)
314   const uptr kTcbHead = 88; // sizeof (tcbhead_t)
315 #elif SANITIZER_RISCV64
316   const uptr kTcbHead = 16;  // sizeof (tcbhead_t)
317 #endif
318   const uptr kTlsAlign = 16;
319   const uptr kTlsPreTcbSize =
320       RoundUpTo(ThreadDescriptorSize() + kTcbHead, kTlsAlign);
321   return kTlsPreTcbSize;
322 }
323 #endif
324 
325 namespace {
326 struct TlsBlock {
327   uptr begin, end, align;
328   size_t tls_modid;
operator <__sanitizer::__anonc8edd2fd0111::TlsBlock329   bool operator<(const TlsBlock &rhs) const { return begin < rhs.begin; }
330 };
331 }  // namespace
332 
333 #ifdef __s390__
334 extern "C" uptr __tls_get_offset(void *arg);
335 
TlsGetOffset(uptr ti_module,uptr ti_offset)336 static uptr TlsGetOffset(uptr ti_module, uptr ti_offset) {
337   // The __tls_get_offset ABI requires %r12 to point to GOT and %r2 to be an
338   // offset of a struct tls_index inside GOT. We don't possess either of the
339   // two, so violate the letter of the "ELF Handling For Thread-Local
340   // Storage" document and assume that the implementation just dereferences
341   // %r2 + %r12.
342   uptr tls_index[2] = {ti_module, ti_offset};
343   register uptr r2 asm("2") = 0;
344   register void *r12 asm("12") = tls_index;
345   asm("basr %%r14, %[__tls_get_offset]"
346       : "+r"(r2)
347       : [__tls_get_offset] "r"(__tls_get_offset), "r"(r12)
348       : "memory", "cc", "0", "1", "3", "4", "5", "14");
349   return r2;
350 }
351 #else
352 extern "C" void *__tls_get_addr(size_t *);
353 #endif
354 
355 static size_t main_tls_modid;
356 
CollectStaticTlsBlocks(struct dl_phdr_info * info,size_t size,void * data)357 static int CollectStaticTlsBlocks(struct dl_phdr_info *info, size_t size,
358                                   void *data) {
359   size_t tls_modid;
360 #if SANITIZER_SOLARIS
361   // dlpi_tls_modid is only available since Solaris 11.4 SRU 10.  Use
362   // dlinfo(RTLD_DI_LINKMAP) instead which works on all of Solaris 11.3,
363   // 11.4, and Illumos.  The tlsmodid of the executable was changed to 1 in
364   // 11.4 to match other implementations.
365   if (size >= offsetof(dl_phdr_info_test, dlpi_tls_modid))
366     main_tls_modid = 1;
367   else
368     main_tls_modid = 0;
369   g_use_dlpi_tls_data = 0;
370   Rt_map *map;
371   dlinfo(RTLD_SELF, RTLD_DI_LINKMAP, &map);
372   tls_modid = map->rt_tlsmodid;
373 #else
374   main_tls_modid = 1;
375   tls_modid = info->dlpi_tls_modid;
376 #endif
377 
378   if (tls_modid < main_tls_modid)
379     return 0;
380   uptr begin;
381 #if !SANITIZER_SOLARIS
382   begin = (uptr)info->dlpi_tls_data;
383 #endif
384   if (!g_use_dlpi_tls_data) {
385     // Call __tls_get_addr as a fallback. This forces TLS allocation on glibc
386     // and FreeBSD.
387 #ifdef __s390__
388     begin = (uptr)__builtin_thread_pointer() +
389             TlsGetOffset(tls_modid, 0);
390 #else
391     size_t mod_and_off[2] = {tls_modid, 0};
392     begin = (uptr)__tls_get_addr(mod_and_off);
393 #endif
394   }
395   for (unsigned i = 0; i != info->dlpi_phnum; ++i)
396     if (info->dlpi_phdr[i].p_type == PT_TLS) {
397       static_cast<InternalMmapVector<TlsBlock> *>(data)->push_back(
398           TlsBlock{begin, begin + info->dlpi_phdr[i].p_memsz,
399                    info->dlpi_phdr[i].p_align, tls_modid});
400       break;
401     }
402   return 0;
403 }
404 
GetStaticTlsBoundary(uptr * addr,uptr * size,uptr * align)405 __attribute__((unused)) static void GetStaticTlsBoundary(uptr *addr, uptr *size,
406                                                          uptr *align) {
407   InternalMmapVector<TlsBlock> ranges;
408   dl_iterate_phdr(CollectStaticTlsBlocks, &ranges);
409   uptr len = ranges.size();
410   Sort(ranges.begin(), len);
411   // Find the range with tls_modid == main_tls_modid. For glibc, because
412   // libc.so uses PT_TLS, this module is guaranteed to exist and is one of
413   // the initially loaded modules.
414   uptr one = 0;
415   while (one != len && ranges[one].tls_modid != main_tls_modid) ++one;
416   if (one == len) {
417     // This may happen with musl if no module uses PT_TLS.
418     *addr = 0;
419     *size = 0;
420     *align = 1;
421     return;
422   }
423   // Find the maximum consecutive ranges. We consider two modules consecutive if
424   // the gap is smaller than the alignment of the latter range. The dynamic
425   // loader places static TLS blocks this way not to waste space.
426   uptr l = one;
427   *align = ranges[l].align;
428   while (l != 0 && ranges[l].begin < ranges[l - 1].end + ranges[l].align)
429     *align = Max(*align, ranges[--l].align);
430   uptr r = one + 1;
431   while (r != len && ranges[r].begin < ranges[r - 1].end + ranges[r].align)
432     *align = Max(*align, ranges[r++].align);
433   *addr = ranges[l].begin;
434   *size = ranges[r - 1].end - ranges[l].begin;
435 }
436 #endif  // (x86_64 || i386 || mips || ...) && (SANITIZER_FREEBSD ||
437         // SANITIZER_LINUX) && !SANITIZER_ANDROID && !SANITIZER_GO
438 
439 #if SANITIZER_NETBSD
ThreadSelfTlsTcb()440 static struct tls_tcb * ThreadSelfTlsTcb() {
441   struct tls_tcb *tcb = nullptr;
442 #ifdef __HAVE___LWP_GETTCB_FAST
443   tcb = (struct tls_tcb *)__lwp_gettcb_fast();
444 #elif defined(__HAVE___LWP_GETPRIVATE_FAST)
445   tcb = (struct tls_tcb *)__lwp_getprivate_fast();
446 #endif
447   return tcb;
448 }
449 
ThreadSelf()450 uptr ThreadSelf() {
451   return (uptr)ThreadSelfTlsTcb()->tcb_pthread;
452 }
453 
GetSizeFromHdr(struct dl_phdr_info * info,size_t size,void * data)454 int GetSizeFromHdr(struct dl_phdr_info *info, size_t size, void *data) {
455   const Elf_Phdr *hdr = info->dlpi_phdr;
456   const Elf_Phdr *last_hdr = hdr + info->dlpi_phnum;
457 
458   for (; hdr != last_hdr; ++hdr) {
459     if (hdr->p_type == PT_TLS && info->dlpi_tls_modid == 1) {
460       *(uptr*)data = hdr->p_memsz;
461       break;
462     }
463   }
464   return 0;
465 }
466 #endif  // SANITIZER_NETBSD
467 
468 #if SANITIZER_ANDROID
469 // Bionic provides this API since S.
470 extern "C" SANITIZER_WEAK_ATTRIBUTE void __libc_get_static_tls_bounds(void **,
471                                                                       void **);
472 #endif
473 
474 #if !SANITIZER_GO
GetTls(uptr * addr,uptr * size)475 static void GetTls(uptr *addr, uptr *size) {
476 #if SANITIZER_ANDROID
477   if (&__libc_get_static_tls_bounds) {
478     void *start_addr;
479     void *end_addr;
480     __libc_get_static_tls_bounds(&start_addr, &end_addr);
481     *addr = reinterpret_cast<uptr>(start_addr);
482     *size =
483         reinterpret_cast<uptr>(end_addr) - reinterpret_cast<uptr>(start_addr);
484   } else {
485     *addr = 0;
486     *size = 0;
487   }
488 #elif SANITIZER_GLIBC && defined(__x86_64__)
489   // For aarch64 and x86-64, use an O(1) approach which requires relatively
490   // precise ThreadDescriptorSize. g_tls_size was initialized in InitTlsSize.
491 #  if SANITIZER_X32
492   asm("mov %%fs:8,%0" : "=r"(*addr));
493 #  else
494   asm("mov %%fs:16,%0" : "=r"(*addr));
495 #  endif
496   *size = g_tls_size;
497   *addr -= *size;
498   *addr += ThreadDescriptorSize();
499 #elif SANITIZER_GLIBC && defined(__aarch64__)
500   *addr = reinterpret_cast<uptr>(__builtin_thread_pointer()) -
501           ThreadDescriptorSize();
502   *size = g_tls_size + ThreadDescriptorSize();
503 #elif SANITIZER_GLIBC && defined(__powerpc64__)
504   // Workaround for glibc<2.25(?). 2.27 is known to not need this.
505   uptr tp;
506   asm("addi %0,13,-0x7000" : "=r"(tp));
507   const uptr pre_tcb_size = TlsPreTcbSize();
508   *addr = tp - pre_tcb_size;
509   *size = g_tls_size + pre_tcb_size;
510 #elif SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_SOLARIS
511   uptr align;
512   GetStaticTlsBoundary(addr, size, &align);
513 #if defined(__x86_64__) || defined(__i386__) || defined(__s390__) || \
514     defined(__sparc__)
515   if (SANITIZER_GLIBC) {
516 #if defined(__x86_64__) || defined(__i386__)
517     align = Max<uptr>(align, 64);
518 #else
519     align = Max<uptr>(align, 16);
520 #endif
521   }
522   const uptr tp = RoundUpTo(*addr + *size, align);
523 
524   // lsan requires the range to additionally cover the static TLS surplus
525   // (elf/dl-tls.c defines 1664). Otherwise there may be false positives for
526   // allocations only referenced by tls in dynamically loaded modules.
527   if (SANITIZER_GLIBC)
528     *size += 1644;
529   else if (SANITIZER_FREEBSD)
530     *size += 128;  // RTLD_STATIC_TLS_EXTRA
531 
532   // Extend the range to include the thread control block. On glibc, lsan needs
533   // the range to include pthread::{specific_1stblock,specific} so that
534   // allocations only referenced by pthread_setspecific can be scanned. This may
535   // underestimate by at most TLS_TCB_ALIGN-1 bytes but it should be fine
536   // because the number of bytes after pthread::specific is larger.
537   *addr = tp - RoundUpTo(*size, align);
538   *size = tp - *addr + ThreadDescriptorSize();
539 #else
540   if (SANITIZER_GLIBC)
541     *size += 1664;
542   else if (SANITIZER_FREEBSD)
543     *size += 128;  // RTLD_STATIC_TLS_EXTRA
544 #if defined(__mips__) || defined(__powerpc64__) || SANITIZER_RISCV64
545   const uptr pre_tcb_size = TlsPreTcbSize();
546   *addr -= pre_tcb_size;
547   *size += pre_tcb_size;
548 #else
549   // arm and aarch64 reserve two words at TP, so this underestimates the range.
550   // However, this is sufficient for the purpose of finding the pointers to
551   // thread-specific data keys.
552   const uptr tcb_size = ThreadDescriptorSize();
553   *addr -= tcb_size;
554   *size += tcb_size;
555 #endif
556 #endif
557 #elif SANITIZER_NETBSD
558   struct tls_tcb * const tcb = ThreadSelfTlsTcb();
559   *addr = 0;
560   *size = 0;
561   if (tcb != 0) {
562     // Find size (p_memsz) of dlpi_tls_modid 1 (TLS block of the main program).
563     // ld.elf_so hardcodes the index 1.
564     dl_iterate_phdr(GetSizeFromHdr, size);
565 
566     if (*size != 0) {
567       // The block has been found and tcb_dtv[1] contains the base address
568       *addr = (uptr)tcb->tcb_dtv[1];
569     }
570   }
571 #error "Unknown OS"
572 #endif
573 }
574 #endif
575 
576 #if !SANITIZER_GO
GetTlsSize()577 uptr GetTlsSize() {
578 #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD || \
579     SANITIZER_SOLARIS
580   uptr addr, size;
581   GetTls(&addr, &size);
582   return size;
583 #else
584   return 0;
585 #endif
586 }
587 #endif
588 
GetThreadStackAndTls(bool main,uptr * stk_addr,uptr * stk_size,uptr * tls_addr,uptr * tls_size)589 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
590                           uptr *tls_addr, uptr *tls_size) {
591 #if SANITIZER_GO
592   // Stub implementation for Go.
593   *stk_addr = *stk_size = *tls_addr = *tls_size = 0;
594 #else
595   GetTls(tls_addr, tls_size);
596 
597   uptr stack_top, stack_bottom;
598   GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
599   *stk_addr = stack_bottom;
600   *stk_size = stack_top - stack_bottom;
601 
602   if (!main) {
603     // If stack and tls intersect, make them non-intersecting.
604     if (*tls_addr > *stk_addr && *tls_addr < *stk_addr + *stk_size) {
605       if (*stk_addr + *stk_size < *tls_addr + *tls_size)
606         *tls_size = *stk_addr + *stk_size - *tls_addr;
607       *stk_size = *tls_addr - *stk_addr;
608     }
609   }
610 #endif
611 }
612 
613 #if !SANITIZER_FREEBSD
614 typedef ElfW(Phdr) Elf_Phdr;
615 #elif SANITIZER_WORDSIZE == 32 && __FreeBSD_version <= 902001  // v9.2
616 #define Elf_Phdr XElf32_Phdr
617 #define dl_phdr_info xdl_phdr_info
618 #define dl_iterate_phdr(c, b) xdl_iterate_phdr((c), (b))
619 #endif  // !SANITIZER_FREEBSD
620 
621 struct DlIteratePhdrData {
622   InternalMmapVectorNoCtor<LoadedModule> *modules;
623   bool first;
624 };
625 
AddModuleSegments(const char * module_name,dl_phdr_info * info,InternalMmapVectorNoCtor<LoadedModule> * modules)626 static int AddModuleSegments(const char *module_name, dl_phdr_info *info,
627                              InternalMmapVectorNoCtor<LoadedModule> *modules) {
628   if (module_name[0] == '\0')
629     return 0;
630   LoadedModule cur_module;
631   cur_module.set(module_name, info->dlpi_addr);
632   for (int i = 0; i < (int)info->dlpi_phnum; i++) {
633     const Elf_Phdr *phdr = &info->dlpi_phdr[i];
634     if (phdr->p_type == PT_LOAD) {
635       uptr cur_beg = info->dlpi_addr + phdr->p_vaddr;
636       uptr cur_end = cur_beg + phdr->p_memsz;
637       bool executable = phdr->p_flags & PF_X;
638       bool writable = phdr->p_flags & PF_W;
639       cur_module.addAddressRange(cur_beg, cur_end, executable,
640                                  writable);
641     } else if (phdr->p_type == PT_NOTE) {
642 #  ifdef NT_GNU_BUILD_ID
643       uptr off = 0;
644       while (off + sizeof(ElfW(Nhdr)) < phdr->p_memsz) {
645         auto *nhdr = reinterpret_cast<const ElfW(Nhdr) *>(info->dlpi_addr +
646                                                           phdr->p_vaddr + off);
647         constexpr auto kGnuNamesz = 4;  // "GNU" with NUL-byte.
648         static_assert(kGnuNamesz % 4 == 0, "kGnuNameSize is aligned to 4.");
649         if (nhdr->n_type == NT_GNU_BUILD_ID && nhdr->n_namesz == kGnuNamesz) {
650           if (off + sizeof(ElfW(Nhdr)) + nhdr->n_namesz + nhdr->n_descsz >
651               phdr->p_memsz) {
652             // Something is very wrong, bail out instead of reading potentially
653             // arbitrary memory.
654             break;
655           }
656           const char *name =
657               reinterpret_cast<const char *>(nhdr) + sizeof(*nhdr);
658           if (internal_memcmp(name, "GNU", 3) == 0) {
659             const char *value = reinterpret_cast<const char *>(nhdr) +
660                                 sizeof(*nhdr) + kGnuNamesz;
661             cur_module.setUuid(value, nhdr->n_descsz);
662             break;
663           }
664         }
665         off += sizeof(*nhdr) + RoundUpTo(nhdr->n_namesz, 4) +
666                RoundUpTo(nhdr->n_descsz, 4);
667       }
668 #  endif
669     }
670   }
671   modules->push_back(cur_module);
672   return 0;
673 }
674 
dl_iterate_phdr_cb(dl_phdr_info * info,size_t size,void * arg)675 static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
676   DlIteratePhdrData *data = (DlIteratePhdrData *)arg;
677   if (data->first) {
678     InternalMmapVector<char> module_name(kMaxPathLength);
679     data->first = false;
680     // First module is the binary itself.
681     ReadBinaryNameCached(module_name.data(), module_name.size());
682     return AddModuleSegments(module_name.data(), info, data->modules);
683   }
684 
685   if (info->dlpi_name) {
686     InternalScopedString module_name;
687     module_name.append("%s", info->dlpi_name);
688     return AddModuleSegments(module_name.data(), info, data->modules);
689   }
690 
691   return 0;
692 }
693 
694 #if SANITIZER_ANDROID && __ANDROID_API__ < 21
695 extern "C" __attribute__((weak)) int dl_iterate_phdr(
696     int (*)(struct dl_phdr_info *, size_t, void *), void *);
697 #endif
698 
requiresProcmaps()699 static bool requiresProcmaps() {
700 #if SANITIZER_ANDROID && __ANDROID_API__ <= 22
701   // Fall back to /proc/maps if dl_iterate_phdr is unavailable or broken.
702   // The runtime check allows the same library to work with
703   // both K and L (and future) Android releases.
704   return AndroidGetApiLevel() <= ANDROID_LOLLIPOP_MR1;
705 #else
706   return false;
707 #endif
708 }
709 
procmapsInit(InternalMmapVectorNoCtor<LoadedModule> * modules)710 static void procmapsInit(InternalMmapVectorNoCtor<LoadedModule> *modules) {
711   MemoryMappingLayout memory_mapping(/*cache_enabled*/true);
712   memory_mapping.DumpListOfModules(modules);
713 }
714 
init()715 void ListOfModules::init() {
716   clearOrInit();
717   if (requiresProcmaps()) {
718     procmapsInit(&modules_);
719   } else {
720     DlIteratePhdrData data = {&modules_, true};
721     dl_iterate_phdr(dl_iterate_phdr_cb, &data);
722   }
723 }
724 
725 // When a custom loader is used, dl_iterate_phdr may not contain the full
726 // list of modules. Allow callers to fall back to using procmaps.
fallbackInit()727 void ListOfModules::fallbackInit() {
728   if (!requiresProcmaps()) {
729     clearOrInit();
730     procmapsInit(&modules_);
731   } else {
732     clear();
733   }
734 }
735 
736 // getrusage does not give us the current RSS, only the max RSS.
737 // Still, this is better than nothing if /proc/self/statm is not available
738 // for some reason, e.g. due to a sandbox.
GetRSSFromGetrusage()739 static uptr GetRSSFromGetrusage() {
740   struct rusage usage;
741   if (getrusage(RUSAGE_SELF, &usage))  // Failed, probably due to a sandbox.
742     return 0;
743   return usage.ru_maxrss << 10;  // ru_maxrss is in Kb.
744 }
745 
GetRSS()746 uptr GetRSS() {
747   if (!common_flags()->can_use_proc_maps_statm)
748     return GetRSSFromGetrusage();
749   fd_t fd = OpenFile("/proc/self/statm", RdOnly);
750   if (fd == kInvalidFd)
751     return GetRSSFromGetrusage();
752   char buf[64];
753   uptr len = internal_read(fd, buf, sizeof(buf) - 1);
754   internal_close(fd);
755   if ((sptr)len <= 0)
756     return 0;
757   buf[len] = 0;
758   // The format of the file is:
759   // 1084 89 69 11 0 79 0
760   // We need the second number which is RSS in pages.
761   char *pos = buf;
762   // Skip the first number.
763   while (*pos >= '0' && *pos <= '9')
764     pos++;
765   // Skip whitespaces.
766   while (!(*pos >= '0' && *pos <= '9') && *pos != 0)
767     pos++;
768   // Read the number.
769   uptr rss = 0;
770   while (*pos >= '0' && *pos <= '9')
771     rss = rss * 10 + *pos++ - '0';
772   return rss * GetPageSizeCached();
773 }
774 
775 // sysconf(_SC_NPROCESSORS_{CONF,ONLN}) cannot be used on most platforms as
776 // they allocate memory.
GetNumberOfCPUs()777 u32 GetNumberOfCPUs() {
778 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
779   u32 ncpu;
780   int req[2];
781   uptr len = sizeof(ncpu);
782   req[0] = CTL_HW;
783   req[1] = HW_NCPU;
784   CHECK_EQ(internal_sysctl(req, 2, &ncpu, &len, NULL, 0), 0);
785   return ncpu;
786 #elif SANITIZER_ANDROID && !defined(CPU_COUNT) && !defined(__aarch64__)
787   // Fall back to /sys/devices/system/cpu on Android when cpu_set_t doesn't
788   // exist in sched.h. That is the case for toolchains generated with older
789   // NDKs.
790   // This code doesn't work on AArch64 because internal_getdents makes use of
791   // the 64bit getdents syscall, but cpu_set_t seems to always exist on AArch64.
792   uptr fd = internal_open("/sys/devices/system/cpu", O_RDONLY | O_DIRECTORY);
793   if (internal_iserror(fd))
794     return 0;
795   InternalMmapVector<u8> buffer(4096);
796   uptr bytes_read = buffer.size();
797   uptr n_cpus = 0;
798   u8 *d_type;
799   struct linux_dirent *entry = (struct linux_dirent *)&buffer[bytes_read];
800   while (true) {
801     if ((u8 *)entry >= &buffer[bytes_read]) {
802       bytes_read = internal_getdents(fd, (struct linux_dirent *)buffer.data(),
803                                      buffer.size());
804       if (internal_iserror(bytes_read) || !bytes_read)
805         break;
806       entry = (struct linux_dirent *)buffer.data();
807     }
808     d_type = (u8 *)entry + entry->d_reclen - 1;
809     if (d_type >= &buffer[bytes_read] ||
810         (u8 *)&entry->d_name[3] >= &buffer[bytes_read])
811       break;
812     if (entry->d_ino != 0 && *d_type == DT_DIR) {
813       if (entry->d_name[0] == 'c' && entry->d_name[1] == 'p' &&
814           entry->d_name[2] == 'u' &&
815           entry->d_name[3] >= '0' && entry->d_name[3] <= '9')
816         n_cpus++;
817     }
818     entry = (struct linux_dirent *)(((u8 *)entry) + entry->d_reclen);
819   }
820   internal_close(fd);
821   return n_cpus;
822 #elif SANITIZER_SOLARIS
823   return sysconf(_SC_NPROCESSORS_ONLN);
824 #else
825   cpu_set_t CPUs;
826   CHECK_EQ(sched_getaffinity(0, sizeof(cpu_set_t), &CPUs), 0);
827   return CPU_COUNT(&CPUs);
828 #endif
829 }
830 
831 #if SANITIZER_LINUX
832 
833 #if SANITIZER_ANDROID
834 static atomic_uint8_t android_log_initialized;
835 
AndroidLogInit()836 void AndroidLogInit() {
837   openlog(GetProcessName(), 0, LOG_USER);
838   atomic_store(&android_log_initialized, 1, memory_order_release);
839 }
840 
ShouldLogAfterPrintf()841 static bool ShouldLogAfterPrintf() {
842   return atomic_load(&android_log_initialized, memory_order_acquire);
843 }
844 
845 extern "C" SANITIZER_WEAK_ATTRIBUTE
846 int async_safe_write_log(int pri, const char* tag, const char* msg);
847 extern "C" SANITIZER_WEAK_ATTRIBUTE
848 int __android_log_write(int prio, const char* tag, const char* msg);
849 
850 // ANDROID_LOG_INFO is 4, but can't be resolved at runtime.
851 #define SANITIZER_ANDROID_LOG_INFO 4
852 
853 // async_safe_write_log is a new public version of __libc_write_log that is
854 // used behind syslog. It is preferable to syslog as it will not do any dynamic
855 // memory allocation or formatting.
856 // If the function is not available, syslog is preferred for L+ (it was broken
857 // pre-L) as __android_log_write triggers a racey behavior with the strncpy
858 // interceptor. Fallback to __android_log_write pre-L.
WriteOneLineToSyslog(const char * s)859 void WriteOneLineToSyslog(const char *s) {
860   if (&async_safe_write_log) {
861     async_safe_write_log(SANITIZER_ANDROID_LOG_INFO, GetProcessName(), s);
862   } else if (AndroidGetApiLevel() > ANDROID_KITKAT) {
863     syslog(LOG_INFO, "%s", s);
864   } else {
865     CHECK(&__android_log_write);
866     __android_log_write(SANITIZER_ANDROID_LOG_INFO, nullptr, s);
867   }
868 }
869 
870 extern "C" SANITIZER_WEAK_ATTRIBUTE
871 void android_set_abort_message(const char *);
872 
SetAbortMessage(const char * str)873 void SetAbortMessage(const char *str) {
874   if (&android_set_abort_message)
875     android_set_abort_message(str);
876 }
877 #else
AndroidLogInit()878 void AndroidLogInit() {}
879 
ShouldLogAfterPrintf()880 static bool ShouldLogAfterPrintf() { return true; }
881 
WriteOneLineToSyslog(const char * s)882 void WriteOneLineToSyslog(const char *s) { syslog(LOG_INFO, "%s", s); }
883 
SetAbortMessage(const char * str)884 void SetAbortMessage(const char *str) {}
885 #endif  // SANITIZER_ANDROID
886 
LogMessageOnPrintf(const char * str)887 void LogMessageOnPrintf(const char *str) {
888   if (common_flags()->log_to_syslog && ShouldLogAfterPrintf())
889     WriteToSyslog(str);
890 }
891 
892 #endif  // SANITIZER_LINUX
893 
894 #if SANITIZER_GLIBC && !SANITIZER_GO
895 // glibc crashes when using clock_gettime from a preinit_array function as the
896 // vDSO function pointers haven't been initialized yet. __progname is
897 // initialized after the vDSO function pointers, so if it exists, is not null
898 // and is not empty, we can use clock_gettime.
899 extern "C" SANITIZER_WEAK_ATTRIBUTE char *__progname;
CanUseVDSO()900 inline bool CanUseVDSO() { return &__progname && __progname && *__progname; }
901 
902 // MonotonicNanoTime is a timing function that can leverage the vDSO by calling
903 // clock_gettime. real_clock_gettime only exists if clock_gettime is
904 // intercepted, so define it weakly and use it if available.
905 extern "C" SANITIZER_WEAK_ATTRIBUTE
906 int real_clock_gettime(u32 clk_id, void *tp);
MonotonicNanoTime()907 u64 MonotonicNanoTime() {
908   timespec ts;
909   if (CanUseVDSO()) {
910     if (&real_clock_gettime)
911       real_clock_gettime(CLOCK_MONOTONIC, &ts);
912     else
913       clock_gettime(CLOCK_MONOTONIC, &ts);
914   } else {
915     internal_clock_gettime(CLOCK_MONOTONIC, &ts);
916   }
917   return (u64)ts.tv_sec * (1000ULL * 1000 * 1000) + ts.tv_nsec;
918 }
919 #else
920 // Non-glibc & Go always use the regular function.
MonotonicNanoTime()921 u64 MonotonicNanoTime() {
922   timespec ts;
923   clock_gettime(CLOCK_MONOTONIC, &ts);
924   return (u64)ts.tv_sec * (1000ULL * 1000 * 1000) + ts.tv_nsec;
925 }
926 #endif  // SANITIZER_GLIBC && !SANITIZER_GO
927 
ReExec()928 void ReExec() {
929   const char *pathname = "/proc/self/exe";
930 
931 #if SANITIZER_NETBSD
932   static const int name[] = {
933       CTL_KERN,
934       KERN_PROC_ARGS,
935       -1,
936       KERN_PROC_PATHNAME,
937   };
938   char path[400];
939   uptr len;
940 
941   len = sizeof(path);
942   if (internal_sysctl(name, ARRAY_SIZE(name), path, &len, NULL, 0) != -1)
943     pathname = path;
944 #elif SANITIZER_SOLARIS
945   pathname = getexecname();
946   CHECK_NE(pathname, NULL);
947 #elif SANITIZER_USE_GETAUXVAL
948   // Calling execve with /proc/self/exe sets that as $EXEC_ORIGIN. Binaries that
949   // rely on that will fail to load shared libraries. Query AT_EXECFN instead.
950   pathname = reinterpret_cast<const char *>(getauxval(AT_EXECFN));
951 #endif
952 
953   uptr rv = internal_execve(pathname, GetArgv(), GetEnviron());
954   int rverrno;
955   CHECK_EQ(internal_iserror(rv, &rverrno), true);
956   Printf("execve failed, errno %d\n", rverrno);
957   Die();
958 }
959 
UnmapFromTo(uptr from,uptr to)960 void UnmapFromTo(uptr from, uptr to) {
961   if (to == from)
962     return;
963   CHECK(to >= from);
964   uptr res = internal_munmap(reinterpret_cast<void *>(from), to - from);
965   if (UNLIKELY(internal_iserror(res))) {
966     Report("ERROR: %s failed to unmap 0x%zx (%zd) bytes at address %p\n",
967            SanitizerToolName, to - from, to - from, (void *)from);
968     CHECK("unable to unmap" && 0);
969   }
970 }
971 
MapDynamicShadow(uptr shadow_size_bytes,uptr shadow_scale,uptr min_shadow_base_alignment,UNUSED uptr & high_mem_end)972 uptr MapDynamicShadow(uptr shadow_size_bytes, uptr shadow_scale,
973                       uptr min_shadow_base_alignment,
974                       UNUSED uptr &high_mem_end) {
975   const uptr granularity = GetMmapGranularity();
976   const uptr alignment =
977       Max<uptr>(granularity << shadow_scale, 1ULL << min_shadow_base_alignment);
978   const uptr left_padding =
979       Max<uptr>(granularity, 1ULL << min_shadow_base_alignment);
980 
981   const uptr shadow_size = RoundUpTo(shadow_size_bytes, granularity);
982   const uptr map_size = shadow_size + left_padding + alignment;
983 
984   const uptr map_start = (uptr)MmapNoAccess(map_size);
985   CHECK_NE(map_start, ~(uptr)0);
986 
987   const uptr shadow_start = RoundUpTo(map_start + left_padding, alignment);
988 
989   UnmapFromTo(map_start, shadow_start - left_padding);
990   UnmapFromTo(shadow_start + shadow_size, map_start + map_size);
991 
992   return shadow_start;
993 }
994 
MmapSharedNoReserve(uptr addr,uptr size)995 static uptr MmapSharedNoReserve(uptr addr, uptr size) {
996   return internal_mmap(
997       reinterpret_cast<void *>(addr), size, PROT_READ | PROT_WRITE,
998       MAP_FIXED | MAP_SHARED | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
999 }
1000 
MremapCreateAlias(uptr base_addr,uptr alias_addr,uptr alias_size)1001 static uptr MremapCreateAlias(uptr base_addr, uptr alias_addr,
1002                               uptr alias_size) {
1003 #if SANITIZER_LINUX
1004   return internal_mremap(reinterpret_cast<void *>(base_addr), 0, alias_size,
1005                          MREMAP_MAYMOVE | MREMAP_FIXED,
1006                          reinterpret_cast<void *>(alias_addr));
1007 #else
1008   CHECK(false && "mremap is not supported outside of Linux");
1009   return 0;
1010 #endif
1011 }
1012 
CreateAliases(uptr start_addr,uptr alias_size,uptr num_aliases)1013 static void CreateAliases(uptr start_addr, uptr alias_size, uptr num_aliases) {
1014   uptr total_size = alias_size * num_aliases;
1015   uptr mapped = MmapSharedNoReserve(start_addr, total_size);
1016   CHECK_EQ(mapped, start_addr);
1017 
1018   for (uptr i = 1; i < num_aliases; ++i) {
1019     uptr alias_addr = start_addr + i * alias_size;
1020     CHECK_EQ(MremapCreateAlias(start_addr, alias_addr, alias_size), alias_addr);
1021   }
1022 }
1023 
MapDynamicShadowAndAliases(uptr shadow_size,uptr alias_size,uptr num_aliases,uptr ring_buffer_size)1024 uptr MapDynamicShadowAndAliases(uptr shadow_size, uptr alias_size,
1025                                 uptr num_aliases, uptr ring_buffer_size) {
1026   CHECK_EQ(alias_size & (alias_size - 1), 0);
1027   CHECK_EQ(num_aliases & (num_aliases - 1), 0);
1028   CHECK_EQ(ring_buffer_size & (ring_buffer_size - 1), 0);
1029 
1030   const uptr granularity = GetMmapGranularity();
1031   shadow_size = RoundUpTo(shadow_size, granularity);
1032   CHECK_EQ(shadow_size & (shadow_size - 1), 0);
1033 
1034   const uptr alias_region_size = alias_size * num_aliases;
1035   const uptr alignment =
1036       2 * Max(Max(shadow_size, alias_region_size), ring_buffer_size);
1037   const uptr left_padding = ring_buffer_size;
1038 
1039   const uptr right_size = alignment;
1040   const uptr map_size = left_padding + 2 * alignment;
1041 
1042   const uptr map_start = reinterpret_cast<uptr>(MmapNoAccess(map_size));
1043   CHECK_NE(map_start, static_cast<uptr>(-1));
1044   const uptr right_start = RoundUpTo(map_start + left_padding, alignment);
1045 
1046   UnmapFromTo(map_start, right_start - left_padding);
1047   UnmapFromTo(right_start + right_size, map_start + map_size);
1048 
1049   CreateAliases(right_start + right_size / 2, alias_size, num_aliases);
1050 
1051   return right_start;
1052 }
1053 
InitializePlatformCommonFlags(CommonFlags * cf)1054 void InitializePlatformCommonFlags(CommonFlags *cf) {
1055 #if SANITIZER_ANDROID
1056   if (&__libc_get_static_tls_bounds == nullptr)
1057     cf->detect_leaks = false;
1058 #endif
1059 }
1060 
1061 } // namespace __sanitizer
1062 
1063 #endif
1064