Path: blob/main/contrib/llvm-project/compiler-rt/lib/lsan/lsan_common.h
35233 views
//=-- lsan_common.h -------------------------------------------------------===//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 a part of LeakSanitizer.9// Private LSan header.10//11//===----------------------------------------------------------------------===//1213#ifndef LSAN_COMMON_H14#define LSAN_COMMON_H1516#include "sanitizer_common/sanitizer_allocator.h"17#include "sanitizer_common/sanitizer_common.h"18#include "sanitizer_common/sanitizer_internal_defs.h"19#include "sanitizer_common/sanitizer_platform.h"20#include "sanitizer_common/sanitizer_range.h"21#include "sanitizer_common/sanitizer_stackdepot.h"22#include "sanitizer_common/sanitizer_stoptheworld.h"23#include "sanitizer_common/sanitizer_symbolizer.h"24#include "sanitizer_common/sanitizer_thread_registry.h"2526// LeakSanitizer relies on some Glibc's internals (e.g. TLS machinery) on Linux.27// Also, LSan doesn't like 32 bit architectures28// because of "small" (4 bytes) pointer size that leads to high false negative29// ratio on large leaks. But we still want to have it for some 32 bit arches30// (e.g. x86), see https://github.com/google/sanitizers/issues/403.31// To enable LeakSanitizer on a new architecture, one needs to implement the32// internal_clone function as well as (probably) adjust the TLS machinery for33// the new architecture inside the sanitizer library.34// Exclude leak-detection on arm32 for Android because `__aeabi_read_tp`35// is missing. This caused a link error.36#if SANITIZER_ANDROID && (__ANDROID_API__ < 28 || defined(__arm__))37# define CAN_SANITIZE_LEAKS 038#elif (SANITIZER_LINUX || SANITIZER_APPLE) && (SANITIZER_WORDSIZE == 64) && \39(defined(__x86_64__) || defined(__mips64) || defined(__aarch64__) || \40defined(__powerpc64__) || defined(__s390x__))41# define CAN_SANITIZE_LEAKS 142#elif defined(__i386__) && (SANITIZER_LINUX || SANITIZER_APPLE)43# define CAN_SANITIZE_LEAKS 144#elif defined(__arm__) && SANITIZER_LINUX45# define CAN_SANITIZE_LEAKS 146#elif SANITIZER_LOONGARCH64 && SANITIZER_LINUX47# define CAN_SANITIZE_LEAKS 148#elif SANITIZER_RISCV64 && SANITIZER_LINUX49# define CAN_SANITIZE_LEAKS 150#elif SANITIZER_NETBSD || SANITIZER_FUCHSIA51# define CAN_SANITIZE_LEAKS 152#else53# define CAN_SANITIZE_LEAKS 054#endif5556namespace __sanitizer {57class FlagParser;58class ThreadRegistry;59class ThreadContextBase;60struct DTLS;61}6263// This section defines function and class prototypes which must be implemented64// by the parent tool linking in LSan. There are implementations provided by the65// LSan library which will be linked in when LSan is used as a standalone tool.66namespace __lsan {6768// Chunk tags.69enum ChunkTag {70kDirectlyLeaked = 0, // default71kIndirectlyLeaked = 1,72kReachable = 2,73kIgnored = 374};7576enum IgnoreObjectResult {77kIgnoreObjectSuccess,78kIgnoreObjectAlreadyIgnored,79kIgnoreObjectInvalid80};8182//// --------------------------------------------------------------------------83//// Poisoning prototypes.84//// --------------------------------------------------------------------------8586// Returns true if [addr, addr + sizeof(void *)) is poisoned.87bool WordIsPoisoned(uptr addr);8889//// --------------------------------------------------------------------------90//// Thread prototypes.91//// --------------------------------------------------------------------------9293// Wrappers for ThreadRegistry access.94void LockThreads() SANITIZER_NO_THREAD_SAFETY_ANALYSIS;95void UnlockThreads() SANITIZER_NO_THREAD_SAFETY_ANALYSIS;96// If called from the main thread, updates the main thread's TID in the thread97// registry. We need this to handle processes that fork() without a subsequent98// exec(), which invalidates the recorded TID. To update it, we must call99// gettid() from the main thread. Our solution is to call this function before100// leak checking and also before every call to pthread_create() (to handle cases101// where leak checking is initiated from a non-main thread).102void EnsureMainThreadIDIsCorrect();103104bool GetThreadRangesLocked(tid_t os_id, uptr *stack_begin, uptr *stack_end,105uptr *tls_begin, uptr *tls_end, uptr *cache_begin,106uptr *cache_end, DTLS **dtls);107void GetAllThreadAllocatorCachesLocked(InternalMmapVector<uptr> *caches);108void GetThreadExtraStackRangesLocked(InternalMmapVector<Range> *ranges);109void GetThreadExtraStackRangesLocked(tid_t os_id,110InternalMmapVector<Range> *ranges);111void GetAdditionalThreadContextPtrsLocked(InternalMmapVector<uptr> *ptrs);112void GetRunningThreadsLocked(InternalMmapVector<tid_t> *threads);113114//// --------------------------------------------------------------------------115//// Allocator prototypes.116//// --------------------------------------------------------------------------117118// Wrappers for allocator's ForceLock()/ForceUnlock().119void LockAllocator();120void UnlockAllocator();121122// Lock/unlock global mutext.123void LockGlobal();124void UnlockGlobal();125126// Returns the address range occupied by the global allocator object.127void GetAllocatorGlobalRange(uptr *begin, uptr *end);128// If p points into a chunk that has been allocated to the user, returns its129// user-visible address. Otherwise, returns 0.130uptr PointsIntoChunk(void *p);131// Returns address of user-visible chunk contained in this allocator chunk.132uptr GetUserBegin(uptr chunk);133// Returns user-visible address for chunk. If memory tagging is used this134// function will return the tagged address.135uptr GetUserAddr(uptr chunk);136137// Wrapper for chunk metadata operations.138class LsanMetadata {139public:140// Constructor accepts address of user-visible chunk.141explicit LsanMetadata(uptr chunk);142bool allocated() const;143ChunkTag tag() const;144void set_tag(ChunkTag value);145uptr requested_size() const;146u32 stack_trace_id() const;147148private:149void *metadata_;150};151152// Iterate over all existing chunks. Allocator must be locked.153void ForEachChunk(ForEachChunkCallback callback, void *arg);154155// Helper for __lsan_ignore_object().156IgnoreObjectResult IgnoreObject(const void *p);157158// The rest of the LSan interface which is implemented by library.159160struct ScopedStopTheWorldLock {161ScopedStopTheWorldLock() {162LockThreads();163LockAllocator();164}165166~ScopedStopTheWorldLock() {167UnlockAllocator();168UnlockThreads();169}170171ScopedStopTheWorldLock &operator=(const ScopedStopTheWorldLock &) = delete;172ScopedStopTheWorldLock(const ScopedStopTheWorldLock &) = delete;173};174175struct Flags {176#define LSAN_FLAG(Type, Name, DefaultValue, Description) Type Name;177#include "lsan_flags.inc"178#undef LSAN_FLAG179180void SetDefaults();181uptr pointer_alignment() const {182return use_unaligned ? 1 : sizeof(uptr);183}184};185186extern Flags lsan_flags;187inline Flags *flags() { return &lsan_flags; }188void RegisterLsanFlags(FlagParser *parser, Flags *f);189190struct LeakedChunk {191uptr chunk;192u32 stack_trace_id;193uptr leaked_size;194ChunkTag tag;195};196197using LeakedChunks = InternalMmapVector<LeakedChunk>;198199struct Leak {200u32 id;201uptr hit_count;202uptr total_size;203u32 stack_trace_id;204bool is_directly_leaked;205bool is_suppressed;206};207208struct LeakedObject {209u32 leak_id;210uptr addr;211uptr size;212};213214// Aggregates leaks by stack trace prefix.215class LeakReport {216public:217LeakReport() {}218void AddLeakedChunks(const LeakedChunks &chunks);219void ReportTopLeaks(uptr max_leaks);220void PrintSummary();221uptr ApplySuppressions();222uptr UnsuppressedLeakCount();223uptr IndirectUnsuppressedLeakCount();224225private:226void PrintReportForLeak(uptr index);227void PrintLeakedObjectsForLeak(uptr index);228229u32 next_id_ = 0;230InternalMmapVector<Leak> leaks_;231InternalMmapVector<LeakedObject> leaked_objects_;232};233234typedef InternalMmapVector<uptr> Frontier;235236// Platform-specific functions.237void InitializePlatformSpecificModules();238void ProcessGlobalRegions(Frontier *frontier);239void ProcessPlatformSpecificAllocations(Frontier *frontier);240241// LockStuffAndStopTheWorld can start to use Scan* calls to collect into242// this Frontier vector before the StopTheWorldCallback actually runs.243// This is used when the OS has a unified callback API for suspending244// threads and enumerating roots.245struct CheckForLeaksParam {246Frontier frontier;247LeakedChunks leaks;248tid_t caller_tid;249uptr caller_sp;250bool success = false;251};252253using Region = Range;254255bool HasRootRegions();256void ScanRootRegions(Frontier *frontier,257const InternalMmapVectorNoCtor<Region> ®ion);258// Run stoptheworld while holding any platform-specific locks, as well as the259// allocator and thread registry locks.260void LockStuffAndStopTheWorld(StopTheWorldCallback callback,261CheckForLeaksParam* argument);262263void ScanRangeForPointers(uptr begin, uptr end,264Frontier *frontier,265const char *region_type, ChunkTag tag);266void ScanGlobalRange(uptr begin, uptr end, Frontier *frontier);267void ScanExtraStackRanges(const InternalMmapVector<Range> &ranges,268Frontier *frontier);269270// Functions called from the parent tool.271const char *MaybeCallLsanDefaultOptions();272void InitCommonLsan();273void DoLeakCheck();274void DoRecoverableLeakCheckVoid();275void DisableCounterUnderflow();276bool DisabledInThisThread();277278// Used to implement __lsan::ScopedDisabler.279void DisableInThisThread();280void EnableInThisThread();281// Can be used to ignore memory allocated by an intercepted282// function.283struct ScopedInterceptorDisabler {284ScopedInterceptorDisabler() { DisableInThisThread(); }285~ScopedInterceptorDisabler() { EnableInThisThread(); }286};287288// According to Itanium C++ ABI array cookie is a one word containing289// size of allocated array.290static inline bool IsItaniumABIArrayCookie(uptr chunk_beg, uptr chunk_size,291uptr addr) {292return chunk_size == sizeof(uptr) && chunk_beg + chunk_size == addr &&293*reinterpret_cast<uptr *>(chunk_beg) == 0;294}295296// According to ARM C++ ABI array cookie consists of two words:297// struct array_cookie {298// std::size_t element_size; // element_size != 0299// std::size_t element_count;300// };301static inline bool IsARMABIArrayCookie(uptr chunk_beg, uptr chunk_size,302uptr addr) {303return chunk_size == 2 * sizeof(uptr) && chunk_beg + chunk_size == addr &&304*reinterpret_cast<uptr *>(chunk_beg + sizeof(uptr)) == 0;305}306307// Special case for "new T[0]" where T is a type with DTOR.308// new T[0] will allocate a cookie (one or two words) for the array size (0)309// and store a pointer to the end of allocated chunk. The actual cookie layout310// varies between platforms according to their C++ ABI implementation.311inline bool IsSpecialCaseOfOperatorNew0(uptr chunk_beg, uptr chunk_size,312uptr addr) {313#if defined(__arm__)314return IsARMABIArrayCookie(chunk_beg, chunk_size, addr);315#else316return IsItaniumABIArrayCookie(chunk_beg, chunk_size, addr);317#endif318}319320// Return the linker module, if valid for the platform.321LoadedModule *GetLinker();322323// Return true if LSan has finished leak checking and reported leaks.324bool HasReportedLeaks();325326// Run platform-specific leak handlers.327void HandleLeaks();328329} // namespace __lsan330331extern "C" {332SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE333const char *__lsan_default_options();334335SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE336int __lsan_is_turned_off();337338SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE339const char *__lsan_default_suppressions();340341SANITIZER_INTERFACE_ATTRIBUTE342void __lsan_register_root_region(const void *p, __lsan::uptr size);343344SANITIZER_INTERFACE_ATTRIBUTE345void __lsan_unregister_root_region(const void *p, __lsan::uptr size);346347} // extern "C"348349#endif // LSAN_COMMON_H350351352