llvm/compiler-rt/lib/sanitizer_common/sanitizer_linux_libcdep.cpp

//===-- sanitizer_linux_libcdep.cpp ---------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer
// run-time libraries and implements linux-specific functions from
// sanitizer_libc.h.
//===----------------------------------------------------------------------===//

#include "sanitizer_platform.h"

#if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD || \
    SANITIZER_SOLARIS

#  include "sanitizer_allocator_internal.h"
#  include "sanitizer_atomic.h"
#  include "sanitizer_common.h"
#  include "sanitizer_file.h"
#  include "sanitizer_flags.h"
#  include "sanitizer_getauxval.h"
#  include "sanitizer_glibc_version.h"
#  include "sanitizer_linux.h"
#  include "sanitizer_placement_new.h"
#  include "sanitizer_procmaps.h"
#  include "sanitizer_solaris.h"

#  if SANITIZER_NETBSD
#define _RTLD_SOURCE
#  endif

#  include <dlfcn.h>  // for dlsym()
#  include <link.h>
#  include <pthread.h>
#  include <signal.h>
#  include <sys/mman.h>
#  include <sys/resource.h>
#  include <syslog.h>

#  if !defined(ElfW)
#define ElfW
#  endif

#  if SANITIZER_FREEBSD
#    include <pthread_np.h>
#    include <sys/auxv.h>
#    include <sys/sysctl.h>
#define pthread_getattr_np
// The MAP_NORESERVE define has been removed in FreeBSD 11.x, and even before
// that, it was never implemented. So just define it to zero.
#    undef MAP_NORESERVE
#define MAP_NORESERVE
extern const Elf_Auxinfo *__elf_aux_vector;
extern "C" int __sys_sigaction(int signum, const struct sigaction *act,
                               struct sigaction *oldact);
#  endif

#  if SANITIZER_NETBSD
#    include <lwp.h>
#    include <sys/sysctl.h>
#    include <sys/tls.h>
#  endif

#  if SANITIZER_SOLARIS
#    include <stddef.h>
#    include <stdlib.h>
#    include <thread.h>
#  endif

#  if SANITIZER_ANDROID
#    include <android/api-level.h>
#    if !defined(CPU_COUNT) && !defined(__aarch64__)
#      include <dirent.h>
#      include <fcntl.h>
struct __sanitizer::linux_dirent {
  long d_ino;
  off_t d_off;
  unsigned short d_reclen;
  char d_name[];
};
#    endif
#  endif

#  if !SANITIZER_ANDROID
#    include <elf.h>
#    include <unistd.h>
#  endif

namespace __sanitizer {

SANITIZER_WEAK_ATTRIBUTE int real_sigaction(int signum, const void *act,
                                            void *oldact);

int internal_sigaction(int signum, const void *act, void *oldact) {}

void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
                                uptr *stack_bottom) {}

#  if !SANITIZER_GO
bool SetEnv(const char *name, const char *value) {}
#  endif

__attribute__((unused)) static bool GetLibcVersion(int *major, int *minor,
                                                   int *patch) {}

// True if we can use dlpi_tls_data. glibc before 2.25 may leave NULL (BZ
// #19826) so dlpi_tls_data cannot be used.
//
// musl before 1.2.3 and FreeBSD as of 12.2 incorrectly set dlpi_tls_data to
// the TLS initialization image
// https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=254774
__attribute__((unused)) static int g_use_dlpi_tls_data;

#  if SANITIZER_GLIBC && !SANITIZER_GO
__attribute__((unused)) static size_t g_tls_size;
void InitTlsSize() {}
#  else
void InitTlsSize() {}
#  endif  // SANITIZER_GLIBC && !SANITIZER_GO

// On glibc x86_64, ThreadDescriptorSize() needs to be precise due to the usage
// of g_tls_size. On other targets, ThreadDescriptorSize() is only used by lsan
// to get the pointer to thread-specific data keys in the thread control block.
#  if (SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_SOLARIS) && \
      !SANITIZER_ANDROID && !SANITIZER_GO
// sizeof(struct pthread) from glibc.
static atomic_uintptr_t thread_descriptor_size;

static uptr ThreadDescriptorSizeFallback() {}

uptr ThreadDescriptorSize() {}

#    if defined(__mips__) || defined(__powerpc64__) || SANITIZER_RISCV64 || \
        SANITIZER_LOONGARCH64
