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