Path: blob/main/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_libcdep.cpp
35233 views
//===-- sanitizer_common_libcdep.cpp --------------------------------------===//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//===----------------------------------------------------------------------===//7//8// This file is shared between AddressSanitizer and ThreadSanitizer9// run-time libraries.10//===----------------------------------------------------------------------===//1112#include "sanitizer_allocator.h"13#include "sanitizer_allocator_interface.h"14#include "sanitizer_common.h"15#include "sanitizer_flags.h"16#include "sanitizer_interface_internal.h"17#include "sanitizer_procmaps.h"18#include "sanitizer_stackdepot.h"1920namespace __sanitizer {2122#if (SANITIZER_LINUX || SANITIZER_NETBSD) && !SANITIZER_GO23// Weak default implementation for when sanitizer_stackdepot is not linked in.24SANITIZER_WEAK_ATTRIBUTE StackDepotStats StackDepotGetStats() { return {}; }2526void *BackgroundThread(void *arg) {27VPrintf(1, "%s: Started BackgroundThread\n", SanitizerToolName);28const uptr hard_rss_limit_mb = common_flags()->hard_rss_limit_mb;29const uptr soft_rss_limit_mb = common_flags()->soft_rss_limit_mb;30const bool heap_profile = common_flags()->heap_profile;31uptr prev_reported_rss = 0;32uptr prev_reported_stack_depot_size = 0;33bool reached_soft_rss_limit = false;34uptr rss_during_last_reported_profile = 0;35while (true) {36SleepForMillis(100);37const uptr current_rss_mb = GetRSS() >> 20;38if (Verbosity()) {39// If RSS has grown 10% since last time, print some information.40if (prev_reported_rss * 11 / 10 < current_rss_mb) {41Printf("%s: RSS: %zdMb\n", SanitizerToolName, current_rss_mb);42prev_reported_rss = current_rss_mb;43}44// If stack depot has grown 10% since last time, print it too.45StackDepotStats stack_depot_stats = StackDepotGetStats();46if (prev_reported_stack_depot_size * 11 / 10 <47stack_depot_stats.allocated) {48Printf("%s: StackDepot: %zd ids; %zdM allocated\n", SanitizerToolName,49stack_depot_stats.n_uniq_ids, stack_depot_stats.allocated >> 20);50prev_reported_stack_depot_size = stack_depot_stats.allocated;51}52}53// Check RSS against the limit.54if (hard_rss_limit_mb && hard_rss_limit_mb < current_rss_mb) {55Report("%s: hard rss limit exhausted (%zdMb vs %zdMb)\n",56SanitizerToolName, hard_rss_limit_mb, current_rss_mb);57DumpProcessMap();58Die();59}60if (soft_rss_limit_mb) {61if (soft_rss_limit_mb < current_rss_mb && !reached_soft_rss_limit) {62reached_soft_rss_limit = true;63Report("%s: soft rss limit exhausted (%zdMb vs %zdMb)\n",64SanitizerToolName, soft_rss_limit_mb, current_rss_mb);65SetRssLimitExceeded(true);66} else if (soft_rss_limit_mb >= current_rss_mb &&67reached_soft_rss_limit) {68reached_soft_rss_limit = false;69Report("%s: soft rss limit unexhausted (%zdMb vs %zdMb)\n",70SanitizerToolName, soft_rss_limit_mb, current_rss_mb);71SetRssLimitExceeded(false);72}73}74if (heap_profile &&75current_rss_mb > rss_during_last_reported_profile * 1.1) {76Printf("\n\nHEAP PROFILE at RSS %zdMb\n", current_rss_mb);77__sanitizer_print_memory_profile(90, 20);78rss_during_last_reported_profile = current_rss_mb;79}80}81}8283void MaybeStartBackgroudThread() {84// Need to implement/test on other platforms.85// Start the background thread if one of the rss limits is given.86if (!common_flags()->hard_rss_limit_mb &&87!common_flags()->soft_rss_limit_mb &&88!common_flags()->heap_profile) return;89if (!&internal_pthread_create) {90VPrintf(1, "%s: internal_pthread_create undefined\n", SanitizerToolName);91return; // Can't spawn the thread anyway.92}9394static bool started = false;95if (!started) {96started = true;97internal_start_thread(BackgroundThread, nullptr);98}99}100101# if !SANITIZER_START_BACKGROUND_THREAD_IN_ASAN_INTERNAL102# ifdef __clang__103# pragma clang diagnostic push104// We avoid global-constructors to be sure that globals are ready when105// sanitizers need them. This can happend before global constructors executed.106// Here we don't mind if thread is started on later stages.107# pragma clang diagnostic ignored "-Wglobal-constructors"108# endif109static struct BackgroudThreadStarted {110BackgroudThreadStarted() { MaybeStartBackgroudThread(); }111} background_thread_strarter UNUSED;112# ifdef __clang__113# pragma clang diagnostic pop114# endif115# endif116#else117void MaybeStartBackgroudThread() {}118#endif119120void WriteToSyslog(const char *msg) {121if (!msg)122return;123InternalScopedString msg_copy;124msg_copy.Append(msg);125const char *p = msg_copy.data();126127// Print one line at a time.128// syslog, at least on Android, has an implicit message length limit.129while (char* q = internal_strchr(p, '\n')) {130*q = '\0';131WriteOneLineToSyslog(p);132p = q + 1;133}134// Print remaining characters, if there are any.135// Note that this will add an extra newline at the end.136// FIXME: buffer extra output. This would need a thread-local buffer, which137// on Android requires plugging into the tools (ex. ASan's) Thread class.138if (*p)139WriteOneLineToSyslog(p);140}141142static void (*sandboxing_callback)();143void SetSandboxingCallback(void (*f)()) {144sandboxing_callback = f;145}146147uptr ReservedAddressRange::InitAligned(uptr size, uptr align,148const char *name) {149CHECK(IsPowerOfTwo(align));150if (align <= GetPageSizeCached())151return Init(size, name);152uptr start = Init(size + align, name);153start += align - (start & (align - 1));154return start;155}156157#if !SANITIZER_FUCHSIA158159// Reserve memory range [beg, end].160// We need to use inclusive range because end+1 may not be representable.161void ReserveShadowMemoryRange(uptr beg, uptr end, const char *name,162bool madvise_shadow) {163CHECK_EQ((beg % GetMmapGranularity()), 0);164CHECK_EQ(((end + 1) % GetMmapGranularity()), 0);165uptr size = end - beg + 1;166DecreaseTotalMmap(size); // Don't count the shadow against mmap_limit_mb.167if (madvise_shadow ? !MmapFixedSuperNoReserve(beg, size, name)168: !MmapFixedNoReserve(beg, size, name)) {169Report(170"ReserveShadowMemoryRange failed while trying to map 0x%zx bytes. "171"Perhaps you're using ulimit -v or ulimit -d\n",172size);173Abort();174}175if (madvise_shadow && common_flags()->use_madv_dontdump)176DontDumpShadowMemory(beg, size);177}178179void ProtectGap(uptr addr, uptr size, uptr zero_base_shadow_start,180uptr zero_base_max_shadow_start) {181if (!size)182return;183void *res = MmapFixedNoAccess(addr, size, "shadow gap");184if (addr == (uptr)res)185return;186// A few pages at the start of the address space can not be protected.187// But we really want to protect as much as possible, to prevent this memory188// being returned as a result of a non-FIXED mmap().189if (addr == zero_base_shadow_start) {190uptr step = GetMmapGranularity();191while (size > step && addr < zero_base_max_shadow_start) {192addr += step;193size -= step;194void *res = MmapFixedNoAccess(addr, size, "shadow gap");195if (addr == (uptr)res)196return;197}198}199200Report(201"ERROR: Failed to protect the shadow gap. "202"%s cannot proceed correctly. ABORTING.\n",203SanitizerToolName);204DumpProcessMap();205Die();206}207208#endif // !SANITIZER_FUCHSIA209210#if !SANITIZER_WINDOWS && !SANITIZER_GO211// Weak default implementation for when sanitizer_stackdepot is not linked in.212SANITIZER_WEAK_ATTRIBUTE void StackDepotStopBackgroundThread() {}213static void StopStackDepotBackgroundThread() {214StackDepotStopBackgroundThread();215}216#else217// SANITIZER_WEAK_ATTRIBUTE is unsupported.218static void StopStackDepotBackgroundThread() {}219#endif220221} // namespace __sanitizer222223SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_sandbox_on_notify,224__sanitizer_sandbox_arguments *args) {225__sanitizer::StopStackDepotBackgroundThread();226__sanitizer::PlatformPrepareForSandboxing(args);227if (__sanitizer::sandboxing_callback)228__sanitizer::sandboxing_callback();229}230231232