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