xref: /freebsd/contrib/llvm-project/compiler-rt/lib/scudo/standalone/combined.h (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===-- combined.h ----------------------------------------------*- C++ -*-===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #ifndef SCUDO_COMBINED_H_
100b57cec5SDimitry Andric #define SCUDO_COMBINED_H_
110b57cec5SDimitry Andric 
12*0fca6ea1SDimitry Andric #include "allocator_config_wrapper.h"
13*0fca6ea1SDimitry Andric #include "atomic_helpers.h"
140b57cec5SDimitry Andric #include "chunk.h"
150b57cec5SDimitry Andric #include "common.h"
160b57cec5SDimitry Andric #include "flags.h"
170b57cec5SDimitry Andric #include "flags_parser.h"
180b57cec5SDimitry Andric #include "local_cache.h"
195f757f3fSDimitry Andric #include "mem_map.h"
205ffd83dbSDimitry Andric #include "memtag.h"
21*0fca6ea1SDimitry Andric #include "mutex.h"
22e8d8bef9SDimitry Andric #include "options.h"
230b57cec5SDimitry Andric #include "quarantine.h"
240b57cec5SDimitry Andric #include "report.h"
250b57cec5SDimitry Andric #include "secondary.h"
265ffd83dbSDimitry Andric #include "stack_depot.h"
27480093f4SDimitry Andric #include "string_utils.h"
280b57cec5SDimitry Andric #include "tsd.h"
290b57cec5SDimitry Andric 
305ffd83dbSDimitry Andric #include "scudo/interface.h"
315ffd83dbSDimitry Andric 
32480093f4SDimitry Andric #ifdef GWP_ASAN_HOOKS
33480093f4SDimitry Andric #include "gwp_asan/guarded_pool_allocator.h"
345ffd83dbSDimitry Andric #include "gwp_asan/optional/backtrace.h"
355ffd83dbSDimitry Andric #include "gwp_asan/optional/segv_handler.h"
36480093f4SDimitry Andric #endif // GWP_ASAN_HOOKS
37480093f4SDimitry Andric 
EmptyCallback()38480093f4SDimitry Andric extern "C" inline void EmptyCallback() {}
39480093f4SDimitry Andric 
405ffd83dbSDimitry Andric #ifdef HAVE_ANDROID_UNSAFE_FRAME_POINTER_CHASE
415ffd83dbSDimitry Andric // This function is not part of the NDK so it does not appear in any public
425ffd83dbSDimitry Andric // header files. We only declare/use it when targeting the platform.
435ffd83dbSDimitry Andric extern "C" size_t android_unsafe_frame_pointer_chase(scudo::uptr *buf,
445ffd83dbSDimitry Andric                                                      size_t num_entries);
455ffd83dbSDimitry Andric #endif
465ffd83dbSDimitry Andric 
470b57cec5SDimitry Andric namespace scudo {
480b57cec5SDimitry Andric 
4906c3fb27SDimitry Andric template <class Config, void (*PostInitCallback)(void) = EmptyCallback>
50480093f4SDimitry Andric class Allocator {
510b57cec5SDimitry Andric public:
52*0fca6ea1SDimitry Andric   using AllocatorConfig = BaseConfig<Config>;
53*0fca6ea1SDimitry Andric   using PrimaryT =
54*0fca6ea1SDimitry Andric       typename AllocatorConfig::template PrimaryT<PrimaryConfig<Config>>;
55*0fca6ea1SDimitry Andric   using SecondaryT =
56*0fca6ea1SDimitry Andric       typename AllocatorConfig::template SecondaryT<SecondaryConfig<Config>>;
570b57cec5SDimitry Andric   using CacheT = typename PrimaryT::CacheT;
5806c3fb27SDimitry Andric   typedef Allocator<Config, PostInitCallback> ThisT;
59*0fca6ea1SDimitry Andric   typedef typename AllocatorConfig::template TSDRegistryT<ThisT> TSDRegistryT;
600b57cec5SDimitry Andric 
callPostInitCallback()61480093f4SDimitry Andric   void callPostInitCallback() {
62fe6060f1SDimitry Andric     pthread_once(&PostInitNonce, PostInitCallback);
63480093f4SDimitry Andric   }
64480093f4SDimitry Andric 
650b57cec5SDimitry Andric   struct QuarantineCallback {
QuarantineCallbackQuarantineCallback660b57cec5SDimitry Andric     explicit QuarantineCallback(ThisT &Instance, CacheT &LocalCache)
670b57cec5SDimitry Andric         : Allocator(Instance), Cache(LocalCache) {}
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric     // Chunk recycling function, returns a quarantined chunk to the backend,
700b57cec5SDimitry Andric     // first making sure it hasn't been tampered with.
recycleQuarantineCallback710b57cec5SDimitry Andric     void recycle(void *Ptr) {
720b57cec5SDimitry Andric       Chunk::UnpackedHeader Header;
730b57cec5SDimitry Andric       Chunk::loadHeader(Allocator.Cookie, Ptr, &Header);
740b57cec5SDimitry Andric       if (UNLIKELY(Header.State != Chunk::State::Quarantined))
750b57cec5SDimitry Andric         reportInvalidChunkState(AllocatorAction::Recycling, Ptr);
760b57cec5SDimitry Andric 
775f757f3fSDimitry Andric       Header.State = Chunk::State::Available;
785f757f3fSDimitry Andric       Chunk::storeHeader(Allocator.Cookie, Ptr, &Header);
790b57cec5SDimitry Andric 
80*0fca6ea1SDimitry Andric       if (allocatorSupportsMemoryTagging<AllocatorConfig>())
81fe6060f1SDimitry Andric         Ptr = untagPointer(Ptr);
825f757f3fSDimitry Andric       void *BlockBegin = Allocator::getBlockBegin(Ptr, &Header);
835f757f3fSDimitry Andric       Cache.deallocate(Header.ClassId, BlockBegin);
840b57cec5SDimitry Andric     }
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric     // We take a shortcut when allocating a quarantine batch by working with the
870b57cec5SDimitry Andric     // appropriate class ID instead of using Size. The compiler should optimize
880b57cec5SDimitry Andric     // the class ID computation and work with the associated cache directly.
allocateQuarantineCallback890b57cec5SDimitry Andric     void *allocate(UNUSED uptr Size) {
900b57cec5SDimitry Andric       const uptr QuarantineClassId = SizeClassMap::getClassIdBySize(
910b57cec5SDimitry Andric           sizeof(QuarantineBatch) + Chunk::getHeaderSize());
920b57cec5SDimitry Andric       void *Ptr = Cache.allocate(QuarantineClassId);
930b57cec5SDimitry Andric       // Quarantine batch allocation failure is fatal.
940b57cec5SDimitry Andric       if (UNLIKELY(!Ptr))
950b57cec5SDimitry Andric         reportOutOfMemory(SizeClassMap::getSizeByClassId(QuarantineClassId));
960b57cec5SDimitry Andric 
970b57cec5SDimitry Andric       Ptr = reinterpret_cast<void *>(reinterpret_cast<uptr>(Ptr) +
980b57cec5SDimitry Andric                                      Chunk::getHeaderSize());
990b57cec5SDimitry Andric       Chunk::UnpackedHeader Header = {};
1000b57cec5SDimitry Andric       Header.ClassId = QuarantineClassId & Chunk::ClassIdMask;
1010b57cec5SDimitry Andric       Header.SizeOrUnusedBytes = sizeof(QuarantineBatch);
1020b57cec5SDimitry Andric       Header.State = Chunk::State::Allocated;
1030b57cec5SDimitry Andric       Chunk::storeHeader(Allocator.Cookie, Ptr, &Header);
1040b57cec5SDimitry Andric 
105e8d8bef9SDimitry Andric       // Reset tag to 0 as this chunk may have been previously used for a tagged
106e8d8bef9SDimitry Andric       // user allocation.
107*0fca6ea1SDimitry Andric       if (UNLIKELY(useMemoryTagging<AllocatorConfig>(
108*0fca6ea1SDimitry Andric               Allocator.Primary.Options.load())))
109e8d8bef9SDimitry Andric         storeTags(reinterpret_cast<uptr>(Ptr),
110e8d8bef9SDimitry Andric                   reinterpret_cast<uptr>(Ptr) + sizeof(QuarantineBatch));
111e8d8bef9SDimitry Andric 
1120b57cec5SDimitry Andric       return Ptr;
1130b57cec5SDimitry Andric     }
1140b57cec5SDimitry Andric 
deallocateQuarantineCallback1150b57cec5SDimitry Andric     void deallocate(void *Ptr) {
1160b57cec5SDimitry Andric       const uptr QuarantineClassId = SizeClassMap::getClassIdBySize(
1170b57cec5SDimitry Andric           sizeof(QuarantineBatch) + Chunk::getHeaderSize());
1180b57cec5SDimitry Andric       Chunk::UnpackedHeader Header;
1190b57cec5SDimitry Andric       Chunk::loadHeader(Allocator.Cookie, Ptr, &Header);
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric       if (UNLIKELY(Header.State != Chunk::State::Allocated))
1220b57cec5SDimitry Andric         reportInvalidChunkState(AllocatorAction::Deallocating, Ptr);
1230b57cec5SDimitry Andric       DCHECK_EQ(Header.ClassId, QuarantineClassId);
1240b57cec5SDimitry Andric       DCHECK_EQ(Header.Offset, 0);
1250b57cec5SDimitry Andric       DCHECK_EQ(Header.SizeOrUnusedBytes, sizeof(QuarantineBatch));
1260b57cec5SDimitry Andric 
1275f757f3fSDimitry Andric       Header.State = Chunk::State::Available;
1285f757f3fSDimitry Andric       Chunk::storeHeader(Allocator.Cookie, Ptr, &Header);
1290b57cec5SDimitry Andric       Cache.deallocate(QuarantineClassId,
1300b57cec5SDimitry Andric                        reinterpret_cast<void *>(reinterpret_cast<uptr>(Ptr) -
1310b57cec5SDimitry Andric                                                 Chunk::getHeaderSize()));
1320b57cec5SDimitry Andric     }
1330b57cec5SDimitry Andric 
1340b57cec5SDimitry Andric   private:
1350b57cec5SDimitry Andric     ThisT &Allocator;
1360b57cec5SDimitry Andric     CacheT &Cache;
1370b57cec5SDimitry Andric   };
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric   typedef GlobalQuarantine<QuarantineCallback, void> QuarantineT;
1400b57cec5SDimitry Andric   typedef typename QuarantineT::CacheT QuarantineCacheT;
1410b57cec5SDimitry Andric 
init()142fe6060f1SDimitry Andric   void init() {
1430b57cec5SDimitry Andric     performSanityChecks();
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric     // Check if hardware CRC32 is supported in the binary and by the platform,
1460b57cec5SDimitry Andric     // if so, opt for the CRC32 hardware version of the checksum.
1470b57cec5SDimitry Andric     if (&computeHardwareCRC32 && hasHardwareCRC32())
1480b57cec5SDimitry Andric       HashAlgorithm = Checksum::HardwareCRC32;
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric     if (UNLIKELY(!getRandom(&Cookie, sizeof(Cookie))))
1510b57cec5SDimitry Andric       Cookie = static_cast<u32>(getMonotonicTime() ^
1520b57cec5SDimitry Andric                                 (reinterpret_cast<uptr>(this) >> 4));
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric     initFlags();
1550b57cec5SDimitry Andric     reportUnrecognizedFlags();
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric     // Store some flags locally.
158e8d8bef9SDimitry Andric     if (getFlags()->may_return_null)
159e8d8bef9SDimitry Andric       Primary.Options.set(OptionBit::MayReturnNull);
160e8d8bef9SDimitry Andric     if (getFlags()->zero_contents)
161e8d8bef9SDimitry Andric       Primary.Options.setFillContentsMode(ZeroFill);
162e8d8bef9SDimitry Andric     else if (getFlags()->pattern_fill_contents)
163e8d8bef9SDimitry Andric       Primary.Options.setFillContentsMode(PatternOrZeroFill);
164e8d8bef9SDimitry Andric     if (getFlags()->dealloc_type_mismatch)
165e8d8bef9SDimitry Andric       Primary.Options.set(OptionBit::DeallocTypeMismatch);
166e8d8bef9SDimitry Andric     if (getFlags()->delete_size_mismatch)
167e8d8bef9SDimitry Andric       Primary.Options.set(OptionBit::DeleteSizeMismatch);
168*0fca6ea1SDimitry Andric     if (allocatorSupportsMemoryTagging<AllocatorConfig>() &&
169e8d8bef9SDimitry Andric         systemSupportsMemoryTagging())
170e8d8bef9SDimitry Andric       Primary.Options.set(OptionBit::UseMemoryTagging);
171e8d8bef9SDimitry Andric 
172e8d8bef9SDimitry Andric     QuarantineMaxChunkSize =
17368d75effSDimitry Andric         static_cast<u32>(getFlags()->quarantine_max_chunk_size);
1740b57cec5SDimitry Andric 
175fe6060f1SDimitry Andric     Stats.init();
176*0fca6ea1SDimitry Andric     // TODO(chiahungduan): Given that we support setting the default value in
177*0fca6ea1SDimitry Andric     // the PrimaryConfig and CacheConfig, consider to deprecate the use of
178*0fca6ea1SDimitry Andric     // `release_to_os_interval_ms` flag.
1795ffd83dbSDimitry Andric     const s32 ReleaseToOsIntervalMs = getFlags()->release_to_os_interval_ms;
180fe6060f1SDimitry Andric     Primary.init(ReleaseToOsIntervalMs);
181fe6060f1SDimitry Andric     Secondary.init(&Stats, ReleaseToOsIntervalMs);
18268d75effSDimitry Andric     Quarantine.init(
18368d75effSDimitry Andric         static_cast<uptr>(getFlags()->quarantine_size_kb << 10),
18468d75effSDimitry Andric         static_cast<uptr>(getFlags()->thread_local_quarantine_size_kb << 10));
185*0fca6ea1SDimitry Andric   }
186bdd1243dSDimitry Andric 
enableRingBuffer()187*0fca6ea1SDimitry Andric   void enableRingBuffer() NO_THREAD_SAFETY_ANALYSIS {
188*0fca6ea1SDimitry Andric     AllocationRingBuffer *RB = getRingBuffer();
189*0fca6ea1SDimitry Andric     if (RB)
190*0fca6ea1SDimitry Andric       RB->Depot->enable();
191*0fca6ea1SDimitry Andric     RingBufferInitLock.unlock();
192*0fca6ea1SDimitry Andric   }
193*0fca6ea1SDimitry Andric 
disableRingBuffer()194*0fca6ea1SDimitry Andric   void disableRingBuffer() NO_THREAD_SAFETY_ANALYSIS {
195*0fca6ea1SDimitry Andric     RingBufferInitLock.lock();
196*0fca6ea1SDimitry Andric     AllocationRingBuffer *RB = getRingBuffer();
197*0fca6ea1SDimitry Andric     if (RB)
198*0fca6ea1SDimitry Andric       RB->Depot->disable();
1995ffd83dbSDimitry Andric   }
200480093f4SDimitry Andric 
2015ffd83dbSDimitry Andric   // Initialize the embedded GWP-ASan instance. Requires the main allocator to
2025ffd83dbSDimitry Andric   // be functional, best called from PostInitCallback.
initGwpAsan()2035ffd83dbSDimitry Andric   void initGwpAsan() {
204480093f4SDimitry Andric #ifdef GWP_ASAN_HOOKS
205fe6060f1SDimitry Andric     gwp_asan::options::Options Opt;
206fe6060f1SDimitry Andric     Opt.Enabled = getFlags()->GWP_ASAN_Enabled;
207fe6060f1SDimitry Andric     Opt.MaxSimultaneousAllocations =
208fe6060f1SDimitry Andric         getFlags()->GWP_ASAN_MaxSimultaneousAllocations;
209fe6060f1SDimitry Andric     Opt.SampleRate = getFlags()->GWP_ASAN_SampleRate;
210fe6060f1SDimitry Andric     Opt.InstallSignalHandlers = getFlags()->GWP_ASAN_InstallSignalHandlers;
211bdd1243dSDimitry Andric     Opt.Recoverable = getFlags()->GWP_ASAN_Recoverable;
2125ffd83dbSDimitry Andric     // Embedded GWP-ASan is locked through the Scudo atfork handler (via
2135ffd83dbSDimitry Andric     // Allocator::disable calling GWPASan.disable). Disable GWP-ASan's atfork
2145ffd83dbSDimitry Andric     // handler.
2155ffd83dbSDimitry Andric     Opt.InstallForkHandlers = false;
216e8d8bef9SDimitry Andric     Opt.Backtrace = gwp_asan::backtrace::getBacktraceFunction();
217480093f4SDimitry Andric     GuardedAlloc.init(Opt);
2185ffd83dbSDimitry Andric 
2195ffd83dbSDimitry Andric     if (Opt.InstallSignalHandlers)
220e8d8bef9SDimitry Andric       gwp_asan::segv_handler::installSignalHandlers(
221e8d8bef9SDimitry Andric           &GuardedAlloc, Printf,
222e8d8bef9SDimitry Andric           gwp_asan::backtrace::getPrintBacktraceFunction(),
223bdd1243dSDimitry Andric           gwp_asan::backtrace::getSegvBacktraceFunction(),
224bdd1243dSDimitry Andric           Opt.Recoverable);
225fe6060f1SDimitry Andric 
226fe6060f1SDimitry Andric     GuardedAllocSlotSize =
227fe6060f1SDimitry Andric         GuardedAlloc.getAllocatorState()->maximumAllocationSize();
228fe6060f1SDimitry Andric     Stats.add(StatFree, static_cast<uptr>(Opt.MaxSimultaneousAllocations) *
229fe6060f1SDimitry Andric                             GuardedAllocSlotSize);
230480093f4SDimitry Andric #endif // GWP_ASAN_HOOKS
2310b57cec5SDimitry Andric   }
2320b57cec5SDimitry Andric 
233349cc55cSDimitry Andric #ifdef GWP_ASAN_HOOKS
getGwpAsanAllocationMetadata()234349cc55cSDimitry Andric   const gwp_asan::AllocationMetadata *getGwpAsanAllocationMetadata() {
235349cc55cSDimitry Andric     return GuardedAlloc.getMetadataRegion();
236349cc55cSDimitry Andric   }
237349cc55cSDimitry Andric 
getGwpAsanAllocatorState()238349cc55cSDimitry Andric   const gwp_asan::AllocatorState *getGwpAsanAllocatorState() {
239349cc55cSDimitry Andric     return GuardedAlloc.getAllocatorState();
240349cc55cSDimitry Andric   }
241349cc55cSDimitry Andric #endif // GWP_ASAN_HOOKS
242349cc55cSDimitry Andric 
243e8d8bef9SDimitry Andric   ALWAYS_INLINE void initThreadMaybe(bool MinimalInit = false) {
244e8d8bef9SDimitry Andric     TSDRegistry.initThreadMaybe(this, MinimalInit);
245e8d8bef9SDimitry Andric   }
246e8d8bef9SDimitry Andric 
unmapTestOnly()2470b57cec5SDimitry Andric   void unmapTestOnly() {
24806c3fb27SDimitry Andric     unmapRingBuffer();
249fe6060f1SDimitry Andric     TSDRegistry.unmapTestOnly(this);
2500b57cec5SDimitry Andric     Primary.unmapTestOnly();
251fe6060f1SDimitry Andric     Secondary.unmapTestOnly();
2525ffd83dbSDimitry Andric #ifdef GWP_ASAN_HOOKS
2535ffd83dbSDimitry Andric     if (getFlags()->GWP_ASAN_InstallSignalHandlers)
254e8d8bef9SDimitry Andric       gwp_asan::segv_handler::uninstallSignalHandlers();
2555ffd83dbSDimitry Andric     GuardedAlloc.uninitTestOnly();
2565ffd83dbSDimitry Andric #endif // GWP_ASAN_HOOKS
2570b57cec5SDimitry Andric   }
2580b57cec5SDimitry Andric 
getTSDRegistry()2590b57cec5SDimitry Andric   TSDRegistryT *getTSDRegistry() { return &TSDRegistry; }
getQuarantine()26006c3fb27SDimitry Andric   QuarantineT *getQuarantine() { return &Quarantine; }
2610b57cec5SDimitry Andric 
262480093f4SDimitry Andric   // The Cache must be provided zero-initialized.
initCache(CacheT * Cache)263fe6060f1SDimitry Andric   void initCache(CacheT *Cache) { Cache->init(&Stats, &Primary); }
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric   // Release the resources used by a TSD, which involves:
2660b57cec5SDimitry Andric   // - draining the local quarantine cache to the global quarantine;
2670b57cec5SDimitry Andric   // - releasing the cached pointers back to the Primary;
2680b57cec5SDimitry Andric   // - unlinking the local stats from the global ones (destroying the cache does
2690b57cec5SDimitry Andric   //   the last two items).
commitBack(TSD<ThisT> * TSD)2700b57cec5SDimitry Andric   void commitBack(TSD<ThisT> *TSD) {
2715f757f3fSDimitry Andric     TSD->assertLocked(/*BypassCheck=*/true);
27206c3fb27SDimitry Andric     Quarantine.drain(&TSD->getQuarantineCache(),
27306c3fb27SDimitry Andric                      QuarantineCallback(*this, TSD->getCache()));
27406c3fb27SDimitry Andric     TSD->getCache().destroy(&Stats);
2750b57cec5SDimitry Andric   }
2760b57cec5SDimitry Andric 
drainCache(TSD<ThisT> * TSD)27706c3fb27SDimitry Andric   void drainCache(TSD<ThisT> *TSD) {
2785f757f3fSDimitry Andric     TSD->assertLocked(/*BypassCheck=*/true);
27906c3fb27SDimitry Andric     Quarantine.drainAndRecycle(&TSD->getQuarantineCache(),
28006c3fb27SDimitry Andric                                QuarantineCallback(*this, TSD->getCache()));
28106c3fb27SDimitry Andric     TSD->getCache().drain();
28206c3fb27SDimitry Andric   }
drainCaches()28306c3fb27SDimitry Andric   void drainCaches() { TSDRegistry.drainCaches(this); }
28406c3fb27SDimitry Andric 
getHeaderTaggedPointer(void * Ptr)285fe6060f1SDimitry Andric   ALWAYS_INLINE void *getHeaderTaggedPointer(void *Ptr) {
286*0fca6ea1SDimitry Andric     if (!allocatorSupportsMemoryTagging<AllocatorConfig>())
2875ffd83dbSDimitry Andric       return Ptr;
288fe6060f1SDimitry Andric     auto UntaggedPtr = untagPointer(Ptr);
289fe6060f1SDimitry Andric     if (UntaggedPtr != Ptr)
290fe6060f1SDimitry Andric       return UntaggedPtr;
291fe6060f1SDimitry Andric     // Secondary, or pointer allocated while memory tagging is unsupported or
292fe6060f1SDimitry Andric     // disabled. The tag mismatch is okay in the latter case because tags will
293fe6060f1SDimitry Andric     // not be checked.
294fe6060f1SDimitry Andric     return addHeaderTag(Ptr);
295fe6060f1SDimitry Andric   }
296fe6060f1SDimitry Andric 
addHeaderTag(uptr Ptr)297fe6060f1SDimitry Andric   ALWAYS_INLINE uptr addHeaderTag(uptr Ptr) {
298*0fca6ea1SDimitry Andric     if (!allocatorSupportsMemoryTagging<AllocatorConfig>())
299fe6060f1SDimitry Andric       return Ptr;
300fe6060f1SDimitry Andric     return addFixedTag(Ptr, 2);
301fe6060f1SDimitry Andric   }
302fe6060f1SDimitry Andric 
addHeaderTag(void * Ptr)303fe6060f1SDimitry Andric   ALWAYS_INLINE void *addHeaderTag(void *Ptr) {
304fe6060f1SDimitry Andric     return reinterpret_cast<void *>(addHeaderTag(reinterpret_cast<uptr>(Ptr)));
3055ffd83dbSDimitry Andric   }
3065ffd83dbSDimitry Andric 
collectStackTrace(UNUSED StackDepot * Depot)307*0fca6ea1SDimitry Andric   NOINLINE u32 collectStackTrace(UNUSED StackDepot *Depot) {
3085ffd83dbSDimitry Andric #ifdef HAVE_ANDROID_UNSAFE_FRAME_POINTER_CHASE
3095ffd83dbSDimitry Andric     // Discard collectStackTrace() frame and allocator function frame.
3105ffd83dbSDimitry Andric     constexpr uptr DiscardFrames = 2;
3115ffd83dbSDimitry Andric     uptr Stack[MaxTraceSize + DiscardFrames];
3125ffd83dbSDimitry Andric     uptr Size =
3135ffd83dbSDimitry Andric         android_unsafe_frame_pointer_chase(Stack, MaxTraceSize + DiscardFrames);
3145ffd83dbSDimitry Andric     Size = Min<uptr>(Size, MaxTraceSize + DiscardFrames);
315*0fca6ea1SDimitry Andric     return Depot->insert(Stack + Min<uptr>(DiscardFrames, Size), Stack + Size);
3165ffd83dbSDimitry Andric #else
3175ffd83dbSDimitry Andric     return 0;
3185ffd83dbSDimitry Andric #endif
3195ffd83dbSDimitry Andric   }
3205ffd83dbSDimitry Andric 
computeOddEvenMaskForPointerMaybe(const Options & Options,uptr Ptr,uptr ClassId)3215f757f3fSDimitry Andric   uptr computeOddEvenMaskForPointerMaybe(const Options &Options, uptr Ptr,
322fe6060f1SDimitry Andric                                          uptr ClassId) {
323e8d8bef9SDimitry Andric     if (!Options.get(OptionBit::UseOddEvenTags))
324e8d8bef9SDimitry Andric       return 0;
325e8d8bef9SDimitry Andric 
326e8d8bef9SDimitry Andric     // If a chunk's tag is odd, we want the tags of the surrounding blocks to be
327e8d8bef9SDimitry Andric     // even, and vice versa. Blocks are laid out Size bytes apart, and adding
328e8d8bef9SDimitry Andric     // Size to Ptr will flip the least significant set bit of Size in Ptr, so
329e8d8bef9SDimitry Andric     // that bit will have the pattern 010101... for consecutive blocks, which we
330e8d8bef9SDimitry Andric     // can use to determine which tag mask to use.
331fe6060f1SDimitry Andric     return 0x5555U << ((Ptr >> SizeClassMap::getSizeLSBByClassId(ClassId)) & 1);
332e8d8bef9SDimitry Andric   }
333e8d8bef9SDimitry Andric 
3340b57cec5SDimitry Andric   NOINLINE void *allocate(uptr Size, Chunk::Origin Origin,
3350b57cec5SDimitry Andric                           uptr Alignment = MinAlignment,
33606c3fb27SDimitry Andric                           bool ZeroContents = false) NO_THREAD_SAFETY_ANALYSIS {
3370b57cec5SDimitry Andric     initThreadMaybe();
3380b57cec5SDimitry Andric 
339e8d8bef9SDimitry Andric     const Options Options = Primary.Options.load();
3400b57cec5SDimitry Andric     if (UNLIKELY(Alignment > MaxAlignment)) {
341e8d8bef9SDimitry Andric       if (Options.get(OptionBit::MayReturnNull))
3420b57cec5SDimitry Andric         return nullptr;
3430b57cec5SDimitry Andric       reportAlignmentTooBig(Alignment, MaxAlignment);
3440b57cec5SDimitry Andric     }
34568d75effSDimitry Andric     if (Alignment < MinAlignment)
3460b57cec5SDimitry Andric       Alignment = MinAlignment;
3470b57cec5SDimitry Andric 
348fe6060f1SDimitry Andric #ifdef GWP_ASAN_HOOKS
349fe6060f1SDimitry Andric     if (UNLIKELY(GuardedAlloc.shouldSample())) {
350fe6060f1SDimitry Andric       if (void *Ptr = GuardedAlloc.allocate(Size, Alignment)) {
351fe6060f1SDimitry Andric         Stats.lock();
352fe6060f1SDimitry Andric         Stats.add(StatAllocated, GuardedAllocSlotSize);
353fe6060f1SDimitry Andric         Stats.sub(StatFree, GuardedAllocSlotSize);
354fe6060f1SDimitry Andric         Stats.unlock();
355fe6060f1SDimitry Andric         return Ptr;
356fe6060f1SDimitry Andric       }
357fe6060f1SDimitry Andric     }
358fe6060f1SDimitry Andric #endif // GWP_ASAN_HOOKS
359fe6060f1SDimitry Andric 
360fe6060f1SDimitry Andric     const FillContentsMode FillContents = ZeroContents ? ZeroFill
361fe6060f1SDimitry Andric                                           : TSDRegistry.getDisableMemInit()
362fe6060f1SDimitry Andric                                               ? NoFill
363fe6060f1SDimitry Andric                                               : Options.getFillContentsMode();
364fe6060f1SDimitry Andric 
3650b57cec5SDimitry Andric     // If the requested size happens to be 0 (more common than you might think),
36668d75effSDimitry Andric     // allocate MinAlignment bytes on top of the header. Then add the extra
36768d75effSDimitry Andric     // bytes required to fulfill the alignment requirements: we allocate enough
36868d75effSDimitry Andric     // to be sure that there will be an address in the block that will satisfy
36968d75effSDimitry Andric     // the alignment.
3700b57cec5SDimitry Andric     const uptr NeededSize =
37106c3fb27SDimitry Andric         roundUp(Size, MinAlignment) +
37268d75effSDimitry Andric         ((Alignment > MinAlignment) ? Alignment : Chunk::getHeaderSize());
3730b57cec5SDimitry Andric 
3740b57cec5SDimitry Andric     // Takes care of extravagantly large sizes as well as integer overflows.
375480093f4SDimitry Andric     static_assert(MaxAllowedMallocSize < UINTPTR_MAX - MaxAlignment, "");
376480093f4SDimitry Andric     if (UNLIKELY(Size >= MaxAllowedMallocSize)) {
377e8d8bef9SDimitry Andric       if (Options.get(OptionBit::MayReturnNull))
3780b57cec5SDimitry Andric         return nullptr;
3790b57cec5SDimitry Andric       reportAllocationSizeTooBig(Size, NeededSize, MaxAllowedMallocSize);
3800b57cec5SDimitry Andric     }
381480093f4SDimitry Andric     DCHECK_LE(Size, NeededSize);
3820b57cec5SDimitry Andric 
3835ffd83dbSDimitry Andric     void *Block = nullptr;
3845ffd83dbSDimitry Andric     uptr ClassId = 0;
385e8d8bef9SDimitry Andric     uptr SecondaryBlockEnd = 0;
38668d75effSDimitry Andric     if (LIKELY(PrimaryT::canAllocate(NeededSize))) {
3870b57cec5SDimitry Andric       ClassId = SizeClassMap::getClassIdBySize(NeededSize);
38868d75effSDimitry Andric       DCHECK_NE(ClassId, 0U);
389*0fca6ea1SDimitry Andric       typename TSDRegistryT::ScopedTSD TSD(TSDRegistry);
39006c3fb27SDimitry Andric       Block = TSD->getCache().allocate(ClassId);
3915f757f3fSDimitry Andric       // If the allocation failed, retry in each successively larger class until
3925f757f3fSDimitry Andric       // it fits. If it fails to fit in the largest class, fallback to the
3935f757f3fSDimitry Andric       // Secondary.
3945ffd83dbSDimitry Andric       if (UNLIKELY(!Block)) {
395e8d8bef9SDimitry Andric         while (ClassId < SizeClassMap::LargestClassId && !Block)
39606c3fb27SDimitry Andric           Block = TSD->getCache().allocate(++ClassId);
397e8d8bef9SDimitry Andric         if (!Block)
3985ffd83dbSDimitry Andric           ClassId = 0;
3995ffd83dbSDimitry Andric       }
4000b57cec5SDimitry Andric     }
40106c3fb27SDimitry Andric     if (UNLIKELY(ClassId == 0)) {
402fe6060f1SDimitry Andric       Block = Secondary.allocate(Options, Size, Alignment, &SecondaryBlockEnd,
4035ffd83dbSDimitry Andric                                  FillContents);
40406c3fb27SDimitry Andric     }
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric     if (UNLIKELY(!Block)) {
407e8d8bef9SDimitry Andric       if (Options.get(OptionBit::MayReturnNull))
4080b57cec5SDimitry Andric         return nullptr;
4095f757f3fSDimitry Andric       printStats();
4100b57cec5SDimitry Andric       reportOutOfMemory(NeededSize);
4110b57cec5SDimitry Andric     }
4120b57cec5SDimitry Andric 
413*0fca6ea1SDimitry Andric     const uptr UserPtr = roundUp(
414*0fca6ea1SDimitry Andric         reinterpret_cast<uptr>(Block) + Chunk::getHeaderSize(), Alignment);
415*0fca6ea1SDimitry Andric     const uptr SizeOrUnusedBytes =
416*0fca6ea1SDimitry Andric         ClassId ? Size : SecondaryBlockEnd - (UserPtr + Size);
417480093f4SDimitry Andric 
418*0fca6ea1SDimitry Andric     if (LIKELY(!useMemoryTagging<AllocatorConfig>(Options))) {
419*0fca6ea1SDimitry Andric       return initChunk(ClassId, Origin, Block, UserPtr, SizeOrUnusedBytes,
420*0fca6ea1SDimitry Andric                        FillContents);
421fe6060f1SDimitry Andric     }
4225ffd83dbSDimitry Andric 
423*0fca6ea1SDimitry Andric     return initChunkWithMemoryTagging(ClassId, Origin, Block, UserPtr, Size,
424*0fca6ea1SDimitry Andric                                       SizeOrUnusedBytes, FillContents);
4250b57cec5SDimitry Andric   }
4260b57cec5SDimitry Andric 
4270b57cec5SDimitry Andric   NOINLINE void deallocate(void *Ptr, Chunk::Origin Origin, uptr DeleteSize = 0,
4280b57cec5SDimitry Andric                            UNUSED uptr Alignment = MinAlignment) {
4295f757f3fSDimitry Andric     if (UNLIKELY(!Ptr))
4305f757f3fSDimitry Andric       return;
4315f757f3fSDimitry Andric 
4320b57cec5SDimitry Andric     // For a deallocation, we only ensure minimal initialization, meaning thread
4330b57cec5SDimitry Andric     // local data will be left uninitialized for now (when using ELF TLS). The
4340b57cec5SDimitry Andric     // fallback cache will be used instead. This is a workaround for a situation
4350b57cec5SDimitry Andric     // where the only heap operation performed in a thread would be a free past
4360b57cec5SDimitry Andric     // the TLS destructors, ending up in initialized thread specific data never
4370b57cec5SDimitry Andric     // being destroyed properly. Any other heap operation will do a full init.
4380b57cec5SDimitry Andric     initThreadMaybe(/*MinimalInit=*/true);
4390b57cec5SDimitry Andric 
440fe6060f1SDimitry Andric #ifdef GWP_ASAN_HOOKS
441fe6060f1SDimitry Andric     if (UNLIKELY(GuardedAlloc.pointerIsMine(Ptr))) {
442fe6060f1SDimitry Andric       GuardedAlloc.deallocate(Ptr);
443fe6060f1SDimitry Andric       Stats.lock();
444fe6060f1SDimitry Andric       Stats.add(StatFree, GuardedAllocSlotSize);
445fe6060f1SDimitry Andric       Stats.sub(StatAllocated, GuardedAllocSlotSize);
446fe6060f1SDimitry Andric       Stats.unlock();
447fe6060f1SDimitry Andric       return;
448fe6060f1SDimitry Andric     }
449fe6060f1SDimitry Andric #endif // GWP_ASAN_HOOKS
450fe6060f1SDimitry Andric 
4510b57cec5SDimitry Andric     if (UNLIKELY(!isAligned(reinterpret_cast<uptr>(Ptr), MinAlignment)))
4520b57cec5SDimitry Andric       reportMisalignedPointer(AllocatorAction::Deallocating, Ptr);
4530b57cec5SDimitry Andric 
454fe6060f1SDimitry Andric     void *TaggedPtr = Ptr;
455fe6060f1SDimitry Andric     Ptr = getHeaderTaggedPointer(Ptr);
4565ffd83dbSDimitry Andric 
4570b57cec5SDimitry Andric     Chunk::UnpackedHeader Header;
4580b57cec5SDimitry Andric     Chunk::loadHeader(Cookie, Ptr, &Header);
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric     if (UNLIKELY(Header.State != Chunk::State::Allocated))
4610b57cec5SDimitry Andric       reportInvalidChunkState(AllocatorAction::Deallocating, Ptr);
462e8d8bef9SDimitry Andric 
463e8d8bef9SDimitry Andric     const Options Options = Primary.Options.load();
464e8d8bef9SDimitry Andric     if (Options.get(OptionBit::DeallocTypeMismatch)) {
465e8d8bef9SDimitry Andric       if (UNLIKELY(Header.OriginOrWasZeroed != Origin)) {
4660b57cec5SDimitry Andric         // With the exception of memalign'd chunks, that can be still be free'd.
467e8d8bef9SDimitry Andric         if (Header.OriginOrWasZeroed != Chunk::Origin::Memalign ||
468e8d8bef9SDimitry Andric             Origin != Chunk::Origin::Malloc)
4690b57cec5SDimitry Andric           reportDeallocTypeMismatch(AllocatorAction::Deallocating, Ptr,
470e8d8bef9SDimitry Andric                                     Header.OriginOrWasZeroed, Origin);
4710b57cec5SDimitry Andric       }
4720b57cec5SDimitry Andric     }
4730b57cec5SDimitry Andric 
4740b57cec5SDimitry Andric     const uptr Size = getSize(Ptr, &Header);
475e8d8bef9SDimitry Andric     if (DeleteSize && Options.get(OptionBit::DeleteSizeMismatch)) {
4760b57cec5SDimitry Andric       if (UNLIKELY(DeleteSize != Size))
4770b57cec5SDimitry Andric         reportDeleteSizeMismatch(Ptr, DeleteSize, Size);
4780b57cec5SDimitry Andric     }
4790b57cec5SDimitry Andric 
480fe6060f1SDimitry Andric     quarantineOrDeallocateChunk(Options, TaggedPtr, &Header, Size);
4810b57cec5SDimitry Andric   }
4820b57cec5SDimitry Andric 
4830b57cec5SDimitry Andric   void *reallocate(void *OldPtr, uptr NewSize, uptr Alignment = MinAlignment) {
4840b57cec5SDimitry Andric     initThreadMaybe();
4850b57cec5SDimitry Andric 
486e8d8bef9SDimitry Andric     const Options Options = Primary.Options.load();
4875ffd83dbSDimitry Andric     if (UNLIKELY(NewSize >= MaxAllowedMallocSize)) {
488e8d8bef9SDimitry Andric       if (Options.get(OptionBit::MayReturnNull))
4895ffd83dbSDimitry Andric         return nullptr;
4905ffd83dbSDimitry Andric       reportAllocationSizeTooBig(NewSize, 0, MaxAllowedMallocSize);
4915ffd83dbSDimitry Andric     }
4925ffd83dbSDimitry Andric 
4930b57cec5SDimitry Andric     // The following cases are handled by the C wrappers.
4940b57cec5SDimitry Andric     DCHECK_NE(OldPtr, nullptr);
4950b57cec5SDimitry Andric     DCHECK_NE(NewSize, 0);
4960b57cec5SDimitry Andric 
497480093f4SDimitry Andric #ifdef GWP_ASAN_HOOKS
498480093f4SDimitry Andric     if (UNLIKELY(GuardedAlloc.pointerIsMine(OldPtr))) {
499480093f4SDimitry Andric       uptr OldSize = GuardedAlloc.getSize(OldPtr);
500480093f4SDimitry Andric       void *NewPtr = allocate(NewSize, Chunk::Origin::Malloc, Alignment);
501480093f4SDimitry Andric       if (NewPtr)
502480093f4SDimitry Andric         memcpy(NewPtr, OldPtr, (NewSize < OldSize) ? NewSize : OldSize);
503480093f4SDimitry Andric       GuardedAlloc.deallocate(OldPtr);
504fe6060f1SDimitry Andric       Stats.lock();
505fe6060f1SDimitry Andric       Stats.add(StatFree, GuardedAllocSlotSize);
506fe6060f1SDimitry Andric       Stats.sub(StatAllocated, GuardedAllocSlotSize);
507fe6060f1SDimitry Andric       Stats.unlock();
508480093f4SDimitry Andric       return NewPtr;
509480093f4SDimitry Andric     }
510480093f4SDimitry Andric #endif // GWP_ASAN_HOOKS
511480093f4SDimitry Andric 
512fe6060f1SDimitry Andric     void *OldTaggedPtr = OldPtr;
513fe6060f1SDimitry Andric     OldPtr = getHeaderTaggedPointer(OldPtr);
514fe6060f1SDimitry Andric 
5150b57cec5SDimitry Andric     if (UNLIKELY(!isAligned(reinterpret_cast<uptr>(OldPtr), MinAlignment)))
5160b57cec5SDimitry Andric       reportMisalignedPointer(AllocatorAction::Reallocating, OldPtr);
5170b57cec5SDimitry Andric 
5185f757f3fSDimitry Andric     Chunk::UnpackedHeader Header;
5195f757f3fSDimitry Andric     Chunk::loadHeader(Cookie, OldPtr, &Header);
5200b57cec5SDimitry Andric 
5215f757f3fSDimitry Andric     if (UNLIKELY(Header.State != Chunk::State::Allocated))
5220b57cec5SDimitry Andric       reportInvalidChunkState(AllocatorAction::Reallocating, OldPtr);
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric     // Pointer has to be allocated with a malloc-type function. Some
5250b57cec5SDimitry Andric     // applications think that it is OK to realloc a memalign'ed pointer, which
5260b57cec5SDimitry Andric     // will trigger this check. It really isn't.
527e8d8bef9SDimitry Andric     if (Options.get(OptionBit::DeallocTypeMismatch)) {
5285f757f3fSDimitry Andric       if (UNLIKELY(Header.OriginOrWasZeroed != Chunk::Origin::Malloc))
5290b57cec5SDimitry Andric         reportDeallocTypeMismatch(AllocatorAction::Reallocating, OldPtr,
5305f757f3fSDimitry Andric                                   Header.OriginOrWasZeroed,
531e8d8bef9SDimitry Andric                                   Chunk::Origin::Malloc);
5320b57cec5SDimitry Andric     }
5330b57cec5SDimitry Andric 
5345f757f3fSDimitry Andric     void *BlockBegin = getBlockBegin(OldTaggedPtr, &Header);
53568d75effSDimitry Andric     uptr BlockEnd;
53668d75effSDimitry Andric     uptr OldSize;
5375f757f3fSDimitry Andric     const uptr ClassId = Header.ClassId;
53868d75effSDimitry Andric     if (LIKELY(ClassId)) {
53968d75effSDimitry Andric       BlockEnd = reinterpret_cast<uptr>(BlockBegin) +
54068d75effSDimitry Andric                  SizeClassMap::getSizeByClassId(ClassId);
5415f757f3fSDimitry Andric       OldSize = Header.SizeOrUnusedBytes;
54268d75effSDimitry Andric     } else {
54368d75effSDimitry Andric       BlockEnd = SecondaryT::getBlockEnd(BlockBegin);
544fe6060f1SDimitry Andric       OldSize = BlockEnd - (reinterpret_cast<uptr>(OldTaggedPtr) +
5455f757f3fSDimitry Andric                             Header.SizeOrUnusedBytes);
54668d75effSDimitry Andric     }
54768d75effSDimitry Andric     // If the new chunk still fits in the previously allocated block (with a
54868d75effSDimitry Andric     // reasonable delta), we just keep the old block, and update the chunk
54968d75effSDimitry Andric     // header to reflect the size change.
550fe6060f1SDimitry Andric     if (reinterpret_cast<uptr>(OldTaggedPtr) + NewSize <= BlockEnd) {
5515ffd83dbSDimitry Andric       if (NewSize > OldSize || (OldSize - NewSize) < getPageSizeCached()) {
552*0fca6ea1SDimitry Andric         // If we have reduced the size, set the extra bytes to the fill value
553*0fca6ea1SDimitry Andric         // so that we are ready to grow it again in the future.
554*0fca6ea1SDimitry Andric         if (NewSize < OldSize) {
555*0fca6ea1SDimitry Andric           const FillContentsMode FillContents =
556*0fca6ea1SDimitry Andric               TSDRegistry.getDisableMemInit() ? NoFill
557*0fca6ea1SDimitry Andric                                               : Options.getFillContentsMode();
558*0fca6ea1SDimitry Andric           if (FillContents != NoFill) {
559*0fca6ea1SDimitry Andric             memset(reinterpret_cast<char *>(OldTaggedPtr) + NewSize,
560*0fca6ea1SDimitry Andric                    FillContents == ZeroFill ? 0 : PatternFillByte,
561*0fca6ea1SDimitry Andric                    OldSize - NewSize);
562*0fca6ea1SDimitry Andric           }
563*0fca6ea1SDimitry Andric         }
564*0fca6ea1SDimitry Andric 
5655f757f3fSDimitry Andric         Header.SizeOrUnusedBytes =
56668d75effSDimitry Andric             (ClassId ? NewSize
567fe6060f1SDimitry Andric                      : BlockEnd -
568fe6060f1SDimitry Andric                            (reinterpret_cast<uptr>(OldTaggedPtr) + NewSize)) &
5690b57cec5SDimitry Andric             Chunk::SizeOrUnusedBytesMask;
5705f757f3fSDimitry Andric         Chunk::storeHeader(Cookie, OldPtr, &Header);
571*0fca6ea1SDimitry Andric         if (UNLIKELY(useMemoryTagging<AllocatorConfig>(Options))) {
572fe6060f1SDimitry Andric           if (ClassId) {
5735ffd83dbSDimitry Andric             resizeTaggedChunk(reinterpret_cast<uptr>(OldTaggedPtr) + OldSize,
5745ffd83dbSDimitry Andric                               reinterpret_cast<uptr>(OldTaggedPtr) + NewSize,
575fe6060f1SDimitry Andric                               NewSize, untagPointer(BlockEnd));
576fe6060f1SDimitry Andric             storePrimaryAllocationStackMaybe(Options, OldPtr);
577fe6060f1SDimitry Andric           } else {
578fe6060f1SDimitry Andric             storeSecondaryAllocationStackMaybe(Options, OldPtr, NewSize);
579fe6060f1SDimitry Andric           }
5805ffd83dbSDimitry Andric         }
5815ffd83dbSDimitry Andric         return OldTaggedPtr;
5820b57cec5SDimitry Andric       }
5830b57cec5SDimitry Andric     }
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric     // Otherwise we allocate a new one, and deallocate the old one. Some
5860b57cec5SDimitry Andric     // allocators will allocate an even larger chunk (by a fixed factor) to
5870b57cec5SDimitry Andric     // allow for potential further in-place realloc. The gains of such a trick
5880b57cec5SDimitry Andric     // are currently unclear.
5890b57cec5SDimitry Andric     void *NewPtr = allocate(NewSize, Chunk::Origin::Malloc, Alignment);
590e8d8bef9SDimitry Andric     if (LIKELY(NewPtr)) {
5915ffd83dbSDimitry Andric       memcpy(NewPtr, OldTaggedPtr, Min(NewSize, OldSize));
5925f757f3fSDimitry Andric       quarantineOrDeallocateChunk(Options, OldTaggedPtr, &Header, OldSize);
5930b57cec5SDimitry Andric     }
5940b57cec5SDimitry Andric     return NewPtr;
5950b57cec5SDimitry Andric   }
5960b57cec5SDimitry Andric 
597480093f4SDimitry Andric   // TODO(kostyak): disable() is currently best-effort. There are some small
598480093f4SDimitry Andric   //                windows of time when an allocation could still succeed after
599480093f4SDimitry Andric   //                this function finishes. We will revisit that later.
disable()60006c3fb27SDimitry Andric   void disable() NO_THREAD_SAFETY_ANALYSIS {
6010b57cec5SDimitry Andric     initThreadMaybe();
6025ffd83dbSDimitry Andric #ifdef GWP_ASAN_HOOKS
6035ffd83dbSDimitry Andric     GuardedAlloc.disable();
6045ffd83dbSDimitry Andric #endif
605480093f4SDimitry Andric     TSDRegistry.disable();
606480093f4SDimitry Andric     Stats.disable();
607480093f4SDimitry Andric     Quarantine.disable();
6080b57cec5SDimitry Andric     Primary.disable();
6090b57cec5SDimitry Andric     Secondary.disable();
610*0fca6ea1SDimitry Andric     disableRingBuffer();
6110b57cec5SDimitry Andric   }
6120b57cec5SDimitry Andric 
enable()61306c3fb27SDimitry Andric   void enable() NO_THREAD_SAFETY_ANALYSIS {
6140b57cec5SDimitry Andric     initThreadMaybe();
615*0fca6ea1SDimitry Andric     enableRingBuffer();
6160b57cec5SDimitry Andric     Secondary.enable();
6170b57cec5SDimitry Andric     Primary.enable();
618480093f4SDimitry Andric     Quarantine.enable();
619480093f4SDimitry Andric     Stats.enable();
620480093f4SDimitry Andric     TSDRegistry.enable();
6215ffd83dbSDimitry Andric #ifdef GWP_ASAN_HOOKS
6225ffd83dbSDimitry Andric     GuardedAlloc.enable();
6235ffd83dbSDimitry Andric #endif
6240b57cec5SDimitry Andric   }
6250b57cec5SDimitry Andric 
62668d75effSDimitry Andric   // The function returns the amount of bytes required to store the statistics,
62768d75effSDimitry Andric   // which might be larger than the amount of bytes provided. Note that the
62868d75effSDimitry Andric   // statistics buffer is not necessarily constant between calls to this
62968d75effSDimitry Andric   // function. This can be called with a null buffer or zero size for buffer
63068d75effSDimitry Andric   // sizing purposes.
getStats(char * Buffer,uptr Size)63168d75effSDimitry Andric   uptr getStats(char *Buffer, uptr Size) {
632fe6060f1SDimitry Andric     ScopedString Str;
63368d75effSDimitry Andric     const uptr Length = getStats(&Str) + 1;
63468d75effSDimitry Andric     if (Length < Size)
63568d75effSDimitry Andric       Size = Length;
63668d75effSDimitry Andric     if (Buffer && Size) {
63768d75effSDimitry Andric       memcpy(Buffer, Str.data(), Size);
63868d75effSDimitry Andric       Buffer[Size - 1] = '\0';
63968d75effSDimitry Andric     }
64068d75effSDimitry Andric     return Length;
64168d75effSDimitry Andric   }
64268d75effSDimitry Andric 
printStats()64368d75effSDimitry Andric   void printStats() {
644fe6060f1SDimitry Andric     ScopedString Str;
64568d75effSDimitry Andric     getStats(&Str);
64668d75effSDimitry Andric     Str.output();
6470b57cec5SDimitry Andric   }
6480b57cec5SDimitry Andric 
printFragmentationInfo()6495f757f3fSDimitry Andric   void printFragmentationInfo() {
6505f757f3fSDimitry Andric     ScopedString Str;
6515f757f3fSDimitry Andric     Primary.getFragmentationInfo(&Str);
6525f757f3fSDimitry Andric     // Secondary allocator dumps the fragmentation data in getStats().
6535f757f3fSDimitry Andric     Str.output();
6545f757f3fSDimitry Andric   }
6555f757f3fSDimitry Andric 
releaseToOS(ReleaseToOS ReleaseType)65606c3fb27SDimitry Andric   void releaseToOS(ReleaseToOS ReleaseType) {
657480093f4SDimitry Andric     initThreadMaybe();
65806c3fb27SDimitry Andric     if (ReleaseType == ReleaseToOS::ForceAll)
65906c3fb27SDimitry Andric       drainCaches();
66006c3fb27SDimitry Andric     Primary.releaseToOS(ReleaseType);
6615ffd83dbSDimitry Andric     Secondary.releaseToOS();
662480093f4SDimitry Andric   }
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric   // Iterate over all chunks and call a callback for all busy chunks located
6650b57cec5SDimitry Andric   // within the provided memory range. Said callback must not use this allocator
6660b57cec5SDimitry Andric   // or a deadlock can ensue. This fits Android's malloc_iterate() needs.
iterateOverChunks(uptr Base,uptr Size,iterate_callback Callback,void * Arg)6670b57cec5SDimitry Andric   void iterateOverChunks(uptr Base, uptr Size, iterate_callback Callback,
6680b57cec5SDimitry Andric                          void *Arg) {
6690b57cec5SDimitry Andric     initThreadMaybe();
670fe6060f1SDimitry Andric     if (archSupportsMemoryTagging())
671fe6060f1SDimitry Andric       Base = untagPointer(Base);
6720b57cec5SDimitry Andric     const uptr From = Base;
6730b57cec5SDimitry Andric     const uptr To = Base + Size;
674*0fca6ea1SDimitry Andric     bool MayHaveTaggedPrimary =
675*0fca6ea1SDimitry Andric         allocatorSupportsMemoryTagging<AllocatorConfig>() &&
676fe6060f1SDimitry Andric         systemSupportsMemoryTagging();
677fe6060f1SDimitry Andric     auto Lambda = [this, From, To, MayHaveTaggedPrimary, Callback,
678fe6060f1SDimitry Andric                    Arg](uptr Block) {
67968d75effSDimitry Andric       if (Block < From || Block >= To)
6800b57cec5SDimitry Andric         return;
681480093f4SDimitry Andric       uptr Chunk;
682480093f4SDimitry Andric       Chunk::UnpackedHeader Header;
683fe6060f1SDimitry Andric       if (MayHaveTaggedPrimary) {
684fe6060f1SDimitry Andric         // A chunk header can either have a zero tag (tagged primary) or the
685fe6060f1SDimitry Andric         // header tag (secondary, or untagged primary). We don't know which so
686fe6060f1SDimitry Andric         // try both.
687fe6060f1SDimitry Andric         ScopedDisableMemoryTagChecks x;
688fe6060f1SDimitry Andric         if (!getChunkFromBlock(Block, &Chunk, &Header) &&
689fe6060f1SDimitry Andric             !getChunkFromBlock(addHeaderTag(Block), &Chunk, &Header))
690fe6060f1SDimitry Andric           return;
691fe6060f1SDimitry Andric       } else {
692fe6060f1SDimitry Andric         if (!getChunkFromBlock(addHeaderTag(Block), &Chunk, &Header))
693fe6060f1SDimitry Andric           return;
694fe6060f1SDimitry Andric       }
695fe6060f1SDimitry Andric       if (Header.State == Chunk::State::Allocated) {
6965ffd83dbSDimitry Andric         uptr TaggedChunk = Chunk;
697*0fca6ea1SDimitry Andric         if (allocatorSupportsMemoryTagging<AllocatorConfig>())
698fe6060f1SDimitry Andric           TaggedChunk = untagPointer(TaggedChunk);
699*0fca6ea1SDimitry Andric         if (useMemoryTagging<AllocatorConfig>(Primary.Options.load()))
7005ffd83dbSDimitry Andric           TaggedChunk = loadTag(Chunk);
7015ffd83dbSDimitry Andric         Callback(TaggedChunk, getSize(reinterpret_cast<void *>(Chunk), &Header),
7025ffd83dbSDimitry Andric                  Arg);
7035ffd83dbSDimitry Andric       }
7040b57cec5SDimitry Andric     };
7050b57cec5SDimitry Andric     Primary.iterateOverBlocks(Lambda);
7060b57cec5SDimitry Andric     Secondary.iterateOverBlocks(Lambda);
7075ffd83dbSDimitry Andric #ifdef GWP_ASAN_HOOKS
7085ffd83dbSDimitry Andric     GuardedAlloc.iterate(reinterpret_cast<void *>(Base), Size, Callback, Arg);
7095ffd83dbSDimitry Andric #endif
7100b57cec5SDimitry Andric   }
7110b57cec5SDimitry Andric 
canReturnNull()7120b57cec5SDimitry Andric   bool canReturnNull() {
7130b57cec5SDimitry Andric     initThreadMaybe();
714e8d8bef9SDimitry Andric     return Primary.Options.load().get(OptionBit::MayReturnNull);
7150b57cec5SDimitry Andric   }
7160b57cec5SDimitry Andric 
setOption(Option O,sptr Value)7175ffd83dbSDimitry Andric   bool setOption(Option O, sptr Value) {
718e8d8bef9SDimitry Andric     initThreadMaybe();
719e8d8bef9SDimitry Andric     if (O == Option::MemtagTuning) {
720e8d8bef9SDimitry Andric       // Enabling odd/even tags involves a tradeoff between use-after-free
721e8d8bef9SDimitry Andric       // detection and buffer overflow detection. Odd/even tags make it more
722e8d8bef9SDimitry Andric       // likely for buffer overflows to be detected by increasing the size of
723e8d8bef9SDimitry Andric       // the guaranteed "red zone" around the allocation, but on the other hand
724e8d8bef9SDimitry Andric       // use-after-free is less likely to be detected because the tag space for
725e8d8bef9SDimitry Andric       // any particular chunk is cut in half. Therefore we use this tuning
726e8d8bef9SDimitry Andric       // setting to control whether odd/even tags are enabled.
727e8d8bef9SDimitry Andric       if (Value == M_MEMTAG_TUNING_BUFFER_OVERFLOW)
728e8d8bef9SDimitry Andric         Primary.Options.set(OptionBit::UseOddEvenTags);
729e8d8bef9SDimitry Andric       else if (Value == M_MEMTAG_TUNING_UAF)
730e8d8bef9SDimitry Andric         Primary.Options.clear(OptionBit::UseOddEvenTags);
7315ffd83dbSDimitry Andric       return true;
732e8d8bef9SDimitry Andric     } else {
733e8d8bef9SDimitry Andric       // We leave it to the various sub-components to decide whether or not they
734e8d8bef9SDimitry Andric       // want to handle the option, but we do not want to short-circuit
735e8d8bef9SDimitry Andric       // execution if one of the setOption was to return false.
736e8d8bef9SDimitry Andric       const bool PrimaryResult = Primary.setOption(O, Value);
737e8d8bef9SDimitry Andric       const bool SecondaryResult = Secondary.setOption(O, Value);
738e8d8bef9SDimitry Andric       const bool RegistryResult = TSDRegistry.setOption(O, Value);
739e8d8bef9SDimitry Andric       return PrimaryResult && SecondaryResult && RegistryResult;
7405ffd83dbSDimitry Andric     }
7415ffd83dbSDimitry Andric     return false;
7425ffd83dbSDimitry Andric   }
7430b57cec5SDimitry Andric 
7440b57cec5SDimitry Andric   // Return the usable size for a given chunk. Technically we lie, as we just
7450b57cec5SDimitry Andric   // report the actual size of a chunk. This is done to counteract code actively
7460b57cec5SDimitry Andric   // writing past the end of a chunk (like sqlite3) when the usable size allows
7470b57cec5SDimitry Andric   // for it, which then forces realloc to copy the usable size of a chunk as
7480b57cec5SDimitry Andric   // opposed to its actual size.
getUsableSize(const void * Ptr)7490b57cec5SDimitry Andric   uptr getUsableSize(const void *Ptr) {
7500b57cec5SDimitry Andric     if (UNLIKELY(!Ptr))
7510b57cec5SDimitry Andric       return 0;
752480093f4SDimitry Andric 
7535f757f3fSDimitry Andric     return getAllocSize(Ptr);
7545f757f3fSDimitry Andric   }
7555f757f3fSDimitry Andric 
getAllocSize(const void * Ptr)7565f757f3fSDimitry Andric   uptr getAllocSize(const void *Ptr) {
7575f757f3fSDimitry Andric     initThreadMaybe();
7585f757f3fSDimitry Andric 
759480093f4SDimitry Andric #ifdef GWP_ASAN_HOOKS
760480093f4SDimitry Andric     if (UNLIKELY(GuardedAlloc.pointerIsMine(Ptr)))
761480093f4SDimitry Andric       return GuardedAlloc.getSize(Ptr);
762480093f4SDimitry Andric #endif // GWP_ASAN_HOOKS
763480093f4SDimitry Andric 
764fe6060f1SDimitry Andric     Ptr = getHeaderTaggedPointer(const_cast<void *>(Ptr));
7650b57cec5SDimitry Andric     Chunk::UnpackedHeader Header;
7660b57cec5SDimitry Andric     Chunk::loadHeader(Cookie, Ptr, &Header);
7675f757f3fSDimitry Andric 
7685f757f3fSDimitry Andric     // Getting the alloc size of a chunk only makes sense if it's allocated.
7690b57cec5SDimitry Andric     if (UNLIKELY(Header.State != Chunk::State::Allocated))
7700b57cec5SDimitry Andric       reportInvalidChunkState(AllocatorAction::Sizing, const_cast<void *>(Ptr));
7715f757f3fSDimitry Andric 
7720b57cec5SDimitry Andric     return getSize(Ptr, &Header);
7730b57cec5SDimitry Andric   }
7740b57cec5SDimitry Andric 
getStats(StatCounters S)7750b57cec5SDimitry Andric   void getStats(StatCounters S) {
7760b57cec5SDimitry Andric     initThreadMaybe();
7770b57cec5SDimitry Andric     Stats.get(S);
7780b57cec5SDimitry Andric   }
7790b57cec5SDimitry Andric 
780480093f4SDimitry Andric   // Returns true if the pointer provided was allocated by the current
781480093f4SDimitry Andric   // allocator instance, which is compliant with tcmalloc's ownership concept.
782480093f4SDimitry Andric   // A corrupted chunk will not be reported as owned, which is WAI.
isOwned(const void * Ptr)783480093f4SDimitry Andric   bool isOwned(const void *Ptr) {
784480093f4SDimitry Andric     initThreadMaybe();
785480093f4SDimitry Andric #ifdef GWP_ASAN_HOOKS
786480093f4SDimitry Andric     if (GuardedAlloc.pointerIsMine(Ptr))
787480093f4SDimitry Andric       return true;
788480093f4SDimitry Andric #endif // GWP_ASAN_HOOKS
789480093f4SDimitry Andric     if (!Ptr || !isAligned(reinterpret_cast<uptr>(Ptr), MinAlignment))
790480093f4SDimitry Andric       return false;
791fe6060f1SDimitry Andric     Ptr = getHeaderTaggedPointer(const_cast<void *>(Ptr));
792480093f4SDimitry Andric     Chunk::UnpackedHeader Header;
793480093f4SDimitry Andric     return Chunk::isValid(Cookie, Ptr, &Header) &&
794480093f4SDimitry Andric            Header.State == Chunk::State::Allocated;
795480093f4SDimitry Andric   }
796480093f4SDimitry Andric 
useMemoryTaggingTestOnly()797e8d8bef9SDimitry Andric   bool useMemoryTaggingTestOnly() const {
798*0fca6ea1SDimitry Andric     return useMemoryTagging<AllocatorConfig>(Primary.Options.load());
799e8d8bef9SDimitry Andric   }
disableMemoryTagging()800e8d8bef9SDimitry Andric   void disableMemoryTagging() {
801fe6060f1SDimitry Andric     // If we haven't been initialized yet, we need to initialize now in order to
802fe6060f1SDimitry Andric     // prevent a future call to initThreadMaybe() from enabling memory tagging
803fe6060f1SDimitry Andric     // based on feature detection. But don't call initThreadMaybe() because it
804fe6060f1SDimitry Andric     // may end up calling the allocator (via pthread_atfork, via the post-init
805fe6060f1SDimitry Andric     // callback), which may cause mappings to be created with memory tagging
806fe6060f1SDimitry Andric     // enabled.
807fe6060f1SDimitry Andric     TSDRegistry.initOnceMaybe(this);
808*0fca6ea1SDimitry Andric     if (allocatorSupportsMemoryTagging<AllocatorConfig>()) {
809fe6060f1SDimitry Andric       Secondary.disableMemoryTagging();
810e8d8bef9SDimitry Andric       Primary.Options.clear(OptionBit::UseMemoryTagging);
811e8d8bef9SDimitry Andric     }
812fe6060f1SDimitry Andric   }
8135ffd83dbSDimitry Andric 
setTrackAllocationStacks(bool Track)8145ffd83dbSDimitry Andric   void setTrackAllocationStacks(bool Track) {
8155ffd83dbSDimitry Andric     initThreadMaybe();
8165f757f3fSDimitry Andric     if (getFlags()->allocation_ring_buffer_size <= 0) {
817bdd1243dSDimitry Andric       DCHECK(!Primary.Options.load().get(OptionBit::TrackAllocationStacks));
818bdd1243dSDimitry Andric       return;
819bdd1243dSDimitry Andric     }
820*0fca6ea1SDimitry Andric 
821*0fca6ea1SDimitry Andric     if (Track) {
822*0fca6ea1SDimitry Andric       initRingBufferMaybe();
823e8d8bef9SDimitry Andric       Primary.Options.set(OptionBit::TrackAllocationStacks);
824*0fca6ea1SDimitry Andric     } else
825e8d8bef9SDimitry Andric       Primary.Options.clear(OptionBit::TrackAllocationStacks);
8265ffd83dbSDimitry Andric   }
8275ffd83dbSDimitry Andric 
setFillContents(FillContentsMode FillContents)8285ffd83dbSDimitry Andric   void setFillContents(FillContentsMode FillContents) {
8295ffd83dbSDimitry Andric     initThreadMaybe();
830e8d8bef9SDimitry Andric     Primary.Options.setFillContentsMode(FillContents);
8315ffd83dbSDimitry Andric   }
8325ffd83dbSDimitry Andric 
setAddLargeAllocationSlack(bool AddSlack)833fe6060f1SDimitry Andric   void setAddLargeAllocationSlack(bool AddSlack) {
834fe6060f1SDimitry Andric     initThreadMaybe();
835fe6060f1SDimitry Andric     if (AddSlack)
836fe6060f1SDimitry Andric       Primary.Options.set(OptionBit::AddLargeAllocationSlack);
837fe6060f1SDimitry Andric     else
838fe6060f1SDimitry Andric       Primary.Options.clear(OptionBit::AddLargeAllocationSlack);
839fe6060f1SDimitry Andric   }
840fe6060f1SDimitry Andric 
getStackDepotAddress()841*0fca6ea1SDimitry Andric   const char *getStackDepotAddress() {
842*0fca6ea1SDimitry Andric     initThreadMaybe();
843*0fca6ea1SDimitry Andric     AllocationRingBuffer *RB = getRingBuffer();
844*0fca6ea1SDimitry Andric     return RB ? reinterpret_cast<char *>(RB->Depot) : nullptr;
845*0fca6ea1SDimitry Andric   }
846*0fca6ea1SDimitry Andric 
getStackDepotSize()847*0fca6ea1SDimitry Andric   uptr getStackDepotSize() {
848*0fca6ea1SDimitry Andric     initThreadMaybe();
849*0fca6ea1SDimitry Andric     AllocationRingBuffer *RB = getRingBuffer();
850*0fca6ea1SDimitry Andric     return RB ? RB->StackDepotSize : 0;
8515ffd83dbSDimitry Andric   }
8525ffd83dbSDimitry Andric 
getRegionInfoArrayAddress()8535ffd83dbSDimitry Andric   const char *getRegionInfoArrayAddress() const {
8545ffd83dbSDimitry Andric     return Primary.getRegionInfoArrayAddress();
8555ffd83dbSDimitry Andric   }
8565ffd83dbSDimitry Andric 
getRegionInfoArraySize()8575ffd83dbSDimitry Andric   static uptr getRegionInfoArraySize() {
8585ffd83dbSDimitry Andric     return PrimaryT::getRegionInfoArraySize();
8595ffd83dbSDimitry Andric   }
8605ffd83dbSDimitry Andric 
getRingBufferAddress()861bdd1243dSDimitry Andric   const char *getRingBufferAddress() {
862bdd1243dSDimitry Andric     initThreadMaybe();
863*0fca6ea1SDimitry Andric     return reinterpret_cast<char *>(getRingBuffer());
864fe6060f1SDimitry Andric   }
8655ffd83dbSDimitry Andric 
getRingBufferSize()866bdd1243dSDimitry Andric   uptr getRingBufferSize() {
867bdd1243dSDimitry Andric     initThreadMaybe();
868*0fca6ea1SDimitry Andric     AllocationRingBuffer *RB = getRingBuffer();
869*0fca6ea1SDimitry Andric     return RB && RB->RingBufferElements
870*0fca6ea1SDimitry Andric                ? ringBufferSizeInBytes(RB->RingBufferElements)
871*0fca6ea1SDimitry Andric                : 0;
872bdd1243dSDimitry Andric   }
873bdd1243dSDimitry Andric 
874fe6060f1SDimitry Andric   static const uptr MaxTraceSize = 64;
8755ffd83dbSDimitry Andric 
collectTraceMaybe(const StackDepot * Depot,uintptr_t (& Trace)[MaxTraceSize],u32 Hash)876fe6060f1SDimitry Andric   static void collectTraceMaybe(const StackDepot *Depot,
877fe6060f1SDimitry Andric                                 uintptr_t (&Trace)[MaxTraceSize], u32 Hash) {
8785ffd83dbSDimitry Andric     uptr RingPos, Size;
8795ffd83dbSDimitry Andric     if (!Depot->find(Hash, &RingPos, &Size))
8805ffd83dbSDimitry Andric       return;
8815ffd83dbSDimitry Andric     for (unsigned I = 0; I != Size && I != MaxTraceSize; ++I)
882*0fca6ea1SDimitry Andric       Trace[I] = static_cast<uintptr_t>(Depot->at(RingPos + I));
883fe6060f1SDimitry Andric   }
8845ffd83dbSDimitry Andric 
getErrorInfo(struct scudo_error_info * ErrorInfo,uintptr_t FaultAddr,const char * DepotPtr,size_t DepotSize,const char * RegionInfoPtr,const char * RingBufferPtr,size_t RingBufferSize,const char * Memory,const char * MemoryTags,uintptr_t MemoryAddr,size_t MemorySize)885fe6060f1SDimitry Andric   static void getErrorInfo(struct scudo_error_info *ErrorInfo,
886fe6060f1SDimitry Andric                            uintptr_t FaultAddr, const char *DepotPtr,
887*0fca6ea1SDimitry Andric                            size_t DepotSize, const char *RegionInfoPtr,
888*0fca6ea1SDimitry Andric                            const char *RingBufferPtr, size_t RingBufferSize,
889*0fca6ea1SDimitry Andric                            const char *Memory, const char *MemoryTags,
890*0fca6ea1SDimitry Andric                            uintptr_t MemoryAddr, size_t MemorySize) {
891*0fca6ea1SDimitry Andric     // N.B. we need to support corrupted data in any of the buffers here. We get
892*0fca6ea1SDimitry Andric     // this information from an external process (the crashing process) that
893*0fca6ea1SDimitry Andric     // should not be able to crash the crash dumper (crash_dump on Android).
894*0fca6ea1SDimitry Andric     // See also the get_error_info_fuzzer.
895fe6060f1SDimitry Andric     *ErrorInfo = {};
896*0fca6ea1SDimitry Andric     if (!allocatorSupportsMemoryTagging<AllocatorConfig>() ||
897fe6060f1SDimitry Andric         MemoryAddr + MemorySize < MemoryAddr)
898fe6060f1SDimitry Andric       return;
899fe6060f1SDimitry Andric 
900*0fca6ea1SDimitry Andric     const StackDepot *Depot = nullptr;
901*0fca6ea1SDimitry Andric     if (DepotPtr) {
902*0fca6ea1SDimitry Andric       // check for corrupted StackDepot. First we need to check whether we can
903*0fca6ea1SDimitry Andric       // read the metadata, then whether the metadata matches the size.
904*0fca6ea1SDimitry Andric       if (DepotSize < sizeof(*Depot))
905*0fca6ea1SDimitry Andric         return;
906*0fca6ea1SDimitry Andric       Depot = reinterpret_cast<const StackDepot *>(DepotPtr);
907*0fca6ea1SDimitry Andric       if (!Depot->isValid(DepotSize))
908*0fca6ea1SDimitry Andric         return;
909*0fca6ea1SDimitry Andric     }
910*0fca6ea1SDimitry Andric 
9115ffd83dbSDimitry Andric     size_t NextErrorReport = 0;
9125ffd83dbSDimitry Andric 
913fe6060f1SDimitry Andric     // Check for OOB in the current block and the two surrounding blocks. Beyond
914fe6060f1SDimitry Andric     // that, UAF is more likely.
915fe6060f1SDimitry Andric     if (extractTag(FaultAddr) != 0)
916fe6060f1SDimitry Andric       getInlineErrorInfo(ErrorInfo, NextErrorReport, FaultAddr, Depot,
917fe6060f1SDimitry Andric                          RegionInfoPtr, Memory, MemoryTags, MemoryAddr,
918fe6060f1SDimitry Andric                          MemorySize, 0, 2);
9195ffd83dbSDimitry Andric 
920fe6060f1SDimitry Andric     // Check the ring buffer. For primary allocations this will only find UAF;
921fe6060f1SDimitry Andric     // for secondary allocations we can find either UAF or OOB.
922fe6060f1SDimitry Andric     getRingBufferErrorInfo(ErrorInfo, NextErrorReport, FaultAddr, Depot,
9235f757f3fSDimitry Andric                            RingBufferPtr, RingBufferSize);
9245ffd83dbSDimitry Andric 
925fe6060f1SDimitry Andric     // Check for OOB in the 28 blocks surrounding the 3 we checked earlier.
926fe6060f1SDimitry Andric     // Beyond that we are likely to hit false positives.
927fe6060f1SDimitry Andric     if (extractTag(FaultAddr) != 0)
928fe6060f1SDimitry Andric       getInlineErrorInfo(ErrorInfo, NextErrorReport, FaultAddr, Depot,
929fe6060f1SDimitry Andric                          RegionInfoPtr, Memory, MemoryTags, MemoryAddr,
930fe6060f1SDimitry Andric                          MemorySize, 2, 16);
9315ffd83dbSDimitry Andric   }
9325ffd83dbSDimitry Andric 
9330b57cec5SDimitry Andric private:
9340b57cec5SDimitry Andric   typedef typename PrimaryT::SizeClassMap SizeClassMap;
9350b57cec5SDimitry Andric 
9360b57cec5SDimitry Andric   static const uptr MinAlignmentLog = SCUDO_MIN_ALIGNMENT_LOG;
9370b57cec5SDimitry Andric   static const uptr MaxAlignmentLog = 24U; // 16 MB seems reasonable.
9380b57cec5SDimitry Andric   static const uptr MinAlignment = 1UL << MinAlignmentLog;
9390b57cec5SDimitry Andric   static const uptr MaxAlignment = 1UL << MaxAlignmentLog;
9400b57cec5SDimitry Andric   static const uptr MaxAllowedMallocSize =
9410b57cec5SDimitry Andric       FIRST_32_SECOND_64(1UL << 31, 1ULL << 40);
9420b57cec5SDimitry Andric 
943480093f4SDimitry Andric   static_assert(MinAlignment >= sizeof(Chunk::PackedHeader),
944480093f4SDimitry Andric                 "Minimal alignment must at least cover a chunk header.");
945*0fca6ea1SDimitry Andric   static_assert(!allocatorSupportsMemoryTagging<AllocatorConfig>() ||
9465ffd83dbSDimitry Andric                     MinAlignment >= archMemoryTagGranuleSize(),
9475ffd83dbSDimitry Andric                 "");
948480093f4SDimitry Andric 
9490b57cec5SDimitry Andric   static const u32 BlockMarker = 0x44554353U;
9500b57cec5SDimitry Andric 
9515ffd83dbSDimitry Andric   // These are indexes into an "array" of 32-bit values that store information
9525ffd83dbSDimitry Andric   // inline with a chunk that is relevant to diagnosing memory tag faults, where
953fe6060f1SDimitry Andric   // 0 corresponds to the address of the user memory. This means that only
954fe6060f1SDimitry Andric   // negative indexes may be used. The smallest index that may be used is -2,
955fe6060f1SDimitry Andric   // which corresponds to 8 bytes before the user memory, because the chunk
956fe6060f1SDimitry Andric   // header size is 8 bytes and in allocators that support memory tagging the
957fe6060f1SDimitry Andric   // minimum alignment is at least the tag granule size (16 on aarch64).
9585ffd83dbSDimitry Andric   static const sptr MemTagAllocationTraceIndex = -2;
9595ffd83dbSDimitry Andric   static const sptr MemTagAllocationTidIndex = -1;
9605ffd83dbSDimitry Andric 
961fe6060f1SDimitry Andric   u32 Cookie = 0;
962fe6060f1SDimitry Andric   u32 QuarantineMaxChunkSize = 0;
963e8d8bef9SDimitry Andric 
9640b57cec5SDimitry Andric   GlobalStats Stats;
9650b57cec5SDimitry Andric   PrimaryT Primary;
9660b57cec5SDimitry Andric   SecondaryT Secondary;
9670b57cec5SDimitry Andric   QuarantineT Quarantine;
968e8d8bef9SDimitry Andric   TSDRegistryT TSDRegistry;
969fe6060f1SDimitry Andric   pthread_once_t PostInitNonce = PTHREAD_ONCE_INIT;
9700b57cec5SDimitry Andric 
9715ffd83dbSDimitry Andric #ifdef GWP_ASAN_HOOKS
9725ffd83dbSDimitry Andric   gwp_asan::GuardedPoolAllocator GuardedAlloc;
973fe6060f1SDimitry Andric   uptr GuardedAllocSlotSize = 0;
9745ffd83dbSDimitry Andric #endif // GWP_ASAN_HOOKS
9755ffd83dbSDimitry Andric 
976fe6060f1SDimitry Andric   struct AllocationRingBuffer {
977fe6060f1SDimitry Andric     struct Entry {
978fe6060f1SDimitry Andric       atomic_uptr Ptr;
979fe6060f1SDimitry Andric       atomic_uptr AllocationSize;
980fe6060f1SDimitry Andric       atomic_u32 AllocationTrace;
981fe6060f1SDimitry Andric       atomic_u32 AllocationTid;
982fe6060f1SDimitry Andric       atomic_u32 DeallocationTrace;
983fe6060f1SDimitry Andric       atomic_u32 DeallocationTid;
984fe6060f1SDimitry Andric     };
985*0fca6ea1SDimitry Andric     StackDepot *Depot = nullptr;
986*0fca6ea1SDimitry Andric     uptr StackDepotSize = 0;
987*0fca6ea1SDimitry Andric     MemMapT RawRingBufferMap;
988*0fca6ea1SDimitry Andric     MemMapT RawStackDepotMap;
989*0fca6ea1SDimitry Andric     u32 RingBufferElements = 0;
990fe6060f1SDimitry Andric     atomic_uptr Pos;
991bdd1243dSDimitry Andric     // An array of Size (at least one) elements of type Entry is immediately
992bdd1243dSDimitry Andric     // following to this struct.
993fe6060f1SDimitry Andric   };
994*0fca6ea1SDimitry Andric   static_assert(sizeof(AllocationRingBuffer) %
995*0fca6ea1SDimitry Andric                         alignof(typename AllocationRingBuffer::Entry) ==
996*0fca6ea1SDimitry Andric                     0,
997*0fca6ea1SDimitry Andric                 "invalid alignment");
998*0fca6ea1SDimitry Andric 
999*0fca6ea1SDimitry Andric   // Lock to initialize the RingBuffer
1000*0fca6ea1SDimitry Andric   HybridMutex RingBufferInitLock;
1001*0fca6ea1SDimitry Andric 
1002bdd1243dSDimitry Andric   // Pointer to memory mapped area starting with AllocationRingBuffer struct,
1003bdd1243dSDimitry Andric   // and immediately followed by Size elements of type Entry.
1004*0fca6ea1SDimitry Andric   atomic_uptr RingBufferAddress = {};
1005*0fca6ea1SDimitry Andric 
getRingBuffer()1006*0fca6ea1SDimitry Andric   AllocationRingBuffer *getRingBuffer() {
1007*0fca6ea1SDimitry Andric     return reinterpret_cast<AllocationRingBuffer *>(
1008*0fca6ea1SDimitry Andric         atomic_load(&RingBufferAddress, memory_order_acquire));
1009*0fca6ea1SDimitry Andric   }
1010fe6060f1SDimitry Andric 
10110b57cec5SDimitry Andric   // The following might get optimized out by the compiler.
performSanityChecks()10120b57cec5SDimitry Andric   NOINLINE void performSanityChecks() {
10130b57cec5SDimitry Andric     // Verify that the header offset field can hold the maximum offset. In the
10140b57cec5SDimitry Andric     // case of the Secondary allocator, it takes care of alignment and the
10150b57cec5SDimitry Andric     // offset will always be small. In the case of the Primary, the worst case
10160b57cec5SDimitry Andric     // scenario happens in the last size class, when the backend allocation
10170b57cec5SDimitry Andric     // would already be aligned on the requested alignment, which would happen
10180b57cec5SDimitry Andric     // to be the maximum alignment that would fit in that size class. As a
10190b57cec5SDimitry Andric     // result, the maximum offset will be at most the maximum alignment for the
10200b57cec5SDimitry Andric     // last size class minus the header size, in multiples of MinAlignment.
10210b57cec5SDimitry Andric     Chunk::UnpackedHeader Header = {};
10220b57cec5SDimitry Andric     const uptr MaxPrimaryAlignment = 1UL << getMostSignificantSetBitIndex(
10230b57cec5SDimitry Andric                                          SizeClassMap::MaxSize - MinAlignment);
10240b57cec5SDimitry Andric     const uptr MaxOffset =
10250b57cec5SDimitry Andric         (MaxPrimaryAlignment - Chunk::getHeaderSize()) >> MinAlignmentLog;
10260b57cec5SDimitry Andric     Header.Offset = MaxOffset & Chunk::OffsetMask;
10270b57cec5SDimitry Andric     if (UNLIKELY(Header.Offset != MaxOffset))
10280b57cec5SDimitry Andric       reportSanityCheckError("offset");
10290b57cec5SDimitry Andric 
10300b57cec5SDimitry Andric     // Verify that we can fit the maximum size or amount of unused bytes in the
10310b57cec5SDimitry Andric     // header. Given that the Secondary fits the allocation to a page, the worst
10320b57cec5SDimitry Andric     // case scenario happens in the Primary. It will depend on the second to
10330b57cec5SDimitry Andric     // last and last class sizes, as well as the dynamic base for the Primary.
10340b57cec5SDimitry Andric     // The following is an over-approximation that works for our needs.
10350b57cec5SDimitry Andric     const uptr MaxSizeOrUnusedBytes = SizeClassMap::MaxSize - 1;
103668d75effSDimitry Andric     Header.SizeOrUnusedBytes = MaxSizeOrUnusedBytes;
10370b57cec5SDimitry Andric     if (UNLIKELY(Header.SizeOrUnusedBytes != MaxSizeOrUnusedBytes))
10380b57cec5SDimitry Andric       reportSanityCheckError("size (or unused bytes)");
10390b57cec5SDimitry Andric 
10400b57cec5SDimitry Andric     const uptr LargestClassId = SizeClassMap::LargestClassId;
10410b57cec5SDimitry Andric     Header.ClassId = LargestClassId;
10420b57cec5SDimitry Andric     if (UNLIKELY(Header.ClassId != LargestClassId))
10430b57cec5SDimitry Andric       reportSanityCheckError("class ID");
10440b57cec5SDimitry Andric   }
10450b57cec5SDimitry Andric 
getBlockBegin(const void * Ptr,Chunk::UnpackedHeader * Header)1046480093f4SDimitry Andric   static inline void *getBlockBegin(const void *Ptr,
10470b57cec5SDimitry Andric                                     Chunk::UnpackedHeader *Header) {
104868d75effSDimitry Andric     return reinterpret_cast<void *>(
104968d75effSDimitry Andric         reinterpret_cast<uptr>(Ptr) - Chunk::getHeaderSize() -
105068d75effSDimitry Andric         (static_cast<uptr>(Header->Offset) << MinAlignmentLog));
10510b57cec5SDimitry Andric   }
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric   // Return the size of a chunk as requested during its allocation.
getSize(const void * Ptr,Chunk::UnpackedHeader * Header)1054480093f4SDimitry Andric   inline uptr getSize(const void *Ptr, Chunk::UnpackedHeader *Header) {
10550b57cec5SDimitry Andric     const uptr SizeOrUnusedBytes = Header->SizeOrUnusedBytes;
105668d75effSDimitry Andric     if (LIKELY(Header->ClassId))
10570b57cec5SDimitry Andric       return SizeOrUnusedBytes;
1058*0fca6ea1SDimitry Andric     if (allocatorSupportsMemoryTagging<AllocatorConfig>())
1059fe6060f1SDimitry Andric       Ptr = untagPointer(const_cast<void *>(Ptr));
10600b57cec5SDimitry Andric     return SecondaryT::getBlockEnd(getBlockBegin(Ptr, Header)) -
10610b57cec5SDimitry Andric            reinterpret_cast<uptr>(Ptr) - SizeOrUnusedBytes;
10620b57cec5SDimitry Andric   }
10630b57cec5SDimitry Andric 
initChunk(const uptr ClassId,const Chunk::Origin Origin,void * Block,const uptr UserPtr,const uptr SizeOrUnusedBytes,const FillContentsMode FillContents)1064*0fca6ea1SDimitry Andric   ALWAYS_INLINE void *initChunk(const uptr ClassId, const Chunk::Origin Origin,
1065*0fca6ea1SDimitry Andric                                 void *Block, const uptr UserPtr,
1066*0fca6ea1SDimitry Andric                                 const uptr SizeOrUnusedBytes,
1067*0fca6ea1SDimitry Andric                                 const FillContentsMode FillContents) {
1068*0fca6ea1SDimitry Andric     // Compute the default pointer before adding the header tag
1069*0fca6ea1SDimitry Andric     const uptr DefaultAlignedPtr =
1070*0fca6ea1SDimitry Andric         reinterpret_cast<uptr>(Block) + Chunk::getHeaderSize();
1071*0fca6ea1SDimitry Andric 
1072*0fca6ea1SDimitry Andric     Block = addHeaderTag(Block);
1073*0fca6ea1SDimitry Andric     // Only do content fill when it's from primary allocator because secondary
1074*0fca6ea1SDimitry Andric     // allocator has filled the content.
1075*0fca6ea1SDimitry Andric     if (ClassId != 0 && UNLIKELY(FillContents != NoFill)) {
1076*0fca6ea1SDimitry Andric       // This condition is not necessarily unlikely, but since memset is
1077*0fca6ea1SDimitry Andric       // costly, we might as well mark it as such.
1078*0fca6ea1SDimitry Andric       memset(Block, FillContents == ZeroFill ? 0 : PatternFillByte,
1079*0fca6ea1SDimitry Andric              PrimaryT::getSizeByClassId(ClassId));
1080*0fca6ea1SDimitry Andric     }
1081*0fca6ea1SDimitry Andric 
1082*0fca6ea1SDimitry Andric     Chunk::UnpackedHeader Header = {};
1083*0fca6ea1SDimitry Andric 
1084*0fca6ea1SDimitry Andric     if (UNLIKELY(DefaultAlignedPtr != UserPtr)) {
1085*0fca6ea1SDimitry Andric       const uptr Offset = UserPtr - DefaultAlignedPtr;
1086*0fca6ea1SDimitry Andric       DCHECK_GE(Offset, 2 * sizeof(u32));
1087*0fca6ea1SDimitry Andric       // The BlockMarker has no security purpose, but is specifically meant for
1088*0fca6ea1SDimitry Andric       // the chunk iteration function that can be used in debugging situations.
1089*0fca6ea1SDimitry Andric       // It is the only situation where we have to locate the start of a chunk
1090*0fca6ea1SDimitry Andric       // based on its block address.
1091*0fca6ea1SDimitry Andric       reinterpret_cast<u32 *>(Block)[0] = BlockMarker;
1092*0fca6ea1SDimitry Andric       reinterpret_cast<u32 *>(Block)[1] = static_cast<u32>(Offset);
1093*0fca6ea1SDimitry Andric       Header.Offset = (Offset >> MinAlignmentLog) & Chunk::OffsetMask;
1094*0fca6ea1SDimitry Andric     }
1095*0fca6ea1SDimitry Andric 
1096*0fca6ea1SDimitry Andric     Header.ClassId = ClassId & Chunk::ClassIdMask;
1097*0fca6ea1SDimitry Andric     Header.State = Chunk::State::Allocated;
1098*0fca6ea1SDimitry Andric     Header.OriginOrWasZeroed = Origin & Chunk::OriginMask;
1099*0fca6ea1SDimitry Andric     Header.SizeOrUnusedBytes = SizeOrUnusedBytes & Chunk::SizeOrUnusedBytesMask;
1100*0fca6ea1SDimitry Andric     Chunk::storeHeader(Cookie, reinterpret_cast<void *>(addHeaderTag(UserPtr)),
1101*0fca6ea1SDimitry Andric                        &Header);
1102*0fca6ea1SDimitry Andric 
1103*0fca6ea1SDimitry Andric     return reinterpret_cast<void *>(UserPtr);
1104*0fca6ea1SDimitry Andric   }
1105*0fca6ea1SDimitry Andric 
1106*0fca6ea1SDimitry Andric   NOINLINE void *
initChunkWithMemoryTagging(const uptr ClassId,const Chunk::Origin Origin,void * Block,const uptr UserPtr,const uptr Size,const uptr SizeOrUnusedBytes,const FillContentsMode FillContents)1107*0fca6ea1SDimitry Andric   initChunkWithMemoryTagging(const uptr ClassId, const Chunk::Origin Origin,
1108*0fca6ea1SDimitry Andric                              void *Block, const uptr UserPtr, const uptr Size,
1109*0fca6ea1SDimitry Andric                              const uptr SizeOrUnusedBytes,
1110*0fca6ea1SDimitry Andric                              const FillContentsMode FillContents) {
1111*0fca6ea1SDimitry Andric     const Options Options = Primary.Options.load();
1112*0fca6ea1SDimitry Andric     DCHECK(useMemoryTagging<AllocatorConfig>(Options));
1113*0fca6ea1SDimitry Andric 
1114*0fca6ea1SDimitry Andric     // Compute the default pointer before adding the header tag
1115*0fca6ea1SDimitry Andric     const uptr DefaultAlignedPtr =
1116*0fca6ea1SDimitry Andric         reinterpret_cast<uptr>(Block) + Chunk::getHeaderSize();
1117*0fca6ea1SDimitry Andric 
1118*0fca6ea1SDimitry Andric     void *Ptr = reinterpret_cast<void *>(UserPtr);
1119*0fca6ea1SDimitry Andric     void *TaggedPtr = Ptr;
1120*0fca6ea1SDimitry Andric 
1121*0fca6ea1SDimitry Andric     if (LIKELY(ClassId)) {
1122*0fca6ea1SDimitry Andric       // Init the primary chunk.
1123*0fca6ea1SDimitry Andric       //
1124*0fca6ea1SDimitry Andric       // We only need to zero or tag the contents for Primary backed
1125*0fca6ea1SDimitry Andric       // allocations. We only set tags for primary allocations in order to avoid
1126*0fca6ea1SDimitry Andric       // faulting potentially large numbers of pages for large secondary
1127*0fca6ea1SDimitry Andric       // allocations. We assume that guard pages are enough to protect these
1128*0fca6ea1SDimitry Andric       // allocations.
1129*0fca6ea1SDimitry Andric       //
1130*0fca6ea1SDimitry Andric       // FIXME: When the kernel provides a way to set the background tag of a
1131*0fca6ea1SDimitry Andric       // mapping, we should be able to tag secondary allocations as well.
1132*0fca6ea1SDimitry Andric       //
1133*0fca6ea1SDimitry Andric       // When memory tagging is enabled, zeroing the contents is done as part of
1134*0fca6ea1SDimitry Andric       // setting the tag.
1135*0fca6ea1SDimitry Andric 
1136*0fca6ea1SDimitry Andric       Chunk::UnpackedHeader Header;
1137*0fca6ea1SDimitry Andric       const uptr BlockSize = PrimaryT::getSizeByClassId(ClassId);
1138*0fca6ea1SDimitry Andric       const uptr BlockUptr = reinterpret_cast<uptr>(Block);
1139*0fca6ea1SDimitry Andric       const uptr BlockEnd = BlockUptr + BlockSize;
1140*0fca6ea1SDimitry Andric       // If possible, try to reuse the UAF tag that was set by deallocate().
1141*0fca6ea1SDimitry Andric       // For simplicity, only reuse tags if we have the same start address as
1142*0fca6ea1SDimitry Andric       // the previous allocation. This handles the majority of cases since
1143*0fca6ea1SDimitry Andric       // most allocations will not be more aligned than the minimum alignment.
1144*0fca6ea1SDimitry Andric       //
1145*0fca6ea1SDimitry Andric       // We need to handle situations involving reclaimed chunks, and retag
1146*0fca6ea1SDimitry Andric       // the reclaimed portions if necessary. In the case where the chunk is
1147*0fca6ea1SDimitry Andric       // fully reclaimed, the chunk's header will be zero, which will trigger
1148*0fca6ea1SDimitry Andric       // the code path for new mappings and invalid chunks that prepares the
1149*0fca6ea1SDimitry Andric       // chunk from scratch. There are three possibilities for partial
1150*0fca6ea1SDimitry Andric       // reclaiming:
1151*0fca6ea1SDimitry Andric       //
1152*0fca6ea1SDimitry Andric       // (1) Header was reclaimed, data was partially reclaimed.
1153*0fca6ea1SDimitry Andric       // (2) Header was not reclaimed, all data was reclaimed (e.g. because
1154*0fca6ea1SDimitry Andric       //     data started on a page boundary).
1155*0fca6ea1SDimitry Andric       // (3) Header was not reclaimed, data was partially reclaimed.
1156*0fca6ea1SDimitry Andric       //
1157*0fca6ea1SDimitry Andric       // Case (1) will be handled in the same way as for full reclaiming,
1158*0fca6ea1SDimitry Andric       // since the header will be zero.
1159*0fca6ea1SDimitry Andric       //
1160*0fca6ea1SDimitry Andric       // We can detect case (2) by loading the tag from the start
1161*0fca6ea1SDimitry Andric       // of the chunk. If it is zero, it means that either all data was
1162*0fca6ea1SDimitry Andric       // reclaimed (since we never use zero as the chunk tag), or that the
1163*0fca6ea1SDimitry Andric       // previous allocation was of size zero. Either way, we need to prepare
1164*0fca6ea1SDimitry Andric       // a new chunk from scratch.
1165*0fca6ea1SDimitry Andric       //
1166*0fca6ea1SDimitry Andric       // We can detect case (3) by moving to the next page (if covered by the
1167*0fca6ea1SDimitry Andric       // chunk) and loading the tag of its first granule. If it is zero, it
1168*0fca6ea1SDimitry Andric       // means that all following pages may need to be retagged. On the other
1169*0fca6ea1SDimitry Andric       // hand, if it is nonzero, we can assume that all following pages are
1170*0fca6ea1SDimitry Andric       // still tagged, according to the logic that if any of the pages
1171*0fca6ea1SDimitry Andric       // following the next page were reclaimed, the next page would have been
1172*0fca6ea1SDimitry Andric       // reclaimed as well.
1173*0fca6ea1SDimitry Andric       uptr TaggedUserPtr;
1174*0fca6ea1SDimitry Andric       uptr PrevUserPtr;
1175*0fca6ea1SDimitry Andric       if (getChunkFromBlock(BlockUptr, &PrevUserPtr, &Header) &&
1176*0fca6ea1SDimitry Andric           PrevUserPtr == UserPtr &&
1177*0fca6ea1SDimitry Andric           (TaggedUserPtr = loadTag(UserPtr)) != UserPtr) {
1178*0fca6ea1SDimitry Andric         uptr PrevEnd = TaggedUserPtr + Header.SizeOrUnusedBytes;
1179*0fca6ea1SDimitry Andric         const uptr NextPage = roundUp(TaggedUserPtr, getPageSizeCached());
1180*0fca6ea1SDimitry Andric         if (NextPage < PrevEnd && loadTag(NextPage) != NextPage)
1181*0fca6ea1SDimitry Andric           PrevEnd = NextPage;
1182*0fca6ea1SDimitry Andric         TaggedPtr = reinterpret_cast<void *>(TaggedUserPtr);
1183*0fca6ea1SDimitry Andric         resizeTaggedChunk(PrevEnd, TaggedUserPtr + Size, Size, BlockEnd);
1184*0fca6ea1SDimitry Andric         if (UNLIKELY(FillContents != NoFill && !Header.OriginOrWasZeroed)) {
1185*0fca6ea1SDimitry Andric           // If an allocation needs to be zeroed (i.e. calloc) we can normally
1186*0fca6ea1SDimitry Andric           // avoid zeroing the memory now since we can rely on memory having
1187*0fca6ea1SDimitry Andric           // been zeroed on free, as this is normally done while setting the
1188*0fca6ea1SDimitry Andric           // UAF tag. But if tagging was disabled per-thread when the memory
1189*0fca6ea1SDimitry Andric           // was freed, it would not have been retagged and thus zeroed, and
1190*0fca6ea1SDimitry Andric           // therefore it needs to be zeroed now.
1191*0fca6ea1SDimitry Andric           memset(TaggedPtr, 0,
1192*0fca6ea1SDimitry Andric                  Min(Size, roundUp(PrevEnd - TaggedUserPtr,
1193*0fca6ea1SDimitry Andric                                    archMemoryTagGranuleSize())));
1194*0fca6ea1SDimitry Andric         } else if (Size) {
1195*0fca6ea1SDimitry Andric           // Clear any stack metadata that may have previously been stored in
1196*0fca6ea1SDimitry Andric           // the chunk data.
1197*0fca6ea1SDimitry Andric           memset(TaggedPtr, 0, archMemoryTagGranuleSize());
1198*0fca6ea1SDimitry Andric         }
1199*0fca6ea1SDimitry Andric       } else {
1200*0fca6ea1SDimitry Andric         const uptr OddEvenMask =
1201*0fca6ea1SDimitry Andric             computeOddEvenMaskForPointerMaybe(Options, BlockUptr, ClassId);
1202*0fca6ea1SDimitry Andric         TaggedPtr = prepareTaggedChunk(Ptr, Size, OddEvenMask, BlockEnd);
1203*0fca6ea1SDimitry Andric       }
1204*0fca6ea1SDimitry Andric       storePrimaryAllocationStackMaybe(Options, Ptr);
1205*0fca6ea1SDimitry Andric     } else {
1206*0fca6ea1SDimitry Andric       // Init the secondary chunk.
1207*0fca6ea1SDimitry Andric 
1208*0fca6ea1SDimitry Andric       Block = addHeaderTag(Block);
1209*0fca6ea1SDimitry Andric       Ptr = addHeaderTag(Ptr);
1210*0fca6ea1SDimitry Andric       storeTags(reinterpret_cast<uptr>(Block), reinterpret_cast<uptr>(Ptr));
1211*0fca6ea1SDimitry Andric       storeSecondaryAllocationStackMaybe(Options, Ptr, Size);
1212*0fca6ea1SDimitry Andric     }
1213*0fca6ea1SDimitry Andric 
1214*0fca6ea1SDimitry Andric     Chunk::UnpackedHeader Header = {};
1215*0fca6ea1SDimitry Andric 
1216*0fca6ea1SDimitry Andric     if (UNLIKELY(DefaultAlignedPtr != UserPtr)) {
1217*0fca6ea1SDimitry Andric       const uptr Offset = UserPtr - DefaultAlignedPtr;
1218*0fca6ea1SDimitry Andric       DCHECK_GE(Offset, 2 * sizeof(u32));
1219*0fca6ea1SDimitry Andric       // The BlockMarker has no security purpose, but is specifically meant for
1220*0fca6ea1SDimitry Andric       // the chunk iteration function that can be used in debugging situations.
1221*0fca6ea1SDimitry Andric       // It is the only situation where we have to locate the start of a chunk
1222*0fca6ea1SDimitry Andric       // based on its block address.
1223*0fca6ea1SDimitry Andric       reinterpret_cast<u32 *>(Block)[0] = BlockMarker;
1224*0fca6ea1SDimitry Andric       reinterpret_cast<u32 *>(Block)[1] = static_cast<u32>(Offset);
1225*0fca6ea1SDimitry Andric       Header.Offset = (Offset >> MinAlignmentLog) & Chunk::OffsetMask;
1226*0fca6ea1SDimitry Andric     }
1227*0fca6ea1SDimitry Andric 
1228*0fca6ea1SDimitry Andric     Header.ClassId = ClassId & Chunk::ClassIdMask;
1229*0fca6ea1SDimitry Andric     Header.State = Chunk::State::Allocated;
1230*0fca6ea1SDimitry Andric     Header.OriginOrWasZeroed = Origin & Chunk::OriginMask;
1231*0fca6ea1SDimitry Andric     Header.SizeOrUnusedBytes = SizeOrUnusedBytes & Chunk::SizeOrUnusedBytesMask;
1232*0fca6ea1SDimitry Andric     Chunk::storeHeader(Cookie, Ptr, &Header);
1233*0fca6ea1SDimitry Andric 
1234*0fca6ea1SDimitry Andric     return TaggedPtr;
1235*0fca6ea1SDimitry Andric   }
1236*0fca6ea1SDimitry Andric 
quarantineOrDeallocateChunk(const Options & Options,void * TaggedPtr,Chunk::UnpackedHeader * Header,uptr Size)12375f757f3fSDimitry Andric   void quarantineOrDeallocateChunk(const Options &Options, void *TaggedPtr,
123806c3fb27SDimitry Andric                                    Chunk::UnpackedHeader *Header,
123906c3fb27SDimitry Andric                                    uptr Size) NO_THREAD_SAFETY_ANALYSIS {
1240fe6060f1SDimitry Andric     void *Ptr = getHeaderTaggedPointer(TaggedPtr);
1241fe6060f1SDimitry Andric     // If the quarantine is disabled, the actual size of a chunk is 0 or larger
1242fe6060f1SDimitry Andric     // than the maximum allowed, we return a chunk directly to the backend.
1243fe6060f1SDimitry Andric     // This purposefully underflows for Size == 0.
1244fe6060f1SDimitry Andric     const bool BypassQuarantine = !Quarantine.getCacheSize() ||
1245fe6060f1SDimitry Andric                                   ((Size - 1) >= QuarantineMaxChunkSize) ||
12465f757f3fSDimitry Andric                                   !Header->ClassId;
1247fe6060f1SDimitry Andric     if (BypassQuarantine)
12485f757f3fSDimitry Andric       Header->State = Chunk::State::Available;
1249fe6060f1SDimitry Andric     else
12505f757f3fSDimitry Andric       Header->State = Chunk::State::Quarantined;
1251*0fca6ea1SDimitry Andric 
1252*0fca6ea1SDimitry Andric     void *BlockBegin;
1253*0fca6ea1SDimitry Andric     if (LIKELY(!useMemoryTagging<AllocatorConfig>(Options))) {
1254*0fca6ea1SDimitry Andric       Header->OriginOrWasZeroed = 0U;
1255*0fca6ea1SDimitry Andric       if (BypassQuarantine && allocatorSupportsMemoryTagging<AllocatorConfig>())
1256*0fca6ea1SDimitry Andric         Ptr = untagPointer(Ptr);
1257*0fca6ea1SDimitry Andric       BlockBegin = getBlockBegin(Ptr, Header);
1258*0fca6ea1SDimitry Andric     } else {
1259*0fca6ea1SDimitry Andric       Header->OriginOrWasZeroed =
1260*0fca6ea1SDimitry Andric           Header->ClassId && !TSDRegistry.getDisableMemInit();
1261*0fca6ea1SDimitry Andric       BlockBegin =
1262*0fca6ea1SDimitry Andric           retagBlock(Options, TaggedPtr, Ptr, Header, Size, BypassQuarantine);
1263*0fca6ea1SDimitry Andric     }
1264*0fca6ea1SDimitry Andric 
12655f757f3fSDimitry Andric     Chunk::storeHeader(Cookie, Ptr, Header);
1266fe6060f1SDimitry Andric 
1267*0fca6ea1SDimitry Andric     if (BypassQuarantine) {
1268*0fca6ea1SDimitry Andric       const uptr ClassId = Header->ClassId;
1269*0fca6ea1SDimitry Andric       if (LIKELY(ClassId)) {
1270*0fca6ea1SDimitry Andric         bool CacheDrained;
1271*0fca6ea1SDimitry Andric         {
1272*0fca6ea1SDimitry Andric           typename TSDRegistryT::ScopedTSD TSD(TSDRegistry);
1273*0fca6ea1SDimitry Andric           CacheDrained = TSD->getCache().deallocate(ClassId, BlockBegin);
1274*0fca6ea1SDimitry Andric         }
1275*0fca6ea1SDimitry Andric         // When we have drained some blocks back to the Primary from TSD, that
1276*0fca6ea1SDimitry Andric         // implies that we may have the chance to release some pages as well.
1277*0fca6ea1SDimitry Andric         // Note that in order not to block other thread's accessing the TSD,
1278*0fca6ea1SDimitry Andric         // release the TSD first then try the page release.
1279*0fca6ea1SDimitry Andric         if (CacheDrained)
1280*0fca6ea1SDimitry Andric           Primary.tryReleaseToOS(ClassId, ReleaseToOS::Normal);
1281*0fca6ea1SDimitry Andric       } else {
1282*0fca6ea1SDimitry Andric         Secondary.deallocate(Options, BlockBegin);
1283*0fca6ea1SDimitry Andric       }
1284*0fca6ea1SDimitry Andric     } else {
1285*0fca6ea1SDimitry Andric       typename TSDRegistryT::ScopedTSD TSD(TSDRegistry);
1286*0fca6ea1SDimitry Andric       Quarantine.put(&TSD->getQuarantineCache(),
1287*0fca6ea1SDimitry Andric                      QuarantineCallback(*this, TSD->getCache()), Ptr, Size);
1288*0fca6ea1SDimitry Andric     }
1289*0fca6ea1SDimitry Andric   }
1290*0fca6ea1SDimitry Andric 
retagBlock(const Options & Options,void * TaggedPtr,void * & Ptr,Chunk::UnpackedHeader * Header,const uptr Size,bool BypassQuarantine)1291*0fca6ea1SDimitry Andric   NOINLINE void *retagBlock(const Options &Options, void *TaggedPtr, void *&Ptr,
1292*0fca6ea1SDimitry Andric                             Chunk::UnpackedHeader *Header, const uptr Size,
1293*0fca6ea1SDimitry Andric                             bool BypassQuarantine) {
1294*0fca6ea1SDimitry Andric     DCHECK(useMemoryTagging<AllocatorConfig>(Options));
1295*0fca6ea1SDimitry Andric 
1296*0fca6ea1SDimitry Andric     const u8 PrevTag = extractTag(reinterpret_cast<uptr>(TaggedPtr));
1297fe6060f1SDimitry Andric     storeDeallocationStackMaybe(Options, Ptr, PrevTag, Size);
1298*0fca6ea1SDimitry Andric     if (Header->ClassId && !TSDRegistry.getDisableMemInit()) {
12995ffd83dbSDimitry Andric       uptr TaggedBegin, TaggedEnd;
1300e8d8bef9SDimitry Andric       const uptr OddEvenMask = computeOddEvenMaskForPointerMaybe(
13015f757f3fSDimitry Andric           Options, reinterpret_cast<uptr>(getBlockBegin(Ptr, Header)),
13025f757f3fSDimitry Andric           Header->ClassId);
1303fe6060f1SDimitry Andric       // Exclude the previous tag so that immediate use after free is
1304fe6060f1SDimitry Andric       // detected 100% of the time.
1305e8d8bef9SDimitry Andric       setRandomTag(Ptr, Size, OddEvenMask | (1UL << PrevTag), &TaggedBegin,
1306e8d8bef9SDimitry Andric                    &TaggedEnd);
1307e8d8bef9SDimitry Andric     }
1308*0fca6ea1SDimitry Andric 
1309fe6060f1SDimitry Andric     Ptr = untagPointer(Ptr);
13105f757f3fSDimitry Andric     void *BlockBegin = getBlockBegin(Ptr, Header);
1311*0fca6ea1SDimitry Andric     if (BypassQuarantine && !Header->ClassId) {
1312fe6060f1SDimitry Andric       storeTags(reinterpret_cast<uptr>(BlockBegin),
1313fe6060f1SDimitry Andric                 reinterpret_cast<uptr>(Ptr));
13140b57cec5SDimitry Andric     }
1315*0fca6ea1SDimitry Andric 
1316*0fca6ea1SDimitry Andric     return BlockBegin;
13170b57cec5SDimitry Andric   }
13180b57cec5SDimitry Andric 
getChunkFromBlock(uptr Block,uptr * Chunk,Chunk::UnpackedHeader * Header)1319480093f4SDimitry Andric   bool getChunkFromBlock(uptr Block, uptr *Chunk,
1320480093f4SDimitry Andric                          Chunk::UnpackedHeader *Header) {
13215ffd83dbSDimitry Andric     *Chunk =
13225ffd83dbSDimitry Andric         Block + getChunkOffsetFromBlock(reinterpret_cast<const char *>(Block));
1323480093f4SDimitry Andric     return Chunk::isValid(Cookie, reinterpret_cast<void *>(*Chunk), Header);
13240b57cec5SDimitry Andric   }
132568d75effSDimitry Andric 
getChunkOffsetFromBlock(const char * Block)13265ffd83dbSDimitry Andric   static uptr getChunkOffsetFromBlock(const char *Block) {
13275ffd83dbSDimitry Andric     u32 Offset = 0;
13285ffd83dbSDimitry Andric     if (reinterpret_cast<const u32 *>(Block)[0] == BlockMarker)
13295ffd83dbSDimitry Andric       Offset = reinterpret_cast<const u32 *>(Block)[1];
13305ffd83dbSDimitry Andric     return Offset + Chunk::getHeaderSize();
13315ffd83dbSDimitry Andric   }
13325ffd83dbSDimitry Andric 
1333fe6060f1SDimitry Andric   // Set the tag of the granule past the end of the allocation to 0, to catch
1334fe6060f1SDimitry Andric   // linear overflows even if a previous larger allocation used the same block
1335fe6060f1SDimitry Andric   // and tag. Only do this if the granule past the end is in our block, because
1336fe6060f1SDimitry Andric   // this would otherwise lead to a SEGV if the allocation covers the entire
1337fe6060f1SDimitry Andric   // block and our block is at the end of a mapping. The tag of the next block's
1338fe6060f1SDimitry Andric   // header granule will be set to 0, so it will serve the purpose of catching
1339fe6060f1SDimitry Andric   // linear overflows in this case.
1340fe6060f1SDimitry Andric   //
1341fe6060f1SDimitry Andric   // For allocations of size 0 we do not end up storing the address tag to the
1342fe6060f1SDimitry Andric   // memory tag space, which getInlineErrorInfo() normally relies on to match
1343fe6060f1SDimitry Andric   // address tags against chunks. To allow matching in this case we store the
1344fe6060f1SDimitry Andric   // address tag in the first byte of the chunk.
storeEndMarker(uptr End,uptr Size,uptr BlockEnd)1345fe6060f1SDimitry Andric   void storeEndMarker(uptr End, uptr Size, uptr BlockEnd) {
1346fe6060f1SDimitry Andric     DCHECK_EQ(BlockEnd, untagPointer(BlockEnd));
1347fe6060f1SDimitry Andric     uptr UntaggedEnd = untagPointer(End);
1348fe6060f1SDimitry Andric     if (UntaggedEnd != BlockEnd) {
1349fe6060f1SDimitry Andric       storeTag(UntaggedEnd);
1350fe6060f1SDimitry Andric       if (Size == 0)
1351fe6060f1SDimitry Andric         *reinterpret_cast<u8 *>(UntaggedEnd) = extractTag(End);
1352fe6060f1SDimitry Andric     }
1353fe6060f1SDimitry Andric   }
1354fe6060f1SDimitry Andric 
prepareTaggedChunk(void * Ptr,uptr Size,uptr ExcludeMask,uptr BlockEnd)1355fe6060f1SDimitry Andric   void *prepareTaggedChunk(void *Ptr, uptr Size, uptr ExcludeMask,
1356fe6060f1SDimitry Andric                            uptr BlockEnd) {
1357fe6060f1SDimitry Andric     // Prepare the granule before the chunk to store the chunk header by setting
1358fe6060f1SDimitry Andric     // its tag to 0. Normally its tag will already be 0, but in the case where a
1359fe6060f1SDimitry Andric     // chunk holding a low alignment allocation is reused for a higher alignment
1360fe6060f1SDimitry Andric     // allocation, the chunk may already have a non-zero tag from the previous
1361fe6060f1SDimitry Andric     // allocation.
1362fe6060f1SDimitry Andric     storeTag(reinterpret_cast<uptr>(Ptr) - archMemoryTagGranuleSize());
1363fe6060f1SDimitry Andric 
1364fe6060f1SDimitry Andric     uptr TaggedBegin, TaggedEnd;
1365fe6060f1SDimitry Andric     setRandomTag(Ptr, Size, ExcludeMask, &TaggedBegin, &TaggedEnd);
1366fe6060f1SDimitry Andric 
1367fe6060f1SDimitry Andric     storeEndMarker(TaggedEnd, Size, BlockEnd);
1368fe6060f1SDimitry Andric     return reinterpret_cast<void *>(TaggedBegin);
1369fe6060f1SDimitry Andric   }
1370fe6060f1SDimitry Andric 
resizeTaggedChunk(uptr OldPtr,uptr NewPtr,uptr NewSize,uptr BlockEnd)1371fe6060f1SDimitry Andric   void resizeTaggedChunk(uptr OldPtr, uptr NewPtr, uptr NewSize,
1372fe6060f1SDimitry Andric                          uptr BlockEnd) {
137306c3fb27SDimitry Andric     uptr RoundOldPtr = roundUp(OldPtr, archMemoryTagGranuleSize());
1374fe6060f1SDimitry Andric     uptr RoundNewPtr;
1375fe6060f1SDimitry Andric     if (RoundOldPtr >= NewPtr) {
1376fe6060f1SDimitry Andric       // If the allocation is shrinking we just need to set the tag past the end
1377fe6060f1SDimitry Andric       // of the allocation to 0. See explanation in storeEndMarker() above.
137806c3fb27SDimitry Andric       RoundNewPtr = roundUp(NewPtr, archMemoryTagGranuleSize());
1379fe6060f1SDimitry Andric     } else {
1380fe6060f1SDimitry Andric       // Set the memory tag of the region
138106c3fb27SDimitry Andric       // [RoundOldPtr, roundUp(NewPtr, archMemoryTagGranuleSize()))
1382fe6060f1SDimitry Andric       // to the pointer tag stored in OldPtr.
1383fe6060f1SDimitry Andric       RoundNewPtr = storeTags(RoundOldPtr, NewPtr);
1384fe6060f1SDimitry Andric     }
1385fe6060f1SDimitry Andric     storeEndMarker(RoundNewPtr, NewSize, BlockEnd);
1386fe6060f1SDimitry Andric   }
1387fe6060f1SDimitry Andric 
storePrimaryAllocationStackMaybe(const Options & Options,void * Ptr)13885f757f3fSDimitry Andric   void storePrimaryAllocationStackMaybe(const Options &Options, void *Ptr) {
1389e8d8bef9SDimitry Andric     if (!UNLIKELY(Options.get(OptionBit::TrackAllocationStacks)))
13905ffd83dbSDimitry Andric       return;
1391*0fca6ea1SDimitry Andric     AllocationRingBuffer *RB = getRingBuffer();
1392*0fca6ea1SDimitry Andric     if (!RB)
1393*0fca6ea1SDimitry Andric       return;
13945ffd83dbSDimitry Andric     auto *Ptr32 = reinterpret_cast<u32 *>(Ptr);
1395*0fca6ea1SDimitry Andric     Ptr32[MemTagAllocationTraceIndex] = collectStackTrace(RB->Depot);
13965ffd83dbSDimitry Andric     Ptr32[MemTagAllocationTidIndex] = getThreadID();
13975ffd83dbSDimitry Andric   }
13985ffd83dbSDimitry Andric 
storeRingBufferEntry(AllocationRingBuffer * RB,void * Ptr,u32 AllocationTrace,u32 AllocationTid,uptr AllocationSize,u32 DeallocationTrace,u32 DeallocationTid)1399*0fca6ea1SDimitry Andric   void storeRingBufferEntry(AllocationRingBuffer *RB, void *Ptr,
1400*0fca6ea1SDimitry Andric                             u32 AllocationTrace, u32 AllocationTid,
1401fe6060f1SDimitry Andric                             uptr AllocationSize, u32 DeallocationTrace,
1402fe6060f1SDimitry Andric                             u32 DeallocationTid) {
1403*0fca6ea1SDimitry Andric     uptr Pos = atomic_fetch_add(&RB->Pos, 1, memory_order_relaxed);
1404fe6060f1SDimitry Andric     typename AllocationRingBuffer::Entry *Entry =
1405*0fca6ea1SDimitry Andric         getRingBufferEntry(RB, Pos % RB->RingBufferElements);
1406fe6060f1SDimitry Andric 
1407fe6060f1SDimitry Andric     // First invalidate our entry so that we don't attempt to interpret a
1408fe6060f1SDimitry Andric     // partially written state in getSecondaryErrorInfo(). The fences below
1409fe6060f1SDimitry Andric     // ensure that the compiler does not move the stores to Ptr in between the
1410fe6060f1SDimitry Andric     // stores to the other fields.
1411fe6060f1SDimitry Andric     atomic_store_relaxed(&Entry->Ptr, 0);
1412fe6060f1SDimitry Andric 
1413fe6060f1SDimitry Andric     __atomic_signal_fence(__ATOMIC_SEQ_CST);
1414fe6060f1SDimitry Andric     atomic_store_relaxed(&Entry->AllocationTrace, AllocationTrace);
1415fe6060f1SDimitry Andric     atomic_store_relaxed(&Entry->AllocationTid, AllocationTid);
1416fe6060f1SDimitry Andric     atomic_store_relaxed(&Entry->AllocationSize, AllocationSize);
1417fe6060f1SDimitry Andric     atomic_store_relaxed(&Entry->DeallocationTrace, DeallocationTrace);
1418fe6060f1SDimitry Andric     atomic_store_relaxed(&Entry->DeallocationTid, DeallocationTid);
1419fe6060f1SDimitry Andric     __atomic_signal_fence(__ATOMIC_SEQ_CST);
1420fe6060f1SDimitry Andric 
1421fe6060f1SDimitry Andric     atomic_store_relaxed(&Entry->Ptr, reinterpret_cast<uptr>(Ptr));
1422fe6060f1SDimitry Andric   }
1423fe6060f1SDimitry Andric 
storeSecondaryAllocationStackMaybe(const Options & Options,void * Ptr,uptr Size)14245f757f3fSDimitry Andric   void storeSecondaryAllocationStackMaybe(const Options &Options, void *Ptr,
1425fe6060f1SDimitry Andric                                           uptr Size) {
1426e8d8bef9SDimitry Andric     if (!UNLIKELY(Options.get(OptionBit::TrackAllocationStacks)))
14275ffd83dbSDimitry Andric       return;
1428*0fca6ea1SDimitry Andric     AllocationRingBuffer *RB = getRingBuffer();
1429*0fca6ea1SDimitry Andric     if (!RB)
1430*0fca6ea1SDimitry Andric       return;
1431*0fca6ea1SDimitry Andric     u32 Trace = collectStackTrace(RB->Depot);
1432fe6060f1SDimitry Andric     u32 Tid = getThreadID();
1433fe6060f1SDimitry Andric 
14345ffd83dbSDimitry Andric     auto *Ptr32 = reinterpret_cast<u32 *>(Ptr);
1435fe6060f1SDimitry Andric     Ptr32[MemTagAllocationTraceIndex] = Trace;
1436fe6060f1SDimitry Andric     Ptr32[MemTagAllocationTidIndex] = Tid;
1437fe6060f1SDimitry Andric 
1438*0fca6ea1SDimitry Andric     storeRingBufferEntry(RB, untagPointer(Ptr), Trace, Tid, Size, 0, 0);
1439fe6060f1SDimitry Andric   }
1440fe6060f1SDimitry Andric 
storeDeallocationStackMaybe(const Options & Options,void * Ptr,u8 PrevTag,uptr Size)14415f757f3fSDimitry Andric   void storeDeallocationStackMaybe(const Options &Options, void *Ptr,
14425f757f3fSDimitry Andric                                    u8 PrevTag, uptr Size) {
1443fe6060f1SDimitry Andric     if (!UNLIKELY(Options.get(OptionBit::TrackAllocationStacks)))
1444fe6060f1SDimitry Andric       return;
1445*0fca6ea1SDimitry Andric     AllocationRingBuffer *RB = getRingBuffer();
1446*0fca6ea1SDimitry Andric     if (!RB)
1447*0fca6ea1SDimitry Andric       return;
1448fe6060f1SDimitry Andric     auto *Ptr32 = reinterpret_cast<u32 *>(Ptr);
1449fe6060f1SDimitry Andric     u32 AllocationTrace = Ptr32[MemTagAllocationTraceIndex];
1450fe6060f1SDimitry Andric     u32 AllocationTid = Ptr32[MemTagAllocationTidIndex];
1451fe6060f1SDimitry Andric 
1452*0fca6ea1SDimitry Andric     u32 DeallocationTrace = collectStackTrace(RB->Depot);
1453fe6060f1SDimitry Andric     u32 DeallocationTid = getThreadID();
1454fe6060f1SDimitry Andric 
1455*0fca6ea1SDimitry Andric     storeRingBufferEntry(RB, addFixedTag(untagPointer(Ptr), PrevTag),
1456fe6060f1SDimitry Andric                          AllocationTrace, AllocationTid, Size,
1457fe6060f1SDimitry Andric                          DeallocationTrace, DeallocationTid);
1458fe6060f1SDimitry Andric   }
1459fe6060f1SDimitry Andric 
1460fe6060f1SDimitry Andric   static const size_t NumErrorReports =
146181ad6265SDimitry Andric       sizeof(((scudo_error_info *)nullptr)->reports) /
146281ad6265SDimitry Andric       sizeof(((scudo_error_info *)nullptr)->reports[0]);
1463fe6060f1SDimitry Andric 
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)1464fe6060f1SDimitry Andric   static void getInlineErrorInfo(struct scudo_error_info *ErrorInfo,
1465fe6060f1SDimitry Andric                                  size_t &NextErrorReport, uintptr_t FaultAddr,
1466fe6060f1SDimitry Andric                                  const StackDepot *Depot,
1467fe6060f1SDimitry Andric                                  const char *RegionInfoPtr, const char *Memory,
1468fe6060f1SDimitry Andric                                  const char *MemoryTags, uintptr_t MemoryAddr,
1469fe6060f1SDimitry Andric                                  size_t MemorySize, size_t MinDistance,
1470fe6060f1SDimitry Andric                                  size_t MaxDistance) {
1471fe6060f1SDimitry Andric     uptr UntaggedFaultAddr = untagPointer(FaultAddr);
1472fe6060f1SDimitry Andric     u8 FaultAddrTag = extractTag(FaultAddr);
1473fe6060f1SDimitry Andric     BlockInfo Info =
1474fe6060f1SDimitry Andric         PrimaryT::findNearestBlock(RegionInfoPtr, UntaggedFaultAddr);
1475fe6060f1SDimitry Andric 
1476fe6060f1SDimitry Andric     auto GetGranule = [&](uptr Addr, const char **Data, uint8_t *Tag) -> bool {
1477fe6060f1SDimitry Andric       if (Addr < MemoryAddr || Addr + archMemoryTagGranuleSize() < Addr ||
1478fe6060f1SDimitry Andric           Addr + archMemoryTagGranuleSize() > MemoryAddr + MemorySize)
1479fe6060f1SDimitry Andric         return false;
1480fe6060f1SDimitry Andric       *Data = &Memory[Addr - MemoryAddr];
1481fe6060f1SDimitry Andric       *Tag = static_cast<u8>(
1482fe6060f1SDimitry Andric           MemoryTags[(Addr - MemoryAddr) / archMemoryTagGranuleSize()]);
1483fe6060f1SDimitry Andric       return true;
1484fe6060f1SDimitry Andric     };
1485fe6060f1SDimitry Andric 
1486fe6060f1SDimitry Andric     auto ReadBlock = [&](uptr Addr, uptr *ChunkAddr,
1487fe6060f1SDimitry Andric                          Chunk::UnpackedHeader *Header, const u32 **Data,
1488fe6060f1SDimitry Andric                          u8 *Tag) {
1489fe6060f1SDimitry Andric       const char *BlockBegin;
1490fe6060f1SDimitry Andric       u8 BlockBeginTag;
1491fe6060f1SDimitry Andric       if (!GetGranule(Addr, &BlockBegin, &BlockBeginTag))
1492fe6060f1SDimitry Andric         return false;
1493fe6060f1SDimitry Andric       uptr ChunkOffset = getChunkOffsetFromBlock(BlockBegin);
1494fe6060f1SDimitry Andric       *ChunkAddr = Addr + ChunkOffset;
1495fe6060f1SDimitry Andric 
1496fe6060f1SDimitry Andric       const char *ChunkBegin;
1497fe6060f1SDimitry Andric       if (!GetGranule(*ChunkAddr, &ChunkBegin, Tag))
1498fe6060f1SDimitry Andric         return false;
1499fe6060f1SDimitry Andric       *Header = *reinterpret_cast<const Chunk::UnpackedHeader *>(
1500fe6060f1SDimitry Andric           ChunkBegin - Chunk::getHeaderSize());
1501fe6060f1SDimitry Andric       *Data = reinterpret_cast<const u32 *>(ChunkBegin);
1502fe6060f1SDimitry Andric 
1503fe6060f1SDimitry Andric       // Allocations of size 0 will have stashed the tag in the first byte of
1504fe6060f1SDimitry Andric       // the chunk, see storeEndMarker().
1505fe6060f1SDimitry Andric       if (Header->SizeOrUnusedBytes == 0)
1506fe6060f1SDimitry Andric         *Tag = static_cast<u8>(*ChunkBegin);
1507fe6060f1SDimitry Andric 
1508fe6060f1SDimitry Andric       return true;
1509fe6060f1SDimitry Andric     };
1510fe6060f1SDimitry Andric 
1511fe6060f1SDimitry Andric     if (NextErrorReport == NumErrorReports)
1512fe6060f1SDimitry Andric       return;
1513fe6060f1SDimitry Andric 
1514fe6060f1SDimitry Andric     auto CheckOOB = [&](uptr BlockAddr) {
1515fe6060f1SDimitry Andric       if (BlockAddr < Info.RegionBegin || BlockAddr >= Info.RegionEnd)
1516fe6060f1SDimitry Andric         return false;
1517fe6060f1SDimitry Andric 
1518fe6060f1SDimitry Andric       uptr ChunkAddr;
1519fe6060f1SDimitry Andric       Chunk::UnpackedHeader Header;
1520fe6060f1SDimitry Andric       const u32 *Data;
1521fe6060f1SDimitry Andric       uint8_t Tag;
1522fe6060f1SDimitry Andric       if (!ReadBlock(BlockAddr, &ChunkAddr, &Header, &Data, &Tag) ||
1523fe6060f1SDimitry Andric           Header.State != Chunk::State::Allocated || Tag != FaultAddrTag)
1524fe6060f1SDimitry Andric         return false;
1525fe6060f1SDimitry Andric 
1526fe6060f1SDimitry Andric       auto *R = &ErrorInfo->reports[NextErrorReport++];
1527fe6060f1SDimitry Andric       R->error_type =
1528fe6060f1SDimitry Andric           UntaggedFaultAddr < ChunkAddr ? BUFFER_UNDERFLOW : BUFFER_OVERFLOW;
1529fe6060f1SDimitry Andric       R->allocation_address = ChunkAddr;
1530fe6060f1SDimitry Andric       R->allocation_size = Header.SizeOrUnusedBytes;
1531*0fca6ea1SDimitry Andric       if (Depot) {
1532fe6060f1SDimitry Andric         collectTraceMaybe(Depot, R->allocation_trace,
1533fe6060f1SDimitry Andric                           Data[MemTagAllocationTraceIndex]);
1534*0fca6ea1SDimitry Andric       }
1535fe6060f1SDimitry Andric       R->allocation_tid = Data[MemTagAllocationTidIndex];
1536fe6060f1SDimitry Andric       return NextErrorReport == NumErrorReports;
1537fe6060f1SDimitry Andric     };
1538fe6060f1SDimitry Andric 
1539fe6060f1SDimitry Andric     if (MinDistance == 0 && CheckOOB(Info.BlockBegin))
1540fe6060f1SDimitry Andric       return;
1541fe6060f1SDimitry Andric 
1542fe6060f1SDimitry Andric     for (size_t I = Max<size_t>(MinDistance, 1); I != MaxDistance; ++I)
1543fe6060f1SDimitry Andric       if (CheckOOB(Info.BlockBegin + I * Info.BlockSize) ||
1544fe6060f1SDimitry Andric           CheckOOB(Info.BlockBegin - I * Info.BlockSize))
1545fe6060f1SDimitry Andric         return;
1546fe6060f1SDimitry Andric   }
1547fe6060f1SDimitry Andric 
getRingBufferErrorInfo(struct scudo_error_info * ErrorInfo,size_t & NextErrorReport,uintptr_t FaultAddr,const StackDepot * Depot,const char * RingBufferPtr,size_t RingBufferSize)1548fe6060f1SDimitry Andric   static void getRingBufferErrorInfo(struct scudo_error_info *ErrorInfo,
1549fe6060f1SDimitry Andric                                      size_t &NextErrorReport,
1550fe6060f1SDimitry Andric                                      uintptr_t FaultAddr,
1551fe6060f1SDimitry Andric                                      const StackDepot *Depot,
15525f757f3fSDimitry Andric                                      const char *RingBufferPtr,
15535f757f3fSDimitry Andric                                      size_t RingBufferSize) {
1554fe6060f1SDimitry Andric     auto *RingBuffer =
1555fe6060f1SDimitry Andric         reinterpret_cast<const AllocationRingBuffer *>(RingBufferPtr);
15565f757f3fSDimitry Andric     size_t RingBufferElements = ringBufferElementsFromBytes(RingBufferSize);
1557*0fca6ea1SDimitry Andric     if (!RingBuffer || RingBufferElements == 0 || !Depot)
1558bdd1243dSDimitry Andric       return;
1559fe6060f1SDimitry Andric     uptr Pos = atomic_load_relaxed(&RingBuffer->Pos);
1560fe6060f1SDimitry Andric 
15615f757f3fSDimitry Andric     for (uptr I = Pos - 1; I != Pos - 1 - RingBufferElements &&
15625f757f3fSDimitry Andric                            NextErrorReport != NumErrorReports;
1563fe6060f1SDimitry Andric          --I) {
1564*0fca6ea1SDimitry Andric       auto *Entry = getRingBufferEntry(RingBuffer, I % RingBufferElements);
1565fe6060f1SDimitry Andric       uptr EntryPtr = atomic_load_relaxed(&Entry->Ptr);
1566fe6060f1SDimitry Andric       if (!EntryPtr)
1567fe6060f1SDimitry Andric         continue;
1568fe6060f1SDimitry Andric 
1569fe6060f1SDimitry Andric       uptr UntaggedEntryPtr = untagPointer(EntryPtr);
1570fe6060f1SDimitry Andric       uptr EntrySize = atomic_load_relaxed(&Entry->AllocationSize);
1571fe6060f1SDimitry Andric       u32 AllocationTrace = atomic_load_relaxed(&Entry->AllocationTrace);
1572fe6060f1SDimitry Andric       u32 AllocationTid = atomic_load_relaxed(&Entry->AllocationTid);
1573fe6060f1SDimitry Andric       u32 DeallocationTrace = atomic_load_relaxed(&Entry->DeallocationTrace);
1574fe6060f1SDimitry Andric       u32 DeallocationTid = atomic_load_relaxed(&Entry->DeallocationTid);
1575fe6060f1SDimitry Andric 
1576fe6060f1SDimitry Andric       if (DeallocationTid) {
1577fe6060f1SDimitry Andric         // For UAF we only consider in-bounds fault addresses because
1578fe6060f1SDimitry Andric         // out-of-bounds UAF is rare and attempting to detect it is very likely
1579fe6060f1SDimitry Andric         // to result in false positives.
1580fe6060f1SDimitry Andric         if (FaultAddr < EntryPtr || FaultAddr >= EntryPtr + EntrySize)
1581fe6060f1SDimitry Andric           continue;
1582fe6060f1SDimitry Andric       } else {
1583fe6060f1SDimitry Andric         // Ring buffer OOB is only possible with secondary allocations. In this
1584fe6060f1SDimitry Andric         // case we are guaranteed a guard region of at least a page on either
1585fe6060f1SDimitry Andric         // side of the allocation (guard page on the right, guard page + tagged
1586fe6060f1SDimitry Andric         // region on the left), so ignore any faults outside of that range.
1587fe6060f1SDimitry Andric         if (FaultAddr < EntryPtr - getPageSizeCached() ||
1588fe6060f1SDimitry Andric             FaultAddr >= EntryPtr + EntrySize + getPageSizeCached())
1589fe6060f1SDimitry Andric           continue;
1590fe6060f1SDimitry Andric 
1591fe6060f1SDimitry Andric         // For UAF the ring buffer will contain two entries, one for the
1592fe6060f1SDimitry Andric         // allocation and another for the deallocation. Don't report buffer
1593fe6060f1SDimitry Andric         // overflow/underflow using the allocation entry if we have already
1594fe6060f1SDimitry Andric         // collected a report from the deallocation entry.
1595fe6060f1SDimitry Andric         bool Found = false;
1596fe6060f1SDimitry Andric         for (uptr J = 0; J != NextErrorReport; ++J) {
1597fe6060f1SDimitry Andric           if (ErrorInfo->reports[J].allocation_address == UntaggedEntryPtr) {
1598fe6060f1SDimitry Andric             Found = true;
1599fe6060f1SDimitry Andric             break;
1600fe6060f1SDimitry Andric           }
1601fe6060f1SDimitry Andric         }
1602fe6060f1SDimitry Andric         if (Found)
1603fe6060f1SDimitry Andric           continue;
1604fe6060f1SDimitry Andric       }
1605fe6060f1SDimitry Andric 
1606fe6060f1SDimitry Andric       auto *R = &ErrorInfo->reports[NextErrorReport++];
1607fe6060f1SDimitry Andric       if (DeallocationTid)
1608fe6060f1SDimitry Andric         R->error_type = USE_AFTER_FREE;
1609fe6060f1SDimitry Andric       else if (FaultAddr < EntryPtr)
1610fe6060f1SDimitry Andric         R->error_type = BUFFER_UNDERFLOW;
1611fe6060f1SDimitry Andric       else
1612fe6060f1SDimitry Andric         R->error_type = BUFFER_OVERFLOW;
1613fe6060f1SDimitry Andric 
1614fe6060f1SDimitry Andric       R->allocation_address = UntaggedEntryPtr;
1615fe6060f1SDimitry Andric       R->allocation_size = EntrySize;
1616fe6060f1SDimitry Andric       collectTraceMaybe(Depot, R->allocation_trace, AllocationTrace);
1617fe6060f1SDimitry Andric       R->allocation_tid = AllocationTid;
1618fe6060f1SDimitry Andric       collectTraceMaybe(Depot, R->deallocation_trace, DeallocationTrace);
1619fe6060f1SDimitry Andric       R->deallocation_tid = DeallocationTid;
1620fe6060f1SDimitry Andric     }
16215ffd83dbSDimitry Andric   }
16225ffd83dbSDimitry Andric 
getStats(ScopedString * Str)162368d75effSDimitry Andric   uptr getStats(ScopedString *Str) {
162468d75effSDimitry Andric     Primary.getStats(Str);
162568d75effSDimitry Andric     Secondary.getStats(Str);
162668d75effSDimitry Andric     Quarantine.getStats(Str);
162706c3fb27SDimitry Andric     TSDRegistry.getStats(Str);
162868d75effSDimitry Andric     return Str->length();
162968d75effSDimitry Andric   }
1630bdd1243dSDimitry Andric 
1631bdd1243dSDimitry Andric   static typename AllocationRingBuffer::Entry *
getRingBufferEntry(AllocationRingBuffer * RB,uptr N)1632*0fca6ea1SDimitry Andric   getRingBufferEntry(AllocationRingBuffer *RB, uptr N) {
1633*0fca6ea1SDimitry Andric     char *RBEntryStart =
1634*0fca6ea1SDimitry Andric         &reinterpret_cast<char *>(RB)[sizeof(AllocationRingBuffer)];
1635bdd1243dSDimitry Andric     return &reinterpret_cast<typename AllocationRingBuffer::Entry *>(
1636*0fca6ea1SDimitry Andric         RBEntryStart)[N];
1637bdd1243dSDimitry Andric   }
1638bdd1243dSDimitry Andric   static const typename AllocationRingBuffer::Entry *
getRingBufferEntry(const AllocationRingBuffer * RB,uptr N)1639*0fca6ea1SDimitry Andric   getRingBufferEntry(const AllocationRingBuffer *RB, uptr N) {
1640*0fca6ea1SDimitry Andric     const char *RBEntryStart =
1641*0fca6ea1SDimitry Andric         &reinterpret_cast<const char *>(RB)[sizeof(AllocationRingBuffer)];
1642bdd1243dSDimitry Andric     return &reinterpret_cast<const typename AllocationRingBuffer::Entry *>(
1643*0fca6ea1SDimitry Andric         RBEntryStart)[N];
1644bdd1243dSDimitry Andric   }
1645bdd1243dSDimitry Andric 
initRingBufferMaybe()1646*0fca6ea1SDimitry Andric   void initRingBufferMaybe() {
1647*0fca6ea1SDimitry Andric     ScopedLock L(RingBufferInitLock);
1648*0fca6ea1SDimitry Andric     if (getRingBuffer() != nullptr)
16495f757f3fSDimitry Andric       return;
1650*0fca6ea1SDimitry Andric 
1651*0fca6ea1SDimitry Andric     int ring_buffer_size = getFlags()->allocation_ring_buffer_size;
1652*0fca6ea1SDimitry Andric     if (ring_buffer_size <= 0)
1653*0fca6ea1SDimitry Andric       return;
1654*0fca6ea1SDimitry Andric 
1655*0fca6ea1SDimitry Andric     u32 AllocationRingBufferSize = static_cast<u32>(ring_buffer_size);
1656*0fca6ea1SDimitry Andric 
1657*0fca6ea1SDimitry Andric     // We store alloc and free stacks for each entry.
1658*0fca6ea1SDimitry Andric     constexpr u32 kStacksPerRingBufferEntry = 2;
1659*0fca6ea1SDimitry Andric     constexpr u32 kMaxU32Pow2 = ~(UINT32_MAX >> 1);
1660*0fca6ea1SDimitry Andric     static_assert(isPowerOfTwo(kMaxU32Pow2));
1661*0fca6ea1SDimitry Andric     // On Android we always have 3 frames at the bottom: __start_main,
1662*0fca6ea1SDimitry Andric     // __libc_init, main, and 3 at the top: malloc, scudo_malloc and
1663*0fca6ea1SDimitry Andric     // Allocator::allocate. This leaves 10 frames for the user app. The next
1664*0fca6ea1SDimitry Andric     // smallest power of two (8) would only leave 2, which is clearly too
1665*0fca6ea1SDimitry Andric     // little.
1666*0fca6ea1SDimitry Andric     constexpr u32 kFramesPerStack = 16;
1667*0fca6ea1SDimitry Andric     static_assert(isPowerOfTwo(kFramesPerStack));
1668*0fca6ea1SDimitry Andric 
1669*0fca6ea1SDimitry Andric     if (AllocationRingBufferSize > kMaxU32Pow2 / kStacksPerRingBufferEntry)
1670*0fca6ea1SDimitry Andric       return;
1671*0fca6ea1SDimitry Andric     u32 TabSize = static_cast<u32>(roundUpPowerOfTwo(kStacksPerRingBufferEntry *
1672*0fca6ea1SDimitry Andric                                                      AllocationRingBufferSize));
1673*0fca6ea1SDimitry Andric     if (TabSize > UINT32_MAX / kFramesPerStack)
1674*0fca6ea1SDimitry Andric       return;
1675*0fca6ea1SDimitry Andric     u32 RingSize = static_cast<u32>(TabSize * kFramesPerStack);
1676*0fca6ea1SDimitry Andric 
1677*0fca6ea1SDimitry Andric     uptr StackDepotSize = sizeof(StackDepot) + sizeof(atomic_u64) * RingSize +
1678*0fca6ea1SDimitry Andric                           sizeof(atomic_u32) * TabSize;
1679*0fca6ea1SDimitry Andric     MemMapT DepotMap;
1680*0fca6ea1SDimitry Andric     DepotMap.map(
1681*0fca6ea1SDimitry Andric         /*Addr=*/0U, roundUp(StackDepotSize, getPageSizeCached()),
1682*0fca6ea1SDimitry Andric         "scudo:stack_depot");
1683*0fca6ea1SDimitry Andric     auto *Depot = reinterpret_cast<StackDepot *>(DepotMap.getBase());
1684*0fca6ea1SDimitry Andric     Depot->init(RingSize, TabSize);
1685*0fca6ea1SDimitry Andric 
16865f757f3fSDimitry Andric     MemMapT MemMap;
16875f757f3fSDimitry Andric     MemMap.map(
16885f757f3fSDimitry Andric         /*Addr=*/0U,
168906c3fb27SDimitry Andric         roundUp(ringBufferSizeInBytes(AllocationRingBufferSize),
169006c3fb27SDimitry Andric                 getPageSizeCached()),
16915f757f3fSDimitry Andric         "scudo:ring_buffer");
1692*0fca6ea1SDimitry Andric     auto *RB = reinterpret_cast<AllocationRingBuffer *>(MemMap.getBase());
1693*0fca6ea1SDimitry Andric     RB->RawRingBufferMap = MemMap;
1694*0fca6ea1SDimitry Andric     RB->RingBufferElements = AllocationRingBufferSize;
1695*0fca6ea1SDimitry Andric     RB->Depot = Depot;
1696*0fca6ea1SDimitry Andric     RB->StackDepotSize = StackDepotSize;
1697*0fca6ea1SDimitry Andric     RB->RawStackDepotMap = DepotMap;
1698*0fca6ea1SDimitry Andric 
1699*0fca6ea1SDimitry Andric     atomic_store(&RingBufferAddress, reinterpret_cast<uptr>(RB),
1700*0fca6ea1SDimitry Andric                  memory_order_release);
1701bdd1243dSDimitry Andric   }
1702bdd1243dSDimitry Andric 
unmapRingBuffer()170306c3fb27SDimitry Andric   void unmapRingBuffer() {
1704*0fca6ea1SDimitry Andric     AllocationRingBuffer *RB = getRingBuffer();
1705*0fca6ea1SDimitry Andric     if (RB == nullptr)
1706*0fca6ea1SDimitry Andric       return;
1707*0fca6ea1SDimitry Andric     // N.B. because RawStackDepotMap is part of RawRingBufferMap, the order
1708*0fca6ea1SDimitry Andric     // is very important.
1709*0fca6ea1SDimitry Andric     RB->RawStackDepotMap.unmap(RB->RawStackDepotMap.getBase(),
1710*0fca6ea1SDimitry Andric                                RB->RawStackDepotMap.getCapacity());
1711*0fca6ea1SDimitry Andric     // Note that the `RB->RawRingBufferMap` is stored on the pages managed by
1712*0fca6ea1SDimitry Andric     // itself. Take over the ownership before calling unmap() so that any
1713*0fca6ea1SDimitry Andric     // operation along with unmap() won't touch inaccessible pages.
1714*0fca6ea1SDimitry Andric     MemMapT RawRingBufferMap = RB->RawRingBufferMap;
17155f757f3fSDimitry Andric     RawRingBufferMap.unmap(RawRingBufferMap.getBase(),
17165f757f3fSDimitry Andric                            RawRingBufferMap.getCapacity());
1717*0fca6ea1SDimitry Andric     atomic_store(&RingBufferAddress, 0, memory_order_release);
171806c3fb27SDimitry Andric   }
171906c3fb27SDimitry Andric 
ringBufferSizeInBytes(u32 RingBufferElements)17205f757f3fSDimitry Andric   static constexpr size_t ringBufferSizeInBytes(u32 RingBufferElements) {
1721bdd1243dSDimitry Andric     return sizeof(AllocationRingBuffer) +
17225f757f3fSDimitry Andric            RingBufferElements * sizeof(typename AllocationRingBuffer::Entry);
17235f757f3fSDimitry Andric   }
17245f757f3fSDimitry Andric 
ringBufferElementsFromBytes(size_t Bytes)17255f757f3fSDimitry Andric   static constexpr size_t ringBufferElementsFromBytes(size_t Bytes) {
17265f757f3fSDimitry Andric     if (Bytes < sizeof(AllocationRingBuffer)) {
17275f757f3fSDimitry Andric       return 0;
17285f757f3fSDimitry Andric     }
17295f757f3fSDimitry Andric     return (Bytes - sizeof(AllocationRingBuffer)) /
1730bdd1243dSDimitry Andric            sizeof(typename AllocationRingBuffer::Entry);
1731bdd1243dSDimitry Andric   }
17320b57cec5SDimitry Andric };
17330b57cec5SDimitry Andric 
17340b57cec5SDimitry Andric } // namespace scudo
17350b57cec5SDimitry Andric 
17360b57cec5SDimitry Andric #endif // SCUDO_COMBINED_H_
1737