13cab2bb3Spatrick //===-- combined.h ----------------------------------------------*- C++ -*-===//
23cab2bb3Spatrick //
33cab2bb3Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
43cab2bb3Spatrick // See https://llvm.org/LICENSE.txt for license information.
53cab2bb3Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
63cab2bb3Spatrick //
73cab2bb3Spatrick //===----------------------------------------------------------------------===//
83cab2bb3Spatrick
93cab2bb3Spatrick #ifndef SCUDO_COMBINED_H_
103cab2bb3Spatrick #define SCUDO_COMBINED_H_
113cab2bb3Spatrick
123cab2bb3Spatrick #include "chunk.h"
133cab2bb3Spatrick #include "common.h"
143cab2bb3Spatrick #include "flags.h"
153cab2bb3Spatrick #include "flags_parser.h"
163cab2bb3Spatrick #include "local_cache.h"
171f9cb04fSpatrick #include "memtag.h"
18d89ec533Spatrick #include "options.h"
193cab2bb3Spatrick #include "quarantine.h"
203cab2bb3Spatrick #include "report.h"
21*810390e3Srobert #include "rss_limit_checker.h"
223cab2bb3Spatrick #include "secondary.h"
231f9cb04fSpatrick #include "stack_depot.h"
243cab2bb3Spatrick #include "string_utils.h"
253cab2bb3Spatrick #include "tsd.h"
263cab2bb3Spatrick
271f9cb04fSpatrick #include "scudo/interface.h"
281f9cb04fSpatrick
293cab2bb3Spatrick #ifdef GWP_ASAN_HOOKS
303cab2bb3Spatrick #include "gwp_asan/guarded_pool_allocator.h"
311f9cb04fSpatrick #include "gwp_asan/optional/backtrace.h"
321f9cb04fSpatrick #include "gwp_asan/optional/segv_handler.h"
333cab2bb3Spatrick #endif // GWP_ASAN_HOOKS
343cab2bb3Spatrick
EmptyCallback()353cab2bb3Spatrick extern "C" inline void EmptyCallback() {}
363cab2bb3Spatrick
371f9cb04fSpatrick #ifdef HAVE_ANDROID_UNSAFE_FRAME_POINTER_CHASE
381f9cb04fSpatrick // This function is not part of the NDK so it does not appear in any public
391f9cb04fSpatrick // header files. We only declare/use it when targeting the platform.
401f9cb04fSpatrick extern "C" size_t android_unsafe_frame_pointer_chase(scudo::uptr *buf,
411f9cb04fSpatrick size_t num_entries);
421f9cb04fSpatrick #endif
431f9cb04fSpatrick
443cab2bb3Spatrick namespace scudo {
453cab2bb3Spatrick
463cab2bb3Spatrick template <class Params, void (*PostInitCallback)(void) = EmptyCallback>
473cab2bb3Spatrick class Allocator {
483cab2bb3Spatrick public:
493cab2bb3Spatrick using PrimaryT = typename Params::Primary;
503cab2bb3Spatrick using CacheT = typename PrimaryT::CacheT;
513cab2bb3Spatrick typedef Allocator<Params, PostInitCallback> ThisT;
523cab2bb3Spatrick typedef typename Params::template TSDRegistryT<ThisT> TSDRegistryT;
533cab2bb3Spatrick
callPostInitCallback()543cab2bb3Spatrick void callPostInitCallback() {
55d89ec533Spatrick pthread_once(&PostInitNonce, PostInitCallback);
563cab2bb3Spatrick }
573cab2bb3Spatrick
583cab2bb3Spatrick struct QuarantineCallback {
QuarantineCallbackQuarantineCallback593cab2bb3Spatrick explicit QuarantineCallback(ThisT &Instance, CacheT &LocalCache)
603cab2bb3Spatrick : Allocator(Instance), Cache(LocalCache) {}
613cab2bb3Spatrick
623cab2bb3Spatrick // Chunk recycling function, returns a quarantined chunk to the backend,
633cab2bb3Spatrick // first making sure it hasn't been tampered with.
recycleQuarantineCallback643cab2bb3Spatrick void recycle(void *Ptr) {
653cab2bb3Spatrick Chunk::UnpackedHeader Header;
663cab2bb3Spatrick Chunk::loadHeader(Allocator.Cookie, Ptr, &Header);
673cab2bb3Spatrick if (UNLIKELY(Header.State != Chunk::State::Quarantined))
683cab2bb3Spatrick reportInvalidChunkState(AllocatorAction::Recycling, Ptr);
693cab2bb3Spatrick
703cab2bb3Spatrick Chunk::UnpackedHeader NewHeader = Header;
713cab2bb3Spatrick NewHeader.State = Chunk::State::Available;
723cab2bb3Spatrick Chunk::compareExchangeHeader(Allocator.Cookie, Ptr, &NewHeader, &Header);
733cab2bb3Spatrick
74d89ec533Spatrick if (allocatorSupportsMemoryTagging<Params>())
75d89ec533Spatrick Ptr = untagPointer(Ptr);
763cab2bb3Spatrick void *BlockBegin = Allocator::getBlockBegin(Ptr, &NewHeader);
77d89ec533Spatrick Cache.deallocate(NewHeader.ClassId, BlockBegin);
783cab2bb3Spatrick }
793cab2bb3Spatrick
803cab2bb3Spatrick // We take a shortcut when allocating a quarantine batch by working with the
813cab2bb3Spatrick // appropriate class ID instead of using Size. The compiler should optimize
823cab2bb3Spatrick // the class ID computation and work with the associated cache directly.
allocateQuarantineCallback833cab2bb3Spatrick void *allocate(UNUSED uptr Size) {
843cab2bb3Spatrick const uptr QuarantineClassId = SizeClassMap::getClassIdBySize(
853cab2bb3Spatrick sizeof(QuarantineBatch) + Chunk::getHeaderSize());
863cab2bb3Spatrick void *Ptr = Cache.allocate(QuarantineClassId);
873cab2bb3Spatrick // Quarantine batch allocation failure is fatal.
883cab2bb3Spatrick if (UNLIKELY(!Ptr))
893cab2bb3Spatrick reportOutOfMemory(SizeClassMap::getSizeByClassId(QuarantineClassId));
903cab2bb3Spatrick
913cab2bb3Spatrick Ptr = reinterpret_cast<void *>(reinterpret_cast<uptr>(Ptr) +
923cab2bb3Spatrick Chunk::getHeaderSize());
933cab2bb3Spatrick Chunk::UnpackedHeader Header = {};
943cab2bb3Spatrick Header.ClassId = QuarantineClassId & Chunk::ClassIdMask;
953cab2bb3Spatrick Header.SizeOrUnusedBytes = sizeof(QuarantineBatch);
963cab2bb3Spatrick Header.State = Chunk::State::Allocated;
973cab2bb3Spatrick Chunk::storeHeader(Allocator.Cookie, Ptr, &Header);
983cab2bb3Spatrick
99d89ec533Spatrick // Reset tag to 0 as this chunk may have been previously used for a tagged
100d89ec533Spatrick // user allocation.
101d89ec533Spatrick if (UNLIKELY(useMemoryTagging<Params>(Allocator.Primary.Options.load())))
102d89ec533Spatrick storeTags(reinterpret_cast<uptr>(Ptr),
103d89ec533Spatrick reinterpret_cast<uptr>(Ptr) + sizeof(QuarantineBatch));
104d89ec533Spatrick
1053cab2bb3Spatrick return Ptr;
1063cab2bb3Spatrick }
1073cab2bb3Spatrick
deallocateQuarantineCallback1083cab2bb3Spatrick void deallocate(void *Ptr) {
1093cab2bb3Spatrick const uptr QuarantineClassId = SizeClassMap::getClassIdBySize(
1103cab2bb3Spatrick sizeof(QuarantineBatch) + Chunk::getHeaderSize());
1113cab2bb3Spatrick Chunk::UnpackedHeader Header;
1123cab2bb3Spatrick Chunk::loadHeader(Allocator.Cookie, Ptr, &Header);
1133cab2bb3Spatrick
1143cab2bb3Spatrick if (UNLIKELY(Header.State != Chunk::State::Allocated))
1153cab2bb3Spatrick reportInvalidChunkState(AllocatorAction::Deallocating, Ptr);
1163cab2bb3Spatrick DCHECK_EQ(Header.ClassId, QuarantineClassId);
1173cab2bb3Spatrick DCHECK_EQ(Header.Offset, 0);
1183cab2bb3Spatrick DCHECK_EQ(Header.SizeOrUnusedBytes, sizeof(QuarantineBatch));
1193cab2bb3Spatrick
1203cab2bb3Spatrick Chunk::UnpackedHeader NewHeader = Header;
1213cab2bb3Spatrick NewHeader.State = Chunk::State::Available;
1223cab2bb3Spatrick Chunk::compareExchangeHeader(Allocator.Cookie, Ptr, &NewHeader, &Header);
1233cab2bb3Spatrick Cache.deallocate(QuarantineClassId,
1243cab2bb3Spatrick reinterpret_cast<void *>(reinterpret_cast<uptr>(Ptr) -
1253cab2bb3Spatrick Chunk::getHeaderSize()));
1263cab2bb3Spatrick }
1273cab2bb3Spatrick
1283cab2bb3Spatrick private:
1293cab2bb3Spatrick ThisT &Allocator;
1303cab2bb3Spatrick CacheT &Cache;
1313cab2bb3Spatrick };
1323cab2bb3Spatrick
1333cab2bb3Spatrick typedef GlobalQuarantine<QuarantineCallback, void> QuarantineT;
1343cab2bb3Spatrick typedef typename QuarantineT::CacheT QuarantineCacheT;
1353cab2bb3Spatrick
init()136d89ec533Spatrick void init() {
1373cab2bb3Spatrick performSanityChecks();
1383cab2bb3Spatrick
1393cab2bb3Spatrick // Check if hardware CRC32 is supported in the binary and by the platform,
1403cab2bb3Spatrick // if so, opt for the CRC32 hardware version of the checksum.
1413cab2bb3Spatrick if (&computeHardwareCRC32 && hasHardwareCRC32())
1423cab2bb3Spatrick HashAlgorithm = Checksum::HardwareCRC32;
1433cab2bb3Spatrick
1443cab2bb3Spatrick if (UNLIKELY(!getRandom(&Cookie, sizeof(Cookie))))
1453cab2bb3Spatrick Cookie = static_cast<u32>(getMonotonicTime() ^
1463cab2bb3Spatrick (reinterpret_cast<uptr>(this) >> 4));
1473cab2bb3Spatrick
1483cab2bb3Spatrick initFlags();
1493cab2bb3Spatrick reportUnrecognizedFlags();
1503cab2bb3Spatrick
151*810390e3Srobert RssChecker.init(scudo::getFlags()->soft_rss_limit_mb,
152*810390e3Srobert scudo::getFlags()->hard_rss_limit_mb);
153*810390e3Srobert
1543cab2bb3Spatrick // Store some flags locally.
155d89ec533Spatrick if (getFlags()->may_return_null)
156d89ec533Spatrick Primary.Options.set(OptionBit::MayReturnNull);
157d89ec533Spatrick if (getFlags()->zero_contents)
158d89ec533Spatrick Primary.Options.setFillContentsMode(ZeroFill);
159d89ec533Spatrick else if (getFlags()->pattern_fill_contents)
160d89ec533Spatrick Primary.Options.setFillContentsMode(PatternOrZeroFill);
161d89ec533Spatrick if (getFlags()->dealloc_type_mismatch)
162d89ec533Spatrick Primary.Options.set(OptionBit::DeallocTypeMismatch);
163d89ec533Spatrick if (getFlags()->delete_size_mismatch)
164d89ec533Spatrick Primary.Options.set(OptionBit::DeleteSizeMismatch);
165d89ec533Spatrick if (allocatorSupportsMemoryTagging<Params>() &&
166d89ec533Spatrick systemSupportsMemoryTagging())
167d89ec533Spatrick Primary.Options.set(OptionBit::UseMemoryTagging);
168d89ec533Spatrick Primary.Options.set(OptionBit::UseOddEvenTags);
169d89ec533Spatrick
170d89ec533Spatrick QuarantineMaxChunkSize =
1713cab2bb3Spatrick static_cast<u32>(getFlags()->quarantine_max_chunk_size);
1723cab2bb3Spatrick
173d89ec533Spatrick Stats.init();
1741f9cb04fSpatrick const s32 ReleaseToOsIntervalMs = getFlags()->release_to_os_interval_ms;
175d89ec533Spatrick Primary.init(ReleaseToOsIntervalMs);
176d89ec533Spatrick Secondary.init(&Stats, ReleaseToOsIntervalMs);
1773cab2bb3Spatrick Quarantine.init(
1783cab2bb3Spatrick static_cast<uptr>(getFlags()->quarantine_size_kb << 10),
1793cab2bb3Spatrick static_cast<uptr>(getFlags()->thread_local_quarantine_size_kb << 10));
180*810390e3Srobert
181*810390e3Srobert initRingBuffer();
1821f9cb04fSpatrick }
1833cab2bb3Spatrick
1841f9cb04fSpatrick // Initialize the embedded GWP-ASan instance. Requires the main allocator to
1851f9cb04fSpatrick // be functional, best called from PostInitCallback.
initGwpAsan()1861f9cb04fSpatrick void initGwpAsan() {
1873cab2bb3Spatrick #ifdef GWP_ASAN_HOOKS
1883cab2bb3Spatrick gwp_asan::options::Options Opt;
1893cab2bb3Spatrick Opt.Enabled = getFlags()->GWP_ASAN_Enabled;
1903cab2bb3Spatrick Opt.MaxSimultaneousAllocations =
1913cab2bb3Spatrick getFlags()->GWP_ASAN_MaxSimultaneousAllocations;
1923cab2bb3Spatrick Opt.SampleRate = getFlags()->GWP_ASAN_SampleRate;
1933cab2bb3Spatrick Opt.InstallSignalHandlers = getFlags()->GWP_ASAN_InstallSignalHandlers;
194*810390e3Srobert Opt.Recoverable = getFlags()->GWP_ASAN_Recoverable;
1951f9cb04fSpatrick // Embedded GWP-ASan is locked through the Scudo atfork handler (via
1961f9cb04fSpatrick // Allocator::disable calling GWPASan.disable). Disable GWP-ASan's atfork
1971f9cb04fSpatrick // handler.
1981f9cb04fSpatrick Opt.InstallForkHandlers = false;
199d89ec533Spatrick Opt.Backtrace = gwp_asan::backtrace::getBacktraceFunction();
2003cab2bb3Spatrick GuardedAlloc.init(Opt);
2011f9cb04fSpatrick
2021f9cb04fSpatrick if (Opt.InstallSignalHandlers)
203d89ec533Spatrick gwp_asan::segv_handler::installSignalHandlers(
204d89ec533Spatrick &GuardedAlloc, Printf,
205d89ec533Spatrick gwp_asan::backtrace::getPrintBacktraceFunction(),
206*810390e3Srobert gwp_asan::backtrace::getSegvBacktraceFunction(),
207*810390e3Srobert Opt.Recoverable);
208d89ec533Spatrick
209d89ec533Spatrick GuardedAllocSlotSize =
210d89ec533Spatrick GuardedAlloc.getAllocatorState()->maximumAllocationSize();
211d89ec533Spatrick Stats.add(StatFree, static_cast<uptr>(Opt.MaxSimultaneousAllocations) *
212d89ec533Spatrick GuardedAllocSlotSize);
2133cab2bb3Spatrick #endif // GWP_ASAN_HOOKS
2143cab2bb3Spatrick }
2153cab2bb3Spatrick
216*810390e3Srobert #ifdef GWP_ASAN_HOOKS
getGwpAsanAllocationMetadata()217*810390e3Srobert const gwp_asan::AllocationMetadata *getGwpAsanAllocationMetadata() {
218*810390e3Srobert return GuardedAlloc.getMetadataRegion();
219*810390e3Srobert }
220*810390e3Srobert
getGwpAsanAllocatorState()221*810390e3Srobert const gwp_asan::AllocatorState *getGwpAsanAllocatorState() {
222*810390e3Srobert return GuardedAlloc.getAllocatorState();
223*810390e3Srobert }
224*810390e3Srobert #endif // GWP_ASAN_HOOKS
225*810390e3Srobert
226d89ec533Spatrick ALWAYS_INLINE void initThreadMaybe(bool MinimalInit = false) {
227d89ec533Spatrick TSDRegistry.initThreadMaybe(this, MinimalInit);
228d89ec533Spatrick }
2293cab2bb3Spatrick
unmapTestOnly()2303cab2bb3Spatrick void unmapTestOnly() {
231d89ec533Spatrick TSDRegistry.unmapTestOnly(this);
2323cab2bb3Spatrick Primary.unmapTestOnly();
233d89ec533Spatrick Secondary.unmapTestOnly();
2341f9cb04fSpatrick #ifdef GWP_ASAN_HOOKS
2351f9cb04fSpatrick if (getFlags()->GWP_ASAN_InstallSignalHandlers)
236d89ec533Spatrick gwp_asan::segv_handler::uninstallSignalHandlers();
2371f9cb04fSpatrick GuardedAlloc.uninitTestOnly();
2381f9cb04fSpatrick #endif // GWP_ASAN_HOOKS
2393cab2bb3Spatrick }
2403cab2bb3Spatrick
getTSDRegistry()2413cab2bb3Spatrick TSDRegistryT *getTSDRegistry() { return &TSDRegistry; }
2423cab2bb3Spatrick
2433cab2bb3Spatrick // The Cache must be provided zero-initialized.
initCache(CacheT * Cache)244d89ec533Spatrick void initCache(CacheT *Cache) { Cache->init(&Stats, &Primary); }
2453cab2bb3Spatrick
2463cab2bb3Spatrick // Release the resources used by a TSD, which involves:
2473cab2bb3Spatrick // - draining the local quarantine cache to the global quarantine;
2483cab2bb3Spatrick // - releasing the cached pointers back to the Primary;
2493cab2bb3Spatrick // - unlinking the local stats from the global ones (destroying the cache does
2503cab2bb3Spatrick // the last two items).
commitBack(TSD<ThisT> * TSD)2513cab2bb3Spatrick void commitBack(TSD<ThisT> *TSD) {
2523cab2bb3Spatrick Quarantine.drain(&TSD->QuarantineCache,
2533cab2bb3Spatrick QuarantineCallback(*this, TSD->Cache));
2543cab2bb3Spatrick TSD->Cache.destroy(&Stats);
2553cab2bb3Spatrick }
2563cab2bb3Spatrick
getHeaderTaggedPointer(void * Ptr)257d89ec533Spatrick ALWAYS_INLINE void *getHeaderTaggedPointer(void *Ptr) {
258d89ec533Spatrick if (!allocatorSupportsMemoryTagging<Params>())
2591f9cb04fSpatrick return Ptr;
260d89ec533Spatrick auto UntaggedPtr = untagPointer(Ptr);
261d89ec533Spatrick if (UntaggedPtr != Ptr)
262d89ec533Spatrick return UntaggedPtr;
263d89ec533Spatrick // Secondary, or pointer allocated while memory tagging is unsupported or
264d89ec533Spatrick // disabled. The tag mismatch is okay in the latter case because tags will
265d89ec533Spatrick // not be checked.
266d89ec533Spatrick return addHeaderTag(Ptr);
267d89ec533Spatrick }
268d89ec533Spatrick
addHeaderTag(uptr Ptr)269d89ec533Spatrick ALWAYS_INLINE uptr addHeaderTag(uptr Ptr) {
270d89ec533Spatrick if (!allocatorSupportsMemoryTagging<Params>())
271d89ec533Spatrick return Ptr;
272d89ec533Spatrick return addFixedTag(Ptr, 2);
273d89ec533Spatrick }
274d89ec533Spatrick
addHeaderTag(void * Ptr)275d89ec533Spatrick ALWAYS_INLINE void *addHeaderTag(void *Ptr) {
276d89ec533Spatrick return reinterpret_cast<void *>(addHeaderTag(reinterpret_cast<uptr>(Ptr)));
2771f9cb04fSpatrick }
2781f9cb04fSpatrick
collectStackTrace()2791f9cb04fSpatrick NOINLINE u32 collectStackTrace() {
2801f9cb04fSpatrick #ifdef HAVE_ANDROID_UNSAFE_FRAME_POINTER_CHASE
2811f9cb04fSpatrick // Discard collectStackTrace() frame and allocator function frame.
2821f9cb04fSpatrick constexpr uptr DiscardFrames = 2;
2831f9cb04fSpatrick uptr Stack[MaxTraceSize + DiscardFrames];
2841f9cb04fSpatrick uptr Size =
2851f9cb04fSpatrick android_unsafe_frame_pointer_chase(Stack, MaxTraceSize + DiscardFrames);
2861f9cb04fSpatrick Size = Min<uptr>(Size, MaxTraceSize + DiscardFrames);
2871f9cb04fSpatrick return Depot.insert(Stack + Min<uptr>(DiscardFrames, Size), Stack + Size);
2881f9cb04fSpatrick #else
2891f9cb04fSpatrick return 0;
2901f9cb04fSpatrick #endif
2911f9cb04fSpatrick }
2921f9cb04fSpatrick
computeOddEvenMaskForPointerMaybe(Options Options,uptr Ptr,uptr ClassId)293d89ec533Spatrick uptr computeOddEvenMaskForPointerMaybe(Options Options, uptr Ptr,
294d89ec533Spatrick uptr ClassId) {
295d89ec533Spatrick if (!Options.get(OptionBit::UseOddEvenTags))
296d89ec533Spatrick return 0;
297d89ec533Spatrick
298d89ec533Spatrick // If a chunk's tag is odd, we want the tags of the surrounding blocks to be
299d89ec533Spatrick // even, and vice versa. Blocks are laid out Size bytes apart, and adding
300d89ec533Spatrick // Size to Ptr will flip the least significant set bit of Size in Ptr, so
301d89ec533Spatrick // that bit will have the pattern 010101... for consecutive blocks, which we
302d89ec533Spatrick // can use to determine which tag mask to use.
303d89ec533Spatrick return 0x5555U << ((Ptr >> SizeClassMap::getSizeLSBByClassId(ClassId)) & 1);
304d89ec533Spatrick }
305d89ec533Spatrick
3063cab2bb3Spatrick NOINLINE void *allocate(uptr Size, Chunk::Origin Origin,
3073cab2bb3Spatrick uptr Alignment = MinAlignment,
3083cab2bb3Spatrick bool ZeroContents = false) {
3093cab2bb3Spatrick initThreadMaybe();
3103cab2bb3Spatrick
311d89ec533Spatrick const Options Options = Primary.Options.load();
3123cab2bb3Spatrick if (UNLIKELY(Alignment > MaxAlignment)) {
313d89ec533Spatrick if (Options.get(OptionBit::MayReturnNull))
3143cab2bb3Spatrick return nullptr;
3153cab2bb3Spatrick reportAlignmentTooBig(Alignment, MaxAlignment);
3163cab2bb3Spatrick }
3173cab2bb3Spatrick if (Alignment < MinAlignment)
3183cab2bb3Spatrick Alignment = MinAlignment;
3193cab2bb3Spatrick
320d89ec533Spatrick #ifdef GWP_ASAN_HOOKS
321d89ec533Spatrick if (UNLIKELY(GuardedAlloc.shouldSample())) {
322d89ec533Spatrick if (void *Ptr = GuardedAlloc.allocate(Size, Alignment)) {
323d89ec533Spatrick if (UNLIKELY(&__scudo_allocate_hook))
324d89ec533Spatrick __scudo_allocate_hook(Ptr, Size);
325d89ec533Spatrick Stats.lock();
326d89ec533Spatrick Stats.add(StatAllocated, GuardedAllocSlotSize);
327d89ec533Spatrick Stats.sub(StatFree, GuardedAllocSlotSize);
328d89ec533Spatrick Stats.unlock();
329d89ec533Spatrick return Ptr;
330d89ec533Spatrick }
331d89ec533Spatrick }
332d89ec533Spatrick #endif // GWP_ASAN_HOOKS
333d89ec533Spatrick
334d89ec533Spatrick const FillContentsMode FillContents = ZeroContents ? ZeroFill
335d89ec533Spatrick : TSDRegistry.getDisableMemInit()
336d89ec533Spatrick ? NoFill
337d89ec533Spatrick : Options.getFillContentsMode();
338d89ec533Spatrick
3393cab2bb3Spatrick // If the requested size happens to be 0 (more common than you might think),
3403cab2bb3Spatrick // allocate MinAlignment bytes on top of the header. Then add the extra
3413cab2bb3Spatrick // bytes required to fulfill the alignment requirements: we allocate enough
3423cab2bb3Spatrick // to be sure that there will be an address in the block that will satisfy
3433cab2bb3Spatrick // the alignment.
3443cab2bb3Spatrick const uptr NeededSize =
3453cab2bb3Spatrick roundUpTo(Size, MinAlignment) +
3463cab2bb3Spatrick ((Alignment > MinAlignment) ? Alignment : Chunk::getHeaderSize());
3473cab2bb3Spatrick
3483cab2bb3Spatrick // Takes care of extravagantly large sizes as well as integer overflows.
3493cab2bb3Spatrick static_assert(MaxAllowedMallocSize < UINTPTR_MAX - MaxAlignment, "");
3503cab2bb3Spatrick if (UNLIKELY(Size >= MaxAllowedMallocSize)) {
351d89ec533Spatrick if (Options.get(OptionBit::MayReturnNull))
3523cab2bb3Spatrick return nullptr;
3533cab2bb3Spatrick reportAllocationSizeTooBig(Size, NeededSize, MaxAllowedMallocSize);
3543cab2bb3Spatrick }
3553cab2bb3Spatrick DCHECK_LE(Size, NeededSize);
3563cab2bb3Spatrick
357*810390e3Srobert switch (RssChecker.getRssLimitExceeded()) {
358*810390e3Srobert case RssLimitChecker::Neither:
359*810390e3Srobert break;
360*810390e3Srobert case RssLimitChecker::Soft:
361*810390e3Srobert if (Options.get(OptionBit::MayReturnNull))
362*810390e3Srobert return nullptr;
363*810390e3Srobert reportSoftRSSLimit(RssChecker.getSoftRssLimit());
364*810390e3Srobert break;
365*810390e3Srobert case RssLimitChecker::Hard:
366*810390e3Srobert reportHardRSSLimit(RssChecker.getHardRssLimit());
367*810390e3Srobert break;
368*810390e3Srobert }
369*810390e3Srobert
3701f9cb04fSpatrick void *Block = nullptr;
3711f9cb04fSpatrick uptr ClassId = 0;
372d89ec533Spatrick uptr SecondaryBlockEnd = 0;
3733cab2bb3Spatrick if (LIKELY(PrimaryT::canAllocate(NeededSize))) {
3743cab2bb3Spatrick ClassId = SizeClassMap::getClassIdBySize(NeededSize);
3753cab2bb3Spatrick DCHECK_NE(ClassId, 0U);
3763cab2bb3Spatrick bool UnlockRequired;
3773cab2bb3Spatrick auto *TSD = TSDRegistry.getTSDAndLock(&UnlockRequired);
3783cab2bb3Spatrick Block = TSD->Cache.allocate(ClassId);
3791f9cb04fSpatrick // If the allocation failed, the most likely reason with a 32-bit primary
3801f9cb04fSpatrick // is the region being full. In that event, retry in each successively
3811f9cb04fSpatrick // larger class until it fits. If it fails to fit in the largest class,
3821f9cb04fSpatrick // fallback to the Secondary.
3831f9cb04fSpatrick if (UNLIKELY(!Block)) {
384d89ec533Spatrick while (ClassId < SizeClassMap::LargestClassId && !Block)
3851f9cb04fSpatrick Block = TSD->Cache.allocate(++ClassId);
386d89ec533Spatrick if (!Block)
3871f9cb04fSpatrick ClassId = 0;
3881f9cb04fSpatrick }
3893cab2bb3Spatrick if (UnlockRequired)
3903cab2bb3Spatrick TSD->unlock();
3913cab2bb3Spatrick }
3921f9cb04fSpatrick if (UNLIKELY(ClassId == 0))
393d89ec533Spatrick Block = Secondary.allocate(Options, Size, Alignment, &SecondaryBlockEnd,
3941f9cb04fSpatrick FillContents);
3953cab2bb3Spatrick
3963cab2bb3Spatrick if (UNLIKELY(!Block)) {
397d89ec533Spatrick if (Options.get(OptionBit::MayReturnNull))
3983cab2bb3Spatrick return nullptr;
3993cab2bb3Spatrick reportOutOfMemory(NeededSize);
4003cab2bb3Spatrick }
4013cab2bb3Spatrick
4021f9cb04fSpatrick const uptr BlockUptr = reinterpret_cast<uptr>(Block);
4031f9cb04fSpatrick const uptr UnalignedUserPtr = BlockUptr + Chunk::getHeaderSize();
4043cab2bb3Spatrick const uptr UserPtr = roundUpTo(UnalignedUserPtr, Alignment);
4053cab2bb3Spatrick
4061f9cb04fSpatrick void *Ptr = reinterpret_cast<void *>(UserPtr);
4071f9cb04fSpatrick void *TaggedPtr = Ptr;
408d89ec533Spatrick if (LIKELY(ClassId)) {
4091f9cb04fSpatrick // We only need to zero or tag the contents for Primary backed
4101f9cb04fSpatrick // allocations. We only set tags for primary allocations in order to avoid
4111f9cb04fSpatrick // faulting potentially large numbers of pages for large secondary
4121f9cb04fSpatrick // allocations. We assume that guard pages are enough to protect these
4131f9cb04fSpatrick // allocations.
4141f9cb04fSpatrick //
4151f9cb04fSpatrick // FIXME: When the kernel provides a way to set the background tag of a
4161f9cb04fSpatrick // mapping, we should be able to tag secondary allocations as well.
4171f9cb04fSpatrick //
4181f9cb04fSpatrick // When memory tagging is enabled, zeroing the contents is done as part of
4191f9cb04fSpatrick // setting the tag.
420d89ec533Spatrick if (UNLIKELY(useMemoryTagging<Params>(Options))) {
4211f9cb04fSpatrick uptr PrevUserPtr;
4221f9cb04fSpatrick Chunk::UnpackedHeader Header;
423d89ec533Spatrick const uptr BlockSize = PrimaryT::getSizeByClassId(ClassId);
424d89ec533Spatrick const uptr BlockEnd = BlockUptr + BlockSize;
4251f9cb04fSpatrick // If possible, try to reuse the UAF tag that was set by deallocate().
4261f9cb04fSpatrick // For simplicity, only reuse tags if we have the same start address as
4271f9cb04fSpatrick // the previous allocation. This handles the majority of cases since
4281f9cb04fSpatrick // most allocations will not be more aligned than the minimum alignment.
4291f9cb04fSpatrick //
4301f9cb04fSpatrick // We need to handle situations involving reclaimed chunks, and retag
4311f9cb04fSpatrick // the reclaimed portions if necessary. In the case where the chunk is
4321f9cb04fSpatrick // fully reclaimed, the chunk's header will be zero, which will trigger
4331f9cb04fSpatrick // the code path for new mappings and invalid chunks that prepares the
4341f9cb04fSpatrick // chunk from scratch. There are three possibilities for partial
4351f9cb04fSpatrick // reclaiming:
4361f9cb04fSpatrick //
4371f9cb04fSpatrick // (1) Header was reclaimed, data was partially reclaimed.
4381f9cb04fSpatrick // (2) Header was not reclaimed, all data was reclaimed (e.g. because
4391f9cb04fSpatrick // data started on a page boundary).
4401f9cb04fSpatrick // (3) Header was not reclaimed, data was partially reclaimed.
4411f9cb04fSpatrick //
4421f9cb04fSpatrick // Case (1) will be handled in the same way as for full reclaiming,
4431f9cb04fSpatrick // since the header will be zero.
4441f9cb04fSpatrick //
4451f9cb04fSpatrick // We can detect case (2) by loading the tag from the start
4461f9cb04fSpatrick // of the chunk. If it is zero, it means that either all data was
4471f9cb04fSpatrick // reclaimed (since we never use zero as the chunk tag), or that the
4481f9cb04fSpatrick // previous allocation was of size zero. Either way, we need to prepare
4491f9cb04fSpatrick // a new chunk from scratch.
4501f9cb04fSpatrick //
4511f9cb04fSpatrick // We can detect case (3) by moving to the next page (if covered by the
4521f9cb04fSpatrick // chunk) and loading the tag of its first granule. If it is zero, it
4531f9cb04fSpatrick // means that all following pages may need to be retagged. On the other
4541f9cb04fSpatrick // hand, if it is nonzero, we can assume that all following pages are
4551f9cb04fSpatrick // still tagged, according to the logic that if any of the pages
4561f9cb04fSpatrick // following the next page were reclaimed, the next page would have been
4571f9cb04fSpatrick // reclaimed as well.
4581f9cb04fSpatrick uptr TaggedUserPtr;
4591f9cb04fSpatrick if (getChunkFromBlock(BlockUptr, &PrevUserPtr, &Header) &&
4601f9cb04fSpatrick PrevUserPtr == UserPtr &&
4611f9cb04fSpatrick (TaggedUserPtr = loadTag(UserPtr)) != UserPtr) {
4621f9cb04fSpatrick uptr PrevEnd = TaggedUserPtr + Header.SizeOrUnusedBytes;
4631f9cb04fSpatrick const uptr NextPage = roundUpTo(TaggedUserPtr, getPageSizeCached());
4641f9cb04fSpatrick if (NextPage < PrevEnd && loadTag(NextPage) != NextPage)
4651f9cb04fSpatrick PrevEnd = NextPage;
4661f9cb04fSpatrick TaggedPtr = reinterpret_cast<void *>(TaggedUserPtr);
467d89ec533Spatrick resizeTaggedChunk(PrevEnd, TaggedUserPtr + Size, Size, BlockEnd);
468d89ec533Spatrick if (UNLIKELY(FillContents != NoFill && !Header.OriginOrWasZeroed)) {
469d89ec533Spatrick // If an allocation needs to be zeroed (i.e. calloc) we can normally
470d89ec533Spatrick // avoid zeroing the memory now since we can rely on memory having
471d89ec533Spatrick // been zeroed on free, as this is normally done while setting the
472d89ec533Spatrick // UAF tag. But if tagging was disabled per-thread when the memory
473d89ec533Spatrick // was freed, it would not have been retagged and thus zeroed, and
474d89ec533Spatrick // therefore it needs to be zeroed now.
475d89ec533Spatrick memset(TaggedPtr, 0,
476d89ec533Spatrick Min(Size, roundUpTo(PrevEnd - TaggedUserPtr,
477d89ec533Spatrick archMemoryTagGranuleSize())));
478d89ec533Spatrick } else if (Size) {
4791f9cb04fSpatrick // Clear any stack metadata that may have previously been stored in
4801f9cb04fSpatrick // the chunk data.
4811f9cb04fSpatrick memset(TaggedPtr, 0, archMemoryTagGranuleSize());
4821f9cb04fSpatrick }
4831f9cb04fSpatrick } else {
484d89ec533Spatrick const uptr OddEvenMask =
485d89ec533Spatrick computeOddEvenMaskForPointerMaybe(Options, BlockUptr, ClassId);
486d89ec533Spatrick TaggedPtr = prepareTaggedChunk(Ptr, Size, OddEvenMask, BlockEnd);
4871f9cb04fSpatrick }
488d89ec533Spatrick storePrimaryAllocationStackMaybe(Options, Ptr);
489d89ec533Spatrick } else {
490d89ec533Spatrick Block = addHeaderTag(Block);
491d89ec533Spatrick Ptr = addHeaderTag(Ptr);
492d89ec533Spatrick if (UNLIKELY(FillContents != NoFill)) {
4931f9cb04fSpatrick // This condition is not necessarily unlikely, but since memset is
4941f9cb04fSpatrick // costly, we might as well mark it as such.
4951f9cb04fSpatrick memset(Block, FillContents == ZeroFill ? 0 : PatternFillByte,
4961f9cb04fSpatrick PrimaryT::getSizeByClassId(ClassId));
4971f9cb04fSpatrick }
4981f9cb04fSpatrick }
499d89ec533Spatrick } else {
500d89ec533Spatrick Block = addHeaderTag(Block);
501d89ec533Spatrick Ptr = addHeaderTag(Ptr);
502d89ec533Spatrick if (UNLIKELY(useMemoryTagging<Params>(Options))) {
503d89ec533Spatrick storeTags(reinterpret_cast<uptr>(Block), reinterpret_cast<uptr>(Ptr));
504d89ec533Spatrick storeSecondaryAllocationStackMaybe(Options, Ptr, Size);
505d89ec533Spatrick }
506d89ec533Spatrick }
5071f9cb04fSpatrick
5083cab2bb3Spatrick Chunk::UnpackedHeader Header = {};
5093cab2bb3Spatrick if (UNLIKELY(UnalignedUserPtr != UserPtr)) {
5103cab2bb3Spatrick const uptr Offset = UserPtr - UnalignedUserPtr;
5113cab2bb3Spatrick DCHECK_GE(Offset, 2 * sizeof(u32));
5123cab2bb3Spatrick // The BlockMarker has no security purpose, but is specifically meant for
5133cab2bb3Spatrick // the chunk iteration function that can be used in debugging situations.
5143cab2bb3Spatrick // It is the only situation where we have to locate the start of a chunk
5153cab2bb3Spatrick // based on its block address.
5163cab2bb3Spatrick reinterpret_cast<u32 *>(Block)[0] = BlockMarker;
5173cab2bb3Spatrick reinterpret_cast<u32 *>(Block)[1] = static_cast<u32>(Offset);
5183cab2bb3Spatrick Header.Offset = (Offset >> MinAlignmentLog) & Chunk::OffsetMask;
5193cab2bb3Spatrick }
5203cab2bb3Spatrick Header.ClassId = ClassId & Chunk::ClassIdMask;
5213cab2bb3Spatrick Header.State = Chunk::State::Allocated;
522d89ec533Spatrick Header.OriginOrWasZeroed = Origin & Chunk::OriginMask;
5231f9cb04fSpatrick Header.SizeOrUnusedBytes =
5241f9cb04fSpatrick (ClassId ? Size : SecondaryBlockEnd - (UserPtr + Size)) &
5253cab2bb3Spatrick Chunk::SizeOrUnusedBytesMask;
5263cab2bb3Spatrick Chunk::storeHeader(Cookie, Ptr, &Header);
5273cab2bb3Spatrick
528d89ec533Spatrick if (UNLIKELY(&__scudo_allocate_hook))
5291f9cb04fSpatrick __scudo_allocate_hook(TaggedPtr, Size);
5303cab2bb3Spatrick
5311f9cb04fSpatrick return TaggedPtr;
5323cab2bb3Spatrick }
5333cab2bb3Spatrick
5343cab2bb3Spatrick NOINLINE void deallocate(void *Ptr, Chunk::Origin Origin, uptr DeleteSize = 0,
5353cab2bb3Spatrick UNUSED uptr Alignment = MinAlignment) {
5363cab2bb3Spatrick // For a deallocation, we only ensure minimal initialization, meaning thread
5373cab2bb3Spatrick // local data will be left uninitialized for now (when using ELF TLS). The
5383cab2bb3Spatrick // fallback cache will be used instead. This is a workaround for a situation
5393cab2bb3Spatrick // where the only heap operation performed in a thread would be a free past
5403cab2bb3Spatrick // the TLS destructors, ending up in initialized thread specific data never
5413cab2bb3Spatrick // being destroyed properly. Any other heap operation will do a full init.
5423cab2bb3Spatrick initThreadMaybe(/*MinimalInit=*/true);
5433cab2bb3Spatrick
544d89ec533Spatrick if (UNLIKELY(&__scudo_deallocate_hook))
5453cab2bb3Spatrick __scudo_deallocate_hook(Ptr);
5463cab2bb3Spatrick
5473cab2bb3Spatrick if (UNLIKELY(!Ptr))
5483cab2bb3Spatrick return;
549d89ec533Spatrick
550d89ec533Spatrick #ifdef GWP_ASAN_HOOKS
551d89ec533Spatrick if (UNLIKELY(GuardedAlloc.pointerIsMine(Ptr))) {
552d89ec533Spatrick GuardedAlloc.deallocate(Ptr);
553d89ec533Spatrick Stats.lock();
554d89ec533Spatrick Stats.add(StatFree, GuardedAllocSlotSize);
555d89ec533Spatrick Stats.sub(StatAllocated, GuardedAllocSlotSize);
556d89ec533Spatrick Stats.unlock();
557d89ec533Spatrick return;
558d89ec533Spatrick }
559d89ec533Spatrick #endif // GWP_ASAN_HOOKS
560d89ec533Spatrick
5613cab2bb3Spatrick if (UNLIKELY(!isAligned(reinterpret_cast<uptr>(Ptr), MinAlignment)))
5623cab2bb3Spatrick reportMisalignedPointer(AllocatorAction::Deallocating, Ptr);
5633cab2bb3Spatrick
564d89ec533Spatrick void *TaggedPtr = Ptr;
565d89ec533Spatrick Ptr = getHeaderTaggedPointer(Ptr);
5661f9cb04fSpatrick
5673cab2bb3Spatrick Chunk::UnpackedHeader Header;
5683cab2bb3Spatrick Chunk::loadHeader(Cookie, Ptr, &Header);
5693cab2bb3Spatrick
5703cab2bb3Spatrick if (UNLIKELY(Header.State != Chunk::State::Allocated))
5713cab2bb3Spatrick reportInvalidChunkState(AllocatorAction::Deallocating, Ptr);
572d89ec533Spatrick
573d89ec533Spatrick const Options Options = Primary.Options.load();
574d89ec533Spatrick if (Options.get(OptionBit::DeallocTypeMismatch)) {
575d89ec533Spatrick if (UNLIKELY(Header.OriginOrWasZeroed != Origin)) {
5763cab2bb3Spatrick // With the exception of memalign'd chunks, that can be still be free'd.
577d89ec533Spatrick if (Header.OriginOrWasZeroed != Chunk::Origin::Memalign ||
578d89ec533Spatrick Origin != Chunk::Origin::Malloc)
5793cab2bb3Spatrick reportDeallocTypeMismatch(AllocatorAction::Deallocating, Ptr,
580d89ec533Spatrick Header.OriginOrWasZeroed, Origin);
5813cab2bb3Spatrick }
5823cab2bb3Spatrick }
5833cab2bb3Spatrick
5843cab2bb3Spatrick const uptr Size = getSize(Ptr, &Header);
585d89ec533Spatrick if (DeleteSize && Options.get(OptionBit::DeleteSizeMismatch)) {
5863cab2bb3Spatrick if (UNLIKELY(DeleteSize != Size))
5873cab2bb3Spatrick reportDeleteSizeMismatch(Ptr, DeleteSize, Size);
5883cab2bb3Spatrick }
5893cab2bb3Spatrick
590d89ec533Spatrick quarantineOrDeallocateChunk(Options, TaggedPtr, &Header, Size);
5913cab2bb3Spatrick }
5923cab2bb3Spatrick
5933cab2bb3Spatrick void *reallocate(void *OldPtr, uptr NewSize, uptr Alignment = MinAlignment) {
5943cab2bb3Spatrick initThreadMaybe();
5953cab2bb3Spatrick
596d89ec533Spatrick const Options Options = Primary.Options.load();
5971f9cb04fSpatrick if (UNLIKELY(NewSize >= MaxAllowedMallocSize)) {
598d89ec533Spatrick if (Options.get(OptionBit::MayReturnNull))
5991f9cb04fSpatrick return nullptr;
6001f9cb04fSpatrick reportAllocationSizeTooBig(NewSize, 0, MaxAllowedMallocSize);
6011f9cb04fSpatrick }
6021f9cb04fSpatrick
6033cab2bb3Spatrick // The following cases are handled by the C wrappers.
6043cab2bb3Spatrick DCHECK_NE(OldPtr, nullptr);
6053cab2bb3Spatrick DCHECK_NE(NewSize, 0);
6063cab2bb3Spatrick
6073cab2bb3Spatrick #ifdef GWP_ASAN_HOOKS
6083cab2bb3Spatrick if (UNLIKELY(GuardedAlloc.pointerIsMine(OldPtr))) {
6093cab2bb3Spatrick uptr OldSize = GuardedAlloc.getSize(OldPtr);
6103cab2bb3Spatrick void *NewPtr = allocate(NewSize, Chunk::Origin::Malloc, Alignment);
6113cab2bb3Spatrick if (NewPtr)
6123cab2bb3Spatrick memcpy(NewPtr, OldPtr, (NewSize < OldSize) ? NewSize : OldSize);
6133cab2bb3Spatrick GuardedAlloc.deallocate(OldPtr);
614d89ec533Spatrick Stats.lock();
615d89ec533Spatrick Stats.add(StatFree, GuardedAllocSlotSize);
616d89ec533Spatrick Stats.sub(StatAllocated, GuardedAllocSlotSize);
617d89ec533Spatrick Stats.unlock();
6183cab2bb3Spatrick return NewPtr;
6193cab2bb3Spatrick }
6203cab2bb3Spatrick #endif // GWP_ASAN_HOOKS
6213cab2bb3Spatrick
622d89ec533Spatrick void *OldTaggedPtr = OldPtr;
623d89ec533Spatrick OldPtr = getHeaderTaggedPointer(OldPtr);
624d89ec533Spatrick
6253cab2bb3Spatrick if (UNLIKELY(!isAligned(reinterpret_cast<uptr>(OldPtr), MinAlignment)))
6263cab2bb3Spatrick reportMisalignedPointer(AllocatorAction::Reallocating, OldPtr);
6273cab2bb3Spatrick
6283cab2bb3Spatrick Chunk::UnpackedHeader OldHeader;
6293cab2bb3Spatrick Chunk::loadHeader(Cookie, OldPtr, &OldHeader);
6303cab2bb3Spatrick
6313cab2bb3Spatrick if (UNLIKELY(OldHeader.State != Chunk::State::Allocated))
6323cab2bb3Spatrick reportInvalidChunkState(AllocatorAction::Reallocating, OldPtr);
6333cab2bb3Spatrick
6343cab2bb3Spatrick // Pointer has to be allocated with a malloc-type function. Some
6353cab2bb3Spatrick // applications think that it is OK to realloc a memalign'ed pointer, which
6363cab2bb3Spatrick // will trigger this check. It really isn't.
637d89ec533Spatrick if (Options.get(OptionBit::DeallocTypeMismatch)) {
638d89ec533Spatrick if (UNLIKELY(OldHeader.OriginOrWasZeroed != Chunk::Origin::Malloc))
6393cab2bb3Spatrick reportDeallocTypeMismatch(AllocatorAction::Reallocating, OldPtr,
640d89ec533Spatrick OldHeader.OriginOrWasZeroed,
641d89ec533Spatrick Chunk::Origin::Malloc);
6423cab2bb3Spatrick }
6433cab2bb3Spatrick
644d89ec533Spatrick void *BlockBegin = getBlockBegin(OldTaggedPtr, &OldHeader);
6453cab2bb3Spatrick uptr BlockEnd;
6463cab2bb3Spatrick uptr OldSize;
6473cab2bb3Spatrick const uptr ClassId = OldHeader.ClassId;
6483cab2bb3Spatrick if (LIKELY(ClassId)) {
6493cab2bb3Spatrick BlockEnd = reinterpret_cast<uptr>(BlockBegin) +
6503cab2bb3Spatrick SizeClassMap::getSizeByClassId(ClassId);
6513cab2bb3Spatrick OldSize = OldHeader.SizeOrUnusedBytes;
6523cab2bb3Spatrick } else {
6533cab2bb3Spatrick BlockEnd = SecondaryT::getBlockEnd(BlockBegin);
654d89ec533Spatrick OldSize = BlockEnd - (reinterpret_cast<uptr>(OldTaggedPtr) +
655d89ec533Spatrick OldHeader.SizeOrUnusedBytes);
6563cab2bb3Spatrick }
6573cab2bb3Spatrick // If the new chunk still fits in the previously allocated block (with a
6583cab2bb3Spatrick // reasonable delta), we just keep the old block, and update the chunk
6593cab2bb3Spatrick // header to reflect the size change.
660d89ec533Spatrick if (reinterpret_cast<uptr>(OldTaggedPtr) + NewSize <= BlockEnd) {
6611f9cb04fSpatrick if (NewSize > OldSize || (OldSize - NewSize) < getPageSizeCached()) {
6623cab2bb3Spatrick Chunk::UnpackedHeader NewHeader = OldHeader;
6633cab2bb3Spatrick NewHeader.SizeOrUnusedBytes =
6643cab2bb3Spatrick (ClassId ? NewSize
665d89ec533Spatrick : BlockEnd -
666d89ec533Spatrick (reinterpret_cast<uptr>(OldTaggedPtr) + NewSize)) &
6673cab2bb3Spatrick Chunk::SizeOrUnusedBytesMask;
6683cab2bb3Spatrick Chunk::compareExchangeHeader(Cookie, OldPtr, &NewHeader, &OldHeader);
669d89ec533Spatrick if (UNLIKELY(useMemoryTagging<Params>(Options))) {
670d89ec533Spatrick if (ClassId) {
6711f9cb04fSpatrick resizeTaggedChunk(reinterpret_cast<uptr>(OldTaggedPtr) + OldSize,
6721f9cb04fSpatrick reinterpret_cast<uptr>(OldTaggedPtr) + NewSize,
673d89ec533Spatrick NewSize, untagPointer(BlockEnd));
674d89ec533Spatrick storePrimaryAllocationStackMaybe(Options, OldPtr);
675d89ec533Spatrick } else {
676d89ec533Spatrick storeSecondaryAllocationStackMaybe(Options, OldPtr, NewSize);
677d89ec533Spatrick }
6781f9cb04fSpatrick }
6791f9cb04fSpatrick return OldTaggedPtr;
6803cab2bb3Spatrick }
6813cab2bb3Spatrick }
6823cab2bb3Spatrick
6833cab2bb3Spatrick // Otherwise we allocate a new one, and deallocate the old one. Some
6843cab2bb3Spatrick // allocators will allocate an even larger chunk (by a fixed factor) to
6853cab2bb3Spatrick // allow for potential further in-place realloc. The gains of such a trick
6863cab2bb3Spatrick // are currently unclear.
6873cab2bb3Spatrick void *NewPtr = allocate(NewSize, Chunk::Origin::Malloc, Alignment);
688d89ec533Spatrick if (LIKELY(NewPtr)) {
6891f9cb04fSpatrick memcpy(NewPtr, OldTaggedPtr, Min(NewSize, OldSize));
690d89ec533Spatrick quarantineOrDeallocateChunk(Options, OldTaggedPtr, &OldHeader, OldSize);
6913cab2bb3Spatrick }
6923cab2bb3Spatrick return NewPtr;
6933cab2bb3Spatrick }
6943cab2bb3Spatrick
6953cab2bb3Spatrick // TODO(kostyak): disable() is currently best-effort. There are some small
6963cab2bb3Spatrick // windows of time when an allocation could still succeed after
6973cab2bb3Spatrick // this function finishes. We will revisit that later.
disable()6983cab2bb3Spatrick void disable() {
6993cab2bb3Spatrick initThreadMaybe();
7001f9cb04fSpatrick #ifdef GWP_ASAN_HOOKS
7011f9cb04fSpatrick GuardedAlloc.disable();
7021f9cb04fSpatrick #endif
7033cab2bb3Spatrick TSDRegistry.disable();
7043cab2bb3Spatrick Stats.disable();
7053cab2bb3Spatrick Quarantine.disable();
7063cab2bb3Spatrick Primary.disable();
7073cab2bb3Spatrick Secondary.disable();
7083cab2bb3Spatrick }
7093cab2bb3Spatrick
enable()7103cab2bb3Spatrick void enable() {
7113cab2bb3Spatrick initThreadMaybe();
7123cab2bb3Spatrick Secondary.enable();
7133cab2bb3Spatrick Primary.enable();
7143cab2bb3Spatrick Quarantine.enable();
7153cab2bb3Spatrick Stats.enable();
7163cab2bb3Spatrick TSDRegistry.enable();
7171f9cb04fSpatrick #ifdef GWP_ASAN_HOOKS
7181f9cb04fSpatrick GuardedAlloc.enable();
7191f9cb04fSpatrick #endif
7203cab2bb3Spatrick }
7213cab2bb3Spatrick
7223cab2bb3Spatrick // The function returns the amount of bytes required to store the statistics,
7233cab2bb3Spatrick // which might be larger than the amount of bytes provided. Note that the
7243cab2bb3Spatrick // statistics buffer is not necessarily constant between calls to this
7253cab2bb3Spatrick // function. This can be called with a null buffer or zero size for buffer
7263cab2bb3Spatrick // sizing purposes.
getStats(char * Buffer,uptr Size)7273cab2bb3Spatrick uptr getStats(char *Buffer, uptr Size) {
728d89ec533Spatrick ScopedString Str;
7293cab2bb3Spatrick disable();
7303cab2bb3Spatrick const uptr Length = getStats(&Str) + 1;
7313cab2bb3Spatrick enable();
7323cab2bb3Spatrick if (Length < Size)
7333cab2bb3Spatrick Size = Length;
7343cab2bb3Spatrick if (Buffer && Size) {
7353cab2bb3Spatrick memcpy(Buffer, Str.data(), Size);
7363cab2bb3Spatrick Buffer[Size - 1] = '\0';
7373cab2bb3Spatrick }
7383cab2bb3Spatrick return Length;
7393cab2bb3Spatrick }
7403cab2bb3Spatrick
printStats()7413cab2bb3Spatrick void printStats() {
742d89ec533Spatrick ScopedString Str;
7433cab2bb3Spatrick disable();
7443cab2bb3Spatrick getStats(&Str);
7453cab2bb3Spatrick enable();
7463cab2bb3Spatrick Str.output();
7473cab2bb3Spatrick }
7483cab2bb3Spatrick
releaseToOS()7493cab2bb3Spatrick void releaseToOS() {
7503cab2bb3Spatrick initThreadMaybe();
7513cab2bb3Spatrick Primary.releaseToOS();
7521f9cb04fSpatrick Secondary.releaseToOS();
7533cab2bb3Spatrick }
7543cab2bb3Spatrick
7553cab2bb3Spatrick // Iterate over all chunks and call a callback for all busy chunks located
7563cab2bb3Spatrick // within the provided memory range. Said callback must not use this allocator
7573cab2bb3Spatrick // or a deadlock can ensue. This fits Android's malloc_iterate() needs.
iterateOverChunks(uptr Base,uptr Size,iterate_callback Callback,void * Arg)7583cab2bb3Spatrick void iterateOverChunks(uptr Base, uptr Size, iterate_callback Callback,
7593cab2bb3Spatrick void *Arg) {
7603cab2bb3Spatrick initThreadMaybe();
761d89ec533Spatrick if (archSupportsMemoryTagging())
762d89ec533Spatrick Base = untagPointer(Base);
7633cab2bb3Spatrick const uptr From = Base;
7643cab2bb3Spatrick const uptr To = Base + Size;
765d89ec533Spatrick bool MayHaveTaggedPrimary = allocatorSupportsMemoryTagging<Params>() &&
766d89ec533Spatrick systemSupportsMemoryTagging();
767d89ec533Spatrick auto Lambda = [this, From, To, MayHaveTaggedPrimary, Callback,
768d89ec533Spatrick Arg](uptr Block) {
7693cab2bb3Spatrick if (Block < From || Block >= To)
7703cab2bb3Spatrick return;
7713cab2bb3Spatrick uptr Chunk;
7723cab2bb3Spatrick Chunk::UnpackedHeader Header;
773d89ec533Spatrick if (MayHaveTaggedPrimary) {
774d89ec533Spatrick // A chunk header can either have a zero tag (tagged primary) or the
775d89ec533Spatrick // header tag (secondary, or untagged primary). We don't know which so
776d89ec533Spatrick // try both.
777d89ec533Spatrick ScopedDisableMemoryTagChecks x;
778d89ec533Spatrick if (!getChunkFromBlock(Block, &Chunk, &Header) &&
779d89ec533Spatrick !getChunkFromBlock(addHeaderTag(Block), &Chunk, &Header))
780d89ec533Spatrick return;
781d89ec533Spatrick } else {
782d89ec533Spatrick if (!getChunkFromBlock(addHeaderTag(Block), &Chunk, &Header))
783d89ec533Spatrick return;
784d89ec533Spatrick }
785d89ec533Spatrick if (Header.State == Chunk::State::Allocated) {
7861f9cb04fSpatrick uptr TaggedChunk = Chunk;
787d89ec533Spatrick if (allocatorSupportsMemoryTagging<Params>())
788d89ec533Spatrick TaggedChunk = untagPointer(TaggedChunk);
789d89ec533Spatrick if (useMemoryTagging<Params>(Primary.Options.load()))
7901f9cb04fSpatrick TaggedChunk = loadTag(Chunk);
7911f9cb04fSpatrick Callback(TaggedChunk, getSize(reinterpret_cast<void *>(Chunk), &Header),
7921f9cb04fSpatrick Arg);
7931f9cb04fSpatrick }
7943cab2bb3Spatrick };
7953cab2bb3Spatrick Primary.iterateOverBlocks(Lambda);
7963cab2bb3Spatrick Secondary.iterateOverBlocks(Lambda);
7971f9cb04fSpatrick #ifdef GWP_ASAN_HOOKS
7981f9cb04fSpatrick GuardedAlloc.iterate(reinterpret_cast<void *>(Base), Size, Callback, Arg);
7991f9cb04fSpatrick #endif
8003cab2bb3Spatrick }
8013cab2bb3Spatrick
canReturnNull()8023cab2bb3Spatrick bool canReturnNull() {
8033cab2bb3Spatrick initThreadMaybe();
804d89ec533Spatrick return Primary.Options.load().get(OptionBit::MayReturnNull);
8053cab2bb3Spatrick }
8063cab2bb3Spatrick
setOption(Option O,sptr Value)8071f9cb04fSpatrick bool setOption(Option O, sptr Value) {
808d89ec533Spatrick initThreadMaybe();
809d89ec533Spatrick if (O == Option::MemtagTuning) {
810d89ec533Spatrick // Enabling odd/even tags involves a tradeoff between use-after-free
811d89ec533Spatrick // detection and buffer overflow detection. Odd/even tags make it more
812d89ec533Spatrick // likely for buffer overflows to be detected by increasing the size of
813d89ec533Spatrick // the guaranteed "red zone" around the allocation, but on the other hand
814d89ec533Spatrick // use-after-free is less likely to be detected because the tag space for
815d89ec533Spatrick // any particular chunk is cut in half. Therefore we use this tuning
816d89ec533Spatrick // setting to control whether odd/even tags are enabled.
817d89ec533Spatrick if (Value == M_MEMTAG_TUNING_BUFFER_OVERFLOW)
818d89ec533Spatrick Primary.Options.set(OptionBit::UseOddEvenTags);
819d89ec533Spatrick else if (Value == M_MEMTAG_TUNING_UAF)
820d89ec533Spatrick Primary.Options.clear(OptionBit::UseOddEvenTags);
8211f9cb04fSpatrick return true;
822d89ec533Spatrick } else {
823d89ec533Spatrick // We leave it to the various sub-components to decide whether or not they
824d89ec533Spatrick // want to handle the option, but we do not want to short-circuit
825d89ec533Spatrick // execution if one of the setOption was to return false.
826d89ec533Spatrick const bool PrimaryResult = Primary.setOption(O, Value);
827d89ec533Spatrick const bool SecondaryResult = Secondary.setOption(O, Value);
828d89ec533Spatrick const bool RegistryResult = TSDRegistry.setOption(O, Value);
829d89ec533Spatrick return PrimaryResult && SecondaryResult && RegistryResult;
8301f9cb04fSpatrick }
8311f9cb04fSpatrick return false;
8321f9cb04fSpatrick }
8333cab2bb3Spatrick
8343cab2bb3Spatrick // Return the usable size for a given chunk. Technically we lie, as we just
8353cab2bb3Spatrick // report the actual size of a chunk. This is done to counteract code actively
8363cab2bb3Spatrick // writing past the end of a chunk (like sqlite3) when the usable size allows
8373cab2bb3Spatrick // for it, which then forces realloc to copy the usable size of a chunk as
8383cab2bb3Spatrick // opposed to its actual size.
getUsableSize(const void * Ptr)8393cab2bb3Spatrick uptr getUsableSize(const void *Ptr) {
8403cab2bb3Spatrick initThreadMaybe();
8413cab2bb3Spatrick if (UNLIKELY(!Ptr))
8423cab2bb3Spatrick return 0;
8433cab2bb3Spatrick
8443cab2bb3Spatrick #ifdef GWP_ASAN_HOOKS
8453cab2bb3Spatrick if (UNLIKELY(GuardedAlloc.pointerIsMine(Ptr)))
8463cab2bb3Spatrick return GuardedAlloc.getSize(Ptr);
8473cab2bb3Spatrick #endif // GWP_ASAN_HOOKS
8483cab2bb3Spatrick
849d89ec533Spatrick Ptr = getHeaderTaggedPointer(const_cast<void *>(Ptr));
8503cab2bb3Spatrick Chunk::UnpackedHeader Header;
8513cab2bb3Spatrick Chunk::loadHeader(Cookie, Ptr, &Header);
8523cab2bb3Spatrick // Getting the usable size of a chunk only makes sense if it's allocated.
8533cab2bb3Spatrick if (UNLIKELY(Header.State != Chunk::State::Allocated))
8543cab2bb3Spatrick reportInvalidChunkState(AllocatorAction::Sizing, const_cast<void *>(Ptr));
8553cab2bb3Spatrick return getSize(Ptr, &Header);
8563cab2bb3Spatrick }
8573cab2bb3Spatrick
getStats(StatCounters S)8583cab2bb3Spatrick void getStats(StatCounters S) {
8593cab2bb3Spatrick initThreadMaybe();
8603cab2bb3Spatrick Stats.get(S);
8613cab2bb3Spatrick }
8623cab2bb3Spatrick
8633cab2bb3Spatrick // Returns true if the pointer provided was allocated by the current
8643cab2bb3Spatrick // allocator instance, which is compliant with tcmalloc's ownership concept.
8653cab2bb3Spatrick // A corrupted chunk will not be reported as owned, which is WAI.
isOwned(const void * Ptr)8663cab2bb3Spatrick bool isOwned(const void *Ptr) {
8673cab2bb3Spatrick initThreadMaybe();
8683cab2bb3Spatrick #ifdef GWP_ASAN_HOOKS
8693cab2bb3Spatrick if (GuardedAlloc.pointerIsMine(Ptr))
8703cab2bb3Spatrick return true;
8713cab2bb3Spatrick #endif // GWP_ASAN_HOOKS
8723cab2bb3Spatrick if (!Ptr || !isAligned(reinterpret_cast<uptr>(Ptr), MinAlignment))
8733cab2bb3Spatrick return false;
874d89ec533Spatrick Ptr = getHeaderTaggedPointer(const_cast<void *>(Ptr));
8753cab2bb3Spatrick Chunk::UnpackedHeader Header;
8763cab2bb3Spatrick return Chunk::isValid(Cookie, Ptr, &Header) &&
8773cab2bb3Spatrick Header.State == Chunk::State::Allocated;
8783cab2bb3Spatrick }
8793cab2bb3Spatrick
setRssLimitsTestOnly(int SoftRssLimitMb,int HardRssLimitMb,bool MayReturnNull)880*810390e3Srobert void setRssLimitsTestOnly(int SoftRssLimitMb, int HardRssLimitMb,
881*810390e3Srobert bool MayReturnNull) {
882*810390e3Srobert RssChecker.init(SoftRssLimitMb, HardRssLimitMb);
883*810390e3Srobert if (MayReturnNull)
884*810390e3Srobert Primary.Options.set(OptionBit::MayReturnNull);
885*810390e3Srobert }
886*810390e3Srobert
useMemoryTaggingTestOnly()887d89ec533Spatrick bool useMemoryTaggingTestOnly() const {
888d89ec533Spatrick return useMemoryTagging<Params>(Primary.Options.load());
889d89ec533Spatrick }
disableMemoryTagging()890d89ec533Spatrick void disableMemoryTagging() {
891d89ec533Spatrick // If we haven't been initialized yet, we need to initialize now in order to
892d89ec533Spatrick // prevent a future call to initThreadMaybe() from enabling memory tagging
893d89ec533Spatrick // based on feature detection. But don't call initThreadMaybe() because it
894d89ec533Spatrick // may end up calling the allocator (via pthread_atfork, via the post-init
895d89ec533Spatrick // callback), which may cause mappings to be created with memory tagging
896d89ec533Spatrick // enabled.
897d89ec533Spatrick TSDRegistry.initOnceMaybe(this);
898d89ec533Spatrick if (allocatorSupportsMemoryTagging<Params>()) {
899d89ec533Spatrick Secondary.disableMemoryTagging();
900d89ec533Spatrick Primary.Options.clear(OptionBit::UseMemoryTagging);
901d89ec533Spatrick }
902d89ec533Spatrick }
9031f9cb04fSpatrick
setTrackAllocationStacks(bool Track)9041f9cb04fSpatrick void setTrackAllocationStacks(bool Track) {
9051f9cb04fSpatrick initThreadMaybe();
906*810390e3Srobert if (getFlags()->allocation_ring_buffer_size == 0) {
907*810390e3Srobert DCHECK(!Primary.Options.load().get(OptionBit::TrackAllocationStacks));
908*810390e3Srobert return;
909*810390e3Srobert }
910d89ec533Spatrick if (Track)
911d89ec533Spatrick Primary.Options.set(OptionBit::TrackAllocationStacks);
912d89ec533Spatrick else
913d89ec533Spatrick Primary.Options.clear(OptionBit::TrackAllocationStacks);
9141f9cb04fSpatrick }
9151f9cb04fSpatrick
setFillContents(FillContentsMode FillContents)9161f9cb04fSpatrick void setFillContents(FillContentsMode FillContents) {
9171f9cb04fSpatrick initThreadMaybe();
918d89ec533Spatrick Primary.Options.setFillContentsMode(FillContents);
919d89ec533Spatrick }
920d89ec533Spatrick
setAddLargeAllocationSlack(bool AddSlack)921d89ec533Spatrick void setAddLargeAllocationSlack(bool AddSlack) {
922d89ec533Spatrick initThreadMaybe();
923d89ec533Spatrick if (AddSlack)
924d89ec533Spatrick Primary.Options.set(OptionBit::AddLargeAllocationSlack);
925d89ec533Spatrick else
926d89ec533Spatrick Primary.Options.clear(OptionBit::AddLargeAllocationSlack);
9271f9cb04fSpatrick }
9281f9cb04fSpatrick
getStackDepotAddress()9291f9cb04fSpatrick const char *getStackDepotAddress() const {
9301f9cb04fSpatrick return reinterpret_cast<const char *>(&Depot);
9311f9cb04fSpatrick }
9321f9cb04fSpatrick
getRegionInfoArrayAddress()9331f9cb04fSpatrick const char *getRegionInfoArrayAddress() const {
9341f9cb04fSpatrick return Primary.getRegionInfoArrayAddress();
9351f9cb04fSpatrick }
9361f9cb04fSpatrick
getRegionInfoArraySize()9371f9cb04fSpatrick static uptr getRegionInfoArraySize() {
9381f9cb04fSpatrick return PrimaryT::getRegionInfoArraySize();
9391f9cb04fSpatrick }
9401f9cb04fSpatrick
getRingBufferAddress()941*810390e3Srobert const char *getRingBufferAddress() {
942*810390e3Srobert initThreadMaybe();
943*810390e3Srobert return RawRingBuffer;
944d89ec533Spatrick }
9451f9cb04fSpatrick
getRingBufferSize()946*810390e3Srobert uptr getRingBufferSize() {
947*810390e3Srobert initThreadMaybe();
948*810390e3Srobert auto *RingBuffer = getRingBuffer();
949*810390e3Srobert return RingBuffer ? ringBufferSizeInBytes(RingBuffer->Size) : 0;
950*810390e3Srobert }
951*810390e3Srobert
setRingBufferSizeForBuffer(char * Buffer,size_t Size)952*810390e3Srobert static bool setRingBufferSizeForBuffer(char *Buffer, size_t Size) {
953*810390e3Srobert // Need at least one entry.
954*810390e3Srobert if (Size < sizeof(AllocationRingBuffer) +
955*810390e3Srobert sizeof(typename AllocationRingBuffer::Entry)) {
956*810390e3Srobert return false;
957*810390e3Srobert }
958*810390e3Srobert AllocationRingBuffer *RingBuffer =
959*810390e3Srobert reinterpret_cast<AllocationRingBuffer *>(Buffer);
960*810390e3Srobert RingBuffer->Size = (Size - sizeof(AllocationRingBuffer)) /
961*810390e3Srobert sizeof(typename AllocationRingBuffer::Entry);
962*810390e3Srobert return true;
963*810390e3Srobert }
9641f9cb04fSpatrick
965d89ec533Spatrick static const uptr MaxTraceSize = 64;
9661f9cb04fSpatrick
collectTraceMaybe(const StackDepot * Depot,uintptr_t (& Trace)[MaxTraceSize],u32 Hash)967d89ec533Spatrick static void collectTraceMaybe(const StackDepot *Depot,
968d89ec533Spatrick uintptr_t (&Trace)[MaxTraceSize], u32 Hash) {
9691f9cb04fSpatrick uptr RingPos, Size;
9701f9cb04fSpatrick if (!Depot->find(Hash, &RingPos, &Size))
9711f9cb04fSpatrick return;
9721f9cb04fSpatrick for (unsigned I = 0; I != Size && I != MaxTraceSize; ++I)
973*810390e3Srobert Trace[I] = static_cast<uintptr_t>((*Depot)[RingPos + I]);
974d89ec533Spatrick }
9751f9cb04fSpatrick
getErrorInfo(struct scudo_error_info * ErrorInfo,uintptr_t FaultAddr,const char * DepotPtr,const char * RegionInfoPtr,const char * RingBufferPtr,const char * Memory,const char * MemoryTags,uintptr_t MemoryAddr,size_t MemorySize)976d89ec533Spatrick static void getErrorInfo(struct scudo_error_info *ErrorInfo,
977d89ec533Spatrick uintptr_t FaultAddr, const char *DepotPtr,
978d89ec533Spatrick const char *RegionInfoPtr, const char *RingBufferPtr,
979d89ec533Spatrick const char *Memory, const char *MemoryTags,
980d89ec533Spatrick uintptr_t MemoryAddr, size_t MemorySize) {
981d89ec533Spatrick *ErrorInfo = {};
982d89ec533Spatrick if (!allocatorSupportsMemoryTagging<Params>() ||
983d89ec533Spatrick MemoryAddr + MemorySize < MemoryAddr)
984d89ec533Spatrick return;
985d89ec533Spatrick
986d89ec533Spatrick auto *Depot = reinterpret_cast<const StackDepot *>(DepotPtr);
9871f9cb04fSpatrick size_t NextErrorReport = 0;
9881f9cb04fSpatrick
989d89ec533Spatrick // Check for OOB in the current block and the two surrounding blocks. Beyond
990d89ec533Spatrick // that, UAF is more likely.
991d89ec533Spatrick if (extractTag(FaultAddr) != 0)
992d89ec533Spatrick getInlineErrorInfo(ErrorInfo, NextErrorReport, FaultAddr, Depot,
993d89ec533Spatrick RegionInfoPtr, Memory, MemoryTags, MemoryAddr,
994d89ec533Spatrick MemorySize, 0, 2);
9951f9cb04fSpatrick
996d89ec533Spatrick // Check the ring buffer. For primary allocations this will only find UAF;
997d89ec533Spatrick // for secondary allocations we can find either UAF or OOB.
998d89ec533Spatrick getRingBufferErrorInfo(ErrorInfo, NextErrorReport, FaultAddr, Depot,
999d89ec533Spatrick RingBufferPtr);
10001f9cb04fSpatrick
1001d89ec533Spatrick // Check for OOB in the 28 blocks surrounding the 3 we checked earlier.
1002d89ec533Spatrick // Beyond that we are likely to hit false positives.
1003d89ec533Spatrick if (extractTag(FaultAddr) != 0)
1004d89ec533Spatrick getInlineErrorInfo(ErrorInfo, NextErrorReport, FaultAddr, Depot,
1005d89ec533Spatrick RegionInfoPtr, Memory, MemoryTags, MemoryAddr,
1006d89ec533Spatrick MemorySize, 2, 16);
10071f9cb04fSpatrick }
10081f9cb04fSpatrick
10093cab2bb3Spatrick private:
1010d89ec533Spatrick using SecondaryT = MapAllocator<Params>;
10113cab2bb3Spatrick typedef typename PrimaryT::SizeClassMap SizeClassMap;
10123cab2bb3Spatrick
10133cab2bb3Spatrick static const uptr MinAlignmentLog = SCUDO_MIN_ALIGNMENT_LOG;
10143cab2bb3Spatrick static const uptr MaxAlignmentLog = 24U; // 16 MB seems reasonable.
10153cab2bb3Spatrick static const uptr MinAlignment = 1UL << MinAlignmentLog;
10163cab2bb3Spatrick static const uptr MaxAlignment = 1UL << MaxAlignmentLog;
10173cab2bb3Spatrick static const uptr MaxAllowedMallocSize =
10183cab2bb3Spatrick FIRST_32_SECOND_64(1UL << 31, 1ULL << 40);
10193cab2bb3Spatrick
10203cab2bb3Spatrick static_assert(MinAlignment >= sizeof(Chunk::PackedHeader),
10213cab2bb3Spatrick "Minimal alignment must at least cover a chunk header.");
1022d89ec533Spatrick static_assert(!allocatorSupportsMemoryTagging<Params>() ||
10231f9cb04fSpatrick MinAlignment >= archMemoryTagGranuleSize(),
10241f9cb04fSpatrick "");
10253cab2bb3Spatrick
10263cab2bb3Spatrick static const u32 BlockMarker = 0x44554353U;
10273cab2bb3Spatrick
10281f9cb04fSpatrick // These are indexes into an "array" of 32-bit values that store information
10291f9cb04fSpatrick // inline with a chunk that is relevant to diagnosing memory tag faults, where
1030d89ec533Spatrick // 0 corresponds to the address of the user memory. This means that only
1031d89ec533Spatrick // negative indexes may be used. The smallest index that may be used is -2,
1032d89ec533Spatrick // which corresponds to 8 bytes before the user memory, because the chunk
1033d89ec533Spatrick // header size is 8 bytes and in allocators that support memory tagging the
1034d89ec533Spatrick // minimum alignment is at least the tag granule size (16 on aarch64).
10351f9cb04fSpatrick static const sptr MemTagAllocationTraceIndex = -2;
10361f9cb04fSpatrick static const sptr MemTagAllocationTidIndex = -1;
10371f9cb04fSpatrick
1038d89ec533Spatrick u32 Cookie = 0;
1039d89ec533Spatrick u32 QuarantineMaxChunkSize = 0;
10401f9cb04fSpatrick
10413cab2bb3Spatrick GlobalStats Stats;
10423cab2bb3Spatrick PrimaryT Primary;
10433cab2bb3Spatrick SecondaryT Secondary;
10443cab2bb3Spatrick QuarantineT Quarantine;
1045d89ec533Spatrick TSDRegistryT TSDRegistry;
1046d89ec533Spatrick pthread_once_t PostInitNonce = PTHREAD_ONCE_INIT;
1047*810390e3Srobert RssLimitChecker RssChecker;
10483cab2bb3Spatrick
10491f9cb04fSpatrick #ifdef GWP_ASAN_HOOKS
10501f9cb04fSpatrick gwp_asan::GuardedPoolAllocator GuardedAlloc;
1051d89ec533Spatrick uptr GuardedAllocSlotSize = 0;
10521f9cb04fSpatrick #endif // GWP_ASAN_HOOKS
10531f9cb04fSpatrick
10541f9cb04fSpatrick StackDepot Depot;
10551f9cb04fSpatrick
1056d89ec533Spatrick struct AllocationRingBuffer {
1057d89ec533Spatrick struct Entry {
1058d89ec533Spatrick atomic_uptr Ptr;
1059d89ec533Spatrick atomic_uptr AllocationSize;
1060d89ec533Spatrick atomic_u32 AllocationTrace;
1061d89ec533Spatrick atomic_u32 AllocationTid;
1062d89ec533Spatrick atomic_u32 DeallocationTrace;
1063d89ec533Spatrick atomic_u32 DeallocationTid;
1064d89ec533Spatrick };
1065d89ec533Spatrick
1066d89ec533Spatrick atomic_uptr Pos;
1067*810390e3Srobert u32 Size;
1068*810390e3Srobert // An array of Size (at least one) elements of type Entry is immediately
1069*810390e3Srobert // following to this struct.
1070d89ec533Spatrick };
1071*810390e3Srobert // Pointer to memory mapped area starting with AllocationRingBuffer struct,
1072*810390e3Srobert // and immediately followed by Size elements of type Entry.
1073*810390e3Srobert char *RawRingBuffer = {};
1074d89ec533Spatrick
10753cab2bb3Spatrick // The following might get optimized out by the compiler.
performSanityChecks()10763cab2bb3Spatrick NOINLINE void performSanityChecks() {
10773cab2bb3Spatrick // Verify that the header offset field can hold the maximum offset. In the
10783cab2bb3Spatrick // case of the Secondary allocator, it takes care of alignment and the
10793cab2bb3Spatrick // offset will always be small. In the case of the Primary, the worst case
10803cab2bb3Spatrick // scenario happens in the last size class, when the backend allocation
10813cab2bb3Spatrick // would already be aligned on the requested alignment, which would happen
10823cab2bb3Spatrick // to be the maximum alignment that would fit in that size class. As a
10833cab2bb3Spatrick // result, the maximum offset will be at most the maximum alignment for the
10843cab2bb3Spatrick // last size class minus the header size, in multiples of MinAlignment.
10853cab2bb3Spatrick Chunk::UnpackedHeader Header = {};
10863cab2bb3Spatrick const uptr MaxPrimaryAlignment = 1UL << getMostSignificantSetBitIndex(
10873cab2bb3Spatrick SizeClassMap::MaxSize - MinAlignment);
10883cab2bb3Spatrick const uptr MaxOffset =
10893cab2bb3Spatrick (MaxPrimaryAlignment - Chunk::getHeaderSize()) >> MinAlignmentLog;
10903cab2bb3Spatrick Header.Offset = MaxOffset & Chunk::OffsetMask;
10913cab2bb3Spatrick if (UNLIKELY(Header.Offset != MaxOffset))
10923cab2bb3Spatrick reportSanityCheckError("offset");
10933cab2bb3Spatrick
10943cab2bb3Spatrick // Verify that we can fit the maximum size or amount of unused bytes in the
10953cab2bb3Spatrick // header. Given that the Secondary fits the allocation to a page, the worst
10963cab2bb3Spatrick // case scenario happens in the Primary. It will depend on the second to
10973cab2bb3Spatrick // last and last class sizes, as well as the dynamic base for the Primary.
10983cab2bb3Spatrick // The following is an over-approximation that works for our needs.
10993cab2bb3Spatrick const uptr MaxSizeOrUnusedBytes = SizeClassMap::MaxSize - 1;
11003cab2bb3Spatrick Header.SizeOrUnusedBytes = MaxSizeOrUnusedBytes;
11013cab2bb3Spatrick if (UNLIKELY(Header.SizeOrUnusedBytes != MaxSizeOrUnusedBytes))
11023cab2bb3Spatrick reportSanityCheckError("size (or unused bytes)");
11033cab2bb3Spatrick
11043cab2bb3Spatrick const uptr LargestClassId = SizeClassMap::LargestClassId;
11053cab2bb3Spatrick Header.ClassId = LargestClassId;
11063cab2bb3Spatrick if (UNLIKELY(Header.ClassId != LargestClassId))
11073cab2bb3Spatrick reportSanityCheckError("class ID");
11083cab2bb3Spatrick }
11093cab2bb3Spatrick
getBlockBegin(const void * Ptr,Chunk::UnpackedHeader * Header)11103cab2bb3Spatrick static inline void *getBlockBegin(const void *Ptr,
11113cab2bb3Spatrick Chunk::UnpackedHeader *Header) {
11123cab2bb3Spatrick return reinterpret_cast<void *>(
11133cab2bb3Spatrick reinterpret_cast<uptr>(Ptr) - Chunk::getHeaderSize() -
11143cab2bb3Spatrick (static_cast<uptr>(Header->Offset) << MinAlignmentLog));
11153cab2bb3Spatrick }
11163cab2bb3Spatrick
11173cab2bb3Spatrick // Return the size of a chunk as requested during its allocation.
getSize(const void * Ptr,Chunk::UnpackedHeader * Header)11183cab2bb3Spatrick inline uptr getSize(const void *Ptr, Chunk::UnpackedHeader *Header) {
11193cab2bb3Spatrick const uptr SizeOrUnusedBytes = Header->SizeOrUnusedBytes;
11203cab2bb3Spatrick if (LIKELY(Header->ClassId))
11213cab2bb3Spatrick return SizeOrUnusedBytes;
1122d89ec533Spatrick if (allocatorSupportsMemoryTagging<Params>())
1123d89ec533Spatrick Ptr = untagPointer(const_cast<void *>(Ptr));
11243cab2bb3Spatrick return SecondaryT::getBlockEnd(getBlockBegin(Ptr, Header)) -
11253cab2bb3Spatrick reinterpret_cast<uptr>(Ptr) - SizeOrUnusedBytes;
11263cab2bb3Spatrick }
11273cab2bb3Spatrick
quarantineOrDeallocateChunk(Options Options,void * TaggedPtr,Chunk::UnpackedHeader * Header,uptr Size)1128d89ec533Spatrick void quarantineOrDeallocateChunk(Options Options, void *TaggedPtr,
1129d89ec533Spatrick Chunk::UnpackedHeader *Header, uptr Size) {
1130d89ec533Spatrick void *Ptr = getHeaderTaggedPointer(TaggedPtr);
11313cab2bb3Spatrick Chunk::UnpackedHeader NewHeader = *Header;
11323cab2bb3Spatrick // If the quarantine is disabled, the actual size of a chunk is 0 or larger
11333cab2bb3Spatrick // than the maximum allowed, we return a chunk directly to the backend.
1134d89ec533Spatrick // This purposefully underflows for Size == 0.
1135d89ec533Spatrick const bool BypassQuarantine = !Quarantine.getCacheSize() ||
1136d89ec533Spatrick ((Size - 1) >= QuarantineMaxChunkSize) ||
1137d89ec533Spatrick !NewHeader.ClassId;
1138d89ec533Spatrick if (BypassQuarantine)
11393cab2bb3Spatrick NewHeader.State = Chunk::State::Available;
1140d89ec533Spatrick else
1141d89ec533Spatrick NewHeader.State = Chunk::State::Quarantined;
1142d89ec533Spatrick NewHeader.OriginOrWasZeroed = useMemoryTagging<Params>(Options) &&
1143d89ec533Spatrick NewHeader.ClassId &&
1144d89ec533Spatrick !TSDRegistry.getDisableMemInit();
11453cab2bb3Spatrick Chunk::compareExchangeHeader(Cookie, Ptr, &NewHeader, Header);
1146d89ec533Spatrick
1147d89ec533Spatrick if (UNLIKELY(useMemoryTagging<Params>(Options))) {
1148d89ec533Spatrick u8 PrevTag = extractTag(reinterpret_cast<uptr>(TaggedPtr));
1149d89ec533Spatrick storeDeallocationStackMaybe(Options, Ptr, PrevTag, Size);
1150d89ec533Spatrick if (NewHeader.ClassId) {
1151d89ec533Spatrick if (!TSDRegistry.getDisableMemInit()) {
1152d89ec533Spatrick uptr TaggedBegin, TaggedEnd;
1153d89ec533Spatrick const uptr OddEvenMask = computeOddEvenMaskForPointerMaybe(
1154d89ec533Spatrick Options, reinterpret_cast<uptr>(getBlockBegin(Ptr, &NewHeader)),
1155d89ec533Spatrick NewHeader.ClassId);
1156d89ec533Spatrick // Exclude the previous tag so that immediate use after free is
1157d89ec533Spatrick // detected 100% of the time.
1158d89ec533Spatrick setRandomTag(Ptr, Size, OddEvenMask | (1UL << PrevTag), &TaggedBegin,
1159d89ec533Spatrick &TaggedEnd);
1160d89ec533Spatrick }
1161d89ec533Spatrick }
1162d89ec533Spatrick }
1163d89ec533Spatrick if (BypassQuarantine) {
1164d89ec533Spatrick if (allocatorSupportsMemoryTagging<Params>())
1165d89ec533Spatrick Ptr = untagPointer(Ptr);
11663cab2bb3Spatrick void *BlockBegin = getBlockBegin(Ptr, &NewHeader);
11673cab2bb3Spatrick const uptr ClassId = NewHeader.ClassId;
11683cab2bb3Spatrick if (LIKELY(ClassId)) {
11693cab2bb3Spatrick bool UnlockRequired;
11703cab2bb3Spatrick auto *TSD = TSDRegistry.getTSDAndLock(&UnlockRequired);
11713cab2bb3Spatrick TSD->Cache.deallocate(ClassId, BlockBegin);
11723cab2bb3Spatrick if (UnlockRequired)
11733cab2bb3Spatrick TSD->unlock();
11743cab2bb3Spatrick } else {
1175d89ec533Spatrick if (UNLIKELY(useMemoryTagging<Params>(Options)))
1176d89ec533Spatrick storeTags(reinterpret_cast<uptr>(BlockBegin),
1177d89ec533Spatrick reinterpret_cast<uptr>(Ptr));
1178d89ec533Spatrick Secondary.deallocate(Options, BlockBegin);
11793cab2bb3Spatrick }
11803cab2bb3Spatrick } else {
11813cab2bb3Spatrick bool UnlockRequired;
11823cab2bb3Spatrick auto *TSD = TSDRegistry.getTSDAndLock(&UnlockRequired);
11833cab2bb3Spatrick Quarantine.put(&TSD->QuarantineCache,
11843cab2bb3Spatrick QuarantineCallback(*this, TSD->Cache), Ptr, Size);
11853cab2bb3Spatrick if (UnlockRequired)
11863cab2bb3Spatrick TSD->unlock();
11873cab2bb3Spatrick }
11883cab2bb3Spatrick }
11893cab2bb3Spatrick
getChunkFromBlock(uptr Block,uptr * Chunk,Chunk::UnpackedHeader * Header)11903cab2bb3Spatrick bool getChunkFromBlock(uptr Block, uptr *Chunk,
11913cab2bb3Spatrick Chunk::UnpackedHeader *Header) {
11921f9cb04fSpatrick *Chunk =
11931f9cb04fSpatrick Block + getChunkOffsetFromBlock(reinterpret_cast<const char *>(Block));
11943cab2bb3Spatrick return Chunk::isValid(Cookie, reinterpret_cast<void *>(*Chunk), Header);
11953cab2bb3Spatrick }
11963cab2bb3Spatrick
getChunkOffsetFromBlock(const char * Block)11971f9cb04fSpatrick static uptr getChunkOffsetFromBlock(const char *Block) {
11981f9cb04fSpatrick u32 Offset = 0;
11991f9cb04fSpatrick if (reinterpret_cast<const u32 *>(Block)[0] == BlockMarker)
12001f9cb04fSpatrick Offset = reinterpret_cast<const u32 *>(Block)[1];
12011f9cb04fSpatrick return Offset + Chunk::getHeaderSize();
12021f9cb04fSpatrick }
12031f9cb04fSpatrick
1204d89ec533Spatrick // Set the tag of the granule past the end of the allocation to 0, to catch
1205d89ec533Spatrick // linear overflows even if a previous larger allocation used the same block
1206d89ec533Spatrick // and tag. Only do this if the granule past the end is in our block, because
1207d89ec533Spatrick // this would otherwise lead to a SEGV if the allocation covers the entire
1208d89ec533Spatrick // block and our block is at the end of a mapping. The tag of the next block's
1209d89ec533Spatrick // header granule will be set to 0, so it will serve the purpose of catching
1210d89ec533Spatrick // linear overflows in this case.
1211d89ec533Spatrick //
1212d89ec533Spatrick // For allocations of size 0 we do not end up storing the address tag to the
1213d89ec533Spatrick // memory tag space, which getInlineErrorInfo() normally relies on to match
1214d89ec533Spatrick // address tags against chunks. To allow matching in this case we store the
1215d89ec533Spatrick // address tag in the first byte of the chunk.
storeEndMarker(uptr End,uptr Size,uptr BlockEnd)1216d89ec533Spatrick void storeEndMarker(uptr End, uptr Size, uptr BlockEnd) {
1217d89ec533Spatrick DCHECK_EQ(BlockEnd, untagPointer(BlockEnd));
1218d89ec533Spatrick uptr UntaggedEnd = untagPointer(End);
1219d89ec533Spatrick if (UntaggedEnd != BlockEnd) {
1220d89ec533Spatrick storeTag(UntaggedEnd);
1221d89ec533Spatrick if (Size == 0)
1222d89ec533Spatrick *reinterpret_cast<u8 *>(UntaggedEnd) = extractTag(End);
1223d89ec533Spatrick }
1224d89ec533Spatrick }
1225d89ec533Spatrick
prepareTaggedChunk(void * Ptr,uptr Size,uptr ExcludeMask,uptr BlockEnd)1226d89ec533Spatrick void *prepareTaggedChunk(void *Ptr, uptr Size, uptr ExcludeMask,
1227d89ec533Spatrick uptr BlockEnd) {
1228d89ec533Spatrick // Prepare the granule before the chunk to store the chunk header by setting
1229d89ec533Spatrick // its tag to 0. Normally its tag will already be 0, but in the case where a
1230d89ec533Spatrick // chunk holding a low alignment allocation is reused for a higher alignment
1231d89ec533Spatrick // allocation, the chunk may already have a non-zero tag from the previous
1232d89ec533Spatrick // allocation.
1233d89ec533Spatrick storeTag(reinterpret_cast<uptr>(Ptr) - archMemoryTagGranuleSize());
1234d89ec533Spatrick
1235d89ec533Spatrick uptr TaggedBegin, TaggedEnd;
1236d89ec533Spatrick setRandomTag(Ptr, Size, ExcludeMask, &TaggedBegin, &TaggedEnd);
1237d89ec533Spatrick
1238d89ec533Spatrick storeEndMarker(TaggedEnd, Size, BlockEnd);
1239d89ec533Spatrick return reinterpret_cast<void *>(TaggedBegin);
1240d89ec533Spatrick }
1241d89ec533Spatrick
resizeTaggedChunk(uptr OldPtr,uptr NewPtr,uptr NewSize,uptr BlockEnd)1242d89ec533Spatrick void resizeTaggedChunk(uptr OldPtr, uptr NewPtr, uptr NewSize,
1243d89ec533Spatrick uptr BlockEnd) {
1244d89ec533Spatrick uptr RoundOldPtr = roundUpTo(OldPtr, archMemoryTagGranuleSize());
1245d89ec533Spatrick uptr RoundNewPtr;
1246d89ec533Spatrick if (RoundOldPtr >= NewPtr) {
1247d89ec533Spatrick // If the allocation is shrinking we just need to set the tag past the end
1248d89ec533Spatrick // of the allocation to 0. See explanation in storeEndMarker() above.
1249d89ec533Spatrick RoundNewPtr = roundUpTo(NewPtr, archMemoryTagGranuleSize());
1250d89ec533Spatrick } else {
1251d89ec533Spatrick // Set the memory tag of the region
1252d89ec533Spatrick // [RoundOldPtr, roundUpTo(NewPtr, archMemoryTagGranuleSize()))
1253d89ec533Spatrick // to the pointer tag stored in OldPtr.
1254d89ec533Spatrick RoundNewPtr = storeTags(RoundOldPtr, NewPtr);
1255d89ec533Spatrick }
1256d89ec533Spatrick storeEndMarker(RoundNewPtr, NewSize, BlockEnd);
1257d89ec533Spatrick }
1258d89ec533Spatrick
storePrimaryAllocationStackMaybe(Options Options,void * Ptr)1259d89ec533Spatrick void storePrimaryAllocationStackMaybe(Options Options, void *Ptr) {
1260d89ec533Spatrick if (!UNLIKELY(Options.get(OptionBit::TrackAllocationStacks)))
12611f9cb04fSpatrick return;
12621f9cb04fSpatrick auto *Ptr32 = reinterpret_cast<u32 *>(Ptr);
12631f9cb04fSpatrick Ptr32[MemTagAllocationTraceIndex] = collectStackTrace();
12641f9cb04fSpatrick Ptr32[MemTagAllocationTidIndex] = getThreadID();
12651f9cb04fSpatrick }
12661f9cb04fSpatrick
storeRingBufferEntry(void * Ptr,u32 AllocationTrace,u32 AllocationTid,uptr AllocationSize,u32 DeallocationTrace,u32 DeallocationTid)1267d89ec533Spatrick void storeRingBufferEntry(void *Ptr, u32 AllocationTrace, u32 AllocationTid,
1268d89ec533Spatrick uptr AllocationSize, u32 DeallocationTrace,
1269d89ec533Spatrick u32 DeallocationTid) {
1270*810390e3Srobert uptr Pos = atomic_fetch_add(&getRingBuffer()->Pos, 1, memory_order_relaxed);
1271d89ec533Spatrick typename AllocationRingBuffer::Entry *Entry =
1272*810390e3Srobert getRingBufferEntry(RawRingBuffer, Pos % getRingBuffer()->Size);
1273d89ec533Spatrick
1274d89ec533Spatrick // First invalidate our entry so that we don't attempt to interpret a
1275d89ec533Spatrick // partially written state in getSecondaryErrorInfo(). The fences below
1276d89ec533Spatrick // ensure that the compiler does not move the stores to Ptr in between the
1277d89ec533Spatrick // stores to the other fields.
1278d89ec533Spatrick atomic_store_relaxed(&Entry->Ptr, 0);
1279d89ec533Spatrick
1280d89ec533Spatrick __atomic_signal_fence(__ATOMIC_SEQ_CST);
1281d89ec533Spatrick atomic_store_relaxed(&Entry->AllocationTrace, AllocationTrace);
1282d89ec533Spatrick atomic_store_relaxed(&Entry->AllocationTid, AllocationTid);
1283d89ec533Spatrick atomic_store_relaxed(&Entry->AllocationSize, AllocationSize);
1284d89ec533Spatrick atomic_store_relaxed(&Entry->DeallocationTrace, DeallocationTrace);
1285d89ec533Spatrick atomic_store_relaxed(&Entry->DeallocationTid, DeallocationTid);
1286d89ec533Spatrick __atomic_signal_fence(__ATOMIC_SEQ_CST);
1287d89ec533Spatrick
1288d89ec533Spatrick atomic_store_relaxed(&Entry->Ptr, reinterpret_cast<uptr>(Ptr));
1289d89ec533Spatrick }
1290d89ec533Spatrick
storeSecondaryAllocationStackMaybe(Options Options,void * Ptr,uptr Size)1291d89ec533Spatrick void storeSecondaryAllocationStackMaybe(Options Options, void *Ptr,
1292d89ec533Spatrick uptr Size) {
1293d89ec533Spatrick if (!UNLIKELY(Options.get(OptionBit::TrackAllocationStacks)))
12941f9cb04fSpatrick return;
12951f9cb04fSpatrick
1296d89ec533Spatrick u32 Trace = collectStackTrace();
1297d89ec533Spatrick u32 Tid = getThreadID();
1298d89ec533Spatrick
12991f9cb04fSpatrick auto *Ptr32 = reinterpret_cast<u32 *>(Ptr);
1300d89ec533Spatrick Ptr32[MemTagAllocationTraceIndex] = Trace;
1301d89ec533Spatrick Ptr32[MemTagAllocationTidIndex] = Tid;
1302d89ec533Spatrick
1303d89ec533Spatrick storeRingBufferEntry(untagPointer(Ptr), Trace, Tid, Size, 0, 0);
1304d89ec533Spatrick }
1305d89ec533Spatrick
storeDeallocationStackMaybe(Options Options,void * Ptr,u8 PrevTag,uptr Size)1306d89ec533Spatrick void storeDeallocationStackMaybe(Options Options, void *Ptr, u8 PrevTag,
1307d89ec533Spatrick uptr Size) {
1308d89ec533Spatrick if (!UNLIKELY(Options.get(OptionBit::TrackAllocationStacks)))
1309d89ec533Spatrick return;
1310d89ec533Spatrick
1311d89ec533Spatrick auto *Ptr32 = reinterpret_cast<u32 *>(Ptr);
1312d89ec533Spatrick u32 AllocationTrace = Ptr32[MemTagAllocationTraceIndex];
1313d89ec533Spatrick u32 AllocationTid = Ptr32[MemTagAllocationTidIndex];
1314d89ec533Spatrick
1315d89ec533Spatrick u32 DeallocationTrace = collectStackTrace();
1316d89ec533Spatrick u32 DeallocationTid = getThreadID();
1317d89ec533Spatrick
1318d89ec533Spatrick storeRingBufferEntry(addFixedTag(untagPointer(Ptr), PrevTag),
1319d89ec533Spatrick AllocationTrace, AllocationTid, Size,
1320d89ec533Spatrick DeallocationTrace, DeallocationTid);
1321d89ec533Spatrick }
1322d89ec533Spatrick
1323d89ec533Spatrick static const size_t NumErrorReports =
1324*810390e3Srobert sizeof(((scudo_error_info *)nullptr)->reports) /
1325*810390e3Srobert sizeof(((scudo_error_info *)nullptr)->reports[0]);
1326d89ec533Spatrick
getInlineErrorInfo(struct scudo_error_info * ErrorInfo,size_t & NextErrorReport,uintptr_t FaultAddr,const StackDepot * Depot,const char * RegionInfoPtr,const char * Memory,const char * MemoryTags,uintptr_t MemoryAddr,size_t MemorySize,size_t MinDistance,size_t MaxDistance)1327d89ec533Spatrick static void getInlineErrorInfo(struct scudo_error_info *ErrorInfo,
1328d89ec533Spatrick size_t &NextErrorReport, uintptr_t FaultAddr,
1329d89ec533Spatrick const StackDepot *Depot,
1330d89ec533Spatrick const char *RegionInfoPtr, const char *Memory,
1331d89ec533Spatrick const char *MemoryTags, uintptr_t MemoryAddr,
1332d89ec533Spatrick size_t MemorySize, size_t MinDistance,
1333d89ec533Spatrick size_t MaxDistance) {
1334d89ec533Spatrick uptr UntaggedFaultAddr = untagPointer(FaultAddr);
1335d89ec533Spatrick u8 FaultAddrTag = extractTag(FaultAddr);
1336d89ec533Spatrick BlockInfo Info =
1337d89ec533Spatrick PrimaryT::findNearestBlock(RegionInfoPtr, UntaggedFaultAddr);
1338d89ec533Spatrick
1339d89ec533Spatrick auto GetGranule = [&](uptr Addr, const char **Data, uint8_t *Tag) -> bool {
1340d89ec533Spatrick if (Addr < MemoryAddr || Addr + archMemoryTagGranuleSize() < Addr ||
1341d89ec533Spatrick Addr + archMemoryTagGranuleSize() > MemoryAddr + MemorySize)
1342d89ec533Spatrick return false;
1343d89ec533Spatrick *Data = &Memory[Addr - MemoryAddr];
1344d89ec533Spatrick *Tag = static_cast<u8>(
1345d89ec533Spatrick MemoryTags[(Addr - MemoryAddr) / archMemoryTagGranuleSize()]);
1346d89ec533Spatrick return true;
1347d89ec533Spatrick };
1348d89ec533Spatrick
1349d89ec533Spatrick auto ReadBlock = [&](uptr Addr, uptr *ChunkAddr,
1350d89ec533Spatrick Chunk::UnpackedHeader *Header, const u32 **Data,
1351d89ec533Spatrick u8 *Tag) {
1352d89ec533Spatrick const char *BlockBegin;
1353d89ec533Spatrick u8 BlockBeginTag;
1354d89ec533Spatrick if (!GetGranule(Addr, &BlockBegin, &BlockBeginTag))
1355d89ec533Spatrick return false;
1356d89ec533Spatrick uptr ChunkOffset = getChunkOffsetFromBlock(BlockBegin);
1357d89ec533Spatrick *ChunkAddr = Addr + ChunkOffset;
1358d89ec533Spatrick
1359d89ec533Spatrick const char *ChunkBegin;
1360d89ec533Spatrick if (!GetGranule(*ChunkAddr, &ChunkBegin, Tag))
1361d89ec533Spatrick return false;
1362d89ec533Spatrick *Header = *reinterpret_cast<const Chunk::UnpackedHeader *>(
1363d89ec533Spatrick ChunkBegin - Chunk::getHeaderSize());
1364d89ec533Spatrick *Data = reinterpret_cast<const u32 *>(ChunkBegin);
1365d89ec533Spatrick
1366d89ec533Spatrick // Allocations of size 0 will have stashed the tag in the first byte of
1367d89ec533Spatrick // the chunk, see storeEndMarker().
1368d89ec533Spatrick if (Header->SizeOrUnusedBytes == 0)
1369d89ec533Spatrick *Tag = static_cast<u8>(*ChunkBegin);
1370d89ec533Spatrick
1371d89ec533Spatrick return true;
1372d89ec533Spatrick };
1373d89ec533Spatrick
1374d89ec533Spatrick if (NextErrorReport == NumErrorReports)
1375d89ec533Spatrick return;
1376d89ec533Spatrick
1377d89ec533Spatrick auto CheckOOB = [&](uptr BlockAddr) {
1378d89ec533Spatrick if (BlockAddr < Info.RegionBegin || BlockAddr >= Info.RegionEnd)
1379d89ec533Spatrick return false;
1380d89ec533Spatrick
1381d89ec533Spatrick uptr ChunkAddr;
1382d89ec533Spatrick Chunk::UnpackedHeader Header;
1383d89ec533Spatrick const u32 *Data;
1384d89ec533Spatrick uint8_t Tag;
1385d89ec533Spatrick if (!ReadBlock(BlockAddr, &ChunkAddr, &Header, &Data, &Tag) ||
1386d89ec533Spatrick Header.State != Chunk::State::Allocated || Tag != FaultAddrTag)
1387d89ec533Spatrick return false;
1388d89ec533Spatrick
1389d89ec533Spatrick auto *R = &ErrorInfo->reports[NextErrorReport++];
1390d89ec533Spatrick R->error_type =
1391d89ec533Spatrick UntaggedFaultAddr < ChunkAddr ? BUFFER_UNDERFLOW : BUFFER_OVERFLOW;
1392d89ec533Spatrick R->allocation_address = ChunkAddr;
1393d89ec533Spatrick R->allocation_size = Header.SizeOrUnusedBytes;
1394d89ec533Spatrick collectTraceMaybe(Depot, R->allocation_trace,
1395d89ec533Spatrick Data[MemTagAllocationTraceIndex]);
1396d89ec533Spatrick R->allocation_tid = Data[MemTagAllocationTidIndex];
1397d89ec533Spatrick return NextErrorReport == NumErrorReports;
1398d89ec533Spatrick };
1399d89ec533Spatrick
1400d89ec533Spatrick if (MinDistance == 0 && CheckOOB(Info.BlockBegin))
1401d89ec533Spatrick return;
1402d89ec533Spatrick
1403d89ec533Spatrick for (size_t I = Max<size_t>(MinDistance, 1); I != MaxDistance; ++I)
1404d89ec533Spatrick if (CheckOOB(Info.BlockBegin + I * Info.BlockSize) ||
1405d89ec533Spatrick CheckOOB(Info.BlockBegin - I * Info.BlockSize))
1406d89ec533Spatrick return;
1407d89ec533Spatrick }
1408d89ec533Spatrick
getRingBufferErrorInfo(struct scudo_error_info * ErrorInfo,size_t & NextErrorReport,uintptr_t FaultAddr,const StackDepot * Depot,const char * RingBufferPtr)1409d89ec533Spatrick static void getRingBufferErrorInfo(struct scudo_error_info *ErrorInfo,
1410d89ec533Spatrick size_t &NextErrorReport,
1411d89ec533Spatrick uintptr_t FaultAddr,
1412d89ec533Spatrick const StackDepot *Depot,
1413d89ec533Spatrick const char *RingBufferPtr) {
1414d89ec533Spatrick auto *RingBuffer =
1415d89ec533Spatrick reinterpret_cast<const AllocationRingBuffer *>(RingBufferPtr);
1416*810390e3Srobert if (!RingBuffer || RingBuffer->Size == 0)
1417*810390e3Srobert return;
1418d89ec533Spatrick uptr Pos = atomic_load_relaxed(&RingBuffer->Pos);
1419d89ec533Spatrick
1420*810390e3Srobert for (uptr I = Pos - 1;
1421*810390e3Srobert I != Pos - 1 - RingBuffer->Size && NextErrorReport != NumErrorReports;
1422d89ec533Spatrick --I) {
1423*810390e3Srobert auto *Entry = getRingBufferEntry(RingBufferPtr, I % RingBuffer->Size);
1424d89ec533Spatrick uptr EntryPtr = atomic_load_relaxed(&Entry->Ptr);
1425d89ec533Spatrick if (!EntryPtr)
1426d89ec533Spatrick continue;
1427d89ec533Spatrick
1428d89ec533Spatrick uptr UntaggedEntryPtr = untagPointer(EntryPtr);
1429d89ec533Spatrick uptr EntrySize = atomic_load_relaxed(&Entry->AllocationSize);
1430d89ec533Spatrick u32 AllocationTrace = atomic_load_relaxed(&Entry->AllocationTrace);
1431d89ec533Spatrick u32 AllocationTid = atomic_load_relaxed(&Entry->AllocationTid);
1432d89ec533Spatrick u32 DeallocationTrace = atomic_load_relaxed(&Entry->DeallocationTrace);
1433d89ec533Spatrick u32 DeallocationTid = atomic_load_relaxed(&Entry->DeallocationTid);
1434d89ec533Spatrick
1435d89ec533Spatrick if (DeallocationTid) {
1436d89ec533Spatrick // For UAF we only consider in-bounds fault addresses because
1437d89ec533Spatrick // out-of-bounds UAF is rare and attempting to detect it is very likely
1438d89ec533Spatrick // to result in false positives.
1439d89ec533Spatrick if (FaultAddr < EntryPtr || FaultAddr >= EntryPtr + EntrySize)
1440d89ec533Spatrick continue;
1441d89ec533Spatrick } else {
1442d89ec533Spatrick // Ring buffer OOB is only possible with secondary allocations. In this
1443d89ec533Spatrick // case we are guaranteed a guard region of at least a page on either
1444d89ec533Spatrick // side of the allocation (guard page on the right, guard page + tagged
1445d89ec533Spatrick // region on the left), so ignore any faults outside of that range.
1446d89ec533Spatrick if (FaultAddr < EntryPtr - getPageSizeCached() ||
1447d89ec533Spatrick FaultAddr >= EntryPtr + EntrySize + getPageSizeCached())
1448d89ec533Spatrick continue;
1449d89ec533Spatrick
1450d89ec533Spatrick // For UAF the ring buffer will contain two entries, one for the
1451d89ec533Spatrick // allocation and another for the deallocation. Don't report buffer
1452d89ec533Spatrick // overflow/underflow using the allocation entry if we have already
1453d89ec533Spatrick // collected a report from the deallocation entry.
1454d89ec533Spatrick bool Found = false;
1455d89ec533Spatrick for (uptr J = 0; J != NextErrorReport; ++J) {
1456d89ec533Spatrick if (ErrorInfo->reports[J].allocation_address == UntaggedEntryPtr) {
1457d89ec533Spatrick Found = true;
1458d89ec533Spatrick break;
1459d89ec533Spatrick }
1460d89ec533Spatrick }
1461d89ec533Spatrick if (Found)
1462d89ec533Spatrick continue;
1463d89ec533Spatrick }
1464d89ec533Spatrick
1465d89ec533Spatrick auto *R = &ErrorInfo->reports[NextErrorReport++];
1466d89ec533Spatrick if (DeallocationTid)
1467d89ec533Spatrick R->error_type = USE_AFTER_FREE;
1468d89ec533Spatrick else if (FaultAddr < EntryPtr)
1469d89ec533Spatrick R->error_type = BUFFER_UNDERFLOW;
1470d89ec533Spatrick else
1471d89ec533Spatrick R->error_type = BUFFER_OVERFLOW;
1472d89ec533Spatrick
1473d89ec533Spatrick R->allocation_address = UntaggedEntryPtr;
1474d89ec533Spatrick R->allocation_size = EntrySize;
1475d89ec533Spatrick collectTraceMaybe(Depot, R->allocation_trace, AllocationTrace);
1476d89ec533Spatrick R->allocation_tid = AllocationTid;
1477d89ec533Spatrick collectTraceMaybe(Depot, R->deallocation_trace, DeallocationTrace);
1478d89ec533Spatrick R->deallocation_tid = DeallocationTid;
1479d89ec533Spatrick }
14801f9cb04fSpatrick }
14811f9cb04fSpatrick
getStats(ScopedString * Str)14823cab2bb3Spatrick uptr getStats(ScopedString *Str) {
14833cab2bb3Spatrick Primary.getStats(Str);
14843cab2bb3Spatrick Secondary.getStats(Str);
14853cab2bb3Spatrick Quarantine.getStats(Str);
14863cab2bb3Spatrick return Str->length();
14873cab2bb3Spatrick }
1488*810390e3Srobert
1489*810390e3Srobert static typename AllocationRingBuffer::Entry *
getRingBufferEntry(char * RawRingBuffer,uptr N)1490*810390e3Srobert getRingBufferEntry(char *RawRingBuffer, uptr N) {
1491*810390e3Srobert return &reinterpret_cast<typename AllocationRingBuffer::Entry *>(
1492*810390e3Srobert &RawRingBuffer[sizeof(AllocationRingBuffer)])[N];
1493*810390e3Srobert }
1494*810390e3Srobert static const typename AllocationRingBuffer::Entry *
getRingBufferEntry(const char * RawRingBuffer,uptr N)1495*810390e3Srobert getRingBufferEntry(const char *RawRingBuffer, uptr N) {
1496*810390e3Srobert return &reinterpret_cast<const typename AllocationRingBuffer::Entry *>(
1497*810390e3Srobert &RawRingBuffer[sizeof(AllocationRingBuffer)])[N];
1498*810390e3Srobert }
1499*810390e3Srobert
initRingBuffer()1500*810390e3Srobert void initRingBuffer() {
1501*810390e3Srobert u32 AllocationRingBufferSize =
1502*810390e3Srobert static_cast<u32>(getFlags()->allocation_ring_buffer_size);
1503*810390e3Srobert if (AllocationRingBufferSize < 1)
1504*810390e3Srobert return;
1505*810390e3Srobert MapPlatformData Data = {};
1506*810390e3Srobert RawRingBuffer = static_cast<char *>(
1507*810390e3Srobert map(/*Addr=*/nullptr,
1508*810390e3Srobert roundUpTo(ringBufferSizeInBytes(AllocationRingBufferSize), getPageSizeCached()),
1509*810390e3Srobert "AllocatorRingBuffer", /*Flags=*/0, &Data));
1510*810390e3Srobert auto *RingBuffer = reinterpret_cast<AllocationRingBuffer *>(RawRingBuffer);
1511*810390e3Srobert RingBuffer->Size = AllocationRingBufferSize;
1512*810390e3Srobert static_assert(sizeof(AllocationRingBuffer) %
1513*810390e3Srobert alignof(typename AllocationRingBuffer::Entry) ==
1514*810390e3Srobert 0,
1515*810390e3Srobert "invalid alignment");
1516*810390e3Srobert }
1517*810390e3Srobert
ringBufferSizeInBytes(u32 AllocationRingBufferSize)1518*810390e3Srobert static constexpr size_t ringBufferSizeInBytes(u32 AllocationRingBufferSize) {
1519*810390e3Srobert return sizeof(AllocationRingBuffer) +
1520*810390e3Srobert AllocationRingBufferSize *
1521*810390e3Srobert sizeof(typename AllocationRingBuffer::Entry);
1522*810390e3Srobert }
1523*810390e3Srobert
getRingBuffer()1524*810390e3Srobert inline AllocationRingBuffer *getRingBuffer() {
1525*810390e3Srobert return reinterpret_cast<AllocationRingBuffer *>(RawRingBuffer);
1526*810390e3Srobert }
15273cab2bb3Spatrick };
15283cab2bb3Spatrick
15293cab2bb3Spatrick } // namespace scudo
15303cab2bb3Spatrick
15313cab2bb3Spatrick #endif // SCUDO_COMBINED_H_
1532