// TlsPreTcbSize includes size of struct pthread_descr and size of tcb
// head structure. It lies before the static tls blocks.
static uptr TlsPreTcbSize() {
#      if defined(__mips__)
  const uptr kTcbHead = 16;  // sizeof (tcbhead_t)
#      elif defined(__powerpc64__)
  const uptr kTcbHead = 88;  // sizeof (tcbhead_t)
#      elif SANITIZER_RISCV64
  const uptr kTcbHead = 16;  // sizeof (tcbhead_t)
#      elif SANITIZER_LOONGARCH64
  const uptr kTcbHead = 16;  // sizeof (tcbhead_t)
#      endif
  const uptr kTlsAlign = 16;
  const uptr kTlsPreTcbSize =
      RoundUpTo(ThreadDescriptorSize() + kTcbHead, kTlsAlign);
  return kTlsPreTcbSize;
}
#    endif

namespace {
struct TlsBlock {};
}  // namespace

#    ifdef __s390__
extern "C" uptr __tls_get_offset(void *arg);

static uptr TlsGetOffset(uptr ti_module, uptr ti_offset) {
  // The __tls_get_offset ABI requires %r12 to point to GOT and %r2 to be an
  // offset of a struct tls_index inside GOT. We don't possess either of the
  // two, so violate the letter of the "ELF Handling For Thread-Local
  // Storage" document and assume that the implementation just dereferences
  // %r2 + %r12.
  uptr tls_index[2] = {ti_module, ti_offset};
  register uptr r2 asm("2") = 0;
  register void *r12 asm("12") = tls_index;
  asm("basr %%r14, %[__tls_get_offset]"
      : "+r"(r2)
      : [__tls_get_offset] "r"(__tls_get_offset), "r"(r12)
      : "memory", "cc", "0", "1", "3", "4", "5", "14");
  return r2;
}
#    else
extern "C" void *__tls_get_addr(size_t *);
#    endif

static size_t main_tls_modid;

static int CollectStaticTlsBlocks(struct dl_phdr_info *info, size_t size,
                                  void *data) {}

__attribute__((unused)) static void GetStaticTlsBoundary(uptr *addr, uptr *size,
                                                         uptr *align) {}
#  endif  // (x86_64 || i386 || mips || ...) && (SANITIZER_FREEBSD ||
          // SANITIZER_LINUX) && !SANITIZER_ANDROID && !SANITIZER_GO

#  if SANITIZER_NETBSD
static struct tls_tcb *ThreadSelfTlsTcb() {
  struct tls_tcb *tcb = nullptr;
#    ifdef __HAVE___LWP_GETTCB_FAST
  tcb = (struct tls_tcb *)__lwp_gettcb_fast();
#    elif defined(__HAVE___LWP_GETPRIVATE_FAST)
  tcb = (struct tls_tcb *)__lwp_getprivate_fast();
#    endif
  return tcb;
}

uptr ThreadSelf() { return (uptr)ThreadSelfTlsTcb()->tcb_pthread; }

int GetSizeFromHdr(struct dl_phdr_info *info, size_t size, void *data) {
  const Elf_Phdr *hdr = info->dlpi_phdr;
  const Elf_Phdr *last_hdr = hdr + info->dlpi_phnum;

  for (; hdr != last_hdr; ++hdr) {
    if (hdr->p_type == PT_TLS && info->dlpi_tls_modid == 1) {
      *(uptr *)data = hdr->p_memsz;
      break;
    }
  }
  return 0;
}
#  endif  // SANITIZER_NETBSD

#  if SANITIZER_ANDROID
// Bionic provides this API since S.
extern "C" SANITIZER_WEAK_ATTRIBUTE void __libc_get_static_tls_bounds(void **,
                                                                      void **);
#  endif

#  if !SANITIZER_GO
static void GetTls(uptr *addr, uptr *size) {}
#  endif

#  if !SANITIZER_GO
uptr GetTlsSize() {}
#  endif

void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
                          uptr *tls_addr, uptr *tls_size) {}

#  if !SANITIZER_FREEBSD
Elf_Phdr;
#  endif

struct DlIteratePhdrData {};

static int AddModuleSegments(const char *module_name, dl_phdr_info *info,
                             InternalMmapVectorNoCtor<LoadedModule> *modules) {}

static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {}

#  if SANITIZER_ANDROID && __ANDROID_API__ < 21
extern "C" __attribute__((weak)) int dl_iterate_phdr(
    int (*)(struct dl_phdr_info *, size_t, void *), void *);
#  endif

static bool requiresProcmaps() {}

static void procmapsInit(InternalMmapVectorNoCtor<LoadedModule> *modules) {}

void ListOfModules::init() {}

// When a custom loader is used, dl_iterate_phdr may not contain the full
// list of modules. Allow callers to fall back to using procmaps.
void ListOfModules::fallbackInit() {}

