1 //===-- scudo_allocator.cpp -------------------------------------*- 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 /// Scudo Hardened Allocator implementation.
10 /// It uses the sanitizer_common allocator as a base and aims at mitigating
11 /// heap corruption vulnerabilities. It provides a checksum-guarded chunk
12 /// header, a delayed free list, and additional sanity checks.
13 ///
14 //===----------------------------------------------------------------------===//
15 
16 #include "scudo_allocator.h"
17 #include "scudo_crc32.h"
18 #include "scudo_errors.h"
19 #include "scudo_flags.h"
20 #include "scudo_interface_internal.h"
21 #include "scudo_tsd.h"
22 #include "scudo_utils.h"
23 
24 #include "sanitizer_common/sanitizer_allocator_checks.h"
25 #include "sanitizer_common/sanitizer_allocator_interface.h"
26 #include "sanitizer_common/sanitizer_quarantine.h"
27 
28 #ifdef GWP_ASAN_HOOKS
29 # include "gwp_asan/guarded_pool_allocator.h"
30 # include "gwp_asan/optional/options_parser.h"
31 #endif // GWP_ASAN_HOOKS
32 
33 #include <errno.h>
34 #include <string.h>
35 
36 namespace __scudo {
37 
38 // Global static cookie, initialized at start-up.
39 static u32 Cookie;
40 
41 // We default to software CRC32 if the alternatives are not supported, either
42 // at compilation or at runtime.
43 static atomic_uint8_t HashAlgorithm = { CRC32Software };
44 
45 INLINE u32 computeCRC32(u32 Crc, uptr Value, uptr *Array, uptr ArraySize) {
46   // If the hardware CRC32 feature is defined here, it was enabled everywhere,
47   // as opposed to only for scudo_crc32.cpp. This means that other hardware
48   // specific instructions were likely emitted at other places, and as a
49   // result there is no reason to not use it here.
50 #if defined(__SSE4_2__) || defined(__ARM_FEATURE_CRC32)
51   Crc = CRC32_INTRINSIC(Crc, Value);
52   for (uptr i = 0; i < ArraySize; i++)
53     Crc = CRC32_INTRINSIC(Crc, Array[i]);
54   return Crc;
55 #else
56   if (atomic_load_relaxed(&HashAlgorithm) == CRC32Hardware) {
57     Crc = computeHardwareCRC32(Crc, Value);
58     for (uptr i = 0; i < ArraySize; i++)
59       Crc = computeHardwareCRC32(Crc, Array[i]);
60     return Crc;
61   }
62   Crc = computeSoftwareCRC32(Crc, Value);
63   for (uptr i = 0; i < ArraySize; i++)
64     Crc = computeSoftwareCRC32(Crc, Array[i]);
65   return Crc;
66 #endif  // defined(__SSE4_2__) || defined(__ARM_FEATURE_CRC32)
67 }
68 
69 static BackendT &getBackend();
70 
71 namespace Chunk {
72   static INLINE AtomicPackedHeader *getAtomicHeader(void *Ptr) {
73     return reinterpret_cast<AtomicPackedHeader *>(reinterpret_cast<uptr>(Ptr) -
74         getHeaderSize());
75   }
76   static INLINE
77   const AtomicPackedHeader *getConstAtomicHeader(const void *Ptr) {
78     return reinterpret_cast<const AtomicPackedHeader *>(
79         reinterpret_cast<uptr>(Ptr) - getHeaderSize());
80   }
81 
82   static INLINE bool isAligned(const void *Ptr) {
83     return IsAligned(reinterpret_cast<uptr>(Ptr), MinAlignment);
84   }
85 
86   // We can't use the offset member of the chunk itself, as we would double
87   // fetch it without any warranty that it wouldn't have been tampered. To
88   // prevent this, we work with a local copy of the header.
89   static INLINE void *getBackendPtr(const void *Ptr, UnpackedHeader *Header) {
90     return reinterpret_cast<void *>(reinterpret_cast<uptr>(Ptr) -
91         getHeaderSize() - (Header->Offset << MinAlignmentLog));
92   }
93 
94   // Returns the usable size for a chunk, meaning the amount of bytes from the
95   // beginning of the user data to the end of the backend allocated chunk.
96   static INLINE uptr getUsableSize(const void *Ptr, UnpackedHeader *Header) {
97     const uptr ClassId = Header->ClassId;
98     if (ClassId)
99       return PrimaryT::ClassIdToSize(ClassId) - getHeaderSize() -
100           (Header->Offset << MinAlignmentLog);
101     return SecondaryT::GetActuallyAllocatedSize(
102         getBackendPtr(Ptr, Header)) - getHeaderSize();
103   }
104 
105   // Returns the size the user requested when allocating the chunk.
106   static INLINE uptr getSize(const void *Ptr, UnpackedHeader *Header) {
107     const uptr SizeOrUnusedBytes = Header->SizeOrUnusedBytes;
108     if (Header->ClassId)
109       return SizeOrUnusedBytes;
110     return SecondaryT::GetActuallyAllocatedSize(
111         getBackendPtr(Ptr, Header)) - getHeaderSize() - SizeOrUnusedBytes;
112   }
113 
114   // Compute the checksum of the chunk pointer and its header.
115   static INLINE u16 computeChecksum(const void *Ptr, UnpackedHeader *Header) {
116     UnpackedHeader ZeroChecksumHeader = *Header;
117     ZeroChecksumHeader.Checksum = 0;
118     uptr HeaderHolder[sizeof(UnpackedHeader) / sizeof(uptr)];
119     memcpy(&HeaderHolder, &ZeroChecksumHeader, sizeof(HeaderHolder));
120     const u32 Crc = computeCRC32(Cookie, reinterpret_cast<uptr>(Ptr),
121                                  HeaderHolder, ARRAY_SIZE(HeaderHolder));
122     return static_cast<u16>(Crc);
123   }
124 
125   // Checks the validity of a chunk by verifying its checksum. It doesn't
126   // incur termination in the event of an invalid chunk.
127   static INLINE bool isValid(const void *Ptr) {
128     PackedHeader NewPackedHeader =
129         atomic_load_relaxed(getConstAtomicHeader(Ptr));
130     UnpackedHeader NewUnpackedHeader =
131         bit_cast<UnpackedHeader>(NewPackedHeader);
132     return (NewUnpackedHeader.Checksum ==
133             computeChecksum(Ptr, &NewUnpackedHeader));
134   }
135 
136   // Ensure that ChunkAvailable is 0, so that if a 0 checksum is ever valid
137   // for a fully nulled out header, its state will be available anyway.
138   COMPILER_CHECK(ChunkAvailable == 0);
139 
140   // Loads and unpacks the header, verifying the checksum in the process.
141   static INLINE
142   void loadHeader(const void *Ptr, UnpackedHeader *NewUnpackedHeader) {
143     PackedHeader NewPackedHeader =
144         atomic_load_relaxed(getConstAtomicHeader(Ptr));
145     *NewUnpackedHeader = bit_cast<UnpackedHeader>(NewPackedHeader);
146     if (UNLIKELY(NewUnpackedHeader->Checksum !=
147         computeChecksum(Ptr, NewUnpackedHeader)))
148       dieWithMessage("corrupted chunk header at address %p\n", Ptr);
149   }
150 
151   // Packs and stores the header, computing the checksum in the process.
152   static INLINE void storeHeader(void *Ptr, UnpackedHeader *NewUnpackedHeader) {
153     NewUnpackedHeader->Checksum = computeChecksum(Ptr, NewUnpackedHeader);
154     PackedHeader NewPackedHeader = bit_cast<PackedHeader>(*NewUnpackedHeader);
155     atomic_store_relaxed(getAtomicHeader(Ptr), NewPackedHeader);
156   }
157 
158   // Packs and stores the header, computing the checksum in the process. We
159   // compare the current header with the expected provided one to ensure that
160   // we are not being raced by a corruption occurring in another thread.
161   static INLINE void compareExchangeHeader(void *Ptr,
162                                            UnpackedHeader *NewUnpackedHeader,
163                                            UnpackedHeader *OldUnpackedHeader) {
164     NewUnpackedHeader->Checksum = computeChecksum(Ptr, NewUnpackedHeader);
165     PackedHeader NewPackedHeader = bit_cast<PackedHeader>(*NewUnpackedHeader);
166     PackedHeader OldPackedHeader = bit_cast<PackedHeader>(*OldUnpackedHeader);
167     if (UNLIKELY(!atomic_compare_exchange_strong(
168             getAtomicHeader(Ptr), &OldPackedHeader, NewPackedHeader,
169             memory_order_relaxed)))
170       dieWithMessage("race on chunk header at address %p\n", Ptr);
171   }
172 }  // namespace Chunk
173 
174 struct QuarantineCallback {
175   explicit QuarantineCallback(AllocatorCacheT *Cache)
176     : Cache_(Cache) {}
177 
178   // Chunk recycling function, returns a quarantined chunk to the backend,
179   // first making sure it hasn't been tampered with.
180   void Recycle(void *Ptr) {
181     UnpackedHeader Header;
182     Chunk::loadHeader(Ptr, &Header);
183     if (UNLIKELY(Header.State != ChunkQuarantine))
184       dieWithMessage("invalid chunk state when recycling address %p\n", Ptr);
185     UnpackedHeader NewHeader = Header;
186     NewHeader.State = ChunkAvailable;
187     Chunk::compareExchangeHeader(Ptr, &NewHeader, &Header);
188     void *BackendPtr = Chunk::getBackendPtr(Ptr, &Header);
189     if (Header.ClassId)
190       getBackend().deallocatePrimary(Cache_, BackendPtr, Header.ClassId);
191     else
192       getBackend().deallocateSecondary(BackendPtr);
193   }
194 
195   // Internal quarantine allocation and deallocation functions. We first check
196   // that the batches are indeed serviced by the Primary.
197   // TODO(kostyak): figure out the best way to protect the batches.
198   void *Allocate(uptr Size) {
199     const uptr BatchClassId = SizeClassMap::ClassID(sizeof(QuarantineBatch));
200     return getBackend().allocatePrimary(Cache_, BatchClassId);
201   }
202 
203   void Deallocate(void *Ptr) {
204     const uptr BatchClassId = SizeClassMap::ClassID(sizeof(QuarantineBatch));
205     getBackend().deallocatePrimary(Cache_, Ptr, BatchClassId);
206   }
207 
208   AllocatorCacheT *Cache_;
209   COMPILER_CHECK(sizeof(QuarantineBatch) < SizeClassMap::kMaxSize);
210 };
211 
212 typedef Quarantine<QuarantineCallback, void> QuarantineT;
213 typedef QuarantineT::Cache QuarantineCacheT;
214 COMPILER_CHECK(sizeof(QuarantineCacheT) <=
215                sizeof(ScudoTSD::QuarantineCachePlaceHolder));
216 
217 QuarantineCacheT *getQuarantineCache(ScudoTSD *TSD) {
218   return reinterpret_cast<QuarantineCacheT *>(TSD->QuarantineCachePlaceHolder);
219 }
220 
221 #ifdef GWP_ASAN_HOOKS
222 static gwp_asan::GuardedPoolAllocator GuardedAlloc;
223 #endif // GWP_ASAN_HOOKS
224 
225 struct Allocator {
226   static const uptr MaxAllowedMallocSize =
227       FIRST_32_SECOND_64(2UL << 30, 1ULL << 40);
228 
229   BackendT Backend;
230   QuarantineT Quarantine;
231 
232   u32 QuarantineChunksUpToSize;
233 
234   bool DeallocationTypeMismatch;
235   bool ZeroContents;
236   bool DeleteSizeMismatch;
237 
238   bool CheckRssLimit;
239   uptr HardRssLimitMb;
240   uptr SoftRssLimitMb;
241   atomic_uint8_t RssLimitExceeded;
242   atomic_uint64_t RssLastCheckedAtNS;
243 
244   explicit Allocator(LinkerInitialized)
245     : Quarantine(LINKER_INITIALIZED) {}
246 
247   NOINLINE void performSanityChecks();
248 
249   void init() {
250     SanitizerToolName = "Scudo";
251     PrimaryAllocatorName = "ScudoPrimary";
252     SecondaryAllocatorName = "ScudoSecondary";
253 
254     initFlags();
255 
256     performSanityChecks();
257 
258     // Check if hardware CRC32 is supported in the binary and by the platform,
259     // if so, opt for the CRC32 hardware version of the checksum.
260     if (&computeHardwareCRC32 && hasHardwareCRC32())
261       atomic_store_relaxed(&HashAlgorithm, CRC32Hardware);
262 
263     SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null);
264     Backend.init(common_flags()->allocator_release_to_os_interval_ms);
265     HardRssLimitMb = common_flags()->hard_rss_limit_mb;
266     SoftRssLimitMb = common_flags()->soft_rss_limit_mb;
267     Quarantine.Init(
268         static_cast<uptr>(getFlags()->QuarantineSizeKb) << 10,
269         static_cast<uptr>(getFlags()->ThreadLocalQuarantineSizeKb) << 10);
270     QuarantineChunksUpToSize = (Quarantine.GetCacheSize() == 0) ? 0 :
271         getFlags()->QuarantineChunksUpToSize;
272     DeallocationTypeMismatch = getFlags()->DeallocationTypeMismatch;
273     DeleteSizeMismatch = getFlags()->DeleteSizeMismatch;
274     ZeroContents = getFlags()->ZeroContents;
275 
276     if (UNLIKELY(!GetRandom(reinterpret_cast<void *>(&Cookie), sizeof(Cookie),
277                             /*blocking=*/false))) {
278       Cookie = static_cast<u32>((NanoTime() >> 12) ^
279                                 (reinterpret_cast<uptr>(this) >> 4));
280     }
281 
282     CheckRssLimit = HardRssLimitMb || SoftRssLimitMb;
283     if (CheckRssLimit)
284       atomic_store_relaxed(&RssLastCheckedAtNS, MonotonicNanoTime());
285   }
286 
287   // Helper function that checks for a valid Scudo chunk. nullptr isn't.
288   bool isValidPointer(const void *Ptr) {
289     initThreadMaybe();
290     if (UNLIKELY(!Ptr))
291       return false;
292     if (!Chunk::isAligned(Ptr))
293       return false;
294     return Chunk::isValid(Ptr);
295   }
296 
297   NOINLINE bool isRssLimitExceeded();
298 
299   // Allocates a chunk.
300   void *allocate(uptr Size, uptr Alignment, AllocType Type,
301                  bool ForceZeroContents = false) {
302     initThreadMaybe();
303 
304 #ifdef GWP_ASAN_HOOKS
305     if (UNLIKELY(GuardedAlloc.shouldSample())) {
306       if (void *Ptr = GuardedAlloc.allocate(Size))
307         return Ptr;
308     }
309 #endif // GWP_ASAN_HOOKS
310 
311     if (UNLIKELY(Alignment > MaxAlignment)) {
312       if (AllocatorMayReturnNull())
313         return nullptr;
314       reportAllocationAlignmentTooBig(Alignment, MaxAlignment);
315     }
316     if (UNLIKELY(Alignment < MinAlignment))
317       Alignment = MinAlignment;
318 
319     const uptr NeededSize = RoundUpTo(Size ? Size : 1, MinAlignment) +
320         Chunk::getHeaderSize();
321     const uptr AlignedSize = (Alignment > MinAlignment) ?
322         NeededSize + (Alignment - Chunk::getHeaderSize()) : NeededSize;
323     if (UNLIKELY(Size >= MaxAllowedMallocSize) ||
324         UNLIKELY(AlignedSize >= MaxAllowedMallocSize)) {
325       if (AllocatorMayReturnNull())
326         return nullptr;
327       reportAllocationSizeTooBig(Size, AlignedSize, MaxAllowedMallocSize);
328     }
329 
330     if (CheckRssLimit && UNLIKELY(isRssLimitExceeded())) {
331       if (AllocatorMayReturnNull())
332         return nullptr;
333       reportRssLimitExceeded();
334     }
335 
336     // Primary and Secondary backed allocations have a different treatment. We
337     // deal with alignment requirements of Primary serviced allocations here,
338     // but the Secondary will take care of its own alignment needs.
339     void *BackendPtr;
340     uptr BackendSize;
341     u8 ClassId;
342     if (PrimaryT::CanAllocate(AlignedSize, MinAlignment)) {
343       BackendSize = AlignedSize;
344       ClassId = SizeClassMap::ClassID(BackendSize);
345       bool UnlockRequired;
346       ScudoTSD *TSD = getTSDAndLock(&UnlockRequired);
347       BackendPtr = Backend.allocatePrimary(&TSD->Cache, ClassId);
348       if (UnlockRequired)
349         TSD->unlock();
350     } else {
351       BackendSize = NeededSize;
352       ClassId = 0;
353       BackendPtr = Backend.allocateSecondary(BackendSize, Alignment);
354     }
355     if (UNLIKELY(!BackendPtr)) {
356       SetAllocatorOutOfMemory();
357       if (AllocatorMayReturnNull())
358         return nullptr;
359       reportOutOfMemory(Size);
360     }
361 
362     // If requested, we will zero out the entire contents of the returned chunk.
363     if ((ForceZeroContents || ZeroContents) && ClassId)
364       memset(BackendPtr, 0, PrimaryT::ClassIdToSize(ClassId));
365 
366     UnpackedHeader Header = {};
367     uptr UserPtr = reinterpret_cast<uptr>(BackendPtr) + Chunk::getHeaderSize();
368     if (UNLIKELY(!IsAligned(UserPtr, Alignment))) {
369       // Since the Secondary takes care of alignment, a non-aligned pointer
370       // means it is from the Primary. It is also the only case where the offset
371       // field of the header would be non-zero.
372       DCHECK(ClassId);
373       const uptr AlignedUserPtr = RoundUpTo(UserPtr, Alignment);
374       Header.Offset = (AlignedUserPtr - UserPtr) >> MinAlignmentLog;
375       UserPtr = AlignedUserPtr;
376     }
377     DCHECK_LE(UserPtr + Size, reinterpret_cast<uptr>(BackendPtr) + BackendSize);
378     Header.State = ChunkAllocated;
379     Header.AllocType = Type;
380     if (ClassId) {
381       Header.ClassId = ClassId;
382       Header.SizeOrUnusedBytes = Size;
383     } else {
384       // The secondary fits the allocations to a page, so the amount of unused
385       // bytes is the difference between the end of the user allocation and the
386       // next page boundary.
387       const uptr PageSize = GetPageSizeCached();
388       const uptr TrailingBytes = (UserPtr + Size) & (PageSize - 1);
389       if (TrailingBytes)
390         Header.SizeOrUnusedBytes = PageSize - TrailingBytes;
391     }
392     void *Ptr = reinterpret_cast<void *>(UserPtr);
393     Chunk::storeHeader(Ptr, &Header);
394     if (SCUDO_CAN_USE_HOOKS && &__sanitizer_malloc_hook)
395       __sanitizer_malloc_hook(Ptr, Size);
396     return Ptr;
397   }
398 
399   // Place a chunk in the quarantine or directly deallocate it in the event of
400   // a zero-sized quarantine, or if the size of the chunk is greater than the
401   // quarantine chunk size threshold.
402   void quarantineOrDeallocateChunk(void *Ptr, UnpackedHeader *Header,
403                                    uptr Size) {
404     const bool BypassQuarantine = !Size || (Size > QuarantineChunksUpToSize);
405     if (BypassQuarantine) {
406       UnpackedHeader NewHeader = *Header;
407       NewHeader.State = ChunkAvailable;
408       Chunk::compareExchangeHeader(Ptr, &NewHeader, Header);
409       void *BackendPtr = Chunk::getBackendPtr(Ptr, Header);
410       if (Header->ClassId) {
411         bool UnlockRequired;
412         ScudoTSD *TSD = getTSDAndLock(&UnlockRequired);
413         getBackend().deallocatePrimary(&TSD->Cache, BackendPtr,
414                                        Header->ClassId);
415         if (UnlockRequired)
416           TSD->unlock();
417       } else {
418         getBackend().deallocateSecondary(BackendPtr);
419       }
420     } else {
421       // If a small memory amount was allocated with a larger alignment, we want
422       // to take that into account. Otherwise the Quarantine would be filled
423       // with tiny chunks, taking a lot of VA memory. This is an approximation
424       // of the usable size, that allows us to not call
425       // GetActuallyAllocatedSize.
426       const uptr EstimatedSize = Size + (Header->Offset << MinAlignmentLog);
427       UnpackedHeader NewHeader = *Header;
428       NewHeader.State = ChunkQuarantine;
429       Chunk::compareExchangeHeader(Ptr, &NewHeader, Header);
430       bool UnlockRequired;
431       ScudoTSD *TSD = getTSDAndLock(&UnlockRequired);
432       Quarantine.Put(getQuarantineCache(TSD), QuarantineCallback(&TSD->Cache),
433                      Ptr, EstimatedSize);
434       if (UnlockRequired)
435         TSD->unlock();
436     }
437   }
438 
439   // Deallocates a Chunk, which means either adding it to the quarantine or
440   // directly returning it to the backend if criteria are met.
441   void deallocate(void *Ptr, uptr DeleteSize, uptr DeleteAlignment,
442                   AllocType Type) {
443     // For a deallocation, we only ensure minimal initialization, meaning thread
444     // local data will be left uninitialized for now (when using ELF TLS). The
445     // fallback cache will be used instead. This is a workaround for a situation
446     // where the only heap operation performed in a thread would be a free past
447     // the TLS destructors, ending up in initialized thread specific data never
448     // being destroyed properly. Any other heap operation will do a full init.
449     initThreadMaybe(/*MinimalInit=*/true);
450     if (SCUDO_CAN_USE_HOOKS && &__sanitizer_free_hook)
451       __sanitizer_free_hook(Ptr);
452     if (UNLIKELY(!Ptr))
453       return;
454 
455 #ifdef GWP_ASAN_HOOKS
456     if (UNLIKELY(GuardedAlloc.pointerIsMine(Ptr))) {
457       GuardedAlloc.deallocate(Ptr);
458       return;
459     }
460 #endif // GWP_ASAN_HOOKS
461 
462     if (UNLIKELY(!Chunk::isAligned(Ptr)))
463       dieWithMessage("misaligned pointer when deallocating address %p\n", Ptr);
464     UnpackedHeader Header;
465     Chunk::loadHeader(Ptr, &Header);
466     if (UNLIKELY(Header.State != ChunkAllocated))
467       dieWithMessage("invalid chunk state when deallocating address %p\n", Ptr);
468     if (DeallocationTypeMismatch) {
469       // The deallocation type has to match the allocation one.
470       if (Header.AllocType != Type) {
471         // With the exception of memalign'd Chunks, that can be still be free'd.
472         if (Header.AllocType != FromMemalign || Type != FromMalloc)
473           dieWithMessage("allocation type mismatch when deallocating address "
474                          "%p\n", Ptr);
475       }
476     }
477     const uptr Size = Chunk::getSize(Ptr, &Header);
478     if (DeleteSizeMismatch) {
479       if (DeleteSize && DeleteSize != Size)
480         dieWithMessage("invalid sized delete when deallocating address %p\n",
481                        Ptr);
482     }
483     (void)DeleteAlignment;  // TODO(kostyak): verify that the alignment matches.
484     quarantineOrDeallocateChunk(Ptr, &Header, Size);
485   }
486 
487   // Reallocates a chunk. We can save on a new allocation if the new requested
488   // size still fits in the chunk.
489   void *reallocate(void *OldPtr, uptr NewSize) {
490     initThreadMaybe();
491 
492 #ifdef GWP_ASAN_HOOKS
493     if (UNLIKELY(GuardedAlloc.pointerIsMine(OldPtr))) {
494       size_t OldSize = GuardedAlloc.getSize(OldPtr);
495       void *NewPtr = allocate(NewSize, MinAlignment, FromMalloc);
496       if (NewPtr)
497         memcpy(NewPtr, OldPtr, (NewSize < OldSize) ? NewSize : OldSize);
498       GuardedAlloc.deallocate(OldPtr);
499       return NewPtr;
500     }
501 #endif // GWP_ASAN_HOOKS
502 
503     if (UNLIKELY(!Chunk::isAligned(OldPtr)))
504       dieWithMessage("misaligned address when reallocating address %p\n",
505                      OldPtr);
506     UnpackedHeader OldHeader;
507     Chunk::loadHeader(OldPtr, &OldHeader);
508     if (UNLIKELY(OldHeader.State != ChunkAllocated))
509       dieWithMessage("invalid chunk state when reallocating address %p\n",
510                      OldPtr);
511     if (DeallocationTypeMismatch) {
512       if (UNLIKELY(OldHeader.AllocType != FromMalloc))
513         dieWithMessage("allocation type mismatch when reallocating address "
514                        "%p\n", OldPtr);
515     }
516     const uptr UsableSize = Chunk::getUsableSize(OldPtr, &OldHeader);
517     // The new size still fits in the current chunk, and the size difference
518     // is reasonable.
519     if (NewSize <= UsableSize &&
520         (UsableSize - NewSize) < (SizeClassMap::kMaxSize / 2)) {
521       UnpackedHeader NewHeader = OldHeader;
522       NewHeader.SizeOrUnusedBytes =
523           OldHeader.ClassId ? NewSize : UsableSize - NewSize;
524       Chunk::compareExchangeHeader(OldPtr, &NewHeader, &OldHeader);
525       return OldPtr;
526     }
527     // Otherwise, we have to allocate a new chunk and copy the contents of the
528     // old one.
529     void *NewPtr = allocate(NewSize, MinAlignment, FromMalloc);
530     if (NewPtr) {
531       const uptr OldSize = OldHeader.ClassId ? OldHeader.SizeOrUnusedBytes :
532           UsableSize - OldHeader.SizeOrUnusedBytes;
533       memcpy(NewPtr, OldPtr, Min(NewSize, UsableSize));
534       quarantineOrDeallocateChunk(OldPtr, &OldHeader, OldSize);
535     }
536     return NewPtr;
537   }
538 
539   // Helper function that returns the actual usable size of a chunk.
540   uptr getUsableSize(const void *Ptr) {
541     initThreadMaybe();
542     if (UNLIKELY(!Ptr))
543       return 0;
544 
545 #ifdef GWP_ASAN_HOOKS
546     if (UNLIKELY(GuardedAlloc.pointerIsMine(Ptr)))
547       return GuardedAlloc.getSize(Ptr);
548 #endif // GWP_ASAN_HOOKS
549 
550     UnpackedHeader Header;
551     Chunk::loadHeader(Ptr, &Header);
552     // Getting the usable size of a chunk only makes sense if it's allocated.
553     if (UNLIKELY(Header.State != ChunkAllocated))
554       dieWithMessage("invalid chunk state when sizing address %p\n", Ptr);
555     return Chunk::getUsableSize(Ptr, &Header);
556   }
557 
558   void *calloc(uptr NMemB, uptr Size) {
559     initThreadMaybe();
560     if (UNLIKELY(CheckForCallocOverflow(NMemB, Size))) {
561       if (AllocatorMayReturnNull())
562         return nullptr;
563       reportCallocOverflow(NMemB, Size);
564     }
565     return allocate(NMemB * Size, MinAlignment, FromMalloc, true);
566   }
567 
568   void commitBack(ScudoTSD *TSD) {
569     Quarantine.Drain(getQuarantineCache(TSD), QuarantineCallback(&TSD->Cache));
570     Backend.destroyCache(&TSD->Cache);
571   }
572 
573   uptr getStats(AllocatorStat StatType) {
574     initThreadMaybe();
575     uptr stats[AllocatorStatCount];
576     Backend.getStats(stats);
577     return stats[StatType];
578   }
579 
580   bool canReturnNull() {
581     initThreadMaybe();
582     return AllocatorMayReturnNull();
583   }
584 
585   void setRssLimit(uptr LimitMb, bool HardLimit) {
586     if (HardLimit)
587       HardRssLimitMb = LimitMb;
588     else
589       SoftRssLimitMb = LimitMb;
590     CheckRssLimit = HardRssLimitMb || SoftRssLimitMb;
591   }
592 
593   void printStats() {
594     initThreadMaybe();
595     Backend.printStats();
596   }
597 };
598 
599 NOINLINE void Allocator::performSanityChecks() {
600   // Verify that the header offset field can hold the maximum offset. In the
601   // case of the Secondary allocator, it takes care of alignment and the
602   // offset will always be 0. In the case of the Primary, the worst case
603   // scenario happens in the last size class, when the backend allocation
604   // would already be aligned on the requested alignment, which would happen
605   // to be the maximum alignment that would fit in that size class. As a
606   // result, the maximum offset will be at most the maximum alignment for the
607   // last size class minus the header size, in multiples of MinAlignment.
608   UnpackedHeader Header = {};
609   const uptr MaxPrimaryAlignment =
610       1 << MostSignificantSetBitIndex(SizeClassMap::kMaxSize - MinAlignment);
611   const uptr MaxOffset =
612       (MaxPrimaryAlignment - Chunk::getHeaderSize()) >> MinAlignmentLog;
613   Header.Offset = MaxOffset;
614   if (Header.Offset != MaxOffset)
615     dieWithMessage("maximum possible offset doesn't fit in header\n");
616   // Verify that we can fit the maximum size or amount of unused bytes in the
617   // header. Given that the Secondary fits the allocation to a page, the worst
618   // case scenario happens in the Primary. It will depend on the second to
619   // last and last class sizes, as well as the dynamic base for the Primary.
620   // The following is an over-approximation that works for our needs.
621   const uptr MaxSizeOrUnusedBytes = SizeClassMap::kMaxSize - 1;
622   Header.SizeOrUnusedBytes = MaxSizeOrUnusedBytes;
623   if (Header.SizeOrUnusedBytes != MaxSizeOrUnusedBytes)
624     dieWithMessage("maximum possible unused bytes doesn't fit in header\n");
625 
626   const uptr LargestClassId = SizeClassMap::kLargestClassID;
627   Header.ClassId = LargestClassId;
628   if (Header.ClassId != LargestClassId)
629     dieWithMessage("largest class ID doesn't fit in header\n");
630 }
631 
632 // Opportunistic RSS limit check. This will update the RSS limit status, if
633 // it can, every 250ms, otherwise it will just return the current one.
634 NOINLINE bool Allocator::isRssLimitExceeded() {
635   u64 LastCheck = atomic_load_relaxed(&RssLastCheckedAtNS);
636   const u64 CurrentCheck = MonotonicNanoTime();
637   if (LIKELY(CurrentCheck < LastCheck + (250ULL * 1000000ULL)))
638     return atomic_load_relaxed(&RssLimitExceeded);
639   if (!atomic_compare_exchange_weak(&RssLastCheckedAtNS, &LastCheck,
640                                     CurrentCheck, memory_order_relaxed))
641     return atomic_load_relaxed(&RssLimitExceeded);
642   // TODO(kostyak): We currently use sanitizer_common's GetRSS which reads the
643   //                RSS from /proc/self/statm by default. We might want to
644   //                call getrusage directly, even if it's less accurate.
645   const uptr CurrentRssMb = GetRSS() >> 20;
646   if (HardRssLimitMb && UNLIKELY(HardRssLimitMb < CurrentRssMb))
647     dieWithMessage("hard RSS limit exhausted (%zdMb vs %zdMb)\n",
648                    HardRssLimitMb, CurrentRssMb);
649   if (SoftRssLimitMb) {
650     if (atomic_load_relaxed(&RssLimitExceeded)) {
651       if (CurrentRssMb <= SoftRssLimitMb)
652         atomic_store_relaxed(&RssLimitExceeded, false);
653     } else {
654       if (CurrentRssMb > SoftRssLimitMb) {
655         atomic_store_relaxed(&RssLimitExceeded, true);
656         Printf("Scudo INFO: soft RSS limit exhausted (%zdMb vs %zdMb)\n",
657                SoftRssLimitMb, CurrentRssMb);
658       }
659     }
660   }
661   return atomic_load_relaxed(&RssLimitExceeded);
662 }
663 
664 static Allocator Instance(LINKER_INITIALIZED);
665 
666 static BackendT &getBackend() {
667   return Instance.Backend;
668 }
669 
670 void initScudo() {
671   Instance.init();
672 #ifdef GWP_ASAN_HOOKS
673   gwp_asan::options::initOptions();
674   GuardedAlloc.init(gwp_asan::options::getOptions());
675 #endif // GWP_ASAN_HOOKS
676 }
677 
678 void ScudoTSD::init() {
679   getBackend().initCache(&Cache);
680   memset(QuarantineCachePlaceHolder, 0, sizeof(QuarantineCachePlaceHolder));
681 }
682 
683 void ScudoTSD::commitBack() {
684   Instance.commitBack(this);
685 }
686 
687 void *scudoAllocate(uptr Size, uptr Alignment, AllocType Type) {
688   if (Alignment && UNLIKELY(!IsPowerOfTwo(Alignment))) {
689     errno = EINVAL;
690     if (Instance.canReturnNull())
691       return nullptr;
692     reportAllocationAlignmentNotPowerOfTwo(Alignment);
693   }
694   return SetErrnoOnNull(Instance.allocate(Size, Alignment, Type));
695 }
696 
697 void scudoDeallocate(void *Ptr, uptr Size, uptr Alignment, AllocType Type) {
698   Instance.deallocate(Ptr, Size, Alignment, Type);
699 }
700 
701 void *scudoRealloc(void *Ptr, uptr Size) {
702   if (!Ptr)
703     return SetErrnoOnNull(Instance.allocate(Size, MinAlignment, FromMalloc));
704   if (Size == 0) {
705     Instance.deallocate(Ptr, 0, 0, FromMalloc);
706     return nullptr;
707   }
708   return SetErrnoOnNull(Instance.reallocate(Ptr, Size));
709 }
710 
711 void *scudoCalloc(uptr NMemB, uptr Size) {
712   return SetErrnoOnNull(Instance.calloc(NMemB, Size));
713 }
714 
715 void *scudoValloc(uptr Size) {
716   return SetErrnoOnNull(
717       Instance.allocate(Size, GetPageSizeCached(), FromMemalign));
718 }
719 
720 void *scudoPvalloc(uptr Size) {
721   const uptr PageSize = GetPageSizeCached();
722   if (UNLIKELY(CheckForPvallocOverflow(Size, PageSize))) {
723     errno = ENOMEM;
724     if (Instance.canReturnNull())
725       return nullptr;
726     reportPvallocOverflow(Size);
727   }
728   // pvalloc(0) should allocate one page.
729   Size = Size ? RoundUpTo(Size, PageSize) : PageSize;
730   return SetErrnoOnNull(Instance.allocate(Size, PageSize, FromMemalign));
731 }
732 
733 int scudoPosixMemalign(void **MemPtr, uptr Alignment, uptr Size) {
734   if (UNLIKELY(!CheckPosixMemalignAlignment(Alignment))) {
735     if (!Instance.canReturnNull())
736       reportInvalidPosixMemalignAlignment(Alignment);
737     return EINVAL;
738   }
739   void *Ptr = Instance.allocate(Size, Alignment, FromMemalign);
740   if (UNLIKELY(!Ptr))
741     return ENOMEM;
742   *MemPtr = Ptr;
743   return 0;
744 }
745 
746 void *scudoAlignedAlloc(uptr Alignment, uptr Size) {
747   if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(Alignment, Size))) {
748     errno = EINVAL;
749     if (Instance.canReturnNull())
750       return nullptr;
751     reportInvalidAlignedAllocAlignment(Size, Alignment);
752   }
753   return SetErrnoOnNull(Instance.allocate(Size, Alignment, FromMalloc));
754 }
755 
756 uptr scudoMallocUsableSize(void *Ptr) {
757   return Instance.getUsableSize(Ptr);
758 }
759 
760 }  // namespace __scudo
761 
762 using namespace __scudo;
763 
764 // MallocExtension helper functions
765 
766 uptr __sanitizer_get_current_allocated_bytes() {
767   return Instance.getStats(AllocatorStatAllocated);
768 }
769 
770 uptr __sanitizer_get_heap_size() {
771   return Instance.getStats(AllocatorStatMapped);
772 }
773 
774 uptr __sanitizer_get_free_bytes() {
775   return 1;
776 }
777 
778 uptr __sanitizer_get_unmapped_bytes() {
779   return 1;
780 }
781 
782 uptr __sanitizer_get_estimated_allocated_size(uptr Size) {
783   return Size;
784 }
785 
786 int __sanitizer_get_ownership(const void *Ptr) {
787   return Instance.isValidPointer(Ptr);
788 }
789 
790 uptr __sanitizer_get_allocated_size(const void *Ptr) {
791   return Instance.getUsableSize(Ptr);
792 }
793 
794 #if !SANITIZER_SUPPORTS_WEAK_HOOKS
795 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_malloc_hook,
796                              void *Ptr, uptr Size) {
797   (void)Ptr;
798   (void)Size;
799 }
800 
801 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_free_hook, void *Ptr) {
802   (void)Ptr;
803 }
804 #endif
805 
806 // Interface functions
807 
808 void __scudo_set_rss_limit(uptr LimitMb, s32 HardLimit) {
809   if (!SCUDO_CAN_USE_PUBLIC_INTERFACE)
810     return;
811   Instance.setRssLimit(LimitMb, !!HardLimit);
812 }
813 
814 void __scudo_print_stats() {
815   Instance.printStats();
816 }
817