combined.h 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440
  1. //===-- combined.h ----------------------------------------------*- 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. #ifndef SCUDO_COMBINED_H_
  9. #define SCUDO_COMBINED_H_
  10. #include "chunk.h"
  11. #include "common.h"
  12. #include "flags.h"
  13. #include "flags_parser.h"
  14. #include "local_cache.h"
  15. #include "memtag.h"
  16. #include "options.h"
  17. #include "quarantine.h"
  18. #include "report.h"
  19. #include "secondary.h"
  20. #include "stack_depot.h"
  21. #include "string_utils.h"
  22. #include "tsd.h"
  23. #include "scudo/interface.h"
  24. #ifdef GWP_ASAN_HOOKS
  25. #include "gwp_asan/guarded_pool_allocator.h"
  26. #include "gwp_asan/optional/backtrace.h"
  27. #include "gwp_asan/optional/segv_handler.h"
  28. #endif // GWP_ASAN_HOOKS
  29. extern "C" inline void EmptyCallback() {}
  30. #ifdef HAVE_ANDROID_UNSAFE_FRAME_POINTER_CHASE
  31. // This function is not part of the NDK so it does not appear in any public
  32. // header files. We only declare/use it when targeting the platform.
  33. extern "C" size_t android_unsafe_frame_pointer_chase(scudo::uptr *buf,
  34. size_t num_entries);
  35. #endif
  36. namespace scudo {
  37. template <class Params, void (*PostInitCallback)(void) = EmptyCallback>
  38. class Allocator {
  39. public:
  40. using PrimaryT = typename Params::Primary;
  41. using CacheT = typename PrimaryT::CacheT;
  42. typedef Allocator<Params, PostInitCallback> ThisT;
  43. typedef typename Params::template TSDRegistryT<ThisT> TSDRegistryT;
  44. void callPostInitCallback() {
  45. pthread_once(&PostInitNonce, PostInitCallback);
  46. }
  47. struct QuarantineCallback {
  48. explicit QuarantineCallback(ThisT &Instance, CacheT &LocalCache)
  49. : Allocator(Instance), Cache(LocalCache) {}
  50. // Chunk recycling function, returns a quarantined chunk to the backend,
  51. // first making sure it hasn't been tampered with.
  52. void recycle(void *Ptr) {
  53. Chunk::UnpackedHeader Header;
  54. Chunk::loadHeader(Allocator.Cookie, Ptr, &Header);
  55. if (UNLIKELY(Header.State != Chunk::State::Quarantined))
  56. reportInvalidChunkState(AllocatorAction::Recycling, Ptr);
  57. Chunk::UnpackedHeader NewHeader = Header;
  58. NewHeader.State = Chunk::State::Available;
  59. Chunk::compareExchangeHeader(Allocator.Cookie, Ptr, &NewHeader, &Header);
  60. if (allocatorSupportsMemoryTagging<Params>())
  61. Ptr = untagPointer(Ptr);
  62. void *BlockBegin = Allocator::getBlockBegin(Ptr, &NewHeader);
  63. Cache.deallocate(NewHeader.ClassId, BlockBegin);
  64. }
  65. // We take a shortcut when allocating a quarantine batch by working with the
  66. // appropriate class ID instead of using Size. The compiler should optimize
  67. // the class ID computation and work with the associated cache directly.
  68. void *allocate(UNUSED uptr Size) {
  69. const uptr QuarantineClassId = SizeClassMap::getClassIdBySize(
  70. sizeof(QuarantineBatch) + Chunk::getHeaderSize());
  71. void *Ptr = Cache.allocate(QuarantineClassId);
  72. // Quarantine batch allocation failure is fatal.
  73. if (UNLIKELY(!Ptr))
  74. reportOutOfMemory(SizeClassMap::getSizeByClassId(QuarantineClassId));
  75. Ptr = reinterpret_cast<void *>(reinterpret_cast<uptr>(Ptr) +
  76. Chunk::getHeaderSize());
  77. Chunk::UnpackedHeader Header = {};
  78. Header.ClassId = QuarantineClassId & Chunk::ClassIdMask;
  79. Header.SizeOrUnusedBytes = sizeof(QuarantineBatch);
  80. Header.State = Chunk::State::Allocated;
  81. Chunk::storeHeader(Allocator.Cookie, Ptr, &Header);
  82. // Reset tag to 0 as this chunk may have been previously used for a tagged
  83. // user allocation.
  84. if (UNLIKELY(useMemoryTagging<Params>(Allocator.Primary.Options.load())))
  85. storeTags(reinterpret_cast<uptr>(Ptr),
  86. reinterpret_cast<uptr>(Ptr) + sizeof(QuarantineBatch));
  87. return Ptr;
  88. }
  89. void deallocate(void *Ptr) {
  90. const uptr QuarantineClassId = SizeClassMap::getClassIdBySize(
  91. sizeof(QuarantineBatch) + Chunk::getHeaderSize());
  92. Chunk::UnpackedHeader Header;
  93. Chunk::loadHeader(Allocator.Cookie, Ptr, &Header);
  94. if (UNLIKELY(Header.State != Chunk::State::Allocated))
  95. reportInvalidChunkState(AllocatorAction::Deallocating, Ptr);
  96. DCHECK_EQ(Header.ClassId, QuarantineClassId);
  97. DCHECK_EQ(Header.Offset, 0);
  98. DCHECK_EQ(Header.SizeOrUnusedBytes, sizeof(QuarantineBatch));
  99. Chunk::UnpackedHeader NewHeader = Header;
  100. NewHeader.State = Chunk::State::Available;
  101. Chunk::compareExchangeHeader(Allocator.Cookie, Ptr, &NewHeader, &Header);
  102. Cache.deallocate(QuarantineClassId,
  103. reinterpret_cast<void *>(reinterpret_cast<uptr>(Ptr) -
  104. Chunk::getHeaderSize()));
  105. }
  106. private:
  107. ThisT &Allocator;
  108. CacheT &Cache;
  109. };
  110. typedef GlobalQuarantine<QuarantineCallback, void> QuarantineT;
  111. typedef typename QuarantineT::CacheT QuarantineCacheT;
  112. void init() {
  113. performSanityChecks();
  114. // Check if hardware CRC32 is supported in the binary and by the platform,
  115. // if so, opt for the CRC32 hardware version of the checksum.
  116. if (&computeHardwareCRC32 && hasHardwareCRC32())
  117. HashAlgorithm = Checksum::HardwareCRC32;
  118. if (UNLIKELY(!getRandom(&Cookie, sizeof(Cookie))))
  119. Cookie = static_cast<u32>(getMonotonicTime() ^
  120. (reinterpret_cast<uptr>(this) >> 4));
  121. initFlags();
  122. reportUnrecognizedFlags();
  123. // Store some flags locally.
  124. if (getFlags()->may_return_null)
  125. Primary.Options.set(OptionBit::MayReturnNull);
  126. if (getFlags()->zero_contents)
  127. Primary.Options.setFillContentsMode(ZeroFill);
  128. else if (getFlags()->pattern_fill_contents)
  129. Primary.Options.setFillContentsMode(PatternOrZeroFill);
  130. if (getFlags()->dealloc_type_mismatch)
  131. Primary.Options.set(OptionBit::DeallocTypeMismatch);
  132. if (getFlags()->delete_size_mismatch)
  133. Primary.Options.set(OptionBit::DeleteSizeMismatch);
  134. if (allocatorSupportsMemoryTagging<Params>() &&
  135. systemSupportsMemoryTagging())
  136. Primary.Options.set(OptionBit::UseMemoryTagging);
  137. Primary.Options.set(OptionBit::UseOddEvenTags);
  138. QuarantineMaxChunkSize =
  139. static_cast<u32>(getFlags()->quarantine_max_chunk_size);
  140. Stats.init();
  141. const s32 ReleaseToOsIntervalMs = getFlags()->release_to_os_interval_ms;
  142. Primary.init(ReleaseToOsIntervalMs);
  143. Secondary.init(&Stats, ReleaseToOsIntervalMs);
  144. Quarantine.init(
  145. static_cast<uptr>(getFlags()->quarantine_size_kb << 10),
  146. static_cast<uptr>(getFlags()->thread_local_quarantine_size_kb << 10));
  147. }
  148. // Initialize the embedded GWP-ASan instance. Requires the main allocator to
  149. // be functional, best called from PostInitCallback.
  150. void initGwpAsan() {
  151. #ifdef GWP_ASAN_HOOKS
  152. gwp_asan::options::Options Opt;
  153. Opt.Enabled = getFlags()->GWP_ASAN_Enabled;
  154. Opt.MaxSimultaneousAllocations =
  155. getFlags()->GWP_ASAN_MaxSimultaneousAllocations;
  156. Opt.SampleRate = getFlags()->GWP_ASAN_SampleRate;
  157. Opt.InstallSignalHandlers = getFlags()->GWP_ASAN_InstallSignalHandlers;
  158. // Embedded GWP-ASan is locked through the Scudo atfork handler (via
  159. // Allocator::disable calling GWPASan.disable). Disable GWP-ASan's atfork
  160. // handler.
  161. Opt.InstallForkHandlers = false;
  162. Opt.Backtrace = gwp_asan::backtrace::getBacktraceFunction();
  163. GuardedAlloc.init(Opt);
  164. if (Opt.InstallSignalHandlers)
  165. gwp_asan::segv_handler::installSignalHandlers(
  166. &GuardedAlloc, Printf,
  167. gwp_asan::backtrace::getPrintBacktraceFunction(),
  168. gwp_asan::backtrace::getSegvBacktraceFunction());
  169. GuardedAllocSlotSize =
  170. GuardedAlloc.getAllocatorState()->maximumAllocationSize();
  171. Stats.add(StatFree, static_cast<uptr>(Opt.MaxSimultaneousAllocations) *
  172. GuardedAllocSlotSize);
  173. #endif // GWP_ASAN_HOOKS
  174. }
  175. #ifdef GWP_ASAN_HOOKS
  176. const gwp_asan::AllocationMetadata *getGwpAsanAllocationMetadata() {
  177. return GuardedAlloc.getMetadataRegion();
  178. }
  179. const gwp_asan::AllocatorState *getGwpAsanAllocatorState() {
  180. return GuardedAlloc.getAllocatorState();
  181. }
  182. #endif // GWP_ASAN_HOOKS
  183. ALWAYS_INLINE void initThreadMaybe(bool MinimalInit = false) {
  184. TSDRegistry.initThreadMaybe(this, MinimalInit);
  185. }
  186. void unmapTestOnly() {
  187. TSDRegistry.unmapTestOnly(this);
  188. Primary.unmapTestOnly();
  189. Secondary.unmapTestOnly();
  190. #ifdef GWP_ASAN_HOOKS
  191. if (getFlags()->GWP_ASAN_InstallSignalHandlers)
  192. gwp_asan::segv_handler::uninstallSignalHandlers();
  193. GuardedAlloc.uninitTestOnly();
  194. #endif // GWP_ASAN_HOOKS
  195. }
  196. TSDRegistryT *getTSDRegistry() { return &TSDRegistry; }
  197. // The Cache must be provided zero-initialized.
  198. void initCache(CacheT *Cache) { Cache->init(&Stats, &Primary); }
  199. // Release the resources used by a TSD, which involves:
  200. // - draining the local quarantine cache to the global quarantine;
  201. // - releasing the cached pointers back to the Primary;
  202. // - unlinking the local stats from the global ones (destroying the cache does
  203. // the last two items).
  204. void commitBack(TSD<ThisT> *TSD) {
  205. Quarantine.drain(&TSD->QuarantineCache,
  206. QuarantineCallback(*this, TSD->Cache));
  207. TSD->Cache.destroy(&Stats);
  208. }
  209. ALWAYS_INLINE void *getHeaderTaggedPointer(void *Ptr) {
  210. if (!allocatorSupportsMemoryTagging<Params>())
  211. return Ptr;
  212. auto UntaggedPtr = untagPointer(Ptr);
  213. if (UntaggedPtr != Ptr)
  214. return UntaggedPtr;
  215. // Secondary, or pointer allocated while memory tagging is unsupported or
  216. // disabled. The tag mismatch is okay in the latter case because tags will
  217. // not be checked.
  218. return addHeaderTag(Ptr);
  219. }
  220. ALWAYS_INLINE uptr addHeaderTag(uptr Ptr) {
  221. if (!allocatorSupportsMemoryTagging<Params>())
  222. return Ptr;
  223. return addFixedTag(Ptr, 2);
  224. }
  225. ALWAYS_INLINE void *addHeaderTag(void *Ptr) {
  226. return reinterpret_cast<void *>(addHeaderTag(reinterpret_cast<uptr>(Ptr)));
  227. }
  228. NOINLINE u32 collectStackTrace() {
  229. #ifdef HAVE_ANDROID_UNSAFE_FRAME_POINTER_CHASE
  230. // Discard collectStackTrace() frame and allocator function frame.
  231. constexpr uptr DiscardFrames = 2;
  232. uptr Stack[MaxTraceSize + DiscardFrames];
  233. uptr Size =
  234. android_unsafe_frame_pointer_chase(Stack, MaxTraceSize + DiscardFrames);
  235. Size = Min<uptr>(Size, MaxTraceSize + DiscardFrames);
  236. return Depot.insert(Stack + Min<uptr>(DiscardFrames, Size), Stack + Size);
  237. #else
  238. return 0;
  239. #endif
  240. }
  241. uptr computeOddEvenMaskForPointerMaybe(Options Options, uptr Ptr,
  242. uptr ClassId) {
  243. if (!Options.get(OptionBit::UseOddEvenTags))
  244. return 0;
  245. // If a chunk's tag is odd, we want the tags of the surrounding blocks to be
  246. // even, and vice versa. Blocks are laid out Size bytes apart, and adding
  247. // Size to Ptr will flip the least significant set bit of Size in Ptr, so
  248. // that bit will have the pattern 010101... for consecutive blocks, which we
  249. // can use to determine which tag mask to use.
  250. return 0x5555U << ((Ptr >> SizeClassMap::getSizeLSBByClassId(ClassId)) & 1);
  251. }
  252. NOINLINE void *allocate(uptr Size, Chunk::Origin Origin,
  253. uptr Alignment = MinAlignment,
  254. bool ZeroContents = false) {
  255. initThreadMaybe();
  256. const Options Options = Primary.Options.load();
  257. if (UNLIKELY(Alignment > MaxAlignment)) {
  258. if (Options.get(OptionBit::MayReturnNull))
  259. return nullptr;
  260. reportAlignmentTooBig(Alignment, MaxAlignment);
  261. }
  262. if (Alignment < MinAlignment)
  263. Alignment = MinAlignment;
  264. #ifdef GWP_ASAN_HOOKS
  265. if (UNLIKELY(GuardedAlloc.shouldSample())) {
  266. if (void *Ptr = GuardedAlloc.allocate(Size, Alignment)) {
  267. if (UNLIKELY(&__scudo_allocate_hook))
  268. __scudo_allocate_hook(Ptr, Size);
  269. Stats.lock();
  270. Stats.add(StatAllocated, GuardedAllocSlotSize);
  271. Stats.sub(StatFree, GuardedAllocSlotSize);
  272. Stats.unlock();
  273. return Ptr;
  274. }
  275. }
  276. #endif // GWP_ASAN_HOOKS
  277. const FillContentsMode FillContents = ZeroContents ? ZeroFill
  278. : TSDRegistry.getDisableMemInit()
  279. ? NoFill
  280. : Options.getFillContentsMode();
  281. // If the requested size happens to be 0 (more common than you might think),
  282. // allocate MinAlignment bytes on top of the header. Then add the extra
  283. // bytes required to fulfill the alignment requirements: we allocate enough
  284. // to be sure that there will be an address in the block that will satisfy
  285. // the alignment.
  286. const uptr NeededSize =
  287. roundUpTo(Size, MinAlignment) +
  288. ((Alignment > MinAlignment) ? Alignment : Chunk::getHeaderSize());
  289. // Takes care of extravagantly large sizes as well as integer overflows.
  290. static_assert(MaxAllowedMallocSize < UINTPTR_MAX - MaxAlignment, "");
  291. if (UNLIKELY(Size >= MaxAllowedMallocSize)) {
  292. if (Options.get(OptionBit::MayReturnNull))
  293. return nullptr;
  294. reportAllocationSizeTooBig(Size, NeededSize, MaxAllowedMallocSize);
  295. }
  296. DCHECK_LE(Size, NeededSize);
  297. void *Block = nullptr;
  298. uptr ClassId = 0;
  299. uptr SecondaryBlockEnd = 0;
  300. if (LIKELY(PrimaryT::canAllocate(NeededSize))) {
  301. ClassId = SizeClassMap::getClassIdBySize(NeededSize);
  302. DCHECK_NE(ClassId, 0U);
  303. bool UnlockRequired;
  304. auto *TSD = TSDRegistry.getTSDAndLock(&UnlockRequired);
  305. Block = TSD->Cache.allocate(ClassId);
  306. // If the allocation failed, the most likely reason with a 32-bit primary
  307. // is the region being full. In that event, retry in each successively
  308. // larger class until it fits. If it fails to fit in the largest class,
  309. // fallback to the Secondary.
  310. if (UNLIKELY(!Block)) {
  311. while (ClassId < SizeClassMap::LargestClassId && !Block)
  312. Block = TSD->Cache.allocate(++ClassId);
  313. if (!Block)
  314. ClassId = 0;
  315. }
  316. if (UnlockRequired)
  317. TSD->unlock();
  318. }
  319. if (UNLIKELY(ClassId == 0))
  320. Block = Secondary.allocate(Options, Size, Alignment, &SecondaryBlockEnd,
  321. FillContents);
  322. if (UNLIKELY(!Block)) {
  323. if (Options.get(OptionBit::MayReturnNull))
  324. return nullptr;
  325. reportOutOfMemory(NeededSize);
  326. }
  327. const uptr BlockUptr = reinterpret_cast<uptr>(Block);
  328. const uptr UnalignedUserPtr = BlockUptr + Chunk::getHeaderSize();
  329. const uptr UserPtr = roundUpTo(UnalignedUserPtr, Alignment);
  330. void *Ptr = reinterpret_cast<void *>(UserPtr);
  331. void *TaggedPtr = Ptr;
  332. if (LIKELY(ClassId)) {
  333. // We only need to zero or tag the contents for Primary backed
  334. // allocations. We only set tags for primary allocations in order to avoid
  335. // faulting potentially large numbers of pages for large secondary
  336. // allocations. We assume that guard pages are enough to protect these
  337. // allocations.
  338. //
  339. // FIXME: When the kernel provides a way to set the background tag of a
  340. // mapping, we should be able to tag secondary allocations as well.
  341. //
  342. // When memory tagging is enabled, zeroing the contents is done as part of
  343. // setting the tag.
  344. if (UNLIKELY(useMemoryTagging<Params>(Options))) {
  345. uptr PrevUserPtr;
  346. Chunk::UnpackedHeader Header;
  347. const uptr BlockSize = PrimaryT::getSizeByClassId(ClassId);
  348. const uptr BlockEnd = BlockUptr + BlockSize;
  349. // If possible, try to reuse the UAF tag that was set by deallocate().
  350. // For simplicity, only reuse tags if we have the same start address as
  351. // the previous allocation. This handles the majority of cases since
  352. // most allocations will not be more aligned than the minimum alignment.
  353. //
  354. // We need to handle situations involving reclaimed chunks, and retag
  355. // the reclaimed portions if necessary. In the case where the chunk is
  356. // fully reclaimed, the chunk's header will be zero, which will trigger
  357. // the code path for new mappings and invalid chunks that prepares the
  358. // chunk from scratch. There are three possibilities for partial
  359. // reclaiming:
  360. //
  361. // (1) Header was reclaimed, data was partially reclaimed.
  362. // (2) Header was not reclaimed, all data was reclaimed (e.g. because
  363. // data started on a page boundary).
  364. // (3) Header was not reclaimed, data was partially reclaimed.
  365. //
  366. // Case (1) will be handled in the same way as for full reclaiming,
  367. // since the header will be zero.
  368. //
  369. // We can detect case (2) by loading the tag from the start
  370. // of the chunk. If it is zero, it means that either all data was
  371. // reclaimed (since we never use zero as the chunk tag), or that the
  372. // previous allocation was of size zero. Either way, we need to prepare
  373. // a new chunk from scratch.
  374. //
  375. // We can detect case (3) by moving to the next page (if covered by the
  376. // chunk) and loading the tag of its first granule. If it is zero, it
  377. // means that all following pages may need to be retagged. On the other
  378. // hand, if it is nonzero, we can assume that all following pages are
  379. // still tagged, according to the logic that if any of the pages
  380. // following the next page were reclaimed, the next page would have been
  381. // reclaimed as well.
  382. uptr TaggedUserPtr;
  383. if (getChunkFromBlock(BlockUptr, &PrevUserPtr, &Header) &&
  384. PrevUserPtr == UserPtr &&
  385. (TaggedUserPtr = loadTag(UserPtr)) != UserPtr) {
  386. uptr PrevEnd = TaggedUserPtr + Header.SizeOrUnusedBytes;
  387. const uptr NextPage = roundUpTo(TaggedUserPtr, getPageSizeCached());
  388. if (NextPage < PrevEnd && loadTag(NextPage) != NextPage)
  389. PrevEnd = NextPage;
  390. TaggedPtr = reinterpret_cast<void *>(TaggedUserPtr);
  391. resizeTaggedChunk(PrevEnd, TaggedUserPtr + Size, Size, BlockEnd);
  392. if (UNLIKELY(FillContents != NoFill && !Header.OriginOrWasZeroed)) {
  393. // If an allocation needs to be zeroed (i.e. calloc) we can normally
  394. // avoid zeroing the memory now since we can rely on memory having
  395. // been zeroed on free, as this is normally done while setting the
  396. // UAF tag. But if tagging was disabled per-thread when the memory
  397. // was freed, it would not have been retagged and thus zeroed, and
  398. // therefore it needs to be zeroed now.
  399. memset(TaggedPtr, 0,
  400. Min(Size, roundUpTo(PrevEnd - TaggedUserPtr,
  401. archMemoryTagGranuleSize())));
  402. } else if (Size) {
  403. // Clear any stack metadata that may have previously been stored in
  404. // the chunk data.
  405. memset(TaggedPtr, 0, archMemoryTagGranuleSize());
  406. }
  407. } else {
  408. const uptr OddEvenMask =
  409. computeOddEvenMaskForPointerMaybe(Options, BlockUptr, ClassId);
  410. TaggedPtr = prepareTaggedChunk(Ptr, Size, OddEvenMask, BlockEnd);
  411. }
  412. storePrimaryAllocationStackMaybe(Options, Ptr);
  413. } else {
  414. Block = addHeaderTag(Block);
  415. Ptr = addHeaderTag(Ptr);
  416. if (UNLIKELY(FillContents != NoFill)) {
  417. // This condition is not necessarily unlikely, but since memset is
  418. // costly, we might as well mark it as such.
  419. memset(Block, FillContents == ZeroFill ? 0 : PatternFillByte,
  420. PrimaryT::getSizeByClassId(ClassId));
  421. }
  422. }
  423. } else {
  424. Block = addHeaderTag(Block);
  425. Ptr = addHeaderTag(Ptr);
  426. if (UNLIKELY(useMemoryTagging<Params>(Options))) {
  427. storeTags(reinterpret_cast<uptr>(Block), reinterpret_cast<uptr>(Ptr));
  428. storeSecondaryAllocationStackMaybe(Options, Ptr, Size);
  429. }
  430. }
  431. Chunk::UnpackedHeader Header = {};
  432. if (UNLIKELY(UnalignedUserPtr != UserPtr)) {
  433. const uptr Offset = UserPtr - UnalignedUserPtr;
  434. DCHECK_GE(Offset, 2 * sizeof(u32));
  435. // The BlockMarker has no security purpose, but is specifically meant for
  436. // the chunk iteration function that can be used in debugging situations.
  437. // It is the only situation where we have to locate the start of a chunk
  438. // based on its block address.
  439. reinterpret_cast<u32 *>(Block)[0] = BlockMarker;
  440. reinterpret_cast<u32 *>(Block)[1] = static_cast<u32>(Offset);
  441. Header.Offset = (Offset >> MinAlignmentLog) & Chunk::OffsetMask;
  442. }
  443. Header.ClassId = ClassId & Chunk::ClassIdMask;
  444. Header.State = Chunk::State::Allocated;
  445. Header.OriginOrWasZeroed = Origin & Chunk::OriginMask;
  446. Header.SizeOrUnusedBytes =
  447. (ClassId ? Size : SecondaryBlockEnd - (UserPtr + Size)) &
  448. Chunk::SizeOrUnusedBytesMask;
  449. Chunk::storeHeader(Cookie, Ptr, &Header);
  450. if (UNLIKELY(&__scudo_allocate_hook))
  451. __scudo_allocate_hook(TaggedPtr, Size);
  452. return TaggedPtr;
  453. }
  454. NOINLINE void deallocate(void *Ptr, Chunk::Origin Origin, uptr DeleteSize = 0,
  455. UNUSED uptr Alignment = MinAlignment) {
  456. // For a deallocation, we only ensure minimal initialization, meaning thread
  457. // local data will be left uninitialized for now (when using ELF TLS). The
  458. // fallback cache will be used instead. This is a workaround for a situation
  459. // where the only heap operation performed in a thread would be a free past
  460. // the TLS destructors, ending up in initialized thread specific data never
  461. // being destroyed properly. Any other heap operation will do a full init.
  462. initThreadMaybe(/*MinimalInit=*/true);
  463. if (UNLIKELY(&__scudo_deallocate_hook))
  464. __scudo_deallocate_hook(Ptr);
  465. if (UNLIKELY(!Ptr))
  466. return;
  467. #ifdef GWP_ASAN_HOOKS
  468. if (UNLIKELY(GuardedAlloc.pointerIsMine(Ptr))) {
  469. GuardedAlloc.deallocate(Ptr);
  470. Stats.lock();
  471. Stats.add(StatFree, GuardedAllocSlotSize);
  472. Stats.sub(StatAllocated, GuardedAllocSlotSize);
  473. Stats.unlock();
  474. return;
  475. }
  476. #endif // GWP_ASAN_HOOKS
  477. if (UNLIKELY(!isAligned(reinterpret_cast<uptr>(Ptr), MinAlignment)))
  478. reportMisalignedPointer(AllocatorAction::Deallocating, Ptr);
  479. void *TaggedPtr = Ptr;
  480. Ptr = getHeaderTaggedPointer(Ptr);
  481. Chunk::UnpackedHeader Header;
  482. Chunk::loadHeader(Cookie, Ptr, &Header);
  483. if (UNLIKELY(Header.State != Chunk::State::Allocated))
  484. reportInvalidChunkState(AllocatorAction::Deallocating, Ptr);
  485. const Options Options = Primary.Options.load();
  486. if (Options.get(OptionBit::DeallocTypeMismatch)) {
  487. if (UNLIKELY(Header.OriginOrWasZeroed != Origin)) {
  488. // With the exception of memalign'd chunks, that can be still be free'd.
  489. if (Header.OriginOrWasZeroed != Chunk::Origin::Memalign ||
  490. Origin != Chunk::Origin::Malloc)
  491. reportDeallocTypeMismatch(AllocatorAction::Deallocating, Ptr,
  492. Header.OriginOrWasZeroed, Origin);
  493. }
  494. }
  495. const uptr Size = getSize(Ptr, &Header);
  496. if (DeleteSize && Options.get(OptionBit::DeleteSizeMismatch)) {
  497. if (UNLIKELY(DeleteSize != Size))
  498. reportDeleteSizeMismatch(Ptr, DeleteSize, Size);
  499. }
  500. quarantineOrDeallocateChunk(Options, TaggedPtr, &Header, Size);
  501. }
  502. void *reallocate(void *OldPtr, uptr NewSize, uptr Alignment = MinAlignment) {
  503. initThreadMaybe();
  504. const Options Options = Primary.Options.load();
  505. if (UNLIKELY(NewSize >= MaxAllowedMallocSize)) {
  506. if (Options.get(OptionBit::MayReturnNull))
  507. return nullptr;
  508. reportAllocationSizeTooBig(NewSize, 0, MaxAllowedMallocSize);
  509. }
  510. // The following cases are handled by the C wrappers.
  511. DCHECK_NE(OldPtr, nullptr);
  512. DCHECK_NE(NewSize, 0);
  513. #ifdef GWP_ASAN_HOOKS
  514. if (UNLIKELY(GuardedAlloc.pointerIsMine(OldPtr))) {
  515. uptr OldSize = GuardedAlloc.getSize(OldPtr);
  516. void *NewPtr = allocate(NewSize, Chunk::Origin::Malloc, Alignment);
  517. if (NewPtr)
  518. memcpy(NewPtr, OldPtr, (NewSize < OldSize) ? NewSize : OldSize);
  519. GuardedAlloc.deallocate(OldPtr);
  520. Stats.lock();
  521. Stats.add(StatFree, GuardedAllocSlotSize);
  522. Stats.sub(StatAllocated, GuardedAllocSlotSize);
  523. Stats.unlock();
  524. return NewPtr;
  525. }
  526. #endif // GWP_ASAN_HOOKS
  527. void *OldTaggedPtr = OldPtr;
  528. OldPtr = getHeaderTaggedPointer(OldPtr);
  529. if (UNLIKELY(!isAligned(reinterpret_cast<uptr>(OldPtr), MinAlignment)))
  530. reportMisalignedPointer(AllocatorAction::Reallocating, OldPtr);
  531. Chunk::UnpackedHeader OldHeader;
  532. Chunk::loadHeader(Cookie, OldPtr, &OldHeader);
  533. if (UNLIKELY(OldHeader.State != Chunk::State::Allocated))
  534. reportInvalidChunkState(AllocatorAction::Reallocating, OldPtr);
  535. // Pointer has to be allocated with a malloc-type function. Some
  536. // applications think that it is OK to realloc a memalign'ed pointer, which
  537. // will trigger this check. It really isn't.
  538. if (Options.get(OptionBit::DeallocTypeMismatch)) {
  539. if (UNLIKELY(OldHeader.OriginOrWasZeroed != Chunk::Origin::Malloc))
  540. reportDeallocTypeMismatch(AllocatorAction::Reallocating, OldPtr,
  541. OldHeader.OriginOrWasZeroed,
  542. Chunk::Origin::Malloc);
  543. }
  544. void *BlockBegin = getBlockBegin(OldTaggedPtr, &OldHeader);
  545. uptr BlockEnd;
  546. uptr OldSize;
  547. const uptr ClassId = OldHeader.ClassId;
  548. if (LIKELY(ClassId)) {
  549. BlockEnd = reinterpret_cast<uptr>(BlockBegin) +
  550. SizeClassMap::getSizeByClassId(ClassId);
  551. OldSize = OldHeader.SizeOrUnusedBytes;
  552. } else {
  553. BlockEnd = SecondaryT::getBlockEnd(BlockBegin);
  554. OldSize = BlockEnd - (reinterpret_cast<uptr>(OldTaggedPtr) +
  555. OldHeader.SizeOrUnusedBytes);
  556. }
  557. // If the new chunk still fits in the previously allocated block (with a
  558. // reasonable delta), we just keep the old block, and update the chunk
  559. // header to reflect the size change.
  560. if (reinterpret_cast<uptr>(OldTaggedPtr) + NewSize <= BlockEnd) {
  561. if (NewSize > OldSize || (OldSize - NewSize) < getPageSizeCached()) {
  562. Chunk::UnpackedHeader NewHeader = OldHeader;
  563. NewHeader.SizeOrUnusedBytes =
  564. (ClassId ? NewSize
  565. : BlockEnd -
  566. (reinterpret_cast<uptr>(OldTaggedPtr) + NewSize)) &
  567. Chunk::SizeOrUnusedBytesMask;
  568. Chunk::compareExchangeHeader(Cookie, OldPtr, &NewHeader, &OldHeader);
  569. if (UNLIKELY(useMemoryTagging<Params>(Options))) {
  570. if (ClassId) {
  571. resizeTaggedChunk(reinterpret_cast<uptr>(OldTaggedPtr) + OldSize,
  572. reinterpret_cast<uptr>(OldTaggedPtr) + NewSize,
  573. NewSize, untagPointer(BlockEnd));
  574. storePrimaryAllocationStackMaybe(Options, OldPtr);
  575. } else {
  576. storeSecondaryAllocationStackMaybe(Options, OldPtr, NewSize);
  577. }
  578. }
  579. return OldTaggedPtr;
  580. }
  581. }
  582. // Otherwise we allocate a new one, and deallocate the old one. Some
  583. // allocators will allocate an even larger chunk (by a fixed factor) to
  584. // allow for potential further in-place realloc. The gains of such a trick
  585. // are currently unclear.
  586. void *NewPtr = allocate(NewSize, Chunk::Origin::Malloc, Alignment);
  587. if (LIKELY(NewPtr)) {
  588. memcpy(NewPtr, OldTaggedPtr, Min(NewSize, OldSize));
  589. quarantineOrDeallocateChunk(Options, OldTaggedPtr, &OldHeader, OldSize);
  590. }
  591. return NewPtr;
  592. }
  593. // TODO(kostyak): disable() is currently best-effort. There are some small
  594. // windows of time when an allocation could still succeed after
  595. // this function finishes. We will revisit that later.
  596. void disable() {
  597. initThreadMaybe();
  598. #ifdef GWP_ASAN_HOOKS
  599. GuardedAlloc.disable();
  600. #endif
  601. TSDRegistry.disable();
  602. Stats.disable();
  603. Quarantine.disable();
  604. Primary.disable();
  605. Secondary.disable();
  606. }
  607. void enable() {
  608. initThreadMaybe();
  609. Secondary.enable();
  610. Primary.enable();
  611. Quarantine.enable();
  612. Stats.enable();
  613. TSDRegistry.enable();
  614. #ifdef GWP_ASAN_HOOKS
  615. GuardedAlloc.enable();
  616. #endif
  617. }
  618. // The function returns the amount of bytes required to store the statistics,
  619. // which might be larger than the amount of bytes provided. Note that the
  620. // statistics buffer is not necessarily constant between calls to this
  621. // function. This can be called with a null buffer or zero size for buffer
  622. // sizing purposes.
  623. uptr getStats(char *Buffer, uptr Size) {
  624. ScopedString Str;
  625. disable();
  626. const uptr Length = getStats(&Str) + 1;
  627. enable();
  628. if (Length < Size)
  629. Size = Length;
  630. if (Buffer && Size) {
  631. memcpy(Buffer, Str.data(), Size);
  632. Buffer[Size - 1] = '\0';
  633. }
  634. return Length;
  635. }
  636. void printStats() {
  637. ScopedString Str;
  638. disable();
  639. getStats(&Str);
  640. enable();
  641. Str.output();
  642. }
  643. void releaseToOS() {
  644. initThreadMaybe();
  645. Primary.releaseToOS();
  646. Secondary.releaseToOS();
  647. }
  648. // Iterate over all chunks and call a callback for all busy chunks located
  649. // within the provided memory range. Said callback must not use this allocator
  650. // or a deadlock can ensue. This fits Android's malloc_iterate() needs.
  651. void iterateOverChunks(uptr Base, uptr Size, iterate_callback Callback,
  652. void *Arg) {
  653. initThreadMaybe();
  654. if (archSupportsMemoryTagging())
  655. Base = untagPointer(Base);
  656. const uptr From = Base;
  657. const uptr To = Base + Size;
  658. bool MayHaveTaggedPrimary = allocatorSupportsMemoryTagging<Params>() &&
  659. systemSupportsMemoryTagging();
  660. auto Lambda = [this, From, To, MayHaveTaggedPrimary, Callback,
  661. Arg](uptr Block) {
  662. if (Block < From || Block >= To)
  663. return;
  664. uptr Chunk;
  665. Chunk::UnpackedHeader Header;
  666. if (MayHaveTaggedPrimary) {
  667. // A chunk header can either have a zero tag (tagged primary) or the
  668. // header tag (secondary, or untagged primary). We don't know which so
  669. // try both.
  670. ScopedDisableMemoryTagChecks x;
  671. if (!getChunkFromBlock(Block, &Chunk, &Header) &&
  672. !getChunkFromBlock(addHeaderTag(Block), &Chunk, &Header))
  673. return;
  674. } else {
  675. if (!getChunkFromBlock(addHeaderTag(Block), &Chunk, &Header))
  676. return;
  677. }
  678. if (Header.State == Chunk::State::Allocated) {
  679. uptr TaggedChunk = Chunk;
  680. if (allocatorSupportsMemoryTagging<Params>())
  681. TaggedChunk = untagPointer(TaggedChunk);
  682. if (useMemoryTagging<Params>(Primary.Options.load()))
  683. TaggedChunk = loadTag(Chunk);
  684. Callback(TaggedChunk, getSize(reinterpret_cast<void *>(Chunk), &Header),
  685. Arg);
  686. }
  687. };
  688. Primary.iterateOverBlocks(Lambda);
  689. Secondary.iterateOverBlocks(Lambda);
  690. #ifdef GWP_ASAN_HOOKS
  691. GuardedAlloc.iterate(reinterpret_cast<void *>(Base), Size, Callback, Arg);
  692. #endif
  693. }
  694. bool canReturnNull() {
  695. initThreadMaybe();
  696. return Primary.Options.load().get(OptionBit::MayReturnNull);
  697. }
  698. bool setOption(Option O, sptr Value) {
  699. initThreadMaybe();
  700. if (O == Option::MemtagTuning) {
  701. // Enabling odd/even tags involves a tradeoff between use-after-free
  702. // detection and buffer overflow detection. Odd/even tags make it more
  703. // likely for buffer overflows to be detected by increasing the size of
  704. // the guaranteed "red zone" around the allocation, but on the other hand
  705. // use-after-free is less likely to be detected because the tag space for
  706. // any particular chunk is cut in half. Therefore we use this tuning
  707. // setting to control whether odd/even tags are enabled.
  708. if (Value == M_MEMTAG_TUNING_BUFFER_OVERFLOW)
  709. Primary.Options.set(OptionBit::UseOddEvenTags);
  710. else if (Value == M_MEMTAG_TUNING_UAF)
  711. Primary.Options.clear(OptionBit::UseOddEvenTags);
  712. return true;
  713. } else {
  714. // We leave it to the various sub-components to decide whether or not they
  715. // want to handle the option, but we do not want to short-circuit
  716. // execution if one of the setOption was to return false.
  717. const bool PrimaryResult = Primary.setOption(O, Value);
  718. const bool SecondaryResult = Secondary.setOption(O, Value);
  719. const bool RegistryResult = TSDRegistry.setOption(O, Value);
  720. return PrimaryResult && SecondaryResult && RegistryResult;
  721. }
  722. return false;
  723. }
  724. // Return the usable size for a given chunk. Technically we lie, as we just
  725. // report the actual size of a chunk. This is done to counteract code actively
  726. // writing past the end of a chunk (like sqlite3) when the usable size allows
  727. // for it, which then forces realloc to copy the usable size of a chunk as
  728. // opposed to its actual size.
  729. uptr getUsableSize(const void *Ptr) {
  730. initThreadMaybe();
  731. if (UNLIKELY(!Ptr))
  732. return 0;
  733. #ifdef GWP_ASAN_HOOKS
  734. if (UNLIKELY(GuardedAlloc.pointerIsMine(Ptr)))
  735. return GuardedAlloc.getSize(Ptr);
  736. #endif // GWP_ASAN_HOOKS
  737. Ptr = getHeaderTaggedPointer(const_cast<void *>(Ptr));
  738. Chunk::UnpackedHeader Header;
  739. Chunk::loadHeader(Cookie, Ptr, &Header);
  740. // Getting the usable size of a chunk only makes sense if it's allocated.
  741. if (UNLIKELY(Header.State != Chunk::State::Allocated))
  742. reportInvalidChunkState(AllocatorAction::Sizing, const_cast<void *>(Ptr));
  743. return getSize(Ptr, &Header);
  744. }
  745. void getStats(StatCounters S) {
  746. initThreadMaybe();
  747. Stats.get(S);
  748. }
  749. // Returns true if the pointer provided was allocated by the current
  750. // allocator instance, which is compliant with tcmalloc's ownership concept.
  751. // A corrupted chunk will not be reported as owned, which is WAI.
  752. bool isOwned(const void *Ptr) {
  753. initThreadMaybe();
  754. #ifdef GWP_ASAN_HOOKS
  755. if (GuardedAlloc.pointerIsMine(Ptr))
  756. return true;
  757. #endif // GWP_ASAN_HOOKS
  758. if (!Ptr || !isAligned(reinterpret_cast<uptr>(Ptr), MinAlignment))
  759. return false;
  760. Ptr = getHeaderTaggedPointer(const_cast<void *>(Ptr));
  761. Chunk::UnpackedHeader Header;
  762. return Chunk::isValid(Cookie, Ptr, &Header) &&
  763. Header.State == Chunk::State::Allocated;
  764. }
  765. bool useMemoryTaggingTestOnly() const {
  766. return useMemoryTagging<Params>(Primary.Options.load());
  767. }
  768. void disableMemoryTagging() {
  769. // If we haven't been initialized yet, we need to initialize now in order to
  770. // prevent a future call to initThreadMaybe() from enabling memory tagging
  771. // based on feature detection. But don't call initThreadMaybe() because it
  772. // may end up calling the allocator (via pthread_atfork, via the post-init
  773. // callback), which may cause mappings to be created with memory tagging
  774. // enabled.
  775. TSDRegistry.initOnceMaybe(this);
  776. if (allocatorSupportsMemoryTagging<Params>()) {
  777. Secondary.disableMemoryTagging();
  778. Primary.Options.clear(OptionBit::UseMemoryTagging);
  779. }
  780. }
  781. void setTrackAllocationStacks(bool Track) {
  782. initThreadMaybe();
  783. if (Track)
  784. Primary.Options.set(OptionBit::TrackAllocationStacks);
  785. else
  786. Primary.Options.clear(OptionBit::TrackAllocationStacks);
  787. }
  788. void setFillContents(FillContentsMode FillContents) {
  789. initThreadMaybe();
  790. Primary.Options.setFillContentsMode(FillContents);
  791. }
  792. void setAddLargeAllocationSlack(bool AddSlack) {
  793. initThreadMaybe();
  794. if (AddSlack)
  795. Primary.Options.set(OptionBit::AddLargeAllocationSlack);
  796. else
  797. Primary.Options.clear(OptionBit::AddLargeAllocationSlack);
  798. }
  799. const char *getStackDepotAddress() const {
  800. return reinterpret_cast<const char *>(&Depot);
  801. }
  802. const char *getRegionInfoArrayAddress() const {
  803. return Primary.getRegionInfoArrayAddress();
  804. }
  805. static uptr getRegionInfoArraySize() {
  806. return PrimaryT::getRegionInfoArraySize();
  807. }
  808. const char *getRingBufferAddress() const {
  809. return reinterpret_cast<const char *>(&RingBuffer);
  810. }
  811. static uptr getRingBufferSize() { return sizeof(RingBuffer); }
  812. static const uptr MaxTraceSize = 64;
  813. static void collectTraceMaybe(const StackDepot *Depot,
  814. uintptr_t (&Trace)[MaxTraceSize], u32 Hash) {
  815. uptr RingPos, Size;
  816. if (!Depot->find(Hash, &RingPos, &Size))
  817. return;
  818. for (unsigned I = 0; I != Size && I != MaxTraceSize; ++I)
  819. Trace[I] = static_cast<uintptr_t>((*Depot)[RingPos + I]);
  820. }
  821. static void getErrorInfo(struct scudo_error_info *ErrorInfo,
  822. uintptr_t FaultAddr, const char *DepotPtr,
  823. const char *RegionInfoPtr, const char *RingBufferPtr,
  824. const char *Memory, const char *MemoryTags,
  825. uintptr_t MemoryAddr, size_t MemorySize) {
  826. *ErrorInfo = {};
  827. if (!allocatorSupportsMemoryTagging<Params>() ||
  828. MemoryAddr + MemorySize < MemoryAddr)
  829. return;
  830. auto *Depot = reinterpret_cast<const StackDepot *>(DepotPtr);
  831. size_t NextErrorReport = 0;
  832. // Check for OOB in the current block and the two surrounding blocks. Beyond
  833. // that, UAF is more likely.
  834. if (extractTag(FaultAddr) != 0)
  835. getInlineErrorInfo(ErrorInfo, NextErrorReport, FaultAddr, Depot,
  836. RegionInfoPtr, Memory, MemoryTags, MemoryAddr,
  837. MemorySize, 0, 2);
  838. // Check the ring buffer. For primary allocations this will only find UAF;
  839. // for secondary allocations we can find either UAF or OOB.
  840. getRingBufferErrorInfo(ErrorInfo, NextErrorReport, FaultAddr, Depot,
  841. RingBufferPtr);
  842. // Check for OOB in the 28 blocks surrounding the 3 we checked earlier.
  843. // Beyond that we are likely to hit false positives.
  844. if (extractTag(FaultAddr) != 0)
  845. getInlineErrorInfo(ErrorInfo, NextErrorReport, FaultAddr, Depot,
  846. RegionInfoPtr, Memory, MemoryTags, MemoryAddr,
  847. MemorySize, 2, 16);
  848. }
  849. private:
  850. using SecondaryT = MapAllocator<Params>;
  851. typedef typename PrimaryT::SizeClassMap SizeClassMap;
  852. static const uptr MinAlignmentLog = SCUDO_MIN_ALIGNMENT_LOG;
  853. static const uptr MaxAlignmentLog = 24U; // 16 MB seems reasonable.
  854. static const uptr MinAlignment = 1UL << MinAlignmentLog;
  855. static const uptr MaxAlignment = 1UL << MaxAlignmentLog;
  856. static const uptr MaxAllowedMallocSize =
  857. FIRST_32_SECOND_64(1UL << 31, 1ULL << 40);
  858. static_assert(MinAlignment >= sizeof(Chunk::PackedHeader),
  859. "Minimal alignment must at least cover a chunk header.");
  860. static_assert(!allocatorSupportsMemoryTagging<Params>() ||
  861. MinAlignment >= archMemoryTagGranuleSize(),
  862. "");
  863. static const u32 BlockMarker = 0x44554353U;
  864. // These are indexes into an "array" of 32-bit values that store information
  865. // inline with a chunk that is relevant to diagnosing memory tag faults, where
  866. // 0 corresponds to the address of the user memory. This means that only
  867. // negative indexes may be used. The smallest index that may be used is -2,
  868. // which corresponds to 8 bytes before the user memory, because the chunk
  869. // header size is 8 bytes and in allocators that support memory tagging the
  870. // minimum alignment is at least the tag granule size (16 on aarch64).
  871. static const sptr MemTagAllocationTraceIndex = -2;
  872. static const sptr MemTagAllocationTidIndex = -1;
  873. u32 Cookie = 0;
  874. u32 QuarantineMaxChunkSize = 0;
  875. GlobalStats Stats;
  876. PrimaryT Primary;
  877. SecondaryT Secondary;
  878. QuarantineT Quarantine;
  879. TSDRegistryT TSDRegistry;
  880. pthread_once_t PostInitNonce = PTHREAD_ONCE_INIT;
  881. #ifdef GWP_ASAN_HOOKS
  882. gwp_asan::GuardedPoolAllocator GuardedAlloc;
  883. uptr GuardedAllocSlotSize = 0;
  884. #endif // GWP_ASAN_HOOKS
  885. StackDepot Depot;
  886. struct AllocationRingBuffer {
  887. struct Entry {
  888. atomic_uptr Ptr;
  889. atomic_uptr AllocationSize;
  890. atomic_u32 AllocationTrace;
  891. atomic_u32 AllocationTid;
  892. atomic_u32 DeallocationTrace;
  893. atomic_u32 DeallocationTid;
  894. };
  895. atomic_uptr Pos;
  896. #ifdef SCUDO_FUZZ
  897. static const uptr NumEntries = 2;
  898. #else
  899. static const uptr NumEntries = 32768;
  900. #endif
  901. Entry Entries[NumEntries];
  902. };
  903. AllocationRingBuffer RingBuffer = {};
  904. // The following might get optimized out by the compiler.
  905. NOINLINE void performSanityChecks() {
  906. // Verify that the header offset field can hold the maximum offset. In the
  907. // case of the Secondary allocator, it takes care of alignment and the
  908. // offset will always be small. In the case of the Primary, the worst case
  909. // scenario happens in the last size class, when the backend allocation
  910. // would already be aligned on the requested alignment, which would happen
  911. // to be the maximum alignment that would fit in that size class. As a
  912. // result, the maximum offset will be at most the maximum alignment for the
  913. // last size class minus the header size, in multiples of MinAlignment.
  914. Chunk::UnpackedHeader Header = {};
  915. const uptr MaxPrimaryAlignment = 1UL << getMostSignificantSetBitIndex(
  916. SizeClassMap::MaxSize - MinAlignment);
  917. const uptr MaxOffset =
  918. (MaxPrimaryAlignment - Chunk::getHeaderSize()) >> MinAlignmentLog;
  919. Header.Offset = MaxOffset & Chunk::OffsetMask;
  920. if (UNLIKELY(Header.Offset != MaxOffset))
  921. reportSanityCheckError("offset");
  922. // Verify that we can fit the maximum size or amount of unused bytes in the
  923. // header. Given that the Secondary fits the allocation to a page, the worst
  924. // case scenario happens in the Primary. It will depend on the second to
  925. // last and last class sizes, as well as the dynamic base for the Primary.
  926. // The following is an over-approximation that works for our needs.
  927. const uptr MaxSizeOrUnusedBytes = SizeClassMap::MaxSize - 1;
  928. Header.SizeOrUnusedBytes = MaxSizeOrUnusedBytes;
  929. if (UNLIKELY(Header.SizeOrUnusedBytes != MaxSizeOrUnusedBytes))
  930. reportSanityCheckError("size (or unused bytes)");
  931. const uptr LargestClassId = SizeClassMap::LargestClassId;
  932. Header.ClassId = LargestClassId;
  933. if (UNLIKELY(Header.ClassId != LargestClassId))
  934. reportSanityCheckError("class ID");
  935. }
  936. static inline void *getBlockBegin(const void *Ptr,
  937. Chunk::UnpackedHeader *Header) {
  938. return reinterpret_cast<void *>(
  939. reinterpret_cast<uptr>(Ptr) - Chunk::getHeaderSize() -
  940. (static_cast<uptr>(Header->Offset) << MinAlignmentLog));
  941. }
  942. // Return the size of a chunk as requested during its allocation.
  943. inline uptr getSize(const void *Ptr, Chunk::UnpackedHeader *Header) {
  944. const uptr SizeOrUnusedBytes = Header->SizeOrUnusedBytes;
  945. if (LIKELY(Header->ClassId))
  946. return SizeOrUnusedBytes;
  947. if (allocatorSupportsMemoryTagging<Params>())
  948. Ptr = untagPointer(const_cast<void *>(Ptr));
  949. return SecondaryT::getBlockEnd(getBlockBegin(Ptr, Header)) -
  950. reinterpret_cast<uptr>(Ptr) - SizeOrUnusedBytes;
  951. }
  952. void quarantineOrDeallocateChunk(Options Options, void *TaggedPtr,
  953. Chunk::UnpackedHeader *Header, uptr Size) {
  954. void *Ptr = getHeaderTaggedPointer(TaggedPtr);
  955. Chunk::UnpackedHeader NewHeader = *Header;
  956. // If the quarantine is disabled, the actual size of a chunk is 0 or larger
  957. // than the maximum allowed, we return a chunk directly to the backend.
  958. // This purposefully underflows for Size == 0.
  959. const bool BypassQuarantine = !Quarantine.getCacheSize() ||
  960. ((Size - 1) >= QuarantineMaxChunkSize) ||
  961. !NewHeader.ClassId;
  962. if (BypassQuarantine)
  963. NewHeader.State = Chunk::State::Available;
  964. else
  965. NewHeader.State = Chunk::State::Quarantined;
  966. NewHeader.OriginOrWasZeroed = useMemoryTagging<Params>(Options) &&
  967. NewHeader.ClassId &&
  968. !TSDRegistry.getDisableMemInit();
  969. Chunk::compareExchangeHeader(Cookie, Ptr, &NewHeader, Header);
  970. if (UNLIKELY(useMemoryTagging<Params>(Options))) {
  971. u8 PrevTag = extractTag(reinterpret_cast<uptr>(TaggedPtr));
  972. storeDeallocationStackMaybe(Options, Ptr, PrevTag, Size);
  973. if (NewHeader.ClassId) {
  974. if (!TSDRegistry.getDisableMemInit()) {
  975. uptr TaggedBegin, TaggedEnd;
  976. const uptr OddEvenMask = computeOddEvenMaskForPointerMaybe(
  977. Options, reinterpret_cast<uptr>(getBlockBegin(Ptr, &NewHeader)),
  978. NewHeader.ClassId);
  979. // Exclude the previous tag so that immediate use after free is
  980. // detected 100% of the time.
  981. setRandomTag(Ptr, Size, OddEvenMask | (1UL << PrevTag), &TaggedBegin,
  982. &TaggedEnd);
  983. }
  984. }
  985. }
  986. if (BypassQuarantine) {
  987. if (allocatorSupportsMemoryTagging<Params>())
  988. Ptr = untagPointer(Ptr);
  989. void *BlockBegin = getBlockBegin(Ptr, &NewHeader);
  990. const uptr ClassId = NewHeader.ClassId;
  991. if (LIKELY(ClassId)) {
  992. bool UnlockRequired;
  993. auto *TSD = TSDRegistry.getTSDAndLock(&UnlockRequired);
  994. TSD->Cache.deallocate(ClassId, BlockBegin);
  995. if (UnlockRequired)
  996. TSD->unlock();
  997. } else {
  998. if (UNLIKELY(useMemoryTagging<Params>(Options)))
  999. storeTags(reinterpret_cast<uptr>(BlockBegin),
  1000. reinterpret_cast<uptr>(Ptr));
  1001. Secondary.deallocate(Options, BlockBegin);
  1002. }
  1003. } else {
  1004. bool UnlockRequired;
  1005. auto *TSD = TSDRegistry.getTSDAndLock(&UnlockRequired);
  1006. Quarantine.put(&TSD->QuarantineCache,
  1007. QuarantineCallback(*this, TSD->Cache), Ptr, Size);
  1008. if (UnlockRequired)
  1009. TSD->unlock();
  1010. }
  1011. }
  1012. bool getChunkFromBlock(uptr Block, uptr *Chunk,
  1013. Chunk::UnpackedHeader *Header) {
  1014. *Chunk =
  1015. Block + getChunkOffsetFromBlock(reinterpret_cast<const char *>(Block));
  1016. return Chunk::isValid(Cookie, reinterpret_cast<void *>(*Chunk), Header);
  1017. }
  1018. static uptr getChunkOffsetFromBlock(const char *Block) {
  1019. u32 Offset = 0;
  1020. if (reinterpret_cast<const u32 *>(Block)[0] == BlockMarker)
  1021. Offset = reinterpret_cast<const u32 *>(Block)[1];
  1022. return Offset + Chunk::getHeaderSize();
  1023. }
  1024. // Set the tag of the granule past the end of the allocation to 0, to catch
  1025. // linear overflows even if a previous larger allocation used the same block
  1026. // and tag. Only do this if the granule past the end is in our block, because
  1027. // this would otherwise lead to a SEGV if the allocation covers the entire
  1028. // block and our block is at the end of a mapping. The tag of the next block's
  1029. // header granule will be set to 0, so it will serve the purpose of catching
  1030. // linear overflows in this case.
  1031. //
  1032. // For allocations of size 0 we do not end up storing the address tag to the
  1033. // memory tag space, which getInlineErrorInfo() normally relies on to match
  1034. // address tags against chunks. To allow matching in this case we store the
  1035. // address tag in the first byte of the chunk.
  1036. void storeEndMarker(uptr End, uptr Size, uptr BlockEnd) {
  1037. DCHECK_EQ(BlockEnd, untagPointer(BlockEnd));
  1038. uptr UntaggedEnd = untagPointer(End);
  1039. if (UntaggedEnd != BlockEnd) {
  1040. storeTag(UntaggedEnd);
  1041. if (Size == 0)
  1042. *reinterpret_cast<u8 *>(UntaggedEnd) = extractTag(End);
  1043. }
  1044. }
  1045. void *prepareTaggedChunk(void *Ptr, uptr Size, uptr ExcludeMask,
  1046. uptr BlockEnd) {
  1047. // Prepare the granule before the chunk to store the chunk header by setting
  1048. // its tag to 0. Normally its tag will already be 0, but in the case where a
  1049. // chunk holding a low alignment allocation is reused for a higher alignment
  1050. // allocation, the chunk may already have a non-zero tag from the previous
  1051. // allocation.
  1052. storeTag(reinterpret_cast<uptr>(Ptr) - archMemoryTagGranuleSize());
  1053. uptr TaggedBegin, TaggedEnd;
  1054. setRandomTag(Ptr, Size, ExcludeMask, &TaggedBegin, &TaggedEnd);
  1055. storeEndMarker(TaggedEnd, Size, BlockEnd);
  1056. return reinterpret_cast<void *>(TaggedBegin);
  1057. }
  1058. void resizeTaggedChunk(uptr OldPtr, uptr NewPtr, uptr NewSize,
  1059. uptr BlockEnd) {
  1060. uptr RoundOldPtr = roundUpTo(OldPtr, archMemoryTagGranuleSize());
  1061. uptr RoundNewPtr;
  1062. if (RoundOldPtr >= NewPtr) {
  1063. // If the allocation is shrinking we just need to set the tag past the end
  1064. // of the allocation to 0. See explanation in storeEndMarker() above.
  1065. RoundNewPtr = roundUpTo(NewPtr, archMemoryTagGranuleSize());
  1066. } else {
  1067. // Set the memory tag of the region
  1068. // [RoundOldPtr, roundUpTo(NewPtr, archMemoryTagGranuleSize()))
  1069. // to the pointer tag stored in OldPtr.
  1070. RoundNewPtr = storeTags(RoundOldPtr, NewPtr);
  1071. }
  1072. storeEndMarker(RoundNewPtr, NewSize, BlockEnd);
  1073. }
  1074. void storePrimaryAllocationStackMaybe(Options Options, void *Ptr) {
  1075. if (!UNLIKELY(Options.get(OptionBit::TrackAllocationStacks)))
  1076. return;
  1077. auto *Ptr32 = reinterpret_cast<u32 *>(Ptr);
  1078. Ptr32[MemTagAllocationTraceIndex] = collectStackTrace();
  1079. Ptr32[MemTagAllocationTidIndex] = getThreadID();
  1080. }
  1081. void storeRingBufferEntry(void *Ptr, u32 AllocationTrace, u32 AllocationTid,
  1082. uptr AllocationSize, u32 DeallocationTrace,
  1083. u32 DeallocationTid) {
  1084. uptr Pos = atomic_fetch_add(&RingBuffer.Pos, 1, memory_order_relaxed);
  1085. typename AllocationRingBuffer::Entry *Entry =
  1086. &RingBuffer.Entries[Pos % AllocationRingBuffer::NumEntries];
  1087. // First invalidate our entry so that we don't attempt to interpret a
  1088. // partially written state in getSecondaryErrorInfo(). The fences below
  1089. // ensure that the compiler does not move the stores to Ptr in between the
  1090. // stores to the other fields.
  1091. atomic_store_relaxed(&Entry->Ptr, 0);
  1092. __atomic_signal_fence(__ATOMIC_SEQ_CST);
  1093. atomic_store_relaxed(&Entry->AllocationTrace, AllocationTrace);
  1094. atomic_store_relaxed(&Entry->AllocationTid, AllocationTid);
  1095. atomic_store_relaxed(&Entry->AllocationSize, AllocationSize);
  1096. atomic_store_relaxed(&Entry->DeallocationTrace, DeallocationTrace);
  1097. atomic_store_relaxed(&Entry->DeallocationTid, DeallocationTid);
  1098. __atomic_signal_fence(__ATOMIC_SEQ_CST);
  1099. atomic_store_relaxed(&Entry->Ptr, reinterpret_cast<uptr>(Ptr));
  1100. }
  1101. void storeSecondaryAllocationStackMaybe(Options Options, void *Ptr,
  1102. uptr Size) {
  1103. if (!UNLIKELY(Options.get(OptionBit::TrackAllocationStacks)))
  1104. return;
  1105. u32 Trace = collectStackTrace();
  1106. u32 Tid = getThreadID();
  1107. auto *Ptr32 = reinterpret_cast<u32 *>(Ptr);
  1108. Ptr32[MemTagAllocationTraceIndex] = Trace;
  1109. Ptr32[MemTagAllocationTidIndex] = Tid;
  1110. storeRingBufferEntry(untagPointer(Ptr), Trace, Tid, Size, 0, 0);
  1111. }
  1112. void storeDeallocationStackMaybe(Options Options, void *Ptr, u8 PrevTag,
  1113. uptr Size) {
  1114. if (!UNLIKELY(Options.get(OptionBit::TrackAllocationStacks)))
  1115. return;
  1116. auto *Ptr32 = reinterpret_cast<u32 *>(Ptr);
  1117. u32 AllocationTrace = Ptr32[MemTagAllocationTraceIndex];
  1118. u32 AllocationTid = Ptr32[MemTagAllocationTidIndex];
  1119. u32 DeallocationTrace = collectStackTrace();
  1120. u32 DeallocationTid = getThreadID();
  1121. storeRingBufferEntry(addFixedTag(untagPointer(Ptr), PrevTag),
  1122. AllocationTrace, AllocationTid, Size,
  1123. DeallocationTrace, DeallocationTid);
  1124. }
  1125. static const size_t NumErrorReports =
  1126. sizeof(((scudo_error_info *)0)->reports) /
  1127. sizeof(((scudo_error_info *)0)->reports[0]);
  1128. static void getInlineErrorInfo(struct scudo_error_info *ErrorInfo,
  1129. size_t &NextErrorReport, uintptr_t FaultAddr,
  1130. const StackDepot *Depot,
  1131. const char *RegionInfoPtr, const char *Memory,
  1132. const char *MemoryTags, uintptr_t MemoryAddr,
  1133. size_t MemorySize, size_t MinDistance,
  1134. size_t MaxDistance) {
  1135. uptr UntaggedFaultAddr = untagPointer(FaultAddr);
  1136. u8 FaultAddrTag = extractTag(FaultAddr);
  1137. BlockInfo Info =
  1138. PrimaryT::findNearestBlock(RegionInfoPtr, UntaggedFaultAddr);
  1139. auto GetGranule = [&](uptr Addr, const char **Data, uint8_t *Tag) -> bool {
  1140. if (Addr < MemoryAddr || Addr + archMemoryTagGranuleSize() < Addr ||
  1141. Addr + archMemoryTagGranuleSize() > MemoryAddr + MemorySize)
  1142. return false;
  1143. *Data = &Memory[Addr - MemoryAddr];
  1144. *Tag = static_cast<u8>(
  1145. MemoryTags[(Addr - MemoryAddr) / archMemoryTagGranuleSize()]);
  1146. return true;
  1147. };
  1148. auto ReadBlock = [&](uptr Addr, uptr *ChunkAddr,
  1149. Chunk::UnpackedHeader *Header, const u32 **Data,
  1150. u8 *Tag) {
  1151. const char *BlockBegin;
  1152. u8 BlockBeginTag;
  1153. if (!GetGranule(Addr, &BlockBegin, &BlockBeginTag))
  1154. return false;
  1155. uptr ChunkOffset = getChunkOffsetFromBlock(BlockBegin);
  1156. *ChunkAddr = Addr + ChunkOffset;
  1157. const char *ChunkBegin;
  1158. if (!GetGranule(*ChunkAddr, &ChunkBegin, Tag))
  1159. return false;
  1160. *Header = *reinterpret_cast<const Chunk::UnpackedHeader *>(
  1161. ChunkBegin - Chunk::getHeaderSize());
  1162. *Data = reinterpret_cast<const u32 *>(ChunkBegin);
  1163. // Allocations of size 0 will have stashed the tag in the first byte of
  1164. // the chunk, see storeEndMarker().
  1165. if (Header->SizeOrUnusedBytes == 0)
  1166. *Tag = static_cast<u8>(*ChunkBegin);
  1167. return true;
  1168. };
  1169. if (NextErrorReport == NumErrorReports)
  1170. return;
  1171. auto CheckOOB = [&](uptr BlockAddr) {
  1172. if (BlockAddr < Info.RegionBegin || BlockAddr >= Info.RegionEnd)
  1173. return false;
  1174. uptr ChunkAddr;
  1175. Chunk::UnpackedHeader Header;
  1176. const u32 *Data;
  1177. uint8_t Tag;
  1178. if (!ReadBlock(BlockAddr, &ChunkAddr, &Header, &Data, &Tag) ||
  1179. Header.State != Chunk::State::Allocated || Tag != FaultAddrTag)
  1180. return false;
  1181. auto *R = &ErrorInfo->reports[NextErrorReport++];
  1182. R->error_type =
  1183. UntaggedFaultAddr < ChunkAddr ? BUFFER_UNDERFLOW : BUFFER_OVERFLOW;
  1184. R->allocation_address = ChunkAddr;
  1185. R->allocation_size = Header.SizeOrUnusedBytes;
  1186. collectTraceMaybe(Depot, R->allocation_trace,
  1187. Data[MemTagAllocationTraceIndex]);
  1188. R->allocation_tid = Data[MemTagAllocationTidIndex];
  1189. return NextErrorReport == NumErrorReports;
  1190. };
  1191. if (MinDistance == 0 && CheckOOB(Info.BlockBegin))
  1192. return;
  1193. for (size_t I = Max<size_t>(MinDistance, 1); I != MaxDistance; ++I)
  1194. if (CheckOOB(Info.BlockBegin + I * Info.BlockSize) ||
  1195. CheckOOB(Info.BlockBegin - I * Info.BlockSize))
  1196. return;
  1197. }
  1198. static void getRingBufferErrorInfo(struct scudo_error_info *ErrorInfo,
  1199. size_t &NextErrorReport,
  1200. uintptr_t FaultAddr,
  1201. const StackDepot *Depot,
  1202. const char *RingBufferPtr) {
  1203. auto *RingBuffer =
  1204. reinterpret_cast<const AllocationRingBuffer *>(RingBufferPtr);
  1205. uptr Pos = atomic_load_relaxed(&RingBuffer->Pos);
  1206. for (uptr I = Pos - 1; I != Pos - 1 - AllocationRingBuffer::NumEntries &&
  1207. NextErrorReport != NumErrorReports;
  1208. --I) {
  1209. auto *Entry = &RingBuffer->Entries[I % AllocationRingBuffer::NumEntries];
  1210. uptr EntryPtr = atomic_load_relaxed(&Entry->Ptr);
  1211. if (!EntryPtr)
  1212. continue;
  1213. uptr UntaggedEntryPtr = untagPointer(EntryPtr);
  1214. uptr EntrySize = atomic_load_relaxed(&Entry->AllocationSize);
  1215. u32 AllocationTrace = atomic_load_relaxed(&Entry->AllocationTrace);
  1216. u32 AllocationTid = atomic_load_relaxed(&Entry->AllocationTid);
  1217. u32 DeallocationTrace = atomic_load_relaxed(&Entry->DeallocationTrace);
  1218. u32 DeallocationTid = atomic_load_relaxed(&Entry->DeallocationTid);
  1219. if (DeallocationTid) {
  1220. // For UAF we only consider in-bounds fault addresses because
  1221. // out-of-bounds UAF is rare and attempting to detect it is very likely
  1222. // to result in false positives.
  1223. if (FaultAddr < EntryPtr || FaultAddr >= EntryPtr + EntrySize)
  1224. continue;
  1225. } else {
  1226. // Ring buffer OOB is only possible with secondary allocations. In this
  1227. // case we are guaranteed a guard region of at least a page on either
  1228. // side of the allocation (guard page on the right, guard page + tagged
  1229. // region on the left), so ignore any faults outside of that range.
  1230. if (FaultAddr < EntryPtr - getPageSizeCached() ||
  1231. FaultAddr >= EntryPtr + EntrySize + getPageSizeCached())
  1232. continue;
  1233. // For UAF the ring buffer will contain two entries, one for the
  1234. // allocation and another for the deallocation. Don't report buffer
  1235. // overflow/underflow using the allocation entry if we have already
  1236. // collected a report from the deallocation entry.
  1237. bool Found = false;
  1238. for (uptr J = 0; J != NextErrorReport; ++J) {
  1239. if (ErrorInfo->reports[J].allocation_address == UntaggedEntryPtr) {
  1240. Found = true;
  1241. break;
  1242. }
  1243. }
  1244. if (Found)
  1245. continue;
  1246. }
  1247. auto *R = &ErrorInfo->reports[NextErrorReport++];
  1248. if (DeallocationTid)
  1249. R->error_type = USE_AFTER_FREE;
  1250. else if (FaultAddr < EntryPtr)
  1251. R->error_type = BUFFER_UNDERFLOW;
  1252. else
  1253. R->error_type = BUFFER_OVERFLOW;
  1254. R->allocation_address = UntaggedEntryPtr;
  1255. R->allocation_size = EntrySize;
  1256. collectTraceMaybe(Depot, R->allocation_trace, AllocationTrace);
  1257. R->allocation_tid = AllocationTid;
  1258. collectTraceMaybe(Depot, R->deallocation_trace, DeallocationTrace);
  1259. R->deallocation_tid = DeallocationTid;
  1260. }
  1261. }
  1262. uptr getStats(ScopedString *Str) {
  1263. Primary.getStats(Str);
  1264. Secondary.getStats(Str);
  1265. Quarantine.getStats(Str);
  1266. return Str->length();
  1267. }
  1268. };
  1269. } // namespace scudo
  1270. #endif // SCUDO_COMBINED_H_