combined.h 61 KB

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