xref: /freebsd/contrib/llvm-project/compiler-rt/lib/scudo/standalone/combined.h (revision 8c2dd68caa963f1900a8228b0732b04f5d530ffa)
1 //===-- combined.h ----------------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef SCUDO_COMBINED_H_
10 #define SCUDO_COMBINED_H_
11 
12 #include "chunk.h"
13 #include "common.h"
14 #include "flags.h"
15 #include "flags_parser.h"
16 #include "local_cache.h"
17 #include "memtag.h"
18 #include "options.h"
19 #include "quarantine.h"
20 #include "report.h"
21 #include "secondary.h"
22 #include "stack_depot.h"
23 #include "string_utils.h"
24 #include "tsd.h"
25 
26 #include "scudo/interface.h"
27 
28 #ifdef GWP_ASAN_HOOKS
29 #include "gwp_asan/guarded_pool_allocator.h"
30 #include "gwp_asan/optional/backtrace.h"
31 #include "gwp_asan/optional/options_parser.h"
32 #include "gwp_asan/optional/segv_handler.h"
33 #endif // GWP_ASAN_HOOKS
34 
35 extern "C" inline void EmptyCallback() {}
36 
37 #ifdef HAVE_ANDROID_UNSAFE_FRAME_POINTER_CHASE
38 // This function is not part of the NDK so it does not appear in any public
39 // header files. We only declare/use it when targeting the platform.
40 extern "C" size_t android_unsafe_frame_pointer_chase(scudo::uptr *buf,
41                                                      size_t num_entries);
42 #endif
43 
44 namespace scudo {
45 
46 template <class Params, void (*PostInitCallback)(void) = EmptyCallback>
47 class Allocator {
48 public:
49   using PrimaryT = typename Params::Primary;
50   using CacheT = typename PrimaryT::CacheT;
51   typedef Allocator<Params, PostInitCallback> ThisT;
52   typedef typename Params::template TSDRegistryT<ThisT> TSDRegistryT;
53 
54   void callPostInitCallback() {
55     static pthread_once_t OnceControl = PTHREAD_ONCE_INIT;
56     pthread_once(&OnceControl, PostInitCallback);
57   }
58 
59   struct QuarantineCallback {
60     explicit QuarantineCallback(ThisT &Instance, CacheT &LocalCache)
61         : Allocator(Instance), Cache(LocalCache) {}
62 
63     // Chunk recycling function, returns a quarantined chunk to the backend,
64     // first making sure it hasn't been tampered with.
65     void recycle(void *Ptr) {
66       Chunk::UnpackedHeader Header;
67       Chunk::loadHeader(Allocator.Cookie, Ptr, &Header);
68       if (UNLIKELY(Header.State != Chunk::State::Quarantined))
69         reportInvalidChunkState(AllocatorAction::Recycling, Ptr);
70 
71       Chunk::UnpackedHeader NewHeader = Header;
72       NewHeader.State = Chunk::State::Available;
73       Chunk::compareExchangeHeader(Allocator.Cookie, Ptr, &NewHeader, &Header);
74 
75       void *BlockBegin = Allocator::getBlockBegin(Ptr, &NewHeader);
76       const uptr ClassId = NewHeader.ClassId;
77       if (LIKELY(ClassId))
78         Cache.deallocate(ClassId, BlockBegin);
79       else
80         Allocator.Secondary.deallocate(BlockBegin);
81     }
82 
83     // We take a shortcut when allocating a quarantine batch by working with the
84     // appropriate class ID instead of using Size. The compiler should optimize
85     // the class ID computation and work with the associated cache directly.
86     void *allocate(UNUSED uptr Size) {
87       const uptr QuarantineClassId = SizeClassMap::getClassIdBySize(
88           sizeof(QuarantineBatch) + Chunk::getHeaderSize());
89       void *Ptr = Cache.allocate(QuarantineClassId);
90       // Quarantine batch allocation failure is fatal.
91       if (UNLIKELY(!Ptr))
92         reportOutOfMemory(SizeClassMap::getSizeByClassId(QuarantineClassId));
93 
94       Ptr = reinterpret_cast<void *>(reinterpret_cast<uptr>(Ptr) +
95                                      Chunk::getHeaderSize());
96       Chunk::UnpackedHeader Header = {};
97       Header.ClassId = QuarantineClassId & Chunk::ClassIdMask;
98       Header.SizeOrUnusedBytes = sizeof(QuarantineBatch);
99       Header.State = Chunk::State::Allocated;
100       Chunk::storeHeader(Allocator.Cookie, Ptr, &Header);
101 
102       // Reset tag to 0 as this chunk may have been previously used for a tagged
103       // user allocation.
104       if (UNLIKELY(useMemoryTagging<Params>(Allocator.Primary.Options.load())))
105         storeTags(reinterpret_cast<uptr>(Ptr),
106                   reinterpret_cast<uptr>(Ptr) + sizeof(QuarantineBatch));
107 
108       return Ptr;
109     }
110 
111     void deallocate(void *Ptr) {
112       const uptr QuarantineClassId = SizeClassMap::getClassIdBySize(
113           sizeof(QuarantineBatch) + Chunk::getHeaderSize());
114       Chunk::UnpackedHeader Header;
115       Chunk::loadHeader(Allocator.Cookie, Ptr, &Header);
116 
117       if (UNLIKELY(Header.State != Chunk::State::Allocated))
118         reportInvalidChunkState(AllocatorAction::Deallocating, Ptr);
119       DCHECK_EQ(Header.ClassId, QuarantineClassId);
120       DCHECK_EQ(Header.Offset, 0);
121       DCHECK_EQ(Header.SizeOrUnusedBytes, sizeof(QuarantineBatch));
122 
123       Chunk::UnpackedHeader NewHeader = Header;
124       NewHeader.State = Chunk::State::Available;
125       Chunk::compareExchangeHeader(Allocator.Cookie, Ptr, &NewHeader, &Header);
126       Cache.deallocate(QuarantineClassId,
127                        reinterpret_cast<void *>(reinterpret_cast<uptr>(Ptr) -
128                                                 Chunk::getHeaderSize()));
129     }
130 
131   private:
132     ThisT &Allocator;
133     CacheT &Cache;
134   };
135 
136   typedef GlobalQuarantine<QuarantineCallback, void> QuarantineT;
137   typedef typename QuarantineT::CacheT QuarantineCacheT;
138 
139   void initLinkerInitialized() {
140     performSanityChecks();
141 
142     // Check if hardware CRC32 is supported in the binary and by the platform,
143     // if so, opt for the CRC32 hardware version of the checksum.
144     if (&computeHardwareCRC32 && hasHardwareCRC32())
145       HashAlgorithm = Checksum::HardwareCRC32;
146 
147     if (UNLIKELY(!getRandom(&Cookie, sizeof(Cookie))))
148       Cookie = static_cast<u32>(getMonotonicTime() ^
149                                 (reinterpret_cast<uptr>(this) >> 4));
150 
151     initFlags();
152     reportUnrecognizedFlags();
153 
154     // Store some flags locally.
155     if (getFlags()->may_return_null)
156       Primary.Options.set(OptionBit::MayReturnNull);
157     if (getFlags()->zero_contents)
158       Primary.Options.setFillContentsMode(ZeroFill);
159     else if (getFlags()->pattern_fill_contents)
160       Primary.Options.setFillContentsMode(PatternOrZeroFill);
161     if (getFlags()->dealloc_type_mismatch)
162       Primary.Options.set(OptionBit::DeallocTypeMismatch);
163     if (getFlags()->delete_size_mismatch)
164       Primary.Options.set(OptionBit::DeleteSizeMismatch);
165     if (allocatorSupportsMemoryTagging<Params>() &&
166         systemSupportsMemoryTagging())
167       Primary.Options.set(OptionBit::UseMemoryTagging);
168     Primary.Options.set(OptionBit::UseOddEvenTags);
169 
170     QuarantineMaxChunkSize =
171         static_cast<u32>(getFlags()->quarantine_max_chunk_size);
172 
173     Stats.initLinkerInitialized();
174     const s32 ReleaseToOsIntervalMs = getFlags()->release_to_os_interval_ms;
175     Primary.initLinkerInitialized(ReleaseToOsIntervalMs);
176     Secondary.initLinkerInitialized(&Stats, ReleaseToOsIntervalMs);
177 
178     Quarantine.init(
179         static_cast<uptr>(getFlags()->quarantine_size_kb << 10),
180         static_cast<uptr>(getFlags()->thread_local_quarantine_size_kb << 10));
181   }
182 
183   // Initialize the embedded GWP-ASan instance. Requires the main allocator to
184   // be functional, best called from PostInitCallback.
185   void initGwpAsan() {
186 #ifdef GWP_ASAN_HOOKS
187     // Bear in mind - Scudo has its own alignment guarantees that are strictly
188     // enforced. Scudo exposes the same allocation function for everything from
189     // malloc() to posix_memalign, so in general this flag goes unused, as Scudo
190     // will always ask GWP-ASan for an aligned amount of bytes.
191     gwp_asan::options::initOptions(getEnv("GWP_ASAN_OPTIONS"), Printf);
192     gwp_asan::options::Options Opt = gwp_asan::options::getOptions();
193     // Embedded GWP-ASan is locked through the Scudo atfork handler (via
194     // Allocator::disable calling GWPASan.disable). Disable GWP-ASan's atfork
195     // handler.
196     Opt.InstallForkHandlers = false;
197     Opt.Backtrace = gwp_asan::backtrace::getBacktraceFunction();
198     GuardedAlloc.init(Opt);
199 
200     if (Opt.InstallSignalHandlers)
201       gwp_asan::segv_handler::installSignalHandlers(
202           &GuardedAlloc, Printf,
203           gwp_asan::backtrace::getPrintBacktraceFunction(),
204           gwp_asan::backtrace::getSegvBacktraceFunction());
205 #endif // GWP_ASAN_HOOKS
206   }
207 
208   ALWAYS_INLINE void initThreadMaybe(bool MinimalInit = false) {
209     TSDRegistry.initThreadMaybe(this, MinimalInit);
210   }
211 
212   void reset() { memset(this, 0, sizeof(*this)); }
213 
214   void unmapTestOnly() {
215     TSDRegistry.unmapTestOnly();
216     Primary.unmapTestOnly();
217 #ifdef GWP_ASAN_HOOKS
218     if (getFlags()->GWP_ASAN_InstallSignalHandlers)
219       gwp_asan::segv_handler::uninstallSignalHandlers();
220     GuardedAlloc.uninitTestOnly();
221 #endif // GWP_ASAN_HOOKS
222   }
223 
224   TSDRegistryT *getTSDRegistry() { return &TSDRegistry; }
225 
226   // The Cache must be provided zero-initialized.
227   void initCache(CacheT *Cache) {
228     Cache->initLinkerInitialized(&Stats, &Primary);
229   }
230 
231   // Release the resources used by a TSD, which involves:
232   // - draining the local quarantine cache to the global quarantine;
233   // - releasing the cached pointers back to the Primary;
234   // - unlinking the local stats from the global ones (destroying the cache does
235   //   the last two items).
236   void commitBack(TSD<ThisT> *TSD) {
237     Quarantine.drain(&TSD->QuarantineCache,
238                      QuarantineCallback(*this, TSD->Cache));
239     TSD->Cache.destroy(&Stats);
240   }
241 
242   ALWAYS_INLINE void *untagPointerMaybe(void *Ptr) {
243     if (allocatorSupportsMemoryTagging<Params>())
244       return reinterpret_cast<void *>(
245           untagPointer(reinterpret_cast<uptr>(Ptr)));
246     return Ptr;
247   }
248 
249   NOINLINE u32 collectStackTrace() {
250 #ifdef HAVE_ANDROID_UNSAFE_FRAME_POINTER_CHASE
251     // Discard collectStackTrace() frame and allocator function frame.
252     constexpr uptr DiscardFrames = 2;
253     uptr Stack[MaxTraceSize + DiscardFrames];
254     uptr Size =
255         android_unsafe_frame_pointer_chase(Stack, MaxTraceSize + DiscardFrames);
256     Size = Min<uptr>(Size, MaxTraceSize + DiscardFrames);
257     return Depot.insert(Stack + Min<uptr>(DiscardFrames, Size), Stack + Size);
258 #else
259     return 0;
260 #endif
261   }
262 
263   uptr computeOddEvenMaskForPointerMaybe(Options Options, uptr Ptr, uptr Size) {
264     if (!Options.get(OptionBit::UseOddEvenTags))
265       return 0;
266 
267     // If a chunk's tag is odd, we want the tags of the surrounding blocks to be
268     // even, and vice versa. Blocks are laid out Size bytes apart, and adding
269     // Size to Ptr will flip the least significant set bit of Size in Ptr, so
270     // that bit will have the pattern 010101... for consecutive blocks, which we
271     // can use to determine which tag mask to use.
272     return (Ptr & (1ULL << getLeastSignificantSetBitIndex(Size))) ? 0xaaaa
273                                                                   : 0x5555;
274   }
275 
276   NOINLINE void *allocate(uptr Size, Chunk::Origin Origin,
277                           uptr Alignment = MinAlignment,
278                           bool ZeroContents = false) {
279     initThreadMaybe();
280 
281 #ifdef GWP_ASAN_HOOKS
282     if (UNLIKELY(GuardedAlloc.shouldSample())) {
283       if (void *Ptr = GuardedAlloc.allocate(roundUpTo(Size, Alignment)))
284         return Ptr;
285     }
286 #endif // GWP_ASAN_HOOKS
287 
288     const Options Options = Primary.Options.load();
289     const FillContentsMode FillContents = ZeroContents ? ZeroFill
290                                           : TSDRegistry.getDisableMemInit()
291                                               ? NoFill
292                                               : Options.getFillContentsMode();
293 
294     if (UNLIKELY(Alignment > MaxAlignment)) {
295       if (Options.get(OptionBit::MayReturnNull))
296         return nullptr;
297       reportAlignmentTooBig(Alignment, MaxAlignment);
298     }
299     if (Alignment < MinAlignment)
300       Alignment = MinAlignment;
301 
302     // If the requested size happens to be 0 (more common than you might think),
303     // allocate MinAlignment bytes on top of the header. Then add the extra
304     // bytes required to fulfill the alignment requirements: we allocate enough
305     // to be sure that there will be an address in the block that will satisfy
306     // the alignment.
307     const uptr NeededSize =
308         roundUpTo(Size, MinAlignment) +
309         ((Alignment > MinAlignment) ? Alignment : Chunk::getHeaderSize());
310 
311     // Takes care of extravagantly large sizes as well as integer overflows.
312     static_assert(MaxAllowedMallocSize < UINTPTR_MAX - MaxAlignment, "");
313     if (UNLIKELY(Size >= MaxAllowedMallocSize)) {
314       if (Options.get(OptionBit::MayReturnNull))
315         return nullptr;
316       reportAllocationSizeTooBig(Size, NeededSize, MaxAllowedMallocSize);
317     }
318     DCHECK_LE(Size, NeededSize);
319 
320     void *Block = nullptr;
321     uptr ClassId = 0;
322     uptr SecondaryBlockEnd = 0;
323     if (LIKELY(PrimaryT::canAllocate(NeededSize))) {
324       ClassId = SizeClassMap::getClassIdBySize(NeededSize);
325       DCHECK_NE(ClassId, 0U);
326       bool UnlockRequired;
327       auto *TSD = TSDRegistry.getTSDAndLock(&UnlockRequired);
328       Block = TSD->Cache.allocate(ClassId);
329       // If the allocation failed, the most likely reason with a 32-bit primary
330       // is the region being full. In that event, retry in each successively
331       // larger class until it fits. If it fails to fit in the largest class,
332       // fallback to the Secondary.
333       if (UNLIKELY(!Block)) {
334         while (ClassId < SizeClassMap::LargestClassId && !Block)
335           Block = TSD->Cache.allocate(++ClassId);
336         if (!Block)
337           ClassId = 0;
338       }
339       if (UnlockRequired)
340         TSD->unlock();
341     }
342     if (UNLIKELY(ClassId == 0))
343       Block = Secondary.allocate(NeededSize, Alignment, &SecondaryBlockEnd,
344                                  FillContents);
345 
346     if (UNLIKELY(!Block)) {
347       if (Options.get(OptionBit::MayReturnNull))
348         return nullptr;
349       reportOutOfMemory(NeededSize);
350     }
351 
352     const uptr BlockUptr = reinterpret_cast<uptr>(Block);
353     const uptr UnalignedUserPtr = BlockUptr + Chunk::getHeaderSize();
354     const uptr UserPtr = roundUpTo(UnalignedUserPtr, Alignment);
355 
356     void *Ptr = reinterpret_cast<void *>(UserPtr);
357     void *TaggedPtr = Ptr;
358     if (LIKELY(ClassId)) {
359       // We only need to zero or tag the contents for Primary backed
360       // allocations. We only set tags for primary allocations in order to avoid
361       // faulting potentially large numbers of pages for large secondary
362       // allocations. We assume that guard pages are enough to protect these
363       // allocations.
364       //
365       // FIXME: When the kernel provides a way to set the background tag of a
366       // mapping, we should be able to tag secondary allocations as well.
367       //
368       // When memory tagging is enabled, zeroing the contents is done as part of
369       // setting the tag.
370       if (UNLIKELY(useMemoryTagging<Params>(Options))) {
371         uptr PrevUserPtr;
372         Chunk::UnpackedHeader Header;
373         const uptr BlockSize = PrimaryT::getSizeByClassId(ClassId);
374         const uptr BlockEnd = BlockUptr + BlockSize;
375         // If possible, try to reuse the UAF tag that was set by deallocate().
376         // For simplicity, only reuse tags if we have the same start address as
377         // the previous allocation. This handles the majority of cases since
378         // most allocations will not be more aligned than the minimum alignment.
379         //
380         // We need to handle situations involving reclaimed chunks, and retag
381         // the reclaimed portions if necessary. In the case where the chunk is
382         // fully reclaimed, the chunk's header will be zero, which will trigger
383         // the code path for new mappings and invalid chunks that prepares the
384         // chunk from scratch. There are three possibilities for partial
385         // reclaiming:
386         //
387         // (1) Header was reclaimed, data was partially reclaimed.
388         // (2) Header was not reclaimed, all data was reclaimed (e.g. because
389         //     data started on a page boundary).
390         // (3) Header was not reclaimed, data was partially reclaimed.
391         //
392         // Case (1) will be handled in the same way as for full reclaiming,
393         // since the header will be zero.
394         //
395         // We can detect case (2) by loading the tag from the start
396         // of the chunk. If it is zero, it means that either all data was
397         // reclaimed (since we never use zero as the chunk tag), or that the
398         // previous allocation was of size zero. Either way, we need to prepare
399         // a new chunk from scratch.
400         //
401         // We can detect case (3) by moving to the next page (if covered by the
402         // chunk) and loading the tag of its first granule. If it is zero, it
403         // means that all following pages may need to be retagged. On the other
404         // hand, if it is nonzero, we can assume that all following pages are
405         // still tagged, according to the logic that if any of the pages
406         // following the next page were reclaimed, the next page would have been
407         // reclaimed as well.
408         uptr TaggedUserPtr;
409         if (getChunkFromBlock(BlockUptr, &PrevUserPtr, &Header) &&
410             PrevUserPtr == UserPtr &&
411             (TaggedUserPtr = loadTag(UserPtr)) != UserPtr) {
412           uptr PrevEnd = TaggedUserPtr + Header.SizeOrUnusedBytes;
413           const uptr NextPage = roundUpTo(TaggedUserPtr, getPageSizeCached());
414           if (NextPage < PrevEnd && loadTag(NextPage) != NextPage)
415             PrevEnd = NextPage;
416           TaggedPtr = reinterpret_cast<void *>(TaggedUserPtr);
417           resizeTaggedChunk(PrevEnd, TaggedUserPtr + Size, BlockEnd);
418           if (UNLIKELY(FillContents != NoFill && !Header.OriginOrWasZeroed)) {
419             // If an allocation needs to be zeroed (i.e. calloc) we can normally
420             // avoid zeroing the memory now since we can rely on memory having
421             // been zeroed on free, as this is normally done while setting the
422             // UAF tag. But if tagging was disabled per-thread when the memory
423             // was freed, it would not have been retagged and thus zeroed, and
424             // therefore it needs to be zeroed now.
425             memset(TaggedPtr, 0,
426                    Min(Size, roundUpTo(PrevEnd - TaggedUserPtr,
427                                        archMemoryTagGranuleSize())));
428           } else if (Size) {
429             // Clear any stack metadata that may have previously been stored in
430             // the chunk data.
431             memset(TaggedPtr, 0, archMemoryTagGranuleSize());
432           }
433         } else {
434           const uptr OddEvenMask =
435               computeOddEvenMaskForPointerMaybe(Options, BlockUptr, BlockSize);
436           TaggedPtr = prepareTaggedChunk(Ptr, Size, OddEvenMask, BlockEnd);
437         }
438         storeAllocationStackMaybe(Options, Ptr);
439       } else if (UNLIKELY(FillContents != NoFill)) {
440         // This condition is not necessarily unlikely, but since memset is
441         // costly, we might as well mark it as such.
442         memset(Block, FillContents == ZeroFill ? 0 : PatternFillByte,
443                PrimaryT::getSizeByClassId(ClassId));
444       }
445     }
446 
447     Chunk::UnpackedHeader Header = {};
448     if (UNLIKELY(UnalignedUserPtr != UserPtr)) {
449       const uptr Offset = UserPtr - UnalignedUserPtr;
450       DCHECK_GE(Offset, 2 * sizeof(u32));
451       // The BlockMarker has no security purpose, but is specifically meant for
452       // the chunk iteration function that can be used in debugging situations.
453       // It is the only situation where we have to locate the start of a chunk
454       // based on its block address.
455       reinterpret_cast<u32 *>(Block)[0] = BlockMarker;
456       reinterpret_cast<u32 *>(Block)[1] = static_cast<u32>(Offset);
457       Header.Offset = (Offset >> MinAlignmentLog) & Chunk::OffsetMask;
458     }
459     Header.ClassId = ClassId & Chunk::ClassIdMask;
460     Header.State = Chunk::State::Allocated;
461     Header.OriginOrWasZeroed = Origin & Chunk::OriginMask;
462     Header.SizeOrUnusedBytes =
463         (ClassId ? Size : SecondaryBlockEnd - (UserPtr + Size)) &
464         Chunk::SizeOrUnusedBytesMask;
465     Chunk::storeHeader(Cookie, Ptr, &Header);
466 
467     if (UNLIKELY(&__scudo_allocate_hook))
468       __scudo_allocate_hook(TaggedPtr, Size);
469 
470     return TaggedPtr;
471   }
472 
473   NOINLINE void deallocate(void *Ptr, Chunk::Origin Origin, uptr DeleteSize = 0,
474                            UNUSED uptr Alignment = MinAlignment) {
475     // For a deallocation, we only ensure minimal initialization, meaning thread
476     // local data will be left uninitialized for now (when using ELF TLS). The
477     // fallback cache will be used instead. This is a workaround for a situation
478     // where the only heap operation performed in a thread would be a free past
479     // the TLS destructors, ending up in initialized thread specific data never
480     // being destroyed properly. Any other heap operation will do a full init.
481     initThreadMaybe(/*MinimalInit=*/true);
482 
483 #ifdef GWP_ASAN_HOOKS
484     if (UNLIKELY(GuardedAlloc.pointerIsMine(Ptr))) {
485       GuardedAlloc.deallocate(Ptr);
486       return;
487     }
488 #endif // GWP_ASAN_HOOKS
489 
490     if (UNLIKELY(&__scudo_deallocate_hook))
491       __scudo_deallocate_hook(Ptr);
492 
493     if (UNLIKELY(!Ptr))
494       return;
495     if (UNLIKELY(!isAligned(reinterpret_cast<uptr>(Ptr), MinAlignment)))
496       reportMisalignedPointer(AllocatorAction::Deallocating, Ptr);
497 
498     Ptr = untagPointerMaybe(Ptr);
499 
500     Chunk::UnpackedHeader Header;
501     Chunk::loadHeader(Cookie, Ptr, &Header);
502 
503     if (UNLIKELY(Header.State != Chunk::State::Allocated))
504       reportInvalidChunkState(AllocatorAction::Deallocating, Ptr);
505 
506     const Options Options = Primary.Options.load();
507     if (Options.get(OptionBit::DeallocTypeMismatch)) {
508       if (UNLIKELY(Header.OriginOrWasZeroed != Origin)) {
509         // With the exception of memalign'd chunks, that can be still be free'd.
510         if (Header.OriginOrWasZeroed != Chunk::Origin::Memalign ||
511             Origin != Chunk::Origin::Malloc)
512           reportDeallocTypeMismatch(AllocatorAction::Deallocating, Ptr,
513                                     Header.OriginOrWasZeroed, Origin);
514       }
515     }
516 
517     const uptr Size = getSize(Ptr, &Header);
518     if (DeleteSize && Options.get(OptionBit::DeleteSizeMismatch)) {
519       if (UNLIKELY(DeleteSize != Size))
520         reportDeleteSizeMismatch(Ptr, DeleteSize, Size);
521     }
522 
523     quarantineOrDeallocateChunk(Options, Ptr, &Header, Size);
524   }
525 
526   void *reallocate(void *OldPtr, uptr NewSize, uptr Alignment = MinAlignment) {
527     initThreadMaybe();
528 
529     const Options Options = Primary.Options.load();
530     if (UNLIKELY(NewSize >= MaxAllowedMallocSize)) {
531       if (Options.get(OptionBit::MayReturnNull))
532         return nullptr;
533       reportAllocationSizeTooBig(NewSize, 0, MaxAllowedMallocSize);
534     }
535 
536     void *OldTaggedPtr = OldPtr;
537     OldPtr = untagPointerMaybe(OldPtr);
538 
539     // The following cases are handled by the C wrappers.
540     DCHECK_NE(OldPtr, nullptr);
541     DCHECK_NE(NewSize, 0);
542 
543 #ifdef GWP_ASAN_HOOKS
544     if (UNLIKELY(GuardedAlloc.pointerIsMine(OldPtr))) {
545       uptr OldSize = GuardedAlloc.getSize(OldPtr);
546       void *NewPtr = allocate(NewSize, Chunk::Origin::Malloc, Alignment);
547       if (NewPtr)
548         memcpy(NewPtr, OldPtr, (NewSize < OldSize) ? NewSize : OldSize);
549       GuardedAlloc.deallocate(OldPtr);
550       return NewPtr;
551     }
552 #endif // GWP_ASAN_HOOKS
553 
554     if (UNLIKELY(!isAligned(reinterpret_cast<uptr>(OldPtr), MinAlignment)))
555       reportMisalignedPointer(AllocatorAction::Reallocating, OldPtr);
556 
557     Chunk::UnpackedHeader OldHeader;
558     Chunk::loadHeader(Cookie, OldPtr, &OldHeader);
559 
560     if (UNLIKELY(OldHeader.State != Chunk::State::Allocated))
561       reportInvalidChunkState(AllocatorAction::Reallocating, OldPtr);
562 
563     // Pointer has to be allocated with a malloc-type function. Some
564     // applications think that it is OK to realloc a memalign'ed pointer, which
565     // will trigger this check. It really isn't.
566     if (Options.get(OptionBit::DeallocTypeMismatch)) {
567       if (UNLIKELY(OldHeader.OriginOrWasZeroed != Chunk::Origin::Malloc))
568         reportDeallocTypeMismatch(AllocatorAction::Reallocating, OldPtr,
569                                   OldHeader.OriginOrWasZeroed,
570                                   Chunk::Origin::Malloc);
571     }
572 
573     void *BlockBegin = getBlockBegin(OldPtr, &OldHeader);
574     uptr BlockEnd;
575     uptr OldSize;
576     const uptr ClassId = OldHeader.ClassId;
577     if (LIKELY(ClassId)) {
578       BlockEnd = reinterpret_cast<uptr>(BlockBegin) +
579                  SizeClassMap::getSizeByClassId(ClassId);
580       OldSize = OldHeader.SizeOrUnusedBytes;
581     } else {
582       BlockEnd = SecondaryT::getBlockEnd(BlockBegin);
583       OldSize = BlockEnd -
584                 (reinterpret_cast<uptr>(OldPtr) + OldHeader.SizeOrUnusedBytes);
585     }
586     // If the new chunk still fits in the previously allocated block (with a
587     // reasonable delta), we just keep the old block, and update the chunk
588     // header to reflect the size change.
589     if (reinterpret_cast<uptr>(OldPtr) + NewSize <= BlockEnd) {
590       if (NewSize > OldSize || (OldSize - NewSize) < getPageSizeCached()) {
591         Chunk::UnpackedHeader NewHeader = OldHeader;
592         NewHeader.SizeOrUnusedBytes =
593             (ClassId ? NewSize
594                      : BlockEnd - (reinterpret_cast<uptr>(OldPtr) + NewSize)) &
595             Chunk::SizeOrUnusedBytesMask;
596         Chunk::compareExchangeHeader(Cookie, OldPtr, &NewHeader, &OldHeader);
597         if (UNLIKELY(ClassId && useMemoryTagging<Params>(Options))) {
598           resizeTaggedChunk(reinterpret_cast<uptr>(OldTaggedPtr) + OldSize,
599                             reinterpret_cast<uptr>(OldTaggedPtr) + NewSize,
600                             BlockEnd);
601           storeAllocationStackMaybe(Options, OldPtr);
602         }
603         return OldTaggedPtr;
604       }
605     }
606 
607     // Otherwise we allocate a new one, and deallocate the old one. Some
608     // allocators will allocate an even larger chunk (by a fixed factor) to
609     // allow for potential further in-place realloc. The gains of such a trick
610     // are currently unclear.
611     void *NewPtr = allocate(NewSize, Chunk::Origin::Malloc, Alignment);
612     if (LIKELY(NewPtr)) {
613       memcpy(NewPtr, OldTaggedPtr, Min(NewSize, OldSize));
614       quarantineOrDeallocateChunk(Options, OldPtr, &OldHeader, OldSize);
615     }
616     return NewPtr;
617   }
618 
619   // TODO(kostyak): disable() is currently best-effort. There are some small
620   //                windows of time when an allocation could still succeed after
621   //                this function finishes. We will revisit that later.
622   void disable() {
623     initThreadMaybe();
624 #ifdef GWP_ASAN_HOOKS
625     GuardedAlloc.disable();
626 #endif
627     TSDRegistry.disable();
628     Stats.disable();
629     Quarantine.disable();
630     Primary.disable();
631     Secondary.disable();
632   }
633 
634   void enable() {
635     initThreadMaybe();
636     Secondary.enable();
637     Primary.enable();
638     Quarantine.enable();
639     Stats.enable();
640     TSDRegistry.enable();
641 #ifdef GWP_ASAN_HOOKS
642     GuardedAlloc.enable();
643 #endif
644   }
645 
646   // The function returns the amount of bytes required to store the statistics,
647   // which might be larger than the amount of bytes provided. Note that the
648   // statistics buffer is not necessarily constant between calls to this
649   // function. This can be called with a null buffer or zero size for buffer
650   // sizing purposes.
651   uptr getStats(char *Buffer, uptr Size) {
652     ScopedString Str(1024);
653     disable();
654     const uptr Length = getStats(&Str) + 1;
655     enable();
656     if (Length < Size)
657       Size = Length;
658     if (Buffer && Size) {
659       memcpy(Buffer, Str.data(), Size);
660       Buffer[Size - 1] = '\0';
661     }
662     return Length;
663   }
664 
665   void printStats() {
666     ScopedString Str(1024);
667     disable();
668     getStats(&Str);
669     enable();
670     Str.output();
671   }
672 
673   void releaseToOS() {
674     initThreadMaybe();
675     Primary.releaseToOS();
676     Secondary.releaseToOS();
677   }
678 
679   // Iterate over all chunks and call a callback for all busy chunks located
680   // within the provided memory range. Said callback must not use this allocator
681   // or a deadlock can ensue. This fits Android's malloc_iterate() needs.
682   void iterateOverChunks(uptr Base, uptr Size, iterate_callback Callback,
683                          void *Arg) {
684     initThreadMaybe();
685     const uptr From = Base;
686     const uptr To = Base + Size;
687     auto Lambda = [this, From, To, Callback, Arg](uptr Block) {
688       if (Block < From || Block >= To)
689         return;
690       uptr Chunk;
691       Chunk::UnpackedHeader Header;
692       if (getChunkFromBlock(Block, &Chunk, &Header) &&
693           Header.State == Chunk::State::Allocated) {
694         uptr TaggedChunk = Chunk;
695         if (useMemoryTagging<Params>(Primary.Options.load()))
696           TaggedChunk = loadTag(Chunk);
697         Callback(TaggedChunk, getSize(reinterpret_cast<void *>(Chunk), &Header),
698                  Arg);
699       }
700     };
701     Primary.iterateOverBlocks(Lambda);
702     Secondary.iterateOverBlocks(Lambda);
703 #ifdef GWP_ASAN_HOOKS
704     GuardedAlloc.iterate(reinterpret_cast<void *>(Base), Size, Callback, Arg);
705 #endif
706   }
707 
708   bool canReturnNull() {
709     initThreadMaybe();
710     return Primary.Options.load().get(OptionBit::MayReturnNull);
711   }
712 
713   bool setOption(Option O, sptr Value) {
714     initThreadMaybe();
715     if (O == Option::MemtagTuning) {
716       // Enabling odd/even tags involves a tradeoff between use-after-free
717       // detection and buffer overflow detection. Odd/even tags make it more
718       // likely for buffer overflows to be detected by increasing the size of
719       // the guaranteed "red zone" around the allocation, but on the other hand
720       // use-after-free is less likely to be detected because the tag space for
721       // any particular chunk is cut in half. Therefore we use this tuning
722       // setting to control whether odd/even tags are enabled.
723       if (Value == M_MEMTAG_TUNING_BUFFER_OVERFLOW)
724         Primary.Options.set(OptionBit::UseOddEvenTags);
725       else if (Value == M_MEMTAG_TUNING_UAF)
726         Primary.Options.clear(OptionBit::UseOddEvenTags);
727       return true;
728     } else {
729       // We leave it to the various sub-components to decide whether or not they
730       // want to handle the option, but we do not want to short-circuit
731       // execution if one of the setOption was to return false.
732       const bool PrimaryResult = Primary.setOption(O, Value);
733       const bool SecondaryResult = Secondary.setOption(O, Value);
734       const bool RegistryResult = TSDRegistry.setOption(O, Value);
735       return PrimaryResult && SecondaryResult && RegistryResult;
736     }
737     return false;
738   }
739 
740   // Return the usable size for a given chunk. Technically we lie, as we just
741   // report the actual size of a chunk. This is done to counteract code actively
742   // writing past the end of a chunk (like sqlite3) when the usable size allows
743   // for it, which then forces realloc to copy the usable size of a chunk as
744   // opposed to its actual size.
745   uptr getUsableSize(const void *Ptr) {
746     initThreadMaybe();
747     if (UNLIKELY(!Ptr))
748       return 0;
749 
750 #ifdef GWP_ASAN_HOOKS
751     if (UNLIKELY(GuardedAlloc.pointerIsMine(Ptr)))
752       return GuardedAlloc.getSize(Ptr);
753 #endif // GWP_ASAN_HOOKS
754 
755     Ptr = untagPointerMaybe(const_cast<void *>(Ptr));
756     Chunk::UnpackedHeader Header;
757     Chunk::loadHeader(Cookie, Ptr, &Header);
758     // Getting the usable size of a chunk only makes sense if it's allocated.
759     if (UNLIKELY(Header.State != Chunk::State::Allocated))
760       reportInvalidChunkState(AllocatorAction::Sizing, const_cast<void *>(Ptr));
761     return getSize(Ptr, &Header);
762   }
763 
764   void getStats(StatCounters S) {
765     initThreadMaybe();
766     Stats.get(S);
767   }
768 
769   // Returns true if the pointer provided was allocated by the current
770   // allocator instance, which is compliant with tcmalloc's ownership concept.
771   // A corrupted chunk will not be reported as owned, which is WAI.
772   bool isOwned(const void *Ptr) {
773     initThreadMaybe();
774 #ifdef GWP_ASAN_HOOKS
775     if (GuardedAlloc.pointerIsMine(Ptr))
776       return true;
777 #endif // GWP_ASAN_HOOKS
778     if (!Ptr || !isAligned(reinterpret_cast<uptr>(Ptr), MinAlignment))
779       return false;
780     Ptr = untagPointerMaybe(const_cast<void *>(Ptr));
781     Chunk::UnpackedHeader Header;
782     return Chunk::isValid(Cookie, Ptr, &Header) &&
783            Header.State == Chunk::State::Allocated;
784   }
785 
786   bool useMemoryTaggingTestOnly() const {
787     return useMemoryTagging<Params>(Primary.Options.load());
788   }
789   void disableMemoryTagging() {
790     if (allocatorSupportsMemoryTagging<Params>())
791       Primary.Options.clear(OptionBit::UseMemoryTagging);
792   }
793 
794   void setTrackAllocationStacks(bool Track) {
795     initThreadMaybe();
796     if (Track)
797       Primary.Options.set(OptionBit::TrackAllocationStacks);
798     else
799       Primary.Options.clear(OptionBit::TrackAllocationStacks);
800   }
801 
802   void setFillContents(FillContentsMode FillContents) {
803     initThreadMaybe();
804     Primary.Options.setFillContentsMode(FillContents);
805   }
806 
807   const char *getStackDepotAddress() const {
808     return reinterpret_cast<const char *>(&Depot);
809   }
810 
811   const char *getRegionInfoArrayAddress() const {
812     return Primary.getRegionInfoArrayAddress();
813   }
814 
815   static uptr getRegionInfoArraySize() {
816     return PrimaryT::getRegionInfoArraySize();
817   }
818 
819   static void getErrorInfo(struct scudo_error_info *ErrorInfo,
820                            uintptr_t FaultAddr, const char *DepotPtr,
821                            const char *RegionInfoPtr, const char *Memory,
822                            const char *MemoryTags, uintptr_t MemoryAddr,
823                            size_t MemorySize) {
824     *ErrorInfo = {};
825     if (!allocatorSupportsMemoryTagging<Params>() ||
826         MemoryAddr + MemorySize < MemoryAddr)
827       return;
828 
829     uptr UntaggedFaultAddr = untagPointer(FaultAddr);
830     u8 FaultAddrTag = extractTag(FaultAddr);
831     BlockInfo Info =
832         PrimaryT::findNearestBlock(RegionInfoPtr, UntaggedFaultAddr);
833 
834     auto GetGranule = [&](uptr Addr, const char **Data, uint8_t *Tag) -> bool {
835       if (Addr < MemoryAddr || Addr + archMemoryTagGranuleSize() < Addr ||
836           Addr + archMemoryTagGranuleSize() > MemoryAddr + MemorySize)
837         return false;
838       *Data = &Memory[Addr - MemoryAddr];
839       *Tag = static_cast<u8>(
840           MemoryTags[(Addr - MemoryAddr) / archMemoryTagGranuleSize()]);
841       return true;
842     };
843 
844     auto ReadBlock = [&](uptr Addr, uptr *ChunkAddr,
845                          Chunk::UnpackedHeader *Header, const u32 **Data,
846                          u8 *Tag) {
847       const char *BlockBegin;
848       u8 BlockBeginTag;
849       if (!GetGranule(Addr, &BlockBegin, &BlockBeginTag))
850         return false;
851       uptr ChunkOffset = getChunkOffsetFromBlock(BlockBegin);
852       *ChunkAddr = Addr + ChunkOffset;
853 
854       const char *ChunkBegin;
855       if (!GetGranule(*ChunkAddr, &ChunkBegin, Tag))
856         return false;
857       *Header = *reinterpret_cast<const Chunk::UnpackedHeader *>(
858           ChunkBegin - Chunk::getHeaderSize());
859       *Data = reinterpret_cast<const u32 *>(ChunkBegin);
860       return true;
861     };
862 
863     auto *Depot = reinterpret_cast<const StackDepot *>(DepotPtr);
864 
865     auto MaybeCollectTrace = [&](uintptr_t(&Trace)[MaxTraceSize], u32 Hash) {
866       uptr RingPos, Size;
867       if (!Depot->find(Hash, &RingPos, &Size))
868         return;
869       for (unsigned I = 0; I != Size && I != MaxTraceSize; ++I)
870         Trace[I] = (*Depot)[RingPos + I];
871     };
872 
873     size_t NextErrorReport = 0;
874 
875     // First, check for UAF.
876     {
877       uptr ChunkAddr;
878       Chunk::UnpackedHeader Header;
879       const u32 *Data;
880       uint8_t Tag;
881       if (ReadBlock(Info.BlockBegin, &ChunkAddr, &Header, &Data, &Tag) &&
882           Header.State != Chunk::State::Allocated &&
883           Data[MemTagPrevTagIndex] == FaultAddrTag) {
884         auto *R = &ErrorInfo->reports[NextErrorReport++];
885         R->error_type = USE_AFTER_FREE;
886         R->allocation_address = ChunkAddr;
887         R->allocation_size = Header.SizeOrUnusedBytes;
888         MaybeCollectTrace(R->allocation_trace,
889                           Data[MemTagAllocationTraceIndex]);
890         R->allocation_tid = Data[MemTagAllocationTidIndex];
891         MaybeCollectTrace(R->deallocation_trace,
892                           Data[MemTagDeallocationTraceIndex]);
893         R->deallocation_tid = Data[MemTagDeallocationTidIndex];
894       }
895     }
896 
897     auto CheckOOB = [&](uptr BlockAddr) {
898       if (BlockAddr < Info.RegionBegin || BlockAddr >= Info.RegionEnd)
899         return false;
900 
901       uptr ChunkAddr;
902       Chunk::UnpackedHeader Header;
903       const u32 *Data;
904       uint8_t Tag;
905       if (!ReadBlock(BlockAddr, &ChunkAddr, &Header, &Data, &Tag) ||
906           Header.State != Chunk::State::Allocated || Tag != FaultAddrTag)
907         return false;
908 
909       auto *R = &ErrorInfo->reports[NextErrorReport++];
910       R->error_type =
911           UntaggedFaultAddr < ChunkAddr ? BUFFER_UNDERFLOW : BUFFER_OVERFLOW;
912       R->allocation_address = ChunkAddr;
913       R->allocation_size = Header.SizeOrUnusedBytes;
914       MaybeCollectTrace(R->allocation_trace, Data[MemTagAllocationTraceIndex]);
915       R->allocation_tid = Data[MemTagAllocationTidIndex];
916       return NextErrorReport ==
917              sizeof(ErrorInfo->reports) / sizeof(ErrorInfo->reports[0]);
918     };
919 
920     if (CheckOOB(Info.BlockBegin))
921       return;
922 
923     // Check for OOB in the 30 surrounding blocks. Beyond that we are likely to
924     // hit false positives.
925     for (int I = 1; I != 16; ++I)
926       if (CheckOOB(Info.BlockBegin + I * Info.BlockSize) ||
927           CheckOOB(Info.BlockBegin - I * Info.BlockSize))
928         return;
929   }
930 
931 private:
932   using SecondaryT = MapAllocator<Params>;
933   typedef typename PrimaryT::SizeClassMap SizeClassMap;
934 
935   static const uptr MinAlignmentLog = SCUDO_MIN_ALIGNMENT_LOG;
936   static const uptr MaxAlignmentLog = 24U; // 16 MB seems reasonable.
937   static const uptr MinAlignment = 1UL << MinAlignmentLog;
938   static const uptr MaxAlignment = 1UL << MaxAlignmentLog;
939   static const uptr MaxAllowedMallocSize =
940       FIRST_32_SECOND_64(1UL << 31, 1ULL << 40);
941 
942   static_assert(MinAlignment >= sizeof(Chunk::PackedHeader),
943                 "Minimal alignment must at least cover a chunk header.");
944   static_assert(!allocatorSupportsMemoryTagging<Params>() ||
945                     MinAlignment >= archMemoryTagGranuleSize(),
946                 "");
947 
948   static const u32 BlockMarker = 0x44554353U;
949 
950   // These are indexes into an "array" of 32-bit values that store information
951   // inline with a chunk that is relevant to diagnosing memory tag faults, where
952   // 0 corresponds to the address of the user memory. This means that negative
953   // indexes may be used to store information about allocations, while positive
954   // indexes may only be used to store information about deallocations, because
955   // the user memory is in use until it has been deallocated. The smallest index
956   // that may be used is -2, which corresponds to 8 bytes before the user
957   // memory, because the chunk header size is 8 bytes and in allocators that
958   // support memory tagging the minimum alignment is at least the tag granule
959   // size (16 on aarch64), and the largest index that may be used is 3 because
960   // we are only guaranteed to have at least a granule's worth of space in the
961   // user memory.
962   static const sptr MemTagAllocationTraceIndex = -2;
963   static const sptr MemTagAllocationTidIndex = -1;
964   static const sptr MemTagDeallocationTraceIndex = 0;
965   static const sptr MemTagDeallocationTidIndex = 1;
966   static const sptr MemTagPrevTagIndex = 2;
967 
968   static const uptr MaxTraceSize = 64;
969 
970   u32 Cookie;
971   u32 QuarantineMaxChunkSize;
972 
973   GlobalStats Stats;
974   PrimaryT Primary;
975   SecondaryT Secondary;
976   QuarantineT Quarantine;
977   TSDRegistryT TSDRegistry;
978 
979 #ifdef GWP_ASAN_HOOKS
980   gwp_asan::GuardedPoolAllocator GuardedAlloc;
981 #endif // GWP_ASAN_HOOKS
982 
983   StackDepot Depot;
984 
985   // The following might get optimized out by the compiler.
986   NOINLINE void performSanityChecks() {
987     // Verify that the header offset field can hold the maximum offset. In the
988     // case of the Secondary allocator, it takes care of alignment and the
989     // offset will always be small. In the case of the Primary, the worst case
990     // scenario happens in the last size class, when the backend allocation
991     // would already be aligned on the requested alignment, which would happen
992     // to be the maximum alignment that would fit in that size class. As a
993     // result, the maximum offset will be at most the maximum alignment for the
994     // last size class minus the header size, in multiples of MinAlignment.
995     Chunk::UnpackedHeader Header = {};
996     const uptr MaxPrimaryAlignment = 1UL << getMostSignificantSetBitIndex(
997                                          SizeClassMap::MaxSize - MinAlignment);
998     const uptr MaxOffset =
999         (MaxPrimaryAlignment - Chunk::getHeaderSize()) >> MinAlignmentLog;
1000     Header.Offset = MaxOffset & Chunk::OffsetMask;
1001     if (UNLIKELY(Header.Offset != MaxOffset))
1002       reportSanityCheckError("offset");
1003 
1004     // Verify that we can fit the maximum size or amount of unused bytes in the
1005     // header. Given that the Secondary fits the allocation to a page, the worst
1006     // case scenario happens in the Primary. It will depend on the second to
1007     // last and last class sizes, as well as the dynamic base for the Primary.
1008     // The following is an over-approximation that works for our needs.
1009     const uptr MaxSizeOrUnusedBytes = SizeClassMap::MaxSize - 1;
1010     Header.SizeOrUnusedBytes = MaxSizeOrUnusedBytes;
1011     if (UNLIKELY(Header.SizeOrUnusedBytes != MaxSizeOrUnusedBytes))
1012       reportSanityCheckError("size (or unused bytes)");
1013 
1014     const uptr LargestClassId = SizeClassMap::LargestClassId;
1015     Header.ClassId = LargestClassId;
1016     if (UNLIKELY(Header.ClassId != LargestClassId))
1017       reportSanityCheckError("class ID");
1018   }
1019 
1020   static inline void *getBlockBegin(const void *Ptr,
1021                                     Chunk::UnpackedHeader *Header) {
1022     return reinterpret_cast<void *>(
1023         reinterpret_cast<uptr>(Ptr) - Chunk::getHeaderSize() -
1024         (static_cast<uptr>(Header->Offset) << MinAlignmentLog));
1025   }
1026 
1027   // Return the size of a chunk as requested during its allocation.
1028   inline uptr getSize(const void *Ptr, Chunk::UnpackedHeader *Header) {
1029     const uptr SizeOrUnusedBytes = Header->SizeOrUnusedBytes;
1030     if (LIKELY(Header->ClassId))
1031       return SizeOrUnusedBytes;
1032     return SecondaryT::getBlockEnd(getBlockBegin(Ptr, Header)) -
1033            reinterpret_cast<uptr>(Ptr) - SizeOrUnusedBytes;
1034   }
1035 
1036   void quarantineOrDeallocateChunk(Options Options, void *Ptr,
1037                                    Chunk::UnpackedHeader *Header, uptr Size) {
1038     Chunk::UnpackedHeader NewHeader = *Header;
1039     if (UNLIKELY(NewHeader.ClassId && useMemoryTagging<Params>(Options))) {
1040       u8 PrevTag = extractTag(loadTag(reinterpret_cast<uptr>(Ptr)));
1041       if (!TSDRegistry.getDisableMemInit()) {
1042         uptr TaggedBegin, TaggedEnd;
1043         const uptr OddEvenMask = computeOddEvenMaskForPointerMaybe(
1044             Options, reinterpret_cast<uptr>(getBlockBegin(Ptr, &NewHeader)),
1045             SizeClassMap::getSizeByClassId(NewHeader.ClassId));
1046         // Exclude the previous tag so that immediate use after free is detected
1047         // 100% of the time.
1048         setRandomTag(Ptr, Size, OddEvenMask | (1UL << PrevTag), &TaggedBegin,
1049                      &TaggedEnd);
1050       }
1051       NewHeader.OriginOrWasZeroed = !TSDRegistry.getDisableMemInit();
1052       storeDeallocationStackMaybe(Options, Ptr, PrevTag);
1053     }
1054     // If the quarantine is disabled, the actual size of a chunk is 0 or larger
1055     // than the maximum allowed, we return a chunk directly to the backend.
1056     // This purposefully underflows for Size == 0.
1057     const bool BypassQuarantine =
1058         !Quarantine.getCacheSize() || ((Size - 1) >= QuarantineMaxChunkSize);
1059     if (BypassQuarantine) {
1060       NewHeader.State = Chunk::State::Available;
1061       Chunk::compareExchangeHeader(Cookie, Ptr, &NewHeader, Header);
1062       void *BlockBegin = getBlockBegin(Ptr, &NewHeader);
1063       const uptr ClassId = NewHeader.ClassId;
1064       if (LIKELY(ClassId)) {
1065         bool UnlockRequired;
1066         auto *TSD = TSDRegistry.getTSDAndLock(&UnlockRequired);
1067         TSD->Cache.deallocate(ClassId, BlockBegin);
1068         if (UnlockRequired)
1069           TSD->unlock();
1070       } else {
1071         Secondary.deallocate(BlockBegin);
1072       }
1073     } else {
1074       NewHeader.State = Chunk::State::Quarantined;
1075       Chunk::compareExchangeHeader(Cookie, Ptr, &NewHeader, Header);
1076       bool UnlockRequired;
1077       auto *TSD = TSDRegistry.getTSDAndLock(&UnlockRequired);
1078       Quarantine.put(&TSD->QuarantineCache,
1079                      QuarantineCallback(*this, TSD->Cache), Ptr, Size);
1080       if (UnlockRequired)
1081         TSD->unlock();
1082     }
1083   }
1084 
1085   bool getChunkFromBlock(uptr Block, uptr *Chunk,
1086                          Chunk::UnpackedHeader *Header) {
1087     *Chunk =
1088         Block + getChunkOffsetFromBlock(reinterpret_cast<const char *>(Block));
1089     return Chunk::isValid(Cookie, reinterpret_cast<void *>(*Chunk), Header);
1090   }
1091 
1092   static uptr getChunkOffsetFromBlock(const char *Block) {
1093     u32 Offset = 0;
1094     if (reinterpret_cast<const u32 *>(Block)[0] == BlockMarker)
1095       Offset = reinterpret_cast<const u32 *>(Block)[1];
1096     return Offset + Chunk::getHeaderSize();
1097   }
1098 
1099   void storeAllocationStackMaybe(Options Options, void *Ptr) {
1100     if (!UNLIKELY(Options.get(OptionBit::TrackAllocationStacks)))
1101       return;
1102     auto *Ptr32 = reinterpret_cast<u32 *>(Ptr);
1103     Ptr32[MemTagAllocationTraceIndex] = collectStackTrace();
1104     Ptr32[MemTagAllocationTidIndex] = getThreadID();
1105   }
1106 
1107   void storeDeallocationStackMaybe(Options Options, void *Ptr,
1108                                    uint8_t PrevTag) {
1109     if (!UNLIKELY(Options.get(OptionBit::TrackAllocationStacks)))
1110       return;
1111 
1112     // Disable tag checks here so that we don't need to worry about zero sized
1113     // allocations.
1114     ScopedDisableMemoryTagChecks x;
1115     auto *Ptr32 = reinterpret_cast<u32 *>(Ptr);
1116     Ptr32[MemTagDeallocationTraceIndex] = collectStackTrace();
1117     Ptr32[MemTagDeallocationTidIndex] = getThreadID();
1118     Ptr32[MemTagPrevTagIndex] = PrevTag;
1119   }
1120 
1121   uptr getStats(ScopedString *Str) {
1122     Primary.getStats(Str);
1123     Secondary.getStats(Str);
1124     Quarantine.getStats(Str);
1125     return Str->length();
1126   }
1127 };
1128 
1129 } // namespace scudo
1130 
1131 #endif // SCUDO_COMBINED_H_
1132