Path: blob/main/contrib/llvm-project/compiler-rt/lib/scudo/standalone/linux.cpp
35291 views
//===-- linux.cpp -----------------------------------------------*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "platform.h"910#if SCUDO_LINUX1112#include "common.h"13#include "internal_defs.h"14#include "linux.h"15#include "mutex.h"16#include "report_linux.h"17#include "string_utils.h"1819#include <errno.h>20#include <fcntl.h>21#include <linux/futex.h>22#include <sched.h>23#include <stdio.h>24#include <stdlib.h>25#include <string.h>26#include <sys/mman.h>27#include <sys/stat.h>28#include <sys/syscall.h>29#include <sys/time.h>30#include <time.h>31#include <unistd.h>3233#if SCUDO_ANDROID34#include <sys/prctl.h>35// Definitions of prctl arguments to set a vma name in Android kernels.36#define ANDROID_PR_SET_VMA 0x53564d4137#define ANDROID_PR_SET_VMA_ANON_NAME 038#endif3940namespace scudo {4142uptr getPageSize() { return static_cast<uptr>(sysconf(_SC_PAGESIZE)); }4344void NORETURN die() { abort(); }4546// TODO: Will be deprecated. Use the interfaces in MemMapLinux instead.47void *map(void *Addr, uptr Size, UNUSED const char *Name, uptr Flags,48UNUSED MapPlatformData *Data) {49int MmapFlags = MAP_PRIVATE | MAP_ANONYMOUS;50int MmapProt;51if (Flags & MAP_NOACCESS) {52MmapFlags |= MAP_NORESERVE;53MmapProt = PROT_NONE;54} else {55MmapProt = PROT_READ | PROT_WRITE;56}57#if defined(__aarch64__)58#ifndef PROT_MTE59#define PROT_MTE 0x2060#endif61if (Flags & MAP_MEMTAG)62MmapProt |= PROT_MTE;63#endif64if (Addr)65MmapFlags |= MAP_FIXED;66void *P = mmap(Addr, Size, MmapProt, MmapFlags, -1, 0);67if (P == MAP_FAILED) {68if (!(Flags & MAP_ALLOWNOMEM) || errno != ENOMEM)69reportMapError(errno == ENOMEM ? Size : 0);70return nullptr;71}72#if SCUDO_ANDROID73if (Name)74prctl(ANDROID_PR_SET_VMA, ANDROID_PR_SET_VMA_ANON_NAME, P, Size, Name);75#endif76return P;77}7879// TODO: Will be deprecated. Use the interfaces in MemMapLinux instead.80void unmap(void *Addr, uptr Size, UNUSED uptr Flags,81UNUSED MapPlatformData *Data) {82if (munmap(Addr, Size) != 0)83reportUnmapError(reinterpret_cast<uptr>(Addr), Size);84}8586// TODO: Will be deprecated. Use the interfaces in MemMapLinux instead.87void setMemoryPermission(uptr Addr, uptr Size, uptr Flags,88UNUSED MapPlatformData *Data) {89int Prot = (Flags & MAP_NOACCESS) ? PROT_NONE : (PROT_READ | PROT_WRITE);90if (mprotect(reinterpret_cast<void *>(Addr), Size, Prot) != 0)91reportProtectError(Addr, Size, Prot);92}9394// TODO: Will be deprecated. Use the interfaces in MemMapLinux instead.95void releasePagesToOS(uptr BaseAddress, uptr Offset, uptr Size,96UNUSED MapPlatformData *Data) {97void *Addr = reinterpret_cast<void *>(BaseAddress + Offset);9899while (madvise(Addr, Size, MADV_DONTNEED) == -1 && errno == EAGAIN) {100}101}102103// Calling getenv should be fine (c)(tm) at any time.104const char *getEnv(const char *Name) { return getenv(Name); }105106namespace {107enum State : u32 { Unlocked = 0, Locked = 1, Sleeping = 2 };108}109110bool HybridMutex::tryLock() {111return atomic_compare_exchange_strong(&M, Unlocked, Locked,112memory_order_acquire) == Unlocked;113}114115// The following is based on https://akkadia.org/drepper/futex.pdf.116void HybridMutex::lockSlow() {117u32 V = atomic_compare_exchange_strong(&M, Unlocked, Locked,118memory_order_acquire);119if (V == Unlocked)120return;121if (V != Sleeping)122V = atomic_exchange(&M, Sleeping, memory_order_acquire);123while (V != Unlocked) {124syscall(SYS_futex, reinterpret_cast<uptr>(&M), FUTEX_WAIT_PRIVATE, Sleeping,125nullptr, nullptr, 0);126V = atomic_exchange(&M, Sleeping, memory_order_acquire);127}128}129130void HybridMutex::unlock() {131if (atomic_fetch_sub(&M, 1U, memory_order_release) != Locked) {132atomic_store(&M, Unlocked, memory_order_release);133syscall(SYS_futex, reinterpret_cast<uptr>(&M), FUTEX_WAKE_PRIVATE, 1,134nullptr, nullptr, 0);135}136}137138void HybridMutex::assertHeldImpl() {139CHECK(atomic_load(&M, memory_order_acquire) != Unlocked);140}141142u64 getMonotonicTime() {143timespec TS;144clock_gettime(CLOCK_MONOTONIC, &TS);145return static_cast<u64>(TS.tv_sec) * (1000ULL * 1000 * 1000) +146static_cast<u64>(TS.tv_nsec);147}148149u64 getMonotonicTimeFast() {150#if defined(CLOCK_MONOTONIC_COARSE)151timespec TS;152clock_gettime(CLOCK_MONOTONIC_COARSE, &TS);153return static_cast<u64>(TS.tv_sec) * (1000ULL * 1000 * 1000) +154static_cast<u64>(TS.tv_nsec);155#else156return getMonotonicTime();157#endif158}159160u32 getNumberOfCPUs() {161cpu_set_t CPUs;162// sched_getaffinity can fail for a variety of legitimate reasons (lack of163// CAP_SYS_NICE, syscall filtering, etc), in which case we shall return 0.164if (sched_getaffinity(0, sizeof(cpu_set_t), &CPUs) != 0)165return 0;166return static_cast<u32>(CPU_COUNT(&CPUs));167}168169u32 getThreadID() {170#if SCUDO_ANDROID171return static_cast<u32>(gettid());172#else173return static_cast<u32>(syscall(SYS_gettid));174#endif175}176177// Blocking is possibly unused if the getrandom block is not compiled in.178bool getRandom(void *Buffer, uptr Length, UNUSED bool Blocking) {179if (!Buffer || !Length || Length > MaxRandomLength)180return false;181ssize_t ReadBytes;182#if defined(SYS_getrandom)183#if !defined(GRND_NONBLOCK)184#define GRND_NONBLOCK 1185#endif186// Up to 256 bytes, getrandom will not be interrupted.187ReadBytes =188syscall(SYS_getrandom, Buffer, Length, Blocking ? 0 : GRND_NONBLOCK);189if (ReadBytes == static_cast<ssize_t>(Length))190return true;191#endif // defined(SYS_getrandom)192// Up to 256 bytes, a read off /dev/urandom will not be interrupted.193// Blocking is moot here, O_NONBLOCK has no effect when opening /dev/urandom.194const int FileDesc = open("/dev/urandom", O_RDONLY);195if (FileDesc == -1)196return false;197ReadBytes = read(FileDesc, Buffer, Length);198close(FileDesc);199return (ReadBytes == static_cast<ssize_t>(Length));200}201202// Allocation free syslog-like API.203extern "C" WEAK int async_safe_write_log(int pri, const char *tag,204const char *msg);205206void outputRaw(const char *Buffer) {207if (&async_safe_write_log) {208constexpr s32 AndroidLogInfo = 4;209constexpr uptr MaxLength = 1024U;210char LocalBuffer[MaxLength];211while (strlen(Buffer) > MaxLength) {212uptr P;213for (P = MaxLength - 1; P > 0; P--) {214if (Buffer[P] == '\n') {215memcpy(LocalBuffer, Buffer, P);216LocalBuffer[P] = '\0';217async_safe_write_log(AndroidLogInfo, "scudo", LocalBuffer);218Buffer = &Buffer[P + 1];219break;220}221}222// If no newline was found, just log the buffer.223if (P == 0)224break;225}226async_safe_write_log(AndroidLogInfo, "scudo", Buffer);227} else {228(void)write(2, Buffer, strlen(Buffer));229}230}231232extern "C" WEAK void android_set_abort_message(const char *);233234void setAbortMessage(const char *Message) {235if (&android_set_abort_message)236android_set_abort_message(Message);237}238239} // namespace scudo240241#endif // SCUDO_LINUX242243244