// getrusage does not give us the current RSS, only the max RSS.
// Still, this is better than nothing if /proc/self/statm is not available
// for some reason, e.g. due to a sandbox.
static uptr GetRSSFromGetrusage() {}

uptr GetRSS() {}

// sysconf(_SC_NPROCESSORS_{CONF,ONLN}) cannot be used on most platforms as
// they allocate memory.
u32 GetNumberOfCPUs() {}

#  if SANITIZER_LINUX

#    if SANITIZER_ANDROID
static atomic_uint8_t android_log_initialized;

void AndroidLogInit() {
  openlog(GetProcessName(), 0, LOG_USER);
  atomic_store(&android_log_initialized, 1, memory_order_release);
}

static bool ShouldLogAfterPrintf() {
  return atomic_load(&android_log_initialized, memory_order_acquire);
}

extern "C" SANITIZER_WEAK_ATTRIBUTE int async_safe_write_log(int pri,
                                                             const char *tag,
                                                             const char *msg);
extern "C" SANITIZER_WEAK_ATTRIBUTE int __android_log_write(int prio,
                                                            const char *tag,
                                                            const char *msg);

// ANDROID_LOG_INFO is 4, but can't be resolved at runtime.
#define SANITIZER_ANDROID_LOG_INFO

// async_safe_write_log is a new public version of __libc_write_log that is
// used behind syslog. It is preferable to syslog as it will not do any dynamic
// memory allocation or formatting.
// If the function is not available, syslog is preferred for L+ (it was broken
// pre-L) as __android_log_write triggers a racey behavior with the strncpy
// interceptor. Fallback to __android_log_write pre-L.
void WriteOneLineToSyslog(const char *s) {
  if (&async_safe_write_log) {
    async_safe_write_log(SANITIZER_ANDROID_LOG_INFO, GetProcessName(), s);
  } else if (AndroidGetApiLevel() > ANDROID_KITKAT) {
    syslog(LOG_INFO, "%s", s);
  } else {
    CHECK(&__android_log_write);
    __android_log_write(SANITIZER_ANDROID_LOG_INFO, nullptr, s);
  }
}

extern "C" SANITIZER_WEAK_ATTRIBUTE void android_set_abort_message(
    const char *);

void SetAbortMessage(const char *str) {
  if (&android_set_abort_message)
    android_set_abort_message(str);
}
#    else
void AndroidLogInit() {}

static bool ShouldLogAfterPrintf() {}

void WriteOneLineToSyslog(const char *s) {}

void SetAbortMessage(const char *str) {}
#    endif  // SANITIZER_ANDROID

void LogMessageOnPrintf(const char *str) {}

#  endif  // SANITIZER_LINUX

#  if SANITIZER_GLIBC && !SANITIZER_GO
// glibc crashes when using clock_gettime from a preinit_array function as the
// vDSO function pointers haven't been initialized yet. __progname is
// initialized after the vDSO function pointers, so if it exists, is not null
// and is not empty, we can use clock_gettime.
extern "C" SANITIZER_WEAK_ATTRIBUTE char *__progname;
inline bool CanUseVDSO() {}

// MonotonicNanoTime is a timing function that can leverage the vDSO by calling
// clock_gettime. real_clock_gettime only exists if clock_gettime is
// intercepted, so define it weakly and use it if available.
extern "C" SANITIZER_WEAK_ATTRIBUTE int real_clock_gettime(u32 clk_id,
                                                           void *tp);
u64 MonotonicNanoTime() {}
#  else
// Non-glibc & Go always use the regular function.
u64 MonotonicNanoTime() {
  timespec ts;
  clock_gettime(CLOCK_MONOTONIC, &ts);
  return (u64)ts.tv_sec * (1000ULL * 1000 * 1000) + ts.tv_nsec;
}
#  endif  // SANITIZER_GLIBC && !SANITIZER_GO

void ReExec() {}

void UnmapFromTo(uptr from, uptr to) {}

uptr MapDynamicShadow(uptr shadow_size_bytes, uptr shadow_scale,
                      uptr min_shadow_base_alignment, UNUSED uptr &high_mem_end,
                      uptr granularity) {}

static uptr MmapSharedNoReserve(uptr addr, uptr size) {}

static uptr MremapCreateAlias(uptr base_addr, uptr alias_addr,
                              uptr alias_size) {}

static void CreateAliases(uptr start_addr, uptr alias_size, uptr num_aliases) {}

uptr MapDynamicShadowAndAliases(uptr shadow_size, uptr alias_size,
                                uptr num_aliases, uptr ring_buffer_size) {}

void InitializePlatformCommonFlags(CommonFlags *cf) {}

}  // namespace __sanitizer

#endif