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