• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "rss_limit_checker.h"
22 #include "secondary.h"
23 #include "stack_depot.h"
24 #include "string_utils.h"
25 #include "tsd.h"
26 
27 #include "scudo/interface.h"
28 
29 #ifdef GWP_ASAN_HOOKS
30 #include "gwp_asan/guarded_pool_allocator.h"
31 #include "gwp_asan/optional/backtrace.h"
32 #include "gwp_asan/optional/segv_handler.h"
33 #endif // GWP_ASAN_HOOKS
34 
EmptyCallback()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 
callPostInitCallback()54   void callPostInitCallback() {
55     pthread_once(&PostInitNonce, PostInitCallback);
56   }
57 
58   struct QuarantineCallback {
QuarantineCallbackQuarantineCallback59     explicit QuarantineCallback(ThisT &Instance, CacheT &LocalCache)
60         : Allocator(Instance), Cache(LocalCache) {}
61 
62     // Chunk recycling function, returns a quarantined chunk to the backend,
63     // first making sure it hasn't been tampered with.
recycleQuarantineCallback64     void recycle(void *Ptr) {
65       Chunk::UnpackedHeader Header;
66       Chunk::loadHeader(Allocator.Cookie, Ptr, &Header);
67       if (UNLIKELY(Header.State != Chunk::State::Quarantined))
68         reportInvalidChunkState(AllocatorAction::Recycling, Ptr);
69 
70       Chunk::UnpackedHeader NewHeader = Header;
71       NewHeader.State = Chunk::State::Available;
72       Chunk::compareExchangeHeader(Allocator.Cookie, Ptr, &NewHeader, &Header);
73 
74       if (allocatorSupportsMemoryTagging<Params>())
75         Ptr = untagPointer(Ptr);
76       void *BlockBegin = Allocator::getBlockBegin(Ptr, &NewHeader);
77       Cache.deallocate(NewHeader.ClassId, BlockBegin);
78     }
79 
80     // We take a shortcut when allocating a quarantine batch by working with the
81     // appropriate class ID instead of using Size. The compiler should optimize
82     // the class ID computation and work with the associated cache directly.
allocateQuarantineCallback83     void *allocate(UNUSED uptr Size) {
84       const uptr QuarantineClassId = SizeClassMap::getClassIdBySize(
85           sizeof(QuarantineBatch) + Chunk::getHeaderSize());
86       void *Ptr = Cache.allocate(QuarantineClassId);
87       // Quarantine batch allocation failure is fatal.
88       if (UNLIKELY(!Ptr))
89         reportOutOfMemory(SizeClassMap::getSizeByClassId(QuarantineClassId));
90 
91       Ptr = reinterpret_cast<void *>(reinterpret_cast<uptr>(Ptr) +
92                                      Chunk::getHeaderSize());
93       Chunk::UnpackedHeader Header = {};
94       Header.ClassId = QuarantineClassId & Chunk::ClassIdMask;
95       Header.SizeOrUnusedBytes = sizeof(QuarantineBatch);
96       Header.State = Chunk::State::Allocated;
97       Chunk::storeHeader(Allocator.Cookie, Ptr, &Header);
98 
99       // Reset tag to 0 as this chunk may have been previously used for a tagged
100       // user allocation.
101       if (UNLIKELY(useMemoryTagging<Params>(Allocator.Primary.Options.load())))
102         storeTags(reinterpret_cast<uptr>(Ptr),
103                   reinterpret_cast<uptr>(Ptr) + sizeof(QuarantineBatch));
104 
105       return Ptr;
106     }
107 
deallocateQuarantineCallback108     void deallocate(void *Ptr) {
109       const uptr QuarantineClassId = SizeClassMap::getClassIdBySize(
110           sizeof(QuarantineBatch) + Chunk::getHeaderSize());
111       Chunk::UnpackedHeader Header;
112       Chunk::loadHeader(Allocator.Cookie, Ptr, &Header);
113 
114       if (UNLIKELY(Header.State != Chunk::State::Allocated))
115         reportInvalidChunkState(AllocatorAction::Deallocating, Ptr);
116       DCHECK_EQ(Header.ClassId, QuarantineClassId);
117       DCHECK_EQ(Header.Offset, 0);
118       DCHECK_EQ(Header.SizeOrUnusedBytes, sizeof(QuarantineBatch));
119 
120       Chunk::UnpackedHeader NewHeader = Header;
121       NewHeader.State = Chunk::State::Available;
122       Chunk::compareExchangeHeader(Allocator.Cookie, Ptr, &NewHeader, &Header);
123       Cache.deallocate(QuarantineClassId,
124                        reinterpret_cast<void *>(reinterpret_cast<uptr>(Ptr) -
125                                                 Chunk::getHeaderSize()));
126     }
127 
128   private:
129     ThisT &Allocator;
130     CacheT &Cache;
131   };
132 
133   typedef GlobalQuarantine<QuarantineCallback, void> QuarantineT;
134   typedef typename QuarantineT::CacheT QuarantineCacheT;
135 
init()136   void init() {
137     performSanityChecks();
138 
139     // Check if hardware CRC32 is supported in the binary and by the platform,
140     // if so, opt for the CRC32 hardware version of the checksum.
141     if (&computeHardwareCRC32 && hasHardwareCRC32())
142       HashAlgorithm = Checksum::HardwareCRC32;
143 
144     if (UNLIKELY(!getRandom(&Cookie, sizeof(Cookie))))
145       Cookie = static_cast<u32>(getMonotonicTime() ^
146                                 (reinterpret_cast<uptr>(this) >> 4));
147 
148     initFlags();
149     reportUnrecognizedFlags();
150 
151     RssChecker.init(scudo::getFlags()->soft_rss_limit_mb,
152                     scudo::getFlags()->hard_rss_limit_mb);
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.init();
174     const s32 ReleaseToOsIntervalMs = getFlags()->release_to_os_interval_ms;
175     Primary.init(ReleaseToOsIntervalMs);
176     Secondary.init(&Stats, ReleaseToOsIntervalMs);
177     Quarantine.init(
178         static_cast<uptr>(getFlags()->quarantine_size_kb << 10),
179         static_cast<uptr>(getFlags()->thread_local_quarantine_size_kb << 10));
180 
181     initRingBuffer();
182   }
183 
184   // Initialize the embedded GWP-ASan instance. Requires the main allocator to
185   // be functional, best called from PostInitCallback.
initGwpAsan()186   void initGwpAsan() {
187 #ifdef GWP_ASAN_HOOKS
188     gwp_asan::options::Options Opt;
189     Opt.Enabled = getFlags()->GWP_ASAN_Enabled;
190     Opt.MaxSimultaneousAllocations =
191         getFlags()->GWP_ASAN_MaxSimultaneousAllocations;
192     Opt.SampleRate = getFlags()->GWP_ASAN_SampleRate;
193     Opt.InstallSignalHandlers = getFlags()->GWP_ASAN_InstallSignalHandlers;
194     Opt.Recoverable = getFlags()->GWP_ASAN_Recoverable;
195     // Embedded GWP-ASan is locked through the Scudo atfork handler (via
196     // Allocator::disable calling GWPASan.disable). Disable GWP-ASan's atfork
197     // handler.
198     Opt.InstallForkHandlers = false;
199     Opt.Backtrace = gwp_asan::backtrace::getBacktraceFunction();
200     GuardedAlloc.init(Opt);
201 
202     if (Opt.InstallSignalHandlers)
203       gwp_asan::segv_handler::installSignalHandlers(
204           &GuardedAlloc, Printf,
205           gwp_asan::backtrace::getPrintBacktraceFunction(),
206           gwp_asan::backtrace::getSegvBacktraceFunction(),
207           Opt.Recoverable);
208 
209     GuardedAllocSlotSize =
210         GuardedAlloc.getAllocatorState()->maximumAllocationSize();
211     Stats.add(StatFree, static_cast<uptr>(Opt.MaxSimultaneousAllocations) *
212                             GuardedAllocSlotSize);
213 #endif // GWP_ASAN_HOOKS
214   }
215 
216 #ifdef GWP_ASAN_HOOKS
getGwpAsanAllocationMetadata()217   const gwp_asan::AllocationMetadata *getGwpAsanAllocationMetadata() {
218     return GuardedAlloc.getMetadataRegion();
219   }
220 
getGwpAsanAllocatorState()221   const gwp_asan::AllocatorState *getGwpAsanAllocatorState() {
222     return GuardedAlloc.getAllocatorState();
223   }
224 #endif // GWP_ASAN_HOOKS
225 
226   ALWAYS_INLINE void initThreadMaybe(bool MinimalInit = false) {
227     TSDRegistry.initThreadMaybe(this, MinimalInit);
228   }
229 
unmapTestOnly()230   void unmapTestOnly() {
231     TSDRegistry.unmapTestOnly(this);
232     Primary.unmapTestOnly();
233     Secondary.unmapTestOnly();
234 #ifdef GWP_ASAN_HOOKS
235     if (getFlags()->GWP_ASAN_InstallSignalHandlers)
236       gwp_asan::segv_handler::uninstallSignalHandlers();
237     GuardedAlloc.uninitTestOnly();
238 #endif // GWP_ASAN_HOOKS
239   }
240 
getTSDRegistry()241   TSDRegistryT *getTSDRegistry() { return &TSDRegistry; }
getQuarantine()242   QuarantineT *getQuarantine() { return &Quarantine; }
243 
244   // The Cache must be provided zero-initialized.
initCache(CacheT * Cache)245   void initCache(CacheT *Cache) { Cache->init(&Stats, &Primary); }
246 
247   // Release the resources used by a TSD, which involves:
248   // - draining the local quarantine cache to the global quarantine;
249   // - releasing the cached pointers back to the Primary;
250   // - unlinking the local stats from the global ones (destroying the cache does
251   //   the last two items).
commitBack(TSD<ThisT> * TSD)252   void commitBack(TSD<ThisT> *TSD) {
253     Quarantine.drain(&TSD->getQuarantineCache(),
254                      QuarantineCallback(*this, TSD->getCache()));
255     TSD->getCache().destroy(&Stats);
256   }
257 
drainCache(TSD<ThisT> * TSD)258   void drainCache(TSD<ThisT> *TSD) {
259     Quarantine.drainAndRecycle(&TSD->getQuarantineCache(),
260                                QuarantineCallback(*this, TSD->getCache()));
261     TSD->getCache().drain();
262   }
drainCaches()263   void drainCaches() { TSDRegistry.drainCaches(this); }
264 
getHeaderTaggedPointer(void * Ptr)265   ALWAYS_INLINE void *getHeaderTaggedPointer(void *Ptr) {
266     if (!allocatorSupportsMemoryTagging<Params>())
267       return Ptr;
268     auto UntaggedPtr = untagPointer(Ptr);
269     if (UntaggedPtr != Ptr)
270       return UntaggedPtr;
271     // Secondary, or pointer allocated while memory tagging is unsupported or
272     // disabled. The tag mismatch is okay in the latter case because tags will
273     // not be checked.
274     return addHeaderTag(Ptr);
275   }
276 
addHeaderTag(uptr Ptr)277   ALWAYS_INLINE uptr addHeaderTag(uptr Ptr) {
278     if (!allocatorSupportsMemoryTagging<Params>())
279       return Ptr;
280     return addFixedTag(Ptr, 2);
281   }
282 
addHeaderTag(void * Ptr)283   ALWAYS_INLINE void *addHeaderTag(void *Ptr) {
284     return reinterpret_cast<void *>(addHeaderTag(reinterpret_cast<uptr>(Ptr)));
285   }
286 
collectStackTrace()287   NOINLINE u32 collectStackTrace() {
288 #ifdef HAVE_ANDROID_UNSAFE_FRAME_POINTER_CHASE
289     // Discard collectStackTrace() frame and allocator function frame.
290     constexpr uptr DiscardFrames = 2;
291     uptr Stack[MaxTraceSize + DiscardFrames];
292     uptr Size =
293         android_unsafe_frame_pointer_chase(Stack, MaxTraceSize + DiscardFrames);
294     Size = Min<uptr>(Size, MaxTraceSize + DiscardFrames);
295     return Depot.insert(Stack + Min<uptr>(DiscardFrames, Size), Stack + Size);
296 #else
297     return 0;
298 #endif
299   }
300 
computeOddEvenMaskForPointerMaybe(Options Options,uptr Ptr,uptr ClassId)301   uptr computeOddEvenMaskForPointerMaybe(Options Options, uptr Ptr,
302                                          uptr ClassId) {
303     if (!Options.get(OptionBit::UseOddEvenTags))
304       return 0;
305 
306     // If a chunk's tag is odd, we want the tags of the surrounding blocks to be
307     // even, and vice versa. Blocks are laid out Size bytes apart, and adding
308     // Size to Ptr will flip the least significant set bit of Size in Ptr, so
309     // that bit will have the pattern 010101... for consecutive blocks, which we
310     // can use to determine which tag mask to use.
311     return 0x5555U << ((Ptr >> SizeClassMap::getSizeLSBByClassId(ClassId)) & 1);
312   }
313 
314   NOINLINE void *allocate(uptr Size, Chunk::Origin Origin,
315                           uptr Alignment = MinAlignment,
316                           bool ZeroContents = false) NO_THREAD_SAFETY_ANALYSIS {
317     initThreadMaybe();
318 
319     const Options Options = Primary.Options.load();
320     if (UNLIKELY(Alignment > MaxAlignment)) {
321       if (Options.get(OptionBit::MayReturnNull))
322         return nullptr;
323       reportAlignmentTooBig(Alignment, MaxAlignment);
324     }
325     if (Alignment < MinAlignment)
326       Alignment = MinAlignment;
327 
328 #ifdef GWP_ASAN_HOOKS
329     if (UNLIKELY(GuardedAlloc.shouldSample())) {
330       if (void *Ptr = GuardedAlloc.allocate(Size, Alignment)) {
331         if (UNLIKELY(&__scudo_allocate_hook))
332           __scudo_allocate_hook(Ptr, Size);
333         Stats.lock();
334         Stats.add(StatAllocated, GuardedAllocSlotSize);
335         Stats.sub(StatFree, GuardedAllocSlotSize);
336         Stats.unlock();
337         return Ptr;
338       }
339     }
340 #endif // GWP_ASAN_HOOKS
341 
342     const FillContentsMode FillContents = ZeroContents ? ZeroFill
343                                           : TSDRegistry.getDisableMemInit()
344                                               ? NoFill
345                                               : Options.getFillContentsMode();
346 
347     // If the requested size happens to be 0 (more common than you might think),
348     // allocate MinAlignment bytes on top of the header. Then add the extra
349     // bytes required to fulfill the alignment requirements: we allocate enough
350     // to be sure that there will be an address in the block that will satisfy
351     // the alignment.
352     const uptr NeededSize =
353         roundUp(Size, MinAlignment) +
354         ((Alignment > MinAlignment) ? Alignment : Chunk::getHeaderSize());
355 
356     // Takes care of extravagantly large sizes as well as integer overflows.
357     static_assert(MaxAllowedMallocSize < UINTPTR_MAX - MaxAlignment, "");
358     if (UNLIKELY(Size >= MaxAllowedMallocSize)) {
359       if (Options.get(OptionBit::MayReturnNull))
360         return nullptr;
361       reportAllocationSizeTooBig(Size, NeededSize, MaxAllowedMallocSize);
362     }
363     DCHECK_LE(Size, NeededSize);
364 
365     switch (RssChecker.getRssLimitExceeded()) {
366     case RssLimitChecker::Neither:
367       break;
368     case RssLimitChecker::Soft:
369       if (Options.get(OptionBit::MayReturnNull))
370         return nullptr;
371       reportSoftRSSLimit(RssChecker.getSoftRssLimit());
372       break;
373     case RssLimitChecker::Hard:
374       reportHardRSSLimit(RssChecker.getHardRssLimit());
375       break;
376     }
377 
378     void *Block = nullptr;
379     uptr ClassId = 0;
380     uptr SecondaryBlockEnd = 0;
381     if (LIKELY(PrimaryT::canAllocate(NeededSize))) {
382       ClassId = SizeClassMap::getClassIdBySize(NeededSize);
383       DCHECK_NE(ClassId, 0U);
384       bool UnlockRequired;
385       auto *TSD = TSDRegistry.getTSDAndLock(&UnlockRequired);
386       Block = TSD->getCache().allocate(ClassId);
387       // If the allocation failed, the most likely reason with a 32-bit primary
388       // is the region being full. In that event, retry in each successively
389       // larger class until it fits. If it fails to fit in the largest class,
390       // fallback to the Secondary.
391       if (UNLIKELY(!Block)) {
392         while (ClassId < SizeClassMap::LargestClassId && !Block)
393           Block = TSD->getCache().allocate(++ClassId);
394         if (!Block)
395           ClassId = 0;
396       }
397       if (UnlockRequired)
398         TSD->unlock();
399     }
400     if (UNLIKELY(ClassId == 0)) {
401       Block = Secondary.allocate(Options, Size, Alignment, &SecondaryBlockEnd,
402                                  FillContents);
403     }
404 
405     if (UNLIKELY(!Block)) {
406       if (Options.get(OptionBit::MayReturnNull))
407         return nullptr;
408       reportOutOfMemory(NeededSize);
409     }
410 
411     const uptr BlockUptr = reinterpret_cast<uptr>(Block);
412     const uptr UnalignedUserPtr = BlockUptr + Chunk::getHeaderSize();
413     const uptr UserPtr = roundUp(UnalignedUserPtr, Alignment);
414 
415     void *Ptr = reinterpret_cast<void *>(UserPtr);
416     void *TaggedPtr = Ptr;
417     if (LIKELY(ClassId)) {
418       // We only need to zero or tag the contents for Primary backed
419       // allocations. We only set tags for primary allocations in order to avoid
420       // faulting potentially large numbers of pages for large secondary
421       // allocations. We assume that guard pages are enough to protect these
422       // allocations.
423       //
424       // FIXME: When the kernel provides a way to set the background tag of a
425       // mapping, we should be able to tag secondary allocations as well.
426       //
427       // When memory tagging is enabled, zeroing the contents is done as part of
428       // setting the tag.
429       if (UNLIKELY(useMemoryTagging<Params>(Options))) {
430         uptr PrevUserPtr;
431         Chunk::UnpackedHeader Header;
432         const uptr BlockSize = PrimaryT::getSizeByClassId(ClassId);
433         const uptr BlockEnd = BlockUptr + BlockSize;
434         // If possible, try to reuse the UAF tag that was set by deallocate().
435         // For simplicity, only reuse tags if we have the same start address as
436         // the previous allocation. This handles the majority of cases since
437         // most allocations will not be more aligned than the minimum alignment.
438         //
439         // We need to handle situations involving reclaimed chunks, and retag
440         // the reclaimed portions if necessary. In the case where the chunk is
441         // fully reclaimed, the chunk's header will be zero, which will trigger
442         // the code path for new mappings and invalid chunks that prepares the
443         // chunk from scratch. There are three possibilities for partial
444         // reclaiming:
445         //
446         // (1) Header was reclaimed, data was partially reclaimed.
447         // (2) Header was not reclaimed, all data was reclaimed (e.g. because
448         //     data started on a page boundary).
449         // (3) Header was not reclaimed, data was partially reclaimed.
450         //
451         // Case (1) will be handled in the same way as for full reclaiming,
452         // since the header will be zero.
453         //
454         // We can detect case (2) by loading the tag from the start
455         // of the chunk. If it is zero, it means that either all data was
456         // reclaimed (since we never use zero as the chunk tag), or that the
457         // previous allocation was of size zero. Either way, we need to prepare
458         // a new chunk from scratch.
459         //
460         // We can detect case (3) by moving to the next page (if covered by the
461         // chunk) and loading the tag of its first granule. If it is zero, it
462         // means that all following pages may need to be retagged. On the other
463         // hand, if it is nonzero, we can assume that all following pages are
464         // still tagged, according to the logic that if any of the pages
465         // following the next page were reclaimed, the next page would have been
466         // reclaimed as well.
467         uptr TaggedUserPtr;
468         if (getChunkFromBlock(BlockUptr, &PrevUserPtr, &Header) &&
469             PrevUserPtr == UserPtr &&
470             (TaggedUserPtr = loadTag(UserPtr)) != UserPtr) {
471           uptr PrevEnd = TaggedUserPtr + Header.SizeOrUnusedBytes;
472           const uptr NextPage = roundUp(TaggedUserPtr, getPageSizeCached());
473           if (NextPage < PrevEnd && loadTag(NextPage) != NextPage)
474             PrevEnd = NextPage;
475           TaggedPtr = reinterpret_cast<void *>(TaggedUserPtr);
476           resizeTaggedChunk(PrevEnd, TaggedUserPtr + Size, Size, BlockEnd);
477           if (UNLIKELY(FillContents != NoFill && !Header.OriginOrWasZeroed)) {
478             // If an allocation needs to be zeroed (i.e. calloc) we can normally
479             // avoid zeroing the memory now since we can rely on memory having
480             // been zeroed on free, as this is normally done while setting the
481             // UAF tag. But if tagging was disabled per-thread when the memory
482             // was freed, it would not have been retagged and thus zeroed, and
483             // therefore it needs to be zeroed now.
484             memset(TaggedPtr, 0,
485                    Min(Size, roundUp(PrevEnd - TaggedUserPtr,
486                                      archMemoryTagGranuleSize())));
487           } else if (Size) {
488             // Clear any stack metadata that may have previously been stored in
489             // the chunk data.
490             memset(TaggedPtr, 0, archMemoryTagGranuleSize());
491           }
492         } else {
493           const uptr OddEvenMask =
494               computeOddEvenMaskForPointerMaybe(Options, BlockUptr, ClassId);
495           TaggedPtr = prepareTaggedChunk(Ptr, Size, OddEvenMask, BlockEnd);
496         }
497         storePrimaryAllocationStackMaybe(Options, Ptr);
498       } else {
499         Block = addHeaderTag(Block);
500         Ptr = addHeaderTag(Ptr);
501         if (UNLIKELY(FillContents != NoFill)) {
502           // This condition is not necessarily unlikely, but since memset is
503           // costly, we might as well mark it as such.
504           memset(Block, FillContents == ZeroFill ? 0 : PatternFillByte,
505                  PrimaryT::getSizeByClassId(ClassId));
506         }
507       }
508     } else {
509       Block = addHeaderTag(Block);
510       Ptr = addHeaderTag(Ptr);
511       if (UNLIKELY(useMemoryTagging<Params>(Options))) {
512         storeTags(reinterpret_cast<uptr>(Block), reinterpret_cast<uptr>(Ptr));
513         storeSecondaryAllocationStackMaybe(Options, Ptr, Size);
514       }
515     }
516 
517     Chunk::UnpackedHeader Header = {};
518     if (UNLIKELY(UnalignedUserPtr != UserPtr)) {
519       const uptr Offset = UserPtr - UnalignedUserPtr;
520       DCHECK_GE(Offset, 2 * sizeof(u32));
521       // The BlockMarker has no security purpose, but is specifically meant for
522       // the chunk iteration function that can be used in debugging situations.
523       // It is the only situation where we have to locate the start of a chunk
524       // based on its block address.
525       reinterpret_cast<u32 *>(Block)[0] = BlockMarker;
526       reinterpret_cast<u32 *>(Block)[1] = static_cast<u32>(Offset);
527       Header.Offset = (Offset >> MinAlignmentLog) & Chunk::OffsetMask;
528     }
529     Header.ClassId = ClassId & Chunk::ClassIdMask;
530     Header.State = Chunk::State::Allocated;
531     Header.OriginOrWasZeroed = Origin & Chunk::OriginMask;
532     Header.SizeOrUnusedBytes =
533         (ClassId ? Size : SecondaryBlockEnd - (UserPtr + Size)) &
534         Chunk::SizeOrUnusedBytesMask;
535     Chunk::storeHeader(Cookie, Ptr, &Header);
536 
537     if (UNLIKELY(&__scudo_allocate_hook))
538       __scudo_allocate_hook(TaggedPtr, Size);
539 
540     return TaggedPtr;
541   }
542 
543   NOINLINE void deallocate(void *Ptr, Chunk::Origin Origin, uptr DeleteSize = 0,
544                            UNUSED uptr Alignment = MinAlignment) {
545     // For a deallocation, we only ensure minimal initialization, meaning thread
546     // local data will be left uninitialized for now (when using ELF TLS). The
547     // fallback cache will be used instead. This is a workaround for a situation
548     // where the only heap operation performed in a thread would be a free past
549     // the TLS destructors, ending up in initialized thread specific data never
550     // being destroyed properly. Any other heap operation will do a full init.
551     initThreadMaybe(/*MinimalInit=*/true);
552 
553     if (UNLIKELY(&__scudo_deallocate_hook))
554       __scudo_deallocate_hook(Ptr);
555 
556     if (UNLIKELY(!Ptr))
557       return;
558 
559 #ifdef GWP_ASAN_HOOKS
560     if (UNLIKELY(GuardedAlloc.pointerIsMine(Ptr))) {
561       GuardedAlloc.deallocate(Ptr);
562       Stats.lock();
563       Stats.add(StatFree, GuardedAllocSlotSize);
564       Stats.sub(StatAllocated, GuardedAllocSlotSize);
565       Stats.unlock();
566       return;
567     }
568 #endif // GWP_ASAN_HOOKS
569 
570     if (UNLIKELY(!isAligned(reinterpret_cast<uptr>(Ptr), MinAlignment)))
571       reportMisalignedPointer(AllocatorAction::Deallocating, Ptr);
572 
573     void *TaggedPtr = Ptr;
574     Ptr = getHeaderTaggedPointer(Ptr);
575 
576     Chunk::UnpackedHeader Header;
577     Chunk::loadHeader(Cookie, Ptr, &Header);
578 
579     if (UNLIKELY(Header.State != Chunk::State::Allocated))
580       reportInvalidChunkState(AllocatorAction::Deallocating, Ptr);
581 
582     const Options Options = Primary.Options.load();
583     if (Options.get(OptionBit::DeallocTypeMismatch)) {
584       if (UNLIKELY(Header.OriginOrWasZeroed != Origin)) {
585         // With the exception of memalign'd chunks, that can be still be free'd.
586         if (Header.OriginOrWasZeroed != Chunk::Origin::Memalign ||
587             Origin != Chunk::Origin::Malloc)
588           reportDeallocTypeMismatch(AllocatorAction::Deallocating, Ptr,
589                                     Header.OriginOrWasZeroed, Origin);
590       }
591     }
592 
593     const uptr Size = getSize(Ptr, &Header);
594     if (DeleteSize && Options.get(OptionBit::DeleteSizeMismatch)) {
595       if (UNLIKELY(DeleteSize != Size))
596         reportDeleteSizeMismatch(Ptr, DeleteSize, Size);
597     }
598 
599     quarantineOrDeallocateChunk(Options, TaggedPtr, &Header, Size);
600   }
601 
602   void *reallocate(void *OldPtr, uptr NewSize, uptr Alignment = MinAlignment) {
603     initThreadMaybe();
604 
605     const Options Options = Primary.Options.load();
606     if (UNLIKELY(NewSize >= MaxAllowedMallocSize)) {
607       if (Options.get(OptionBit::MayReturnNull))
608         return nullptr;
609       reportAllocationSizeTooBig(NewSize, 0, MaxAllowedMallocSize);
610     }
611 
612     // The following cases are handled by the C wrappers.
613     DCHECK_NE(OldPtr, nullptr);
614     DCHECK_NE(NewSize, 0);
615 
616 #ifdef GWP_ASAN_HOOKS
617     if (UNLIKELY(GuardedAlloc.pointerIsMine(OldPtr))) {
618       uptr OldSize = GuardedAlloc.getSize(OldPtr);
619       void *NewPtr = allocate(NewSize, Chunk::Origin::Malloc, Alignment);
620       if (NewPtr)
621         memcpy(NewPtr, OldPtr, (NewSize < OldSize) ? NewSize : OldSize);
622       GuardedAlloc.deallocate(OldPtr);
623       Stats.lock();
624       Stats.add(StatFree, GuardedAllocSlotSize);
625       Stats.sub(StatAllocated, GuardedAllocSlotSize);
626       Stats.unlock();
627       return NewPtr;
628     }
629 #endif // GWP_ASAN_HOOKS
630 
631     void *OldTaggedPtr = OldPtr;
632     OldPtr = getHeaderTaggedPointer(OldPtr);
633 
634     if (UNLIKELY(!isAligned(reinterpret_cast<uptr>(OldPtr), MinAlignment)))
635       reportMisalignedPointer(AllocatorAction::Reallocating, OldPtr);
636 
637     Chunk::UnpackedHeader OldHeader;
638     Chunk::loadHeader(Cookie, OldPtr, &OldHeader);
639 
640     if (UNLIKELY(OldHeader.State != Chunk::State::Allocated))
641       reportInvalidChunkState(AllocatorAction::Reallocating, OldPtr);
642 
643     // Pointer has to be allocated with a malloc-type function. Some
644     // applications think that it is OK to realloc a memalign'ed pointer, which
645     // will trigger this check. It really isn't.
646     if (Options.get(OptionBit::DeallocTypeMismatch)) {
647       if (UNLIKELY(OldHeader.OriginOrWasZeroed != Chunk::Origin::Malloc))
648         reportDeallocTypeMismatch(AllocatorAction::Reallocating, OldPtr,
649                                   OldHeader.OriginOrWasZeroed,
650                                   Chunk::Origin::Malloc);
651     }
652 
653     void *BlockBegin = getBlockBegin(OldTaggedPtr, &OldHeader);
654     uptr BlockEnd;
655     uptr OldSize;
656     const uptr ClassId = OldHeader.ClassId;
657     if (LIKELY(ClassId)) {
658       BlockEnd = reinterpret_cast<uptr>(BlockBegin) +
659                  SizeClassMap::getSizeByClassId(ClassId);
660       OldSize = OldHeader.SizeOrUnusedBytes;
661     } else {
662       BlockEnd = SecondaryT::getBlockEnd(BlockBegin);
663       OldSize = BlockEnd - (reinterpret_cast<uptr>(OldTaggedPtr) +
664                             OldHeader.SizeOrUnusedBytes);
665     }
666     // If the new chunk still fits in the previously allocated block (with a
667     // reasonable delta), we just keep the old block, and update the chunk
668     // header to reflect the size change.
669     if (reinterpret_cast<uptr>(OldTaggedPtr) + NewSize <= BlockEnd) {
670       if (NewSize > OldSize || (OldSize - NewSize) < getPageSizeCached()) {
671         Chunk::UnpackedHeader NewHeader = OldHeader;
672         NewHeader.SizeOrUnusedBytes =
673             (ClassId ? NewSize
674                      : BlockEnd -
675                            (reinterpret_cast<uptr>(OldTaggedPtr) + NewSize)) &
676             Chunk::SizeOrUnusedBytesMask;
677         Chunk::compareExchangeHeader(Cookie, OldPtr, &NewHeader, &OldHeader);
678         if (UNLIKELY(useMemoryTagging<Params>(Options))) {
679           if (ClassId) {
680             resizeTaggedChunk(reinterpret_cast<uptr>(OldTaggedPtr) + OldSize,
681                               reinterpret_cast<uptr>(OldTaggedPtr) + NewSize,
682                               NewSize, untagPointer(BlockEnd));
683             storePrimaryAllocationStackMaybe(Options, OldPtr);
684           } else {
685             storeSecondaryAllocationStackMaybe(Options, OldPtr, NewSize);
686           }
687         }
688         return OldTaggedPtr;
689       }
690     }
691 
692     // Otherwise we allocate a new one, and deallocate the old one. Some
693     // allocators will allocate an even larger chunk (by a fixed factor) to
694     // allow for potential further in-place realloc. The gains of such a trick
695     // are currently unclear.
696     void *NewPtr = allocate(NewSize, Chunk::Origin::Malloc, Alignment);
697     if (LIKELY(NewPtr)) {
698       memcpy(NewPtr, OldTaggedPtr, Min(NewSize, OldSize));
699       if (UNLIKELY(&__scudo_deallocate_hook))
700         __scudo_deallocate_hook(OldTaggedPtr);
701       quarantineOrDeallocateChunk(Options, OldTaggedPtr, &OldHeader, OldSize);
702     }
703     return NewPtr;
704   }
705 
706   // TODO(kostyak): disable() is currently best-effort. There are some small
707   //                windows of time when an allocation could still succeed after
708   //                this function finishes. We will revisit that later.
disable()709   void disable() NO_THREAD_SAFETY_ANALYSIS {
710     initThreadMaybe();
711 #ifdef GWP_ASAN_HOOKS
712     GuardedAlloc.disable();
713 #endif
714     TSDRegistry.disable();
715     Stats.disable();
716     Quarantine.disable();
717     Primary.disable();
718     Secondary.disable();
719   }
720 
enable()721   void enable() NO_THREAD_SAFETY_ANALYSIS {
722     initThreadMaybe();
723     Secondary.enable();
724     Primary.enable();
725     Quarantine.enable();
726     Stats.enable();
727     TSDRegistry.enable();
728 #ifdef GWP_ASAN_HOOKS
729     GuardedAlloc.enable();
730 #endif
731   }
732 
733   // The function returns the amount of bytes required to store the statistics,
734   // which might be larger than the amount of bytes provided. Note that the
735   // statistics buffer is not necessarily constant between calls to this
736   // function. This can be called with a null buffer or zero size for buffer
737   // sizing purposes.
getStats(char * Buffer,uptr Size)738   uptr getStats(char *Buffer, uptr Size) {
739     ScopedString Str;
740     const uptr Length = getStats(&Str) + 1;
741     if (Length < Size)
742       Size = Length;
743     if (Buffer && Size) {
744       memcpy(Buffer, Str.data(), Size);
745       Buffer[Size - 1] = '\0';
746     }
747     return Length;
748   }
749 
printStats()750   void printStats() {
751     ScopedString Str;
752     getStats(&Str);
753     Str.output();
754   }
755 
releaseToOS(ReleaseToOS ReleaseType)756   void releaseToOS(ReleaseToOS ReleaseType) {
757     initThreadMaybe();
758     if (ReleaseType == ReleaseToOS::ForceAll)
759       drainCaches();
760     Primary.releaseToOS(ReleaseType);
761     Secondary.releaseToOS();
762   }
763 
764   // Iterate over all chunks and call a callback for all busy chunks located
765   // within the provided memory range. Said callback must not use this allocator
766   // or a deadlock can ensue. This fits Android's malloc_iterate() needs.
iterateOverChunks(uptr Base,uptr Size,iterate_callback Callback,void * Arg)767   void iterateOverChunks(uptr Base, uptr Size, iterate_callback Callback,
768                          void *Arg) {
769     initThreadMaybe();
770     if (archSupportsMemoryTagging())
771       Base = untagPointer(Base);
772     const uptr From = Base;
773     const uptr To = Base + Size;
774     bool MayHaveTaggedPrimary = allocatorSupportsMemoryTagging<Params>() &&
775                                 systemSupportsMemoryTagging();
776     auto Lambda = [this, From, To, MayHaveTaggedPrimary, Callback,
777                    Arg](uptr Block) {
778       if (Block < From || Block >= To)
779         return;
780       uptr Chunk;
781       Chunk::UnpackedHeader Header;
782       if (MayHaveTaggedPrimary) {
783         // A chunk header can either have a zero tag (tagged primary) or the
784         // header tag (secondary, or untagged primary). We don't know which so
785         // try both.
786         ScopedDisableMemoryTagChecks x;
787         if (!getChunkFromBlock(Block, &Chunk, &Header) &&
788             !getChunkFromBlock(addHeaderTag(Block), &Chunk, &Header))
789           return;
790       } else {
791         if (!getChunkFromBlock(addHeaderTag(Block), &Chunk, &Header))
792           return;
793       }
794       if (Header.State == Chunk::State::Allocated) {
795         uptr TaggedChunk = Chunk;
796         if (allocatorSupportsMemoryTagging<Params>())
797           TaggedChunk = untagPointer(TaggedChunk);
798         if (useMemoryTagging<Params>(Primary.Options.load()))
799           TaggedChunk = loadTag(Chunk);
800         Callback(TaggedChunk, getSize(reinterpret_cast<void *>(Chunk), &Header),
801                  Arg);
802       }
803     };
804     Primary.iterateOverBlocks(Lambda);
805     Secondary.iterateOverBlocks(Lambda);
806 #ifdef GWP_ASAN_HOOKS
807     GuardedAlloc.iterate(reinterpret_cast<void *>(Base), Size, Callback, Arg);
808 #endif
809   }
810 
canReturnNull()811   bool canReturnNull() {
812     initThreadMaybe();
813     return Primary.Options.load().get(OptionBit::MayReturnNull);
814   }
815 
setOption(Option O,sptr Value)816   bool setOption(Option O, sptr Value) {
817     initThreadMaybe();
818     if (O == Option::MemtagTuning) {
819       // Enabling odd/even tags involves a tradeoff between use-after-free
820       // detection and buffer overflow detection. Odd/even tags make it more
821       // likely for buffer overflows to be detected by increasing the size of
822       // the guaranteed "red zone" around the allocation, but on the other hand
823       // use-after-free is less likely to be detected because the tag space for
824       // any particular chunk is cut in half. Therefore we use this tuning
825       // setting to control whether odd/even tags are enabled.
826       if (Value == M_MEMTAG_TUNING_BUFFER_OVERFLOW)
827         Primary.Options.set(OptionBit::UseOddEvenTags);
828       else if (Value == M_MEMTAG_TUNING_UAF)
829         Primary.Options.clear(OptionBit::UseOddEvenTags);
830       return true;
831     } else {
832       // We leave it to the various sub-components to decide whether or not they
833       // want to handle the option, but we do not want to short-circuit
834       // execution if one of the setOption was to return false.
835       const bool PrimaryResult = Primary.setOption(O, Value);
836       const bool SecondaryResult = Secondary.setOption(O, Value);
837       const bool RegistryResult = TSDRegistry.setOption(O, Value);
838       return PrimaryResult && SecondaryResult && RegistryResult;
839     }
840     return false;
841   }
842 
843   // Return the usable size for a given chunk. Technically we lie, as we just
844   // report the actual size of a chunk. This is done to counteract code actively
845   // writing past the end of a chunk (like sqlite3) when the usable size allows
846   // for it, which then forces realloc to copy the usable size of a chunk as
847   // opposed to its actual size.
getUsableSize(const void * Ptr)848   uptr getUsableSize(const void *Ptr) {
849     initThreadMaybe();
850     if (UNLIKELY(!Ptr))
851       return 0;
852 
853 #ifdef GWP_ASAN_HOOKS
854     if (UNLIKELY(GuardedAlloc.pointerIsMine(Ptr)))
855       return GuardedAlloc.getSize(Ptr);
856 #endif // GWP_ASAN_HOOKS
857 
858     Ptr = getHeaderTaggedPointer(const_cast<void *>(Ptr));
859     Chunk::UnpackedHeader Header;
860     Chunk::loadHeader(Cookie, Ptr, &Header);
861     // Getting the usable size of a chunk only makes sense if it's allocated.
862     if (UNLIKELY(Header.State != Chunk::State::Allocated))
863       reportInvalidChunkState(AllocatorAction::Sizing, const_cast<void *>(Ptr));
864     return getSize(Ptr, &Header);
865   }
866 
getStats(StatCounters S)867   void getStats(StatCounters S) {
868     initThreadMaybe();
869     Stats.get(S);
870   }
871 
872   // Returns true if the pointer provided was allocated by the current
873   // allocator instance, which is compliant with tcmalloc's ownership concept.
874   // A corrupted chunk will not be reported as owned, which is WAI.
isOwned(const void * Ptr)875   bool isOwned(const void *Ptr) {
876     initThreadMaybe();
877 #ifdef GWP_ASAN_HOOKS
878     if (GuardedAlloc.pointerIsMine(Ptr))
879       return true;
880 #endif // GWP_ASAN_HOOKS
881     if (!Ptr || !isAligned(reinterpret_cast<uptr>(Ptr), MinAlignment))
882       return false;
883     Ptr = getHeaderTaggedPointer(const_cast<void *>(Ptr));
884     Chunk::UnpackedHeader Header;
885     return Chunk::isValid(Cookie, Ptr, &Header) &&
886            Header.State == Chunk::State::Allocated;
887   }
888 
setRssLimitsTestOnly(int SoftRssLimitMb,int HardRssLimitMb,bool MayReturnNull)889   void setRssLimitsTestOnly(int SoftRssLimitMb, int HardRssLimitMb,
890                             bool MayReturnNull) {
891     RssChecker.init(SoftRssLimitMb, HardRssLimitMb);
892     if (MayReturnNull)
893       Primary.Options.set(OptionBit::MayReturnNull);
894   }
895 
useMemoryTaggingTestOnly()896   bool useMemoryTaggingTestOnly() const {
897     return useMemoryTagging<Params>(Primary.Options.load());
898   }
disableMemoryTagging()899   void disableMemoryTagging() {
900     // If we haven't been initialized yet, we need to initialize now in order to
901     // prevent a future call to initThreadMaybe() from enabling memory tagging
902     // based on feature detection. But don't call initThreadMaybe() because it
903     // may end up calling the allocator (via pthread_atfork, via the post-init
904     // callback), which may cause mappings to be created with memory tagging
905     // enabled.
906     TSDRegistry.initOnceMaybe(this);
907     if (allocatorSupportsMemoryTagging<Params>()) {
908       Secondary.disableMemoryTagging();
909       Primary.Options.clear(OptionBit::UseMemoryTagging);
910     }
911   }
912 
setTrackAllocationStacks(bool Track)913   void setTrackAllocationStacks(bool Track) {
914     initThreadMaybe();
915     if (getFlags()->allocation_ring_buffer_size == 0) {
916       DCHECK(!Primary.Options.load().get(OptionBit::TrackAllocationStacks));
917       return;
918     }
919     if (Track)
920       Primary.Options.set(OptionBit::TrackAllocationStacks);
921     else
922       Primary.Options.clear(OptionBit::TrackAllocationStacks);
923   }
924 
setFillContents(FillContentsMode FillContents)925   void setFillContents(FillContentsMode FillContents) {
926     initThreadMaybe();
927     Primary.Options.setFillContentsMode(FillContents);
928   }
929 
setAddLargeAllocationSlack(bool AddSlack)930   void setAddLargeAllocationSlack(bool AddSlack) {
931     initThreadMaybe();
932     if (AddSlack)
933       Primary.Options.set(OptionBit::AddLargeAllocationSlack);
934     else
935       Primary.Options.clear(OptionBit::AddLargeAllocationSlack);
936   }
937 
getStackDepotAddress()938   const char *getStackDepotAddress() const {
939     return reinterpret_cast<const char *>(&Depot);
940   }
941 
getRegionInfoArrayAddress()942   const char *getRegionInfoArrayAddress() const {
943     return Primary.getRegionInfoArrayAddress();
944   }
945 
getRegionInfoArraySize()946   static uptr getRegionInfoArraySize() {
947     return PrimaryT::getRegionInfoArraySize();
948   }
949 
getRingBufferAddress()950   const char *getRingBufferAddress() {
951     initThreadMaybe();
952     return RawRingBuffer;
953   }
954 
getRingBufferSize()955   uptr getRingBufferSize() {
956     initThreadMaybe();
957     auto *RingBuffer = getRingBuffer();
958     return RingBuffer ? ringBufferSizeInBytes(RingBuffer->Size) : 0;
959   }
960 
setRingBufferSizeForBuffer(char * Buffer,size_t Size)961   static bool setRingBufferSizeForBuffer(char *Buffer, size_t Size) {
962     // Need at least one entry.
963     if (Size < sizeof(AllocationRingBuffer) +
964                    sizeof(typename AllocationRingBuffer::Entry)) {
965       return false;
966     }
967     AllocationRingBuffer *RingBuffer =
968         reinterpret_cast<AllocationRingBuffer *>(Buffer);
969     RingBuffer->Size = (Size - sizeof(AllocationRingBuffer)) /
970                        sizeof(typename AllocationRingBuffer::Entry);
971     return true;
972   }
973 
974   static const uptr MaxTraceSize = 64;
975 
collectTraceMaybe(const StackDepot * Depot,uintptr_t (& Trace)[MaxTraceSize],u32 Hash)976   static void collectTraceMaybe(const StackDepot *Depot,
977                                 uintptr_t (&Trace)[MaxTraceSize], u32 Hash) {
978     uptr RingPos, Size;
979     if (!Depot->find(Hash, &RingPos, &Size))
980       return;
981     for (unsigned I = 0; I != Size && I != MaxTraceSize; ++I)
982       Trace[I] = static_cast<uintptr_t>((*Depot)[RingPos + I]);
983   }
984 
getErrorInfo(struct scudo_error_info * ErrorInfo,uintptr_t FaultAddr,const char * DepotPtr,const char * RegionInfoPtr,const char * RingBufferPtr,const char * Memory,const char * MemoryTags,uintptr_t MemoryAddr,size_t MemorySize)985   static void getErrorInfo(struct scudo_error_info *ErrorInfo,
986                            uintptr_t FaultAddr, const char *DepotPtr,
987                            const char *RegionInfoPtr, const char *RingBufferPtr,
988                            const char *Memory, const char *MemoryTags,
989                            uintptr_t MemoryAddr, size_t MemorySize) {
990     *ErrorInfo = {};
991     if (!allocatorSupportsMemoryTagging<Params>() ||
992         MemoryAddr + MemorySize < MemoryAddr)
993       return;
994 
995     auto *Depot = reinterpret_cast<const StackDepot *>(DepotPtr);
996     size_t NextErrorReport = 0;
997 
998     // Check for OOB in the current block and the two surrounding blocks. Beyond
999     // that, UAF is more likely.
1000     if (extractTag(FaultAddr) != 0)
1001       getInlineErrorInfo(ErrorInfo, NextErrorReport, FaultAddr, Depot,
1002                          RegionInfoPtr, Memory, MemoryTags, MemoryAddr,
1003                          MemorySize, 0, 2);
1004 
1005     // Check the ring buffer. For primary allocations this will only find UAF;
1006     // for secondary allocations we can find either UAF or OOB.
1007     getRingBufferErrorInfo(ErrorInfo, NextErrorReport, FaultAddr, Depot,
1008                            RingBufferPtr);
1009 
1010     // Check for OOB in the 28 blocks surrounding the 3 we checked earlier.
1011     // Beyond that we are likely to hit false positives.
1012     if (extractTag(FaultAddr) != 0)
1013       getInlineErrorInfo(ErrorInfo, NextErrorReport, FaultAddr, Depot,
1014                          RegionInfoPtr, Memory, MemoryTags, MemoryAddr,
1015                          MemorySize, 2, 16);
1016   }
1017 
1018 private:
1019   using SecondaryT = MapAllocator<Params>;
1020   typedef typename PrimaryT::SizeClassMap SizeClassMap;
1021 
1022   static const uptr MinAlignmentLog = SCUDO_MIN_ALIGNMENT_LOG;
1023   static const uptr MaxAlignmentLog = 24U; // 16 MB seems reasonable.
1024   static const uptr MinAlignment = 1UL << MinAlignmentLog;
1025   static const uptr MaxAlignment = 1UL << MaxAlignmentLog;
1026   static const uptr MaxAllowedMallocSize =
1027       FIRST_32_SECOND_64(1UL << 31, 1ULL << 40);
1028 
1029   static_assert(MinAlignment >= sizeof(Chunk::PackedHeader),
1030                 "Minimal alignment must at least cover a chunk header.");
1031   static_assert(!allocatorSupportsMemoryTagging<Params>() ||
1032                     MinAlignment >= archMemoryTagGranuleSize(),
1033                 "");
1034 
1035   static const u32 BlockMarker = 0x44554353U;
1036 
1037   // These are indexes into an "array" of 32-bit values that store information
1038   // inline with a chunk that is relevant to diagnosing memory tag faults, where
1039   // 0 corresponds to the address of the user memory. This means that only
1040   // negative indexes may be used. The smallest index that may be used is -2,
1041   // which corresponds to 8 bytes before the user memory, because the chunk
1042   // header size is 8 bytes and in allocators that support memory tagging the
1043   // minimum alignment is at least the tag granule size (16 on aarch64).
1044   static const sptr MemTagAllocationTraceIndex = -2;
1045   static const sptr MemTagAllocationTidIndex = -1;
1046 
1047   u32 Cookie = 0;
1048   u32 QuarantineMaxChunkSize = 0;
1049 
1050   GlobalStats Stats;
1051   PrimaryT Primary;
1052   SecondaryT Secondary;
1053   QuarantineT Quarantine;
1054   TSDRegistryT TSDRegistry;
1055   pthread_once_t PostInitNonce = PTHREAD_ONCE_INIT;
1056   RssLimitChecker RssChecker;
1057 
1058 #ifdef GWP_ASAN_HOOKS
1059   gwp_asan::GuardedPoolAllocator GuardedAlloc;
1060   uptr GuardedAllocSlotSize = 0;
1061 #endif // GWP_ASAN_HOOKS
1062 
1063   StackDepot Depot;
1064 
1065   struct AllocationRingBuffer {
1066     struct Entry {
1067       atomic_uptr Ptr;
1068       atomic_uptr AllocationSize;
1069       atomic_u32 AllocationTrace;
1070       atomic_u32 AllocationTid;
1071       atomic_u32 DeallocationTrace;
1072       atomic_u32 DeallocationTid;
1073     };
1074 
1075     atomic_uptr Pos;
1076     u32 Size;
1077     // An array of Size (at least one) elements of type Entry is immediately
1078     // following to this struct.
1079   };
1080   // Pointer to memory mapped area starting with AllocationRingBuffer struct,
1081   // and immediately followed by Size elements of type Entry.
1082   char *RawRingBuffer = {};
1083 
1084   // The following might get optimized out by the compiler.
performSanityChecks()1085   NOINLINE void performSanityChecks() {
1086     // Verify that the header offset field can hold the maximum offset. In the
1087     // case of the Secondary allocator, it takes care of alignment and the
1088     // offset will always be small. In the case of the Primary, the worst case
1089     // scenario happens in the last size class, when the backend allocation
1090     // would already be aligned on the requested alignment, which would happen
1091     // to be the maximum alignment that would fit in that size class. As a
1092     // result, the maximum offset will be at most the maximum alignment for the
1093     // last size class minus the header size, in multiples of MinAlignment.
1094     Chunk::UnpackedHeader Header = {};
1095     const uptr MaxPrimaryAlignment = 1UL << getMostSignificantSetBitIndex(
1096                                          SizeClassMap::MaxSize - MinAlignment);
1097     const uptr MaxOffset =
1098         (MaxPrimaryAlignment - Chunk::getHeaderSize()) >> MinAlignmentLog;
1099     Header.Offset = MaxOffset & Chunk::OffsetMask;
1100     if (UNLIKELY(Header.Offset != MaxOffset))
1101       reportSanityCheckError("offset");
1102 
1103     // Verify that we can fit the maximum size or amount of unused bytes in the
1104     // header. Given that the Secondary fits the allocation to a page, the worst
1105     // case scenario happens in the Primary. It will depend on the second to
1106     // last and last class sizes, as well as the dynamic base for the Primary.
1107     // The following is an over-approximation that works for our needs.
1108     const uptr MaxSizeOrUnusedBytes = SizeClassMap::MaxSize - 1;
1109     Header.SizeOrUnusedBytes = MaxSizeOrUnusedBytes;
1110     if (UNLIKELY(Header.SizeOrUnusedBytes != MaxSizeOrUnusedBytes))
1111       reportSanityCheckError("size (or unused bytes)");
1112 
1113     const uptr LargestClassId = SizeClassMap::LargestClassId;
1114     Header.ClassId = LargestClassId;
1115     if (UNLIKELY(Header.ClassId != LargestClassId))
1116       reportSanityCheckError("class ID");
1117   }
1118 
getBlockBegin(const void * Ptr,Chunk::UnpackedHeader * Header)1119   static inline void *getBlockBegin(const void *Ptr,
1120                                     Chunk::UnpackedHeader *Header) {
1121     return reinterpret_cast<void *>(
1122         reinterpret_cast<uptr>(Ptr) - Chunk::getHeaderSize() -
1123         (static_cast<uptr>(Header->Offset) << MinAlignmentLog));
1124   }
1125 
1126   // Return the size of a chunk as requested during its allocation.
getSize(const void * Ptr,Chunk::UnpackedHeader * Header)1127   inline uptr getSize(const void *Ptr, Chunk::UnpackedHeader *Header) {
1128     const uptr SizeOrUnusedBytes = Header->SizeOrUnusedBytes;
1129     if (LIKELY(Header->ClassId))
1130       return SizeOrUnusedBytes;
1131     if (allocatorSupportsMemoryTagging<Params>())
1132       Ptr = untagPointer(const_cast<void *>(Ptr));
1133     return SecondaryT::getBlockEnd(getBlockBegin(Ptr, Header)) -
1134            reinterpret_cast<uptr>(Ptr) - SizeOrUnusedBytes;
1135   }
1136 
quarantineOrDeallocateChunk(Options Options,void * TaggedPtr,Chunk::UnpackedHeader * Header,uptr Size)1137   void quarantineOrDeallocateChunk(Options Options, void *TaggedPtr,
1138                                    Chunk::UnpackedHeader *Header,
1139                                    uptr Size) NO_THREAD_SAFETY_ANALYSIS {
1140     void *Ptr = getHeaderTaggedPointer(TaggedPtr);
1141     Chunk::UnpackedHeader NewHeader = *Header;
1142     // If the quarantine is disabled, the actual size of a chunk is 0 or larger
1143     // than the maximum allowed, we return a chunk directly to the backend.
1144     // This purposefully underflows for Size == 0.
1145     const bool BypassQuarantine = !Quarantine.getCacheSize() ||
1146                                   ((Size - 1) >= QuarantineMaxChunkSize) ||
1147                                   !NewHeader.ClassId;
1148     if (BypassQuarantine)
1149       NewHeader.State = Chunk::State::Available;
1150     else
1151       NewHeader.State = Chunk::State::Quarantined;
1152     NewHeader.OriginOrWasZeroed = useMemoryTagging<Params>(Options) &&
1153                                   NewHeader.ClassId &&
1154                                   !TSDRegistry.getDisableMemInit();
1155     Chunk::compareExchangeHeader(Cookie, Ptr, &NewHeader, Header);
1156 
1157     if (UNLIKELY(useMemoryTagging<Params>(Options))) {
1158       u8 PrevTag = extractTag(reinterpret_cast<uptr>(TaggedPtr));
1159       storeDeallocationStackMaybe(Options, Ptr, PrevTag, Size);
1160       if (NewHeader.ClassId) {
1161         if (!TSDRegistry.getDisableMemInit()) {
1162           uptr TaggedBegin, TaggedEnd;
1163           const uptr OddEvenMask = computeOddEvenMaskForPointerMaybe(
1164               Options, reinterpret_cast<uptr>(getBlockBegin(Ptr, &NewHeader)),
1165               NewHeader.ClassId);
1166           // Exclude the previous tag so that immediate use after free is
1167           // detected 100% of the time.
1168           setRandomTag(Ptr, Size, OddEvenMask | (1UL << PrevTag), &TaggedBegin,
1169                        &TaggedEnd);
1170         }
1171       }
1172     }
1173     if (BypassQuarantine) {
1174       if (allocatorSupportsMemoryTagging<Params>())
1175         Ptr = untagPointer(Ptr);
1176       void *BlockBegin = getBlockBegin(Ptr, &NewHeader);
1177       const uptr ClassId = NewHeader.ClassId;
1178       if (LIKELY(ClassId)) {
1179         bool UnlockRequired;
1180         auto *TSD = TSDRegistry.getTSDAndLock(&UnlockRequired);
1181         TSD->getCache().deallocate(ClassId, BlockBegin);
1182         if (UnlockRequired)
1183           TSD->unlock();
1184       } else {
1185         if (UNLIKELY(useMemoryTagging<Params>(Options)))
1186           storeTags(reinterpret_cast<uptr>(BlockBegin),
1187                     reinterpret_cast<uptr>(Ptr));
1188         Secondary.deallocate(Options, BlockBegin);
1189       }
1190     } else {
1191       bool UnlockRequired;
1192       auto *TSD = TSDRegistry.getTSDAndLock(&UnlockRequired);
1193       Quarantine.put(&TSD->getQuarantineCache(),
1194                      QuarantineCallback(*this, TSD->getCache()), Ptr, Size);
1195       if (UnlockRequired)
1196         TSD->unlock();
1197     }
1198   }
1199 
getChunkFromBlock(uptr Block,uptr * Chunk,Chunk::UnpackedHeader * Header)1200   bool getChunkFromBlock(uptr Block, uptr *Chunk,
1201                          Chunk::UnpackedHeader *Header) {
1202     *Chunk =
1203         Block + getChunkOffsetFromBlock(reinterpret_cast<const char *>(Block));
1204     return Chunk::isValid(Cookie, reinterpret_cast<void *>(*Chunk), Header);
1205   }
1206 
getChunkOffsetFromBlock(const char * Block)1207   static uptr getChunkOffsetFromBlock(const char *Block) {
1208     u32 Offset = 0;
1209     if (reinterpret_cast<const u32 *>(Block)[0] == BlockMarker)
1210       Offset = reinterpret_cast<const u32 *>(Block)[1];
1211     return Offset + Chunk::getHeaderSize();
1212   }
1213 
1214   // Set the tag of the granule past the end of the allocation to 0, to catch
1215   // linear overflows even if a previous larger allocation used the same block
1216   // and tag. Only do this if the granule past the end is in our block, because
1217   // this would otherwise lead to a SEGV if the allocation covers the entire
1218   // block and our block is at the end of a mapping. The tag of the next block's
1219   // header granule will be set to 0, so it will serve the purpose of catching
1220   // linear overflows in this case.
1221   //
1222   // For allocations of size 0 we do not end up storing the address tag to the
1223   // memory tag space, which getInlineErrorInfo() normally relies on to match
1224   // address tags against chunks. To allow matching in this case we store the
1225   // address tag in the first byte of the chunk.
storeEndMarker(uptr End,uptr Size,uptr BlockEnd)1226   void storeEndMarker(uptr End, uptr Size, uptr BlockEnd) {
1227     DCHECK_EQ(BlockEnd, untagPointer(BlockEnd));
1228     uptr UntaggedEnd = untagPointer(End);
1229     if (UntaggedEnd != BlockEnd) {
1230       storeTag(UntaggedEnd);
1231       if (Size == 0)
1232         *reinterpret_cast<u8 *>(UntaggedEnd) = extractTag(End);
1233     }
1234   }
1235 
prepareTaggedChunk(void * Ptr,uptr Size,uptr ExcludeMask,uptr BlockEnd)1236   void *prepareTaggedChunk(void *Ptr, uptr Size, uptr ExcludeMask,
1237                            uptr BlockEnd) {
1238     // Prepare the granule before the chunk to store the chunk header by setting
1239     // its tag to 0. Normally its tag will already be 0, but in the case where a
1240     // chunk holding a low alignment allocation is reused for a higher alignment
1241     // allocation, the chunk may already have a non-zero tag from the previous
1242     // allocation.
1243     storeTag(reinterpret_cast<uptr>(Ptr) - archMemoryTagGranuleSize());
1244 
1245     uptr TaggedBegin, TaggedEnd;
1246     setRandomTag(Ptr, Size, ExcludeMask, &TaggedBegin, &TaggedEnd);
1247 
1248     storeEndMarker(TaggedEnd, Size, BlockEnd);
1249     return reinterpret_cast<void *>(TaggedBegin);
1250   }
1251 
resizeTaggedChunk(uptr OldPtr,uptr NewPtr,uptr NewSize,uptr BlockEnd)1252   void resizeTaggedChunk(uptr OldPtr, uptr NewPtr, uptr NewSize,
1253                          uptr BlockEnd) {
1254     uptr RoundOldPtr = roundUp(OldPtr, archMemoryTagGranuleSize());
1255     uptr RoundNewPtr;
1256     if (RoundOldPtr >= NewPtr) {
1257       // If the allocation is shrinking we just need to set the tag past the end
1258       // of the allocation to 0. See explanation in storeEndMarker() above.
1259       RoundNewPtr = roundUp(NewPtr, archMemoryTagGranuleSize());
1260     } else {
1261       // Set the memory tag of the region
1262       // [RoundOldPtr, roundUp(NewPtr, archMemoryTagGranuleSize()))
1263       // to the pointer tag stored in OldPtr.
1264       RoundNewPtr = storeTags(RoundOldPtr, NewPtr);
1265     }
1266     storeEndMarker(RoundNewPtr, NewSize, BlockEnd);
1267   }
1268 
storePrimaryAllocationStackMaybe(Options Options,void * Ptr)1269   void storePrimaryAllocationStackMaybe(Options Options, void *Ptr) {
1270     if (!UNLIKELY(Options.get(OptionBit::TrackAllocationStacks)))
1271       return;
1272     auto *Ptr32 = reinterpret_cast<u32 *>(Ptr);
1273     Ptr32[MemTagAllocationTraceIndex] = collectStackTrace();
1274     Ptr32[MemTagAllocationTidIndex] = getThreadID();
1275   }
1276 
storeRingBufferEntry(void * Ptr,u32 AllocationTrace,u32 AllocationTid,uptr AllocationSize,u32 DeallocationTrace,u32 DeallocationTid)1277   void storeRingBufferEntry(void *Ptr, u32 AllocationTrace, u32 AllocationTid,
1278                             uptr AllocationSize, u32 DeallocationTrace,
1279                             u32 DeallocationTid) {
1280     uptr Pos = atomic_fetch_add(&getRingBuffer()->Pos, 1, memory_order_relaxed);
1281     typename AllocationRingBuffer::Entry *Entry =
1282         getRingBufferEntry(RawRingBuffer, Pos % getRingBuffer()->Size);
1283 
1284     // First invalidate our entry so that we don't attempt to interpret a
1285     // partially written state in getSecondaryErrorInfo(). The fences below
1286     // ensure that the compiler does not move the stores to Ptr in between the
1287     // stores to the other fields.
1288     atomic_store_relaxed(&Entry->Ptr, 0);
1289 
1290     __atomic_signal_fence(__ATOMIC_SEQ_CST);
1291     atomic_store_relaxed(&Entry->AllocationTrace, AllocationTrace);
1292     atomic_store_relaxed(&Entry->AllocationTid, AllocationTid);
1293     atomic_store_relaxed(&Entry->AllocationSize, AllocationSize);
1294     atomic_store_relaxed(&Entry->DeallocationTrace, DeallocationTrace);
1295     atomic_store_relaxed(&Entry->DeallocationTid, DeallocationTid);
1296     __atomic_signal_fence(__ATOMIC_SEQ_CST);
1297 
1298     atomic_store_relaxed(&Entry->Ptr, reinterpret_cast<uptr>(Ptr));
1299   }
1300 
storeSecondaryAllocationStackMaybe(Options Options,void * Ptr,uptr Size)1301   void storeSecondaryAllocationStackMaybe(Options Options, void *Ptr,
1302                                           uptr Size) {
1303     if (!UNLIKELY(Options.get(OptionBit::TrackAllocationStacks)))
1304       return;
1305 
1306     u32 Trace = collectStackTrace();
1307     u32 Tid = getThreadID();
1308 
1309     auto *Ptr32 = reinterpret_cast<u32 *>(Ptr);
1310     Ptr32[MemTagAllocationTraceIndex] = Trace;
1311     Ptr32[MemTagAllocationTidIndex] = Tid;
1312 
1313     storeRingBufferEntry(untagPointer(Ptr), Trace, Tid, Size, 0, 0);
1314   }
1315 
storeDeallocationStackMaybe(Options Options,void * Ptr,u8 PrevTag,uptr Size)1316   void storeDeallocationStackMaybe(Options Options, void *Ptr, u8 PrevTag,
1317                                    uptr Size) {
1318     if (!UNLIKELY(Options.get(OptionBit::TrackAllocationStacks)))
1319       return;
1320 
1321     auto *Ptr32 = reinterpret_cast<u32 *>(Ptr);
1322     u32 AllocationTrace = Ptr32[MemTagAllocationTraceIndex];
1323     u32 AllocationTid = Ptr32[MemTagAllocationTidIndex];
1324 
1325     u32 DeallocationTrace = collectStackTrace();
1326     u32 DeallocationTid = getThreadID();
1327 
1328     storeRingBufferEntry(addFixedTag(untagPointer(Ptr), PrevTag),
1329                          AllocationTrace, AllocationTid, Size,
1330                          DeallocationTrace, DeallocationTid);
1331   }
1332 
1333   static const size_t NumErrorReports =
1334       sizeof(((scudo_error_info *)nullptr)->reports) /
1335       sizeof(((scudo_error_info *)nullptr)->reports[0]);
1336 
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)1337   static void getInlineErrorInfo(struct scudo_error_info *ErrorInfo,
1338                                  size_t &NextErrorReport, uintptr_t FaultAddr,
1339                                  const StackDepot *Depot,
1340                                  const char *RegionInfoPtr, const char *Memory,
1341                                  const char *MemoryTags, uintptr_t MemoryAddr,
1342                                  size_t MemorySize, size_t MinDistance,
1343                                  size_t MaxDistance) {
1344     uptr UntaggedFaultAddr = untagPointer(FaultAddr);
1345     u8 FaultAddrTag = extractTag(FaultAddr);
1346     BlockInfo Info =
1347         PrimaryT::findNearestBlock(RegionInfoPtr, UntaggedFaultAddr);
1348 
1349     auto GetGranule = [&](uptr Addr, const char **Data, uint8_t *Tag) -> bool {
1350       if (Addr < MemoryAddr || Addr + archMemoryTagGranuleSize() < Addr ||
1351           Addr + archMemoryTagGranuleSize() > MemoryAddr + MemorySize)
1352         return false;
1353       *Data = &Memory[Addr - MemoryAddr];
1354       *Tag = static_cast<u8>(
1355           MemoryTags[(Addr - MemoryAddr) / archMemoryTagGranuleSize()]);
1356       return true;
1357     };
1358 
1359     auto ReadBlock = [&](uptr Addr, uptr *ChunkAddr,
1360                          Chunk::UnpackedHeader *Header, const u32 **Data,
1361                          u8 *Tag) {
1362       const char *BlockBegin;
1363       u8 BlockBeginTag;
1364       if (!GetGranule(Addr, &BlockBegin, &BlockBeginTag))
1365         return false;
1366       uptr ChunkOffset = getChunkOffsetFromBlock(BlockBegin);
1367       *ChunkAddr = Addr + ChunkOffset;
1368 
1369       const char *ChunkBegin;
1370       if (!GetGranule(*ChunkAddr, &ChunkBegin, Tag))
1371         return false;
1372       *Header = *reinterpret_cast<const Chunk::UnpackedHeader *>(
1373           ChunkBegin - Chunk::getHeaderSize());
1374       *Data = reinterpret_cast<const u32 *>(ChunkBegin);
1375 
1376       // Allocations of size 0 will have stashed the tag in the first byte of
1377       // the chunk, see storeEndMarker().
1378       if (Header->SizeOrUnusedBytes == 0)
1379         *Tag = static_cast<u8>(*ChunkBegin);
1380 
1381       return true;
1382     };
1383 
1384     if (NextErrorReport == NumErrorReports)
1385       return;
1386 
1387     auto CheckOOB = [&](uptr BlockAddr) {
1388       if (BlockAddr < Info.RegionBegin || BlockAddr >= Info.RegionEnd)
1389         return false;
1390 
1391       uptr ChunkAddr;
1392       Chunk::UnpackedHeader Header;
1393       const u32 *Data;
1394       uint8_t Tag;
1395       if (!ReadBlock(BlockAddr, &ChunkAddr, &Header, &Data, &Tag) ||
1396           Header.State != Chunk::State::Allocated || Tag != FaultAddrTag)
1397         return false;
1398 
1399       auto *R = &ErrorInfo->reports[NextErrorReport++];
1400       R->error_type =
1401           UntaggedFaultAddr < ChunkAddr ? BUFFER_UNDERFLOW : BUFFER_OVERFLOW;
1402       R->allocation_address = ChunkAddr;
1403       R->allocation_size = Header.SizeOrUnusedBytes;
1404       collectTraceMaybe(Depot, R->allocation_trace,
1405                         Data[MemTagAllocationTraceIndex]);
1406       R->allocation_tid = Data[MemTagAllocationTidIndex];
1407       return NextErrorReport == NumErrorReports;
1408     };
1409 
1410     if (MinDistance == 0 && CheckOOB(Info.BlockBegin))
1411       return;
1412 
1413     for (size_t I = Max<size_t>(MinDistance, 1); I != MaxDistance; ++I)
1414       if (CheckOOB(Info.BlockBegin + I * Info.BlockSize) ||
1415           CheckOOB(Info.BlockBegin - I * Info.BlockSize))
1416         return;
1417   }
1418 
getRingBufferErrorInfo(struct scudo_error_info * ErrorInfo,size_t & NextErrorReport,uintptr_t FaultAddr,const StackDepot * Depot,const char * RingBufferPtr)1419   static void getRingBufferErrorInfo(struct scudo_error_info *ErrorInfo,
1420                                      size_t &NextErrorReport,
1421                                      uintptr_t FaultAddr,
1422                                      const StackDepot *Depot,
1423                                      const char *RingBufferPtr) {
1424     auto *RingBuffer =
1425         reinterpret_cast<const AllocationRingBuffer *>(RingBufferPtr);
1426     if (!RingBuffer || RingBuffer->Size == 0)
1427       return;
1428     uptr Pos = atomic_load_relaxed(&RingBuffer->Pos);
1429 
1430     for (uptr I = Pos - 1;
1431          I != Pos - 1 - RingBuffer->Size && NextErrorReport != NumErrorReports;
1432          --I) {
1433       auto *Entry = getRingBufferEntry(RingBufferPtr, I % RingBuffer->Size);
1434       uptr EntryPtr = atomic_load_relaxed(&Entry->Ptr);
1435       if (!EntryPtr)
1436         continue;
1437 
1438       uptr UntaggedEntryPtr = untagPointer(EntryPtr);
1439       uptr EntrySize = atomic_load_relaxed(&Entry->AllocationSize);
1440       u32 AllocationTrace = atomic_load_relaxed(&Entry->AllocationTrace);
1441       u32 AllocationTid = atomic_load_relaxed(&Entry->AllocationTid);
1442       u32 DeallocationTrace = atomic_load_relaxed(&Entry->DeallocationTrace);
1443       u32 DeallocationTid = atomic_load_relaxed(&Entry->DeallocationTid);
1444 
1445       if (DeallocationTid) {
1446         // For UAF we only consider in-bounds fault addresses because
1447         // out-of-bounds UAF is rare and attempting to detect it is very likely
1448         // to result in false positives.
1449         if (FaultAddr < EntryPtr || FaultAddr >= EntryPtr + EntrySize)
1450           continue;
1451       } else {
1452         // Ring buffer OOB is only possible with secondary allocations. In this
1453         // case we are guaranteed a guard region of at least a page on either
1454         // side of the allocation (guard page on the right, guard page + tagged
1455         // region on the left), so ignore any faults outside of that range.
1456         if (FaultAddr < EntryPtr - getPageSizeCached() ||
1457             FaultAddr >= EntryPtr + EntrySize + getPageSizeCached())
1458           continue;
1459 
1460         // For UAF the ring buffer will contain two entries, one for the
1461         // allocation and another for the deallocation. Don't report buffer
1462         // overflow/underflow using the allocation entry if we have already
1463         // collected a report from the deallocation entry.
1464         bool Found = false;
1465         for (uptr J = 0; J != NextErrorReport; ++J) {
1466           if (ErrorInfo->reports[J].allocation_address == UntaggedEntryPtr) {
1467             Found = true;
1468             break;
1469           }
1470         }
1471         if (Found)
1472           continue;
1473       }
1474 
1475       auto *R = &ErrorInfo->reports[NextErrorReport++];
1476       if (DeallocationTid)
1477         R->error_type = USE_AFTER_FREE;
1478       else if (FaultAddr < EntryPtr)
1479         R->error_type = BUFFER_UNDERFLOW;
1480       else
1481         R->error_type = BUFFER_OVERFLOW;
1482 
1483       R->allocation_address = UntaggedEntryPtr;
1484       R->allocation_size = EntrySize;
1485       collectTraceMaybe(Depot, R->allocation_trace, AllocationTrace);
1486       R->allocation_tid = AllocationTid;
1487       collectTraceMaybe(Depot, R->deallocation_trace, DeallocationTrace);
1488       R->deallocation_tid = DeallocationTid;
1489     }
1490   }
1491 
getStats(ScopedString * Str)1492   uptr getStats(ScopedString *Str) {
1493     Primary.getStats(Str);
1494     Secondary.getStats(Str);
1495     Quarantine.getStats(Str);
1496     TSDRegistry.getStats(Str);
1497     return Str->length();
1498   }
1499 
1500   static typename AllocationRingBuffer::Entry *
getRingBufferEntry(char * RawRingBuffer,uptr N)1501   getRingBufferEntry(char *RawRingBuffer, uptr N) {
1502     return &reinterpret_cast<typename AllocationRingBuffer::Entry *>(
1503         &RawRingBuffer[sizeof(AllocationRingBuffer)])[N];
1504   }
1505   static const typename AllocationRingBuffer::Entry *
getRingBufferEntry(const char * RawRingBuffer,uptr N)1506   getRingBufferEntry(const char *RawRingBuffer, uptr N) {
1507     return &reinterpret_cast<const typename AllocationRingBuffer::Entry *>(
1508         &RawRingBuffer[sizeof(AllocationRingBuffer)])[N];
1509   }
1510 
initRingBuffer()1511   void initRingBuffer() {
1512     u32 AllocationRingBufferSize =
1513         static_cast<u32>(getFlags()->allocation_ring_buffer_size);
1514     if (AllocationRingBufferSize < 1)
1515       return;
1516     MapPlatformData Data = {};
1517     RawRingBuffer = static_cast<char *>(
1518         map(/*Addr=*/nullptr,
1519             roundUp(ringBufferSizeInBytes(AllocationRingBufferSize),
1520                     getPageSizeCached()),
1521             "AllocatorRingBuffer", /*Flags=*/0, &Data));
1522     auto *RingBuffer = reinterpret_cast<AllocationRingBuffer *>(RawRingBuffer);
1523     RingBuffer->Size = AllocationRingBufferSize;
1524     static_assert(sizeof(AllocationRingBuffer) %
1525                           alignof(typename AllocationRingBuffer::Entry) ==
1526                       0,
1527                   "invalid alignment");
1528   }
1529 
ringBufferSizeInBytes(u32 AllocationRingBufferSize)1530   static constexpr size_t ringBufferSizeInBytes(u32 AllocationRingBufferSize) {
1531     return sizeof(AllocationRingBuffer) +
1532            AllocationRingBufferSize *
1533                sizeof(typename AllocationRingBuffer::Entry);
1534   }
1535 
getRingBuffer()1536   inline AllocationRingBuffer *getRingBuffer() {
1537     return reinterpret_cast<AllocationRingBuffer *>(RawRingBuffer);
1538   }
1539 };
1540 
1541 } // namespace scudo
1542 
1543 #endif // SCUDO_COMBINED_H_
1544