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 static INLINE AtomicPackedHeader *getAtomicHeader(void *Ptr) { 68 return reinterpret_cast<AtomicPackedHeader *>(reinterpret_cast<uptr>(Ptr) - 69 getHeaderSize()); 70 } 71 static INLINE 72 const AtomicPackedHeader *getConstAtomicHeader(const void *Ptr) { 73 return reinterpret_cast<const AtomicPackedHeader *>( 74 reinterpret_cast<uptr>(Ptr) - getHeaderSize()); 75 } 76 77 static INLINE bool isAligned(const void *Ptr) { 78 return IsAligned(reinterpret_cast<uptr>(Ptr), MinAlignment); 79 } 80 81 // We can't use the offset member of the chunk itself, as we would double 82 // fetch it without any warranty that it wouldn't have been tampered. To 83 // prevent this, we work with a local copy of the header. 84 static INLINE void *getBackendPtr(const void *Ptr, UnpackedHeader *Header) { 85 return reinterpret_cast<void *>(reinterpret_cast<uptr>(Ptr) - 86 getHeaderSize() - (Header->Offset << MinAlignmentLog)); 87 } 88 89 // Returns the usable size for a chunk, meaning the amount of bytes from the 90 // beginning of the user data to the end of the backend allocated chunk. 91 static INLINE uptr getUsableSize(const void *Ptr, UnpackedHeader *Header) { 92 const uptr ClassId = Header->ClassId; 93 if (ClassId) 94 return PrimaryAllocator::ClassIdToSize(ClassId) - getHeaderSize() - 95 (Header->Offset << MinAlignmentLog); 96 return SecondaryAllocator::GetActuallyAllocatedSize( 97 getBackendPtr(Ptr, Header)) - getHeaderSize(); 98 } 99 100 // Returns the size the user requested when allocating the chunk. 101 static INLINE uptr getSize(const void *Ptr, UnpackedHeader *Header) { 102 const uptr SizeOrUnusedBytes = Header->SizeOrUnusedBytes; 103 if (Header->ClassId) 104 return SizeOrUnusedBytes; 105 return SecondaryAllocator::GetActuallyAllocatedSize( 106 getBackendPtr(Ptr, Header)) - getHeaderSize() - SizeOrUnusedBytes; 107 } 108 109 // Compute the checksum of the chunk pointer and its header. 110 static INLINE u16 computeChecksum(const void *Ptr, UnpackedHeader *Header) { 111 UnpackedHeader ZeroChecksumHeader = *Header; 112 ZeroChecksumHeader.Checksum = 0; 113 uptr HeaderHolder[sizeof(UnpackedHeader) / sizeof(uptr)]; 114 memcpy(&HeaderHolder, &ZeroChecksumHeader, sizeof(HeaderHolder)); 115 const u32 Crc = computeCRC32(Cookie, reinterpret_cast<uptr>(Ptr), 116 HeaderHolder, ARRAY_SIZE(HeaderHolder)); 117 return static_cast<u16>(Crc); 118 } 119 120 // Checks the validity of a chunk by verifying its checksum. It doesn't 121 // incur termination in the event of an invalid chunk. 122 static INLINE bool isValid(const void *Ptr) { 123 PackedHeader NewPackedHeader = 124 atomic_load_relaxed(getConstAtomicHeader(Ptr)); 125 UnpackedHeader NewUnpackedHeader = 126 bit_cast<UnpackedHeader>(NewPackedHeader); 127 return (NewUnpackedHeader.Checksum == 128 computeChecksum(Ptr, &NewUnpackedHeader)); 129 } 130 131 // Nulls out a chunk header. When returning the chunk to the backend, there 132 // is no need to store a valid ChunkAvailable header, as this would be 133 // computationally expensive. Zeroing out serves the same purpose by making 134 // the header invalid. In the extremely rare event where 0 would be a valid 135 // checksum for the chunk, the state of the chunk is ChunkAvailable anyway. 136 COMPILER_CHECK(ChunkAvailable == 0); 137 static INLINE void eraseHeader(void *Ptr) { 138 const PackedHeader NullPackedHeader = 0; 139 atomic_store_relaxed(getAtomicHeader(Ptr), NullPackedHeader); 140 } 141 142 // Loads and unpacks the header, verifying the checksum in the process. 143 static INLINE 144 void loadHeader(const void *Ptr, UnpackedHeader *NewUnpackedHeader) { 145 PackedHeader NewPackedHeader = 146 atomic_load_relaxed(getConstAtomicHeader(Ptr)); 147 *NewUnpackedHeader = bit_cast<UnpackedHeader>(NewPackedHeader); 148 if (UNLIKELY(NewUnpackedHeader->Checksum != 149 computeChecksum(Ptr, NewUnpackedHeader))) 150 dieWithMessage("corrupted chunk header at address %p\n", Ptr); 151 } 152 153 // Packs and stores the header, computing the checksum in the process. 154 static INLINE void storeHeader(void *Ptr, UnpackedHeader *NewUnpackedHeader) { 155 NewUnpackedHeader->Checksum = computeChecksum(Ptr, NewUnpackedHeader); 156 PackedHeader NewPackedHeader = bit_cast<PackedHeader>(*NewUnpackedHeader); 157 atomic_store_relaxed(getAtomicHeader(Ptr), NewPackedHeader); 158 } 159 160 // Packs and stores the header, computing the checksum in the process. We 161 // compare the current header with the expected provided one to ensure that 162 // we are not being raced by a corruption occurring in another thread. 163 static INLINE void compareExchangeHeader(void *Ptr, 164 UnpackedHeader *NewUnpackedHeader, 165 UnpackedHeader *OldUnpackedHeader) { 166 NewUnpackedHeader->Checksum = computeChecksum(Ptr, NewUnpackedHeader); 167 PackedHeader NewPackedHeader = bit_cast<PackedHeader>(*NewUnpackedHeader); 168 PackedHeader OldPackedHeader = bit_cast<PackedHeader>(*OldUnpackedHeader); 169 if (UNLIKELY(!atomic_compare_exchange_strong( 170 getAtomicHeader(Ptr), &OldPackedHeader, NewPackedHeader, 171 memory_order_relaxed))) 172 dieWithMessage("race on chunk header at address %p\n", Ptr); 173 } 174 } // namespace Chunk 175 176 struct QuarantineCallback { 177 explicit QuarantineCallback(AllocatorCache *Cache) 178 : Cache_(Cache) {} 179 180 // Chunk recycling function, returns a quarantined chunk to the backend, 181 // first making sure it hasn't been tampered with. 182 void Recycle(void *Ptr) { 183 UnpackedHeader Header; 184 Chunk::loadHeader(Ptr, &Header); 185 if (UNLIKELY(Header.State != ChunkQuarantine)) 186 dieWithMessage("invalid chunk state when recycling address %p\n", Ptr); 187 Chunk::eraseHeader(Ptr); 188 void *BackendPtr = Chunk::getBackendPtr(Ptr, &Header); 189 if (Header.ClassId) 190 getBackendAllocator().deallocatePrimary(Cache_, BackendPtr, 191 Header.ClassId); 192 else 193 getBackendAllocator().deallocateSecondary(BackendPtr); 194 } 195 196 // Internal quarantine allocation and deallocation functions. We first check 197 // that the batches are indeed serviced by the Primary. 198 // TODO(kostyak): figure out the best way to protect the batches. 199 void *Allocate(uptr Size) { 200 return getBackendAllocator().allocatePrimary(Cache_, BatchClassId); 201 } 202 203 void Deallocate(void *Ptr) { 204 getBackendAllocator().deallocatePrimary(Cache_, Ptr, BatchClassId); 205 } 206 207 AllocatorCache *Cache_; 208 COMPILER_CHECK(sizeof(QuarantineBatch) < SizeClassMap::kMaxSize); 209 const uptr BatchClassId = SizeClassMap::ClassID(sizeof(QuarantineBatch)); 210 }; 211 212 typedef Quarantine<QuarantineCallback, void> ScudoQuarantine; 213 typedef ScudoQuarantine::Cache ScudoQuarantineCache; 214 COMPILER_CHECK(sizeof(ScudoQuarantineCache) <= 215 sizeof(ScudoTSD::QuarantineCachePlaceHolder)); 216 217 ScudoQuarantineCache *getQuarantineCache(ScudoTSD *TSD) { 218 return reinterpret_cast<ScudoQuarantineCache *>( 219 TSD->QuarantineCachePlaceHolder); 220 } 221 222 struct ScudoAllocator { 223 static const uptr MaxAllowedMallocSize = 224 FIRST_32_SECOND_64(2UL << 30, 1ULL << 40); 225 226 typedef ReturnNullOrDieOnFailure FailureHandler; 227 228 ScudoBackendAllocator BackendAllocator; 229 ScudoQuarantine AllocatorQuarantine; 230 231 u32 QuarantineChunksUpToSize; 232 233 bool DeallocationTypeMismatch; 234 bool ZeroContents; 235 bool DeleteSizeMismatch; 236 237 bool CheckRssLimit; 238 uptr HardRssLimitMb; 239 uptr SoftRssLimitMb; 240 atomic_uint8_t RssLimitExceeded; 241 atomic_uint64_t RssLastCheckedAtNS; 242 243 explicit ScudoAllocator(LinkerInitialized) 244 : AllocatorQuarantine(LINKER_INITIALIZED) {} 245 246 NOINLINE void performSanityChecks() { 247 // Verify that the header offset field can hold the maximum offset. In the 248 // case of the Secondary allocator, it takes care of alignment and the 249 // offset will always be 0. In the case of the Primary, the worst case 250 // scenario happens in the last size class, when the backend allocation 251 // would already be aligned on the requested alignment, which would happen 252 // to be the maximum alignment that would fit in that size class. As a 253 // result, the maximum offset will be at most the maximum alignment for the 254 // last size class minus the header size, in multiples of MinAlignment. 255 UnpackedHeader Header = {}; 256 const uptr MaxPrimaryAlignment = 257 1 << MostSignificantSetBitIndex(SizeClassMap::kMaxSize - MinAlignment); 258 const uptr MaxOffset = 259 (MaxPrimaryAlignment - Chunk::getHeaderSize()) >> MinAlignmentLog; 260 Header.Offset = MaxOffset; 261 if (Header.Offset != MaxOffset) 262 dieWithMessage("maximum possible offset doesn't fit in header\n"); 263 // Verify that we can fit the maximum size or amount of unused bytes in the 264 // header. Given that the Secondary fits the allocation to a page, the worst 265 // case scenario happens in the Primary. It will depend on the second to 266 // last and last class sizes, as well as the dynamic base for the Primary. 267 // The following is an over-approximation that works for our needs. 268 const uptr MaxSizeOrUnusedBytes = SizeClassMap::kMaxSize - 1; 269 Header.SizeOrUnusedBytes = MaxSizeOrUnusedBytes; 270 if (Header.SizeOrUnusedBytes != MaxSizeOrUnusedBytes) 271 dieWithMessage("maximum possible unused bytes doesn't fit in header\n"); 272 273 const uptr LargestClassId = SizeClassMap::kLargestClassID; 274 Header.ClassId = LargestClassId; 275 if (Header.ClassId != LargestClassId) 276 dieWithMessage("largest class ID doesn't fit in header\n"); 277 } 278 279 void init() { 280 SanitizerToolName = "Scudo"; 281 PrimaryAllocatorName = "ScudoPrimary"; 282 SecondaryAllocatorName = "ScudoSecondary"; 283 284 initFlags(); 285 286 performSanityChecks(); 287 288 // Check if hardware CRC32 is supported in the binary and by the platform, 289 // if so, opt for the CRC32 hardware version of the checksum. 290 if (&computeHardwareCRC32 && hasHardwareCRC32()) 291 atomic_store_relaxed(&HashAlgorithm, CRC32Hardware); 292 293 SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null); 294 BackendAllocator.init(common_flags()->allocator_release_to_os_interval_ms); 295 HardRssLimitMb = common_flags()->hard_rss_limit_mb; 296 SoftRssLimitMb = common_flags()->soft_rss_limit_mb; 297 AllocatorQuarantine.Init( 298 static_cast<uptr>(getFlags()->QuarantineSizeKb) << 10, 299 static_cast<uptr>(getFlags()->ThreadLocalQuarantineSizeKb) << 10); 300 QuarantineChunksUpToSize = getFlags()->QuarantineChunksUpToSize; 301 DeallocationTypeMismatch = getFlags()->DeallocationTypeMismatch; 302 DeleteSizeMismatch = getFlags()->DeleteSizeMismatch; 303 ZeroContents = getFlags()->ZeroContents; 304 305 if (UNLIKELY(!GetRandom(reinterpret_cast<void *>(&Cookie), sizeof(Cookie), 306 /*blocking=*/false))) { 307 Cookie = static_cast<u32>((NanoTime() >> 12) ^ 308 (reinterpret_cast<uptr>(this) >> 4)); 309 } 310 311 CheckRssLimit = HardRssLimitMb || SoftRssLimitMb; 312 if (CheckRssLimit) 313 atomic_store_relaxed(&RssLastCheckedAtNS, MonotonicNanoTime()); 314 } 315 316 // Helper function that checks for a valid Scudo chunk. nullptr isn't. 317 bool isValidPointer(const void *Ptr) { 318 initThreadMaybe(); 319 if (UNLIKELY(!Ptr)) 320 return false; 321 if (!Chunk::isAligned(Ptr)) 322 return false; 323 return Chunk::isValid(Ptr); 324 } 325 326 // Opportunistic RSS limit check. This will update the RSS limit status, if 327 // it can, every 100ms, otherwise it will just return the current one. 328 bool isRssLimitExceeded() { 329 u64 LastCheck = atomic_load_relaxed(&RssLastCheckedAtNS); 330 const u64 CurrentCheck = MonotonicNanoTime(); 331 if (LIKELY(CurrentCheck < LastCheck + (100ULL * 1000000ULL))) 332 return atomic_load_relaxed(&RssLimitExceeded); 333 if (!atomic_compare_exchange_weak(&RssLastCheckedAtNS, &LastCheck, 334 CurrentCheck, memory_order_relaxed)) 335 return atomic_load_relaxed(&RssLimitExceeded); 336 // TODO(kostyak): We currently use sanitizer_common's GetRSS which reads the 337 // RSS from /proc/self/statm by default. We might want to 338 // call getrusage directly, even if it's less accurate. 339 const uptr CurrentRssMb = GetRSS() >> 20; 340 if (HardRssLimitMb && UNLIKELY(HardRssLimitMb < CurrentRssMb)) 341 dieWithMessage("hard RSS limit exhausted (%zdMb vs %zdMb)\n", 342 HardRssLimitMb, CurrentRssMb); 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 Printf("Scudo INFO: soft RSS limit exhausted (%zdMb vs %zdMb)\n", 351 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 const uptr NeededSize = RoundUpTo(Size, MinAlignment) + 372 Chunk::getHeaderSize(); 373 const uptr AlignedSize = (Alignment > MinAlignment) ? 374 NeededSize + (Alignment - Chunk::getHeaderSize()) : NeededSize; 375 if (UNLIKELY(AlignedSize >= MaxAllowedMallocSize)) 376 return FailureHandler::OnBadRequest(); 377 378 if (CheckRssLimit && UNLIKELY(isRssLimitExceeded())) 379 return FailureHandler::OnOOM(); 380 381 // Primary and Secondary backed allocations have a different treatment. We 382 // deal with alignment requirements of Primary serviced allocations here, 383 // but the Secondary will take care of its own alignment needs. 384 void *BackendPtr; 385 uptr BackendSize; 386 u8 ClassId; 387 if (PrimaryAllocator::CanAllocate(AlignedSize, MinAlignment)) { 388 BackendSize = AlignedSize; 389 ClassId = SizeClassMap::ClassID(BackendSize); 390 ScudoTSD *TSD = getTSDAndLock(); 391 BackendPtr = BackendAllocator.allocatePrimary(&TSD->Cache, ClassId); 392 TSD->unlock(); 393 } else { 394 BackendSize = NeededSize; 395 ClassId = 0; 396 BackendPtr = BackendAllocator.allocateSecondary(BackendSize, Alignment); 397 } 398 if (UNLIKELY(!BackendPtr)) 399 return FailureHandler::OnOOM(); 400 401 // If requested, we will zero out the entire contents of the returned chunk. 402 if ((ForceZeroContents || ZeroContents) && ClassId) 403 memset(BackendPtr, 0, PrimaryAllocator::ClassIdToSize(ClassId)); 404 405 UnpackedHeader Header = {}; 406 uptr UserPtr = reinterpret_cast<uptr>(BackendPtr) + Chunk::getHeaderSize(); 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 DCHECK_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 const 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("misaligned pointer when deallocating address %p\n", Ptr); 490 UnpackedHeader Header; 491 Chunk::loadHeader(Ptr, &Header); 492 if (UNLIKELY(Header.State != ChunkAllocated)) 493 dieWithMessage("invalid chunk state when deallocating address %p\n", Ptr); 494 if (DeallocationTypeMismatch) { 495 // The deallocation type has to match the allocation one. 496 if (Header.AllocType != Type) { 497 // With the exception of memalign'd Chunks, that can be still be free'd. 498 if (Header.AllocType != FromMemalign || Type != FromMalloc) 499 dieWithMessage("allocation type mismatch when deallocating address " 500 "%p\n", Ptr); 501 } 502 } 503 const uptr Size = Chunk::getSize(Ptr, &Header); 504 if (DeleteSizeMismatch) { 505 if (DeleteSize && DeleteSize != Size) 506 dieWithMessage("invalid sized delete when deallocating address %p\n", 507 Ptr); 508 } 509 quarantineOrDeallocateChunk(Ptr, &Header, Size); 510 } 511 512 // Reallocates a chunk. We can save on a new allocation if the new requested 513 // size still fits in the chunk. 514 void *reallocate(void *OldPtr, uptr NewSize) { 515 initThreadMaybe(); 516 if (UNLIKELY(!Chunk::isAligned(OldPtr))) 517 dieWithMessage("misaligned address when reallocating address %p\n", 518 OldPtr); 519 UnpackedHeader OldHeader; 520 Chunk::loadHeader(OldPtr, &OldHeader); 521 if (UNLIKELY(OldHeader.State != ChunkAllocated)) 522 dieWithMessage("invalid chunk state when reallocating address %p\n", 523 OldPtr); 524 if (DeallocationTypeMismatch) { 525 if (UNLIKELY(OldHeader.AllocType != FromMalloc)) 526 dieWithMessage("allocation type mismatch when reallocating address " 527 "%p\n", OldPtr); 528 } 529 const uptr UsableSize = Chunk::getUsableSize(OldPtr, &OldHeader); 530 // The new size still fits in the current chunk, and the size difference 531 // is reasonable. 532 if (NewSize <= UsableSize && 533 (UsableSize - NewSize) < (SizeClassMap::kMaxSize / 2)) { 534 UnpackedHeader NewHeader = OldHeader; 535 NewHeader.SizeOrUnusedBytes = 536 OldHeader.ClassId ? NewSize : UsableSize - NewSize; 537 Chunk::compareExchangeHeader(OldPtr, &NewHeader, &OldHeader); 538 return OldPtr; 539 } 540 // Otherwise, we have to allocate a new chunk and copy the contents of the 541 // old one. 542 void *NewPtr = allocate(NewSize, MinAlignment, FromMalloc); 543 if (NewPtr) { 544 const uptr OldSize = OldHeader.ClassId ? OldHeader.SizeOrUnusedBytes : 545 UsableSize - OldHeader.SizeOrUnusedBytes; 546 memcpy(NewPtr, OldPtr, Min(NewSize, UsableSize)); 547 quarantineOrDeallocateChunk(OldPtr, &OldHeader, OldSize); 548 } 549 return NewPtr; 550 } 551 552 // Helper function that returns the actual usable size of a chunk. 553 uptr getUsableSize(const void *Ptr) { 554 initThreadMaybe(); 555 if (UNLIKELY(!Ptr)) 556 return 0; 557 UnpackedHeader Header; 558 Chunk::loadHeader(Ptr, &Header); 559 // Getting the usable size of a chunk only makes sense if it's allocated. 560 if (UNLIKELY(Header.State != ChunkAllocated)) 561 dieWithMessage("invalid chunk state when sizing address %p\n", Ptr); 562 return Chunk::getUsableSize(Ptr, &Header); 563 } 564 565 void *calloc(uptr NMemB, uptr Size) { 566 initThreadMaybe(); 567 if (UNLIKELY(CheckForCallocOverflow(NMemB, Size))) 568 return FailureHandler::OnBadRequest(); 569 return allocate(NMemB * Size, MinAlignment, FromMalloc, true); 570 } 571 572 void commitBack(ScudoTSD *TSD) { 573 AllocatorQuarantine.Drain(getQuarantineCache(TSD), 574 QuarantineCallback(&TSD->Cache)); 575 BackendAllocator.destroyCache(&TSD->Cache); 576 } 577 578 uptr getStats(AllocatorStat StatType) { 579 initThreadMaybe(); 580 uptr stats[AllocatorStatCount]; 581 BackendAllocator.getStats(stats); 582 return stats[StatType]; 583 } 584 585 void *handleBadRequest() { 586 initThreadMaybe(); 587 return FailureHandler::OnBadRequest(); 588 } 589 590 void setRssLimit(uptr LimitMb, bool HardLimit) { 591 if (HardLimit) 592 HardRssLimitMb = LimitMb; 593 else 594 SoftRssLimitMb = LimitMb; 595 CheckRssLimit = HardRssLimitMb || SoftRssLimitMb; 596 } 597 598 void printStats() { 599 initThreadMaybe(); 600 BackendAllocator.printStats(); 601 } 602 }; 603 604 static ScudoAllocator Instance(LINKER_INITIALIZED); 605 606 static ScudoBackendAllocator &getBackendAllocator() { 607 return Instance.BackendAllocator; 608 } 609 610 void initScudo() { 611 Instance.init(); 612 } 613 614 void ScudoTSD::init(bool Shared) { 615 UnlockRequired = Shared; 616 getBackendAllocator().initCache(&Cache); 617 memset(QuarantineCachePlaceHolder, 0, sizeof(QuarantineCachePlaceHolder)); 618 } 619 620 void ScudoTSD::commitBack() { 621 Instance.commitBack(this); 622 } 623 624 void *scudoMalloc(uptr Size, AllocType Type) { 625 return SetErrnoOnNull(Instance.allocate(Size, MinAlignment, Type)); 626 } 627 628 void scudoFree(void *Ptr, AllocType Type) { 629 Instance.deallocate(Ptr, 0, Type); 630 } 631 632 void scudoSizedFree(void *Ptr, uptr Size, AllocType Type) { 633 Instance.deallocate(Ptr, Size, Type); 634 } 635 636 void *scudoRealloc(void *Ptr, uptr Size) { 637 if (!Ptr) 638 return SetErrnoOnNull(Instance.allocate(Size, MinAlignment, FromMalloc)); 639 if (Size == 0) { 640 Instance.deallocate(Ptr, 0, FromMalloc); 641 return nullptr; 642 } 643 return SetErrnoOnNull(Instance.reallocate(Ptr, Size)); 644 } 645 646 void *scudoCalloc(uptr NMemB, uptr Size) { 647 return SetErrnoOnNull(Instance.calloc(NMemB, Size)); 648 } 649 650 void *scudoValloc(uptr Size) { 651 return SetErrnoOnNull( 652 Instance.allocate(Size, GetPageSizeCached(), FromMemalign)); 653 } 654 655 void *scudoPvalloc(uptr Size) { 656 uptr PageSize = GetPageSizeCached(); 657 if (UNLIKELY(CheckForPvallocOverflow(Size, PageSize))) { 658 errno = ENOMEM; 659 return Instance.handleBadRequest(); 660 } 661 // pvalloc(0) should allocate one page. 662 Size = Size ? RoundUpTo(Size, PageSize) : PageSize; 663 return SetErrnoOnNull(Instance.allocate(Size, PageSize, FromMemalign)); 664 } 665 666 void *scudoMemalign(uptr Alignment, uptr Size) { 667 if (UNLIKELY(!IsPowerOfTwo(Alignment))) { 668 errno = EINVAL; 669 return Instance.handleBadRequest(); 670 } 671 return SetErrnoOnNull(Instance.allocate(Size, Alignment, FromMemalign)); 672 } 673 674 int scudoPosixMemalign(void **MemPtr, uptr Alignment, uptr Size) { 675 if (UNLIKELY(!CheckPosixMemalignAlignment(Alignment))) { 676 Instance.handleBadRequest(); 677 return EINVAL; 678 } 679 void *Ptr = Instance.allocate(Size, Alignment, FromMemalign); 680 if (UNLIKELY(!Ptr)) 681 return ENOMEM; 682 *MemPtr = Ptr; 683 return 0; 684 } 685 686 void *scudoAlignedAlloc(uptr Alignment, uptr Size) { 687 if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(Alignment, Size))) { 688 errno = EINVAL; 689 return Instance.handleBadRequest(); 690 } 691 return SetErrnoOnNull(Instance.allocate(Size, Alignment, FromMalloc)); 692 } 693 694 uptr scudoMallocUsableSize(void *Ptr) { 695 return Instance.getUsableSize(Ptr); 696 } 697 698 } // namespace __scudo 699 700 using namespace __scudo; 701 702 // MallocExtension helper functions 703 704 uptr __sanitizer_get_current_allocated_bytes() { 705 return Instance.getStats(AllocatorStatAllocated); 706 } 707 708 uptr __sanitizer_get_heap_size() { 709 return Instance.getStats(AllocatorStatMapped); 710 } 711 712 uptr __sanitizer_get_free_bytes() { 713 return 1; 714 } 715 716 uptr __sanitizer_get_unmapped_bytes() { 717 return 1; 718 } 719 720 uptr __sanitizer_get_estimated_allocated_size(uptr Size) { 721 return Size; 722 } 723 724 int __sanitizer_get_ownership(const void *Ptr) { 725 return Instance.isValidPointer(Ptr); 726 } 727 728 uptr __sanitizer_get_allocated_size(const void *Ptr) { 729 return Instance.getUsableSize(Ptr); 730 } 731 732 #if !SANITIZER_SUPPORTS_WEAK_HOOKS 733 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_malloc_hook, 734 void *Ptr, uptr Size) { 735 (void)Ptr; 736 (void)Size; 737 } 738 739 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_free_hook, void *Ptr) { 740 (void)Ptr; 741 } 742 #endif 743 744 // Interface functions 745 746 void __scudo_set_rss_limit(uptr LimitMb, s32 HardLimit) { 747 if (!SCUDO_CAN_USE_PUBLIC_INTERFACE) 748 return; 749 Instance.setRssLimit(LimitMb, !!HardLimit); 750 } 751 752 void __scudo_print_stats() { 753 Instance.printStats(); 754 } 755