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_interface.h"
23 #include "sanitizer_common/sanitizer_quarantine.h"
24 
25 #include <limits.h>
26 #include <pthread.h>
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 QuarantineSizeMb;
165   u32 ThreadLocalQuarantineSizeKb;
166   bool MayReturnNull;
167   s32 ReleaseToOSIntervalMs;
168   bool DeallocationTypeMismatch;
169   bool DeleteSizeMismatch;
170   bool ZeroContents;
171 
172   void setFrom(const Flags *f, const CommonFlags *cf);
173   void copyTo(Flags *f, CommonFlags *cf) const;
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   QuarantineSizeMb = f->QuarantineSizeMb;
180   ThreadLocalQuarantineSizeKb = f->ThreadLocalQuarantineSizeKb;
181   DeallocationTypeMismatch = f->DeallocationTypeMismatch;
182   DeleteSizeMismatch = f->DeleteSizeMismatch;
183   ZeroContents = f->ZeroContents;
184 }
185 
186 void AllocatorOptions::copyTo(Flags *f, CommonFlags *cf) const {
187   cf->allocator_may_return_null = MayReturnNull;
188   cf->allocator_release_to_os_interval_ms = ReleaseToOSIntervalMs;
189   f->QuarantineSizeMb = QuarantineSizeMb;
190   f->ThreadLocalQuarantineSizeKb = ThreadLocalQuarantineSizeKb;
191   f->DeallocationTypeMismatch = DeallocationTypeMismatch;
192   f->DeleteSizeMismatch = DeleteSizeMismatch;
193   f->ZeroContents = ZeroContents;
194 }
195 
196 static void initScudoInternal(const AllocatorOptions &Options);
197 
198 static bool ScudoInitIsRunning = false;
199 
200 void initScudo() {
201   SanitizerToolName = "Scudo";
202   CHECK(!ScudoInitIsRunning && "Scudo init calls itself!");
203   ScudoInitIsRunning = true;
204 
205   // Check if hardware CRC32 is supported in the binary and by the platform, if
206   // so, opt for the CRC32 hardware version of the checksum.
207   if (computeHardwareCRC32 && testCPUFeature(CRC32CPUFeature))
208     atomic_store_relaxed(&HashAlgorithm, CRC32Hardware);
209 
210   initFlags();
211 
212   AllocatorOptions Options;
213   Options.setFrom(getFlags(), common_flags());
214   initScudoInternal(Options);
215 
216   // TODO(kostyak): determine if MaybeStartBackgroudThread could be of some use.
217 
218   ScudoInitIsRunning = false;
219 }
220 
221 struct QuarantineCallback {
222   explicit QuarantineCallback(AllocatorCache *Cache)
223     : Cache_(Cache) {}
224 
225   // Chunk recycling function, returns a quarantined chunk to the backend,
226   // first making sure it hasn't been tampered with.
227   void Recycle(ScudoChunk *Chunk) {
228     UnpackedHeader Header;
229     Chunk->loadHeader(&Header);
230     if (UNLIKELY(Header.State != ChunkQuarantine)) {
231       dieWithMessage("ERROR: invalid chunk state when recycling address %p\n",
232                      Chunk);
233     }
234     Chunk->eraseHeader();
235     void *Ptr = Chunk->getAllocBeg(&Header);
236     getBackendAllocator().Deallocate(Cache_, Ptr, Header.FromPrimary);
237   }
238 
239   // Internal quarantine allocation and deallocation functions. We first check
240   // that the batches are indeed serviced by the Primary.
241   // TODO(kostyak): figure out the best way to protect the batches.
242   COMPILER_CHECK(sizeof(QuarantineBatch) < SizeClassMap::kMaxSize);
243   void *Allocate(uptr Size) {
244     return getBackendAllocator().Allocate(Cache_, Size, MinAlignment, true);
245   }
246 
247   void Deallocate(void *Ptr) {
248     getBackendAllocator().Deallocate(Cache_, Ptr, true);
249   }
250 
251   AllocatorCache *Cache_;
252 };
253 
254 typedef Quarantine<QuarantineCallback, ScudoChunk> ScudoQuarantine;
255 typedef ScudoQuarantine::Cache ScudoQuarantineCache;
256 COMPILER_CHECK(sizeof(ScudoQuarantineCache) <=
257                sizeof(ScudoThreadContext::QuarantineCachePlaceHolder));
258 
259 AllocatorCache *getAllocatorCache(ScudoThreadContext *ThreadContext) {
260   return &ThreadContext->Cache;
261 }
262 
263 ScudoQuarantineCache *getQuarantineCache(ScudoThreadContext *ThreadContext) {
264   return reinterpret_cast<
265       ScudoQuarantineCache *>(ThreadContext->QuarantineCachePlaceHolder);
266 }
267 
268 Xorshift128Plus *getPrng(ScudoThreadContext *ThreadContext) {
269   return &ThreadContext->Prng;
270 }
271 
272 struct ScudoAllocator {
273   static const uptr MaxAllowedMallocSize =
274       FIRST_32_SECOND_64(2UL << 30, 1ULL << 40);
275 
276   typedef ReturnNullOrDieOnFailure FailureHandler;
277 
278   ScudoBackendAllocator BackendAllocator;
279   ScudoQuarantine AllocatorQuarantine;
280 
281   // The fallback caches are used when the thread local caches have been
282   // 'detroyed' on thread tear-down. They are protected by a Mutex as they can
283   // be accessed by different threads.
284   StaticSpinMutex FallbackMutex;
285   AllocatorCache FallbackAllocatorCache;
286   ScudoQuarantineCache FallbackQuarantineCache;
287   Xorshift128Plus FallbackPrng;
288 
289   bool DeallocationTypeMismatch;
290   bool ZeroContents;
291   bool DeleteSizeMismatch;
292 
293   explicit ScudoAllocator(LinkerInitialized)
294     : AllocatorQuarantine(LINKER_INITIALIZED),
295       FallbackQuarantineCache(LINKER_INITIALIZED) {}
296 
297   void init(const AllocatorOptions &Options) {
298     // Verify that the header offset field can hold the maximum offset. In the
299     // case of the Secondary allocator, it takes care of alignment and the
300     // offset will always be 0. In the case of the Primary, the worst case
301     // scenario happens in the last size class, when the backend allocation
302     // would already be aligned on the requested alignment, which would happen
303     // to be the maximum alignment that would fit in that size class. As a
304     // result, the maximum offset will be at most the maximum alignment for the
305     // last size class minus the header size, in multiples of MinAlignment.
306     UnpackedHeader Header = {};
307     uptr MaxPrimaryAlignment = 1 << MostSignificantSetBitIndex(
308         SizeClassMap::kMaxSize - MinAlignment);
309     uptr MaxOffset = (MaxPrimaryAlignment - AlignedChunkHeaderSize) >>
310         MinAlignmentLog;
311     Header.Offset = MaxOffset;
312     if (Header.Offset != MaxOffset) {
313       dieWithMessage("ERROR: the maximum possible offset doesn't fit in the "
314                      "header\n");
315     }
316     // Verify that we can fit the maximum size or amount of unused bytes in the
317     // header. Given that the Secondary fits the allocation to a page, the worst
318     // case scenario happens in the Primary. It will depend on the second to
319     // last and last class sizes, as well as the dynamic base for the Primary.
320     // The following is an over-approximation that works for our needs.
321     uptr MaxSizeOrUnusedBytes = SizeClassMap::kMaxSize - 1;
322     Header.SizeOrUnusedBytes = MaxSizeOrUnusedBytes;
323     if (Header.SizeOrUnusedBytes != MaxSizeOrUnusedBytes) {
324       dieWithMessage("ERROR: the maximum possible unused bytes doesn't fit in "
325                      "the header\n");
326     }
327 
328     DeallocationTypeMismatch = Options.DeallocationTypeMismatch;
329     DeleteSizeMismatch = Options.DeleteSizeMismatch;
330     ZeroContents = Options.ZeroContents;
331     SetAllocatorMayReturnNull(Options.MayReturnNull);
332     BackendAllocator.Init(Options.ReleaseToOSIntervalMs);
333     AllocatorQuarantine.Init(
334         static_cast<uptr>(Options.QuarantineSizeMb) << 20,
335         static_cast<uptr>(Options.ThreadLocalQuarantineSizeKb) << 10);
336     BackendAllocator.InitCache(&FallbackAllocatorCache);
337     FallbackPrng.initFromURandom();
338     Cookie = FallbackPrng.getNext();
339   }
340 
341   // Helper function that checks for a valid Scudo chunk. nullptr isn't.
342   bool isValidPointer(const void *UserPtr) {
343     initThreadMaybe();
344     if (!UserPtr)
345       return false;
346     uptr UserBeg = reinterpret_cast<uptr>(UserPtr);
347     if (!IsAligned(UserBeg, MinAlignment))
348       return false;
349     return getScudoChunk(UserBeg)->isValid();
350   }
351 
352   // Allocates a chunk.
353   void *allocate(uptr Size, uptr Alignment, AllocType Type,
354                  bool ForceZeroContents = false) {
355     initThreadMaybe();
356     if (UNLIKELY(!IsPowerOfTwo(Alignment))) {
357       dieWithMessage("ERROR: alignment is not a power of 2\n");
358     }
359     if (Alignment > MaxAlignment)
360       return FailureHandler::OnBadRequest();
361     if (Alignment < MinAlignment)
362       Alignment = MinAlignment;
363     if (Size >= MaxAllowedMallocSize)
364       return FailureHandler::OnBadRequest();
365     if (Size == 0)
366       Size = 1;
367 
368     uptr NeededSize = RoundUpTo(Size, MinAlignment) + AlignedChunkHeaderSize;
369     uptr AlignedSize = (Alignment > MinAlignment) ?
370         NeededSize + (Alignment - AlignedChunkHeaderSize) : NeededSize;
371     if (AlignedSize >= MaxAllowedMallocSize)
372       return FailureHandler::OnBadRequest();
373 
374     // Primary and Secondary backed allocations have a different treatment. We
375     // deal with alignment requirements of Primary serviced allocations here,
376     // but the Secondary will take care of its own alignment needs.
377     bool FromPrimary = PrimaryAllocator::CanAllocate(AlignedSize, MinAlignment);
378 
379     void *Ptr;
380     uptr Salt;
381     uptr AllocationSize = FromPrimary ? AlignedSize : NeededSize;
382     uptr AllocationAlignment = FromPrimary ? MinAlignment : Alignment;
383     ScudoThreadContext *ThreadContext = getThreadContextAndLock();
384     if (LIKELY(ThreadContext)) {
385       Salt = getPrng(ThreadContext)->getNext();
386       Ptr = BackendAllocator.Allocate(getAllocatorCache(ThreadContext),
387                                       AllocationSize, AllocationAlignment,
388                                       FromPrimary);
389       ThreadContext->unlock();
390     } else {
391       SpinMutexLock l(&FallbackMutex);
392       Salt = FallbackPrng.getNext();
393       Ptr = BackendAllocator.Allocate(&FallbackAllocatorCache, AllocationSize,
394                                       AllocationAlignment, FromPrimary);
395     }
396     if (!Ptr)
397       return FailureHandler::OnOOM();
398 
399     // If requested, we will zero out the entire contents of the returned chunk.
400     if ((ForceZeroContents || ZeroContents) && FromPrimary)
401        memset(Ptr, 0,
402               BackendAllocator.GetActuallyAllocatedSize(Ptr, FromPrimary));
403 
404     UnpackedHeader Header = {};
405     uptr AllocBeg = reinterpret_cast<uptr>(Ptr);
406     uptr UserBeg = AllocBeg + AlignedChunkHeaderSize;
407     if (!IsAligned(UserBeg, 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       CHECK(FromPrimary);
412       UserBeg = RoundUpTo(UserBeg, Alignment);
413       uptr Offset = UserBeg - AlignedChunkHeaderSize - AllocBeg;
414       Header.Offset = Offset >> MinAlignmentLog;
415     }
416     CHECK_LE(UserBeg + Size, AllocBeg + AllocationSize);
417     Header.State = ChunkAllocated;
418     Header.AllocType = Type;
419     if (FromPrimary) {
420       Header.FromPrimary = FromPrimary;
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       uptr PageSize = GetPageSizeCached();
427       uptr TrailingBytes = (UserBeg + Size) & (PageSize - 1);
428       if (TrailingBytes)
429         Header.SizeOrUnusedBytes = PageSize - TrailingBytes;
430     }
431     Header.Salt = static_cast<u8>(Salt);
432     getScudoChunk(UserBeg)->storeHeader(&Header);
433     void *UserPtr = reinterpret_cast<void *>(UserBeg);
434     // if (&__sanitizer_malloc_hook) __sanitizer_malloc_hook(UserPtr, Size);
435     return UserPtr;
436   }
437 
438   // Place a chunk in the quarantine. In the event of a zero-sized quarantine,
439   // we directly deallocate the chunk, otherwise the flow would lead to the
440   // chunk being loaded (and checked) twice, and stored (and checksummed) once,
441   // with no additional security value.
442   void quarantineOrDeallocateChunk(ScudoChunk *Chunk, UnpackedHeader *Header,
443                                    uptr Size) {
444     bool FromPrimary = Header->FromPrimary;
445     bool BypassQuarantine = (AllocatorQuarantine.GetCacheSize() == 0);
446     if (BypassQuarantine) {
447       Chunk->eraseHeader();
448       void *Ptr = Chunk->getAllocBeg(Header);
449       ScudoThreadContext *ThreadContext = getThreadContextAndLock();
450       if (LIKELY(ThreadContext)) {
451         getBackendAllocator().Deallocate(getAllocatorCache(ThreadContext), Ptr,
452                                          FromPrimary);
453         ThreadContext->unlock();
454       } else {
455         SpinMutexLock Lock(&FallbackMutex);
456         getBackendAllocator().Deallocate(&FallbackAllocatorCache, Ptr,
457                                          FromPrimary);
458       }
459     } else {
460       UnpackedHeader NewHeader = *Header;
461       NewHeader.State = ChunkQuarantine;
462       Chunk->compareExchangeHeader(&NewHeader, Header);
463       ScudoThreadContext *ThreadContext = getThreadContextAndLock();
464       if (LIKELY(ThreadContext)) {
465         AllocatorQuarantine.Put(getQuarantineCache(ThreadContext),
466                                 QuarantineCallback(
467                                     getAllocatorCache(ThreadContext)),
468                                 Chunk, Size);
469         ThreadContext->unlock();
470       } else {
471         SpinMutexLock l(&FallbackMutex);
472         AllocatorQuarantine.Put(&FallbackQuarantineCache,
473                                 QuarantineCallback(&FallbackAllocatorCache),
474                                 Chunk, Size);
475       }
476     }
477   }
478 
479   // Deallocates a Chunk, which means adding it to the delayed free list (or
480   // Quarantine).
481   void deallocate(void *UserPtr, uptr DeleteSize, AllocType Type) {
482     initThreadMaybe();
483     // if (&__sanitizer_free_hook) __sanitizer_free_hook(UserPtr);
484     if (!UserPtr)
485       return;
486     uptr UserBeg = reinterpret_cast<uptr>(UserPtr);
487     if (UNLIKELY(!IsAligned(UserBeg, MinAlignment))) {
488       dieWithMessage("ERROR: attempted to deallocate a chunk not properly "
489                      "aligned at address %p\n", UserPtr);
490     }
491     ScudoChunk *Chunk = getScudoChunk(UserBeg);
492     UnpackedHeader OldHeader;
493     Chunk->loadHeader(&OldHeader);
494     if (UNLIKELY(OldHeader.State != ChunkAllocated)) {
495       dieWithMessage("ERROR: invalid chunk state when deallocating address "
496                      "%p\n", UserPtr);
497     }
498     if (DeallocationTypeMismatch) {
499       // The deallocation type has to match the allocation one.
500       if (OldHeader.AllocType != Type) {
501         // With the exception of memalign'd Chunks, that can be still be free'd.
502         if (OldHeader.AllocType != FromMemalign || Type != FromMalloc) {
503           dieWithMessage("ERROR: allocation type mismatch on address %p\n",
504                          UserPtr);
505         }
506       }
507     }
508     uptr Size = OldHeader.FromPrimary ? OldHeader.SizeOrUnusedBytes :
509         Chunk->getUsableSize(&OldHeader) - OldHeader.SizeOrUnusedBytes;
510     if (DeleteSizeMismatch) {
511       if (DeleteSize && DeleteSize != Size) {
512         dieWithMessage("ERROR: invalid sized delete on chunk at address %p\n",
513                        UserPtr);
514       }
515     }
516 
517     // If a small memory amount was allocated with a larger alignment, we want
518     // to take that into account. Otherwise the Quarantine would be filled with
519     // tiny chunks, taking a lot of VA memory. This is an approximation of the
520     // usable size, that allows us to not call GetActuallyAllocatedSize.
521     uptr LiableSize = Size + (OldHeader.Offset << MinAlignment);
522     quarantineOrDeallocateChunk(Chunk, &OldHeader, LiableSize);
523   }
524 
525   // Reallocates a chunk. We can save on a new allocation if the new requested
526   // size still fits in the chunk.
527   void *reallocate(void *OldPtr, uptr NewSize) {
528     initThreadMaybe();
529     uptr UserBeg = reinterpret_cast<uptr>(OldPtr);
530     if (UNLIKELY(!IsAligned(UserBeg, MinAlignment))) {
531       dieWithMessage("ERROR: attempted to reallocate a chunk not properly "
532                      "aligned at address %p\n", OldPtr);
533     }
534     ScudoChunk *Chunk = getScudoChunk(UserBeg);
535     UnpackedHeader OldHeader;
536     Chunk->loadHeader(&OldHeader);
537     if (UNLIKELY(OldHeader.State != ChunkAllocated)) {
538       dieWithMessage("ERROR: invalid chunk state when reallocating address "
539                      "%p\n", OldPtr);
540     }
541     if (UNLIKELY(OldHeader.AllocType != FromMalloc)) {
542       dieWithMessage("ERROR: invalid chunk type when reallocating address %p\n",
543                      OldPtr);
544     }
545     uptr UsableSize = Chunk->getUsableSize(&OldHeader);
546     // The new size still fits in the current chunk, and the size difference
547     // is reasonable.
548     if (NewSize <= UsableSize &&
549         (UsableSize - NewSize) < (SizeClassMap::kMaxSize / 2)) {
550       UnpackedHeader NewHeader = OldHeader;
551       NewHeader.SizeOrUnusedBytes =
552                 OldHeader.FromPrimary ? NewSize : UsableSize - NewSize;
553       Chunk->compareExchangeHeader(&NewHeader, &OldHeader);
554       return OldPtr;
555     }
556     // Otherwise, we have to allocate a new chunk and copy the contents of the
557     // old one.
558     void *NewPtr = allocate(NewSize, MinAlignment, FromMalloc);
559     if (NewPtr) {
560       uptr OldSize = OldHeader.FromPrimary ? OldHeader.SizeOrUnusedBytes :
561           UsableSize - OldHeader.SizeOrUnusedBytes;
562       memcpy(NewPtr, OldPtr, Min(NewSize, OldSize));
563       quarantineOrDeallocateChunk(Chunk, &OldHeader, UsableSize);
564     }
565     return NewPtr;
566   }
567 
568   // Helper function that returns the actual usable size of a chunk.
569   uptr getUsableSize(const void *Ptr) {
570     initThreadMaybe();
571     if (!Ptr)
572       return 0;
573     uptr UserBeg = reinterpret_cast<uptr>(Ptr);
574     ScudoChunk *Chunk = getScudoChunk(UserBeg);
575     UnpackedHeader Header;
576     Chunk->loadHeader(&Header);
577     // Getting the usable size of a chunk only makes sense if it's allocated.
578     if (UNLIKELY(Header.State != ChunkAllocated)) {
579       dieWithMessage("ERROR: invalid chunk state when sizing address %p\n",
580                      Ptr);
581     }
582     return Chunk->getUsableSize(&Header);
583   }
584 
585   void *calloc(uptr NMemB, uptr Size) {
586     initThreadMaybe();
587     uptr Total = NMemB * Size;
588     if (Size != 0 && Total / Size != NMemB)  // Overflow check
589       return FailureHandler::OnBadRequest();
590     return allocate(Total, MinAlignment, FromMalloc, true);
591   }
592 
593   void commitBack(ScudoThreadContext *ThreadContext) {
594     AllocatorCache *Cache = getAllocatorCache(ThreadContext);
595     AllocatorQuarantine.Drain(getQuarantineCache(ThreadContext),
596                               QuarantineCallback(Cache));
597     BackendAllocator.DestroyCache(Cache);
598   }
599 
600   uptr getStats(AllocatorStat StatType) {
601     initThreadMaybe();
602     uptr stats[AllocatorStatCount];
603     BackendAllocator.GetStats(stats);
604     return stats[StatType];
605   }
606 };
607 
608 static ScudoAllocator Instance(LINKER_INITIALIZED);
609 
610 static ScudoBackendAllocator &getBackendAllocator() {
611   return Instance.BackendAllocator;
612 }
613 
614 static void initScudoInternal(const AllocatorOptions &Options) {
615   Instance.init(Options);
616 }
617 
618 void ScudoThreadContext::init() {
619   getBackendAllocator().InitCache(&Cache);
620   Prng.initFromURandom();
621   memset(QuarantineCachePlaceHolder, 0, sizeof(QuarantineCachePlaceHolder));
622 }
623 
624 void ScudoThreadContext::commitBack() {
625   Instance.commitBack(this);
626 }
627 
628 void *scudoMalloc(uptr Size, AllocType Type) {
629   return Instance.allocate(Size, MinAlignment, Type);
630 }
631 
632 void scudoFree(void *Ptr, AllocType Type) {
633   Instance.deallocate(Ptr, 0, Type);
634 }
635 
636 void scudoSizedFree(void *Ptr, uptr Size, AllocType Type) {
637   Instance.deallocate(Ptr, Size, Type);
638 }
639 
640 void *scudoRealloc(void *Ptr, uptr Size) {
641   if (!Ptr)
642     return Instance.allocate(Size, MinAlignment, FromMalloc);
643   if (Size == 0) {
644     Instance.deallocate(Ptr, 0, FromMalloc);
645     return nullptr;
646   }
647   return Instance.reallocate(Ptr, Size);
648 }
649 
650 void *scudoCalloc(uptr NMemB, uptr Size) {
651   return Instance.calloc(NMemB, Size);
652 }
653 
654 void *scudoValloc(uptr Size) {
655   return Instance.allocate(Size, GetPageSizeCached(), FromMemalign);
656 }
657 
658 void *scudoMemalign(uptr Alignment, uptr Size) {
659   return Instance.allocate(Size, Alignment, FromMemalign);
660 }
661 
662 void *scudoPvalloc(uptr Size) {
663   uptr PageSize = GetPageSizeCached();
664   Size = RoundUpTo(Size, PageSize);
665   if (Size == 0) {
666     // pvalloc(0) should allocate one page.
667     Size = PageSize;
668   }
669   return Instance.allocate(Size, PageSize, FromMemalign);
670 }
671 
672 int scudoPosixMemalign(void **MemPtr, uptr Alignment, uptr Size) {
673   *MemPtr = Instance.allocate(Size, Alignment, FromMemalign);
674   return 0;
675 }
676 
677 void *scudoAlignedAlloc(uptr Alignment, uptr Size) {
678   // size must be a multiple of the alignment. To avoid a division, we first
679   // make sure that alignment is a power of 2.
680   CHECK(IsPowerOfTwo(Alignment));
681   CHECK_EQ((Size & (Alignment - 1)), 0);
682   return Instance.allocate(Size, Alignment, FromMalloc);
683 }
684 
685 uptr scudoMallocUsableSize(void *Ptr) {
686   return Instance.getUsableSize(Ptr);
687 }
688 
689 }  // namespace __scudo
690 
691 using namespace __scudo;
692 
693 // MallocExtension helper functions
694 
695 uptr __sanitizer_get_current_allocated_bytes() {
696   return Instance.getStats(AllocatorStatAllocated);
697 }
698 
699 uptr __sanitizer_get_heap_size() {
700   return Instance.getStats(AllocatorStatMapped);
701 }
702 
703 uptr __sanitizer_get_free_bytes() {
704   return 1;
705 }
706 
707 uptr __sanitizer_get_unmapped_bytes() {
708   return 1;
709 }
710 
711 uptr __sanitizer_get_estimated_allocated_size(uptr size) {
712   return size;
713 }
714 
715 int __sanitizer_get_ownership(const void *Ptr) {
716   return Instance.isValidPointer(Ptr);
717 }
718 
719 uptr __sanitizer_get_allocated_size(const void *Ptr) {
720   return Instance.getUsableSize(Ptr);
721 }
722