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