scudo_allocator.cpp 30 KB

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