asan_allocator.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  1. //===-- asan_allocator.cpp ------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file is a part of AddressSanitizer, an address sanity checker.
  10. //
  11. // Implementation of ASan's memory allocator, 2-nd version.
  12. // This variant uses the allocator from sanitizer_common, i.e. the one shared
  13. // with ThreadSanitizer and MemorySanitizer.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "asan_allocator.h"
  17. #include "asan_mapping.h"
  18. #include "asan_poisoning.h"
  19. #include "asan_report.h"
  20. #include "asan_stack.h"
  21. #include "asan_thread.h"
  22. #include "lsan/lsan_common.h"
  23. #include "sanitizer_common/sanitizer_allocator_checks.h"
  24. #include "sanitizer_common/sanitizer_allocator_interface.h"
  25. #include "sanitizer_common/sanitizer_errno.h"
  26. #include "sanitizer_common/sanitizer_flags.h"
  27. #include "sanitizer_common/sanitizer_internal_defs.h"
  28. #include "sanitizer_common/sanitizer_list.h"
  29. #include "sanitizer_common/sanitizer_quarantine.h"
  30. #include "sanitizer_common/sanitizer_stackdepot.h"
  31. namespace __asan {
  32. // Valid redzone sizes are 16, 32, 64, ... 2048, so we encode them in 3 bits.
  33. // We use adaptive redzones: for larger allocation larger redzones are used.
  34. static u32 RZLog2Size(u32 rz_log) {
  35. CHECK_LT(rz_log, 8);
  36. return 16 << rz_log;
  37. }
  38. static u32 RZSize2Log(u32 rz_size) {
  39. CHECK_GE(rz_size, 16);
  40. CHECK_LE(rz_size, 2048);
  41. CHECK(IsPowerOfTwo(rz_size));
  42. u32 res = Log2(rz_size) - 4;
  43. CHECK_EQ(rz_size, RZLog2Size(res));
  44. return res;
  45. }
  46. static AsanAllocator &get_allocator();
  47. static void AtomicContextStore(volatile atomic_uint64_t *atomic_context,
  48. u32 tid, u32 stack) {
  49. u64 context = tid;
  50. context <<= 32;
  51. context += stack;
  52. atomic_store(atomic_context, context, memory_order_relaxed);
  53. }
  54. static void AtomicContextLoad(const volatile atomic_uint64_t *atomic_context,
  55. u32 &tid, u32 &stack) {
  56. u64 context = atomic_load(atomic_context, memory_order_relaxed);
  57. stack = context;
  58. context >>= 32;
  59. tid = context;
  60. }
  61. // The memory chunk allocated from the underlying allocator looks like this:
  62. // L L L L L L H H U U U U U U R R
  63. // L -- left redzone words (0 or more bytes)
  64. // H -- ChunkHeader (16 bytes), which is also a part of the left redzone.
  65. // U -- user memory.
  66. // R -- right redzone (0 or more bytes)
  67. // ChunkBase consists of ChunkHeader and other bytes that overlap with user
  68. // memory.
  69. // If the left redzone is greater than the ChunkHeader size we store a magic
  70. // value in the first uptr word of the memory block and store the address of
  71. // ChunkBase in the next uptr.
  72. // M B L L L L L L L L L H H U U U U U U
  73. // | ^
  74. // ---------------------|
  75. // M -- magic value kAllocBegMagic
  76. // B -- address of ChunkHeader pointing to the first 'H'
  77. class ChunkHeader {
  78. public:
  79. atomic_uint8_t chunk_state;
  80. u8 alloc_type : 2;
  81. u8 lsan_tag : 2;
  82. // align < 8 -> 0
  83. // else -> log2(min(align, 512)) - 2
  84. u8 user_requested_alignment_log : 3;
  85. private:
  86. u16 user_requested_size_hi;
  87. u32 user_requested_size_lo;
  88. atomic_uint64_t alloc_context_id;
  89. public:
  90. uptr UsedSize() const {
  91. static_assert(sizeof(user_requested_size_lo) == 4,
  92. "Expression below requires this");
  93. return FIRST_32_SECOND_64(0, ((uptr)user_requested_size_hi << 32)) +
  94. user_requested_size_lo;
  95. }
  96. void SetUsedSize(uptr size) {
  97. user_requested_size_lo = size;
  98. static_assert(sizeof(user_requested_size_lo) == 4,
  99. "Expression below requires this");
  100. user_requested_size_hi = FIRST_32_SECOND_64(0, size >> 32);
  101. CHECK_EQ(UsedSize(), size);
  102. }
  103. void SetAllocContext(u32 tid, u32 stack) {
  104. AtomicContextStore(&alloc_context_id, tid, stack);
  105. }
  106. void GetAllocContext(u32 &tid, u32 &stack) const {
  107. AtomicContextLoad(&alloc_context_id, tid, stack);
  108. }
  109. };
  110. class ChunkBase : public ChunkHeader {
  111. atomic_uint64_t free_context_id;
  112. public:
  113. void SetFreeContext(u32 tid, u32 stack) {
  114. AtomicContextStore(&free_context_id, tid, stack);
  115. }
  116. void GetFreeContext(u32 &tid, u32 &stack) const {
  117. AtomicContextLoad(&free_context_id, tid, stack);
  118. }
  119. };
  120. static const uptr kChunkHeaderSize = sizeof(ChunkHeader);
  121. static const uptr kChunkHeader2Size = sizeof(ChunkBase) - kChunkHeaderSize;
  122. COMPILER_CHECK(kChunkHeaderSize == 16);
  123. COMPILER_CHECK(kChunkHeader2Size <= 16);
  124. enum {
  125. // Either just allocated by underlying allocator, but AsanChunk is not yet
  126. // ready, or almost returned to undelying allocator and AsanChunk is already
  127. // meaningless.
  128. CHUNK_INVALID = 0,
  129. // The chunk is allocated and not yet freed.
  130. CHUNK_ALLOCATED = 2,
  131. // The chunk was freed and put into quarantine zone.
  132. CHUNK_QUARANTINE = 3,
  133. };
  134. class AsanChunk : public ChunkBase {
  135. public:
  136. uptr Beg() { return reinterpret_cast<uptr>(this) + kChunkHeaderSize; }
  137. bool AddrIsInside(uptr addr) {
  138. return (addr >= Beg()) && (addr < Beg() + UsedSize());
  139. }
  140. };
  141. class LargeChunkHeader {
  142. static constexpr uptr kAllocBegMagic =
  143. FIRST_32_SECOND_64(0xCC6E96B9, 0xCC6E96B9CC6E96B9ULL);
  144. atomic_uintptr_t magic;
  145. AsanChunk *chunk_header;
  146. public:
  147. AsanChunk *Get() const {
  148. return atomic_load(&magic, memory_order_acquire) == kAllocBegMagic
  149. ? chunk_header
  150. : nullptr;
  151. }
  152. void Set(AsanChunk *p) {
  153. if (p) {
  154. chunk_header = p;
  155. atomic_store(&magic, kAllocBegMagic, memory_order_release);
  156. return;
  157. }
  158. uptr old = kAllocBegMagic;
  159. if (!atomic_compare_exchange_strong(&magic, &old, 0,
  160. memory_order_release)) {
  161. CHECK_EQ(old, kAllocBegMagic);
  162. }
  163. }
  164. };
  165. struct QuarantineCallback {
  166. QuarantineCallback(AllocatorCache *cache, BufferedStackTrace *stack)
  167. : cache_(cache),
  168. stack_(stack) {
  169. }
  170. void Recycle(AsanChunk *m) {
  171. void *p = get_allocator().GetBlockBegin(m);
  172. if (p != m) {
  173. // Clear the magic value, as allocator internals may overwrite the
  174. // contents of deallocated chunk, confusing GetAsanChunk lookup.
  175. reinterpret_cast<LargeChunkHeader *>(p)->Set(nullptr);
  176. }
  177. u8 old_chunk_state = CHUNK_QUARANTINE;
  178. if (!atomic_compare_exchange_strong(&m->chunk_state, &old_chunk_state,
  179. CHUNK_INVALID, memory_order_acquire)) {
  180. CHECK_EQ(old_chunk_state, CHUNK_QUARANTINE);
  181. }
  182. PoisonShadow(m->Beg(), RoundUpTo(m->UsedSize(), ASAN_SHADOW_GRANULARITY),
  183. kAsanHeapLeftRedzoneMagic);
  184. // Statistics.
  185. AsanStats &thread_stats = GetCurrentThreadStats();
  186. thread_stats.real_frees++;
  187. thread_stats.really_freed += m->UsedSize();
  188. get_allocator().Deallocate(cache_, p);
  189. }
  190. void *Allocate(uptr size) {
  191. void *res = get_allocator().Allocate(cache_, size, 1);
  192. // TODO(alekseys): Consider making quarantine OOM-friendly.
  193. if (UNLIKELY(!res))
  194. ReportOutOfMemory(size, stack_);
  195. return res;
  196. }
  197. void Deallocate(void *p) {
  198. get_allocator().Deallocate(cache_, p);
  199. }
  200. private:
  201. AllocatorCache* const cache_;
  202. BufferedStackTrace* const stack_;
  203. };
  204. typedef Quarantine<QuarantineCallback, AsanChunk> AsanQuarantine;
  205. typedef AsanQuarantine::Cache QuarantineCache;
  206. void AsanMapUnmapCallback::OnMap(uptr p, uptr size) const {
  207. PoisonShadow(p, size, kAsanHeapLeftRedzoneMagic);
  208. // Statistics.
  209. AsanStats &thread_stats = GetCurrentThreadStats();
  210. thread_stats.mmaps++;
  211. thread_stats.mmaped += size;
  212. }
  213. void AsanMapUnmapCallback::OnUnmap(uptr p, uptr size) const {
  214. PoisonShadow(p, size, 0);
  215. // We are about to unmap a chunk of user memory.
  216. // Mark the corresponding shadow memory as not needed.
  217. FlushUnneededASanShadowMemory(p, size);
  218. // Statistics.
  219. AsanStats &thread_stats = GetCurrentThreadStats();
  220. thread_stats.munmaps++;
  221. thread_stats.munmaped += size;
  222. }
  223. // We can not use THREADLOCAL because it is not supported on some of the
  224. // platforms we care about (OSX 10.6, Android).
  225. // static THREADLOCAL AllocatorCache cache;
  226. AllocatorCache *GetAllocatorCache(AsanThreadLocalMallocStorage *ms) {
  227. CHECK(ms);
  228. return &ms->allocator_cache;
  229. }
  230. QuarantineCache *GetQuarantineCache(AsanThreadLocalMallocStorage *ms) {
  231. CHECK(ms);
  232. CHECK_LE(sizeof(QuarantineCache), sizeof(ms->quarantine_cache));
  233. return reinterpret_cast<QuarantineCache *>(ms->quarantine_cache);
  234. }
  235. void AllocatorOptions::SetFrom(const Flags *f, const CommonFlags *cf) {
  236. quarantine_size_mb = f->quarantine_size_mb;
  237. thread_local_quarantine_size_kb = f->thread_local_quarantine_size_kb;
  238. min_redzone = f->redzone;
  239. max_redzone = f->max_redzone;
  240. may_return_null = cf->allocator_may_return_null;
  241. alloc_dealloc_mismatch = f->alloc_dealloc_mismatch;
  242. release_to_os_interval_ms = cf->allocator_release_to_os_interval_ms;
  243. }
  244. void AllocatorOptions::CopyTo(Flags *f, CommonFlags *cf) {
  245. f->quarantine_size_mb = quarantine_size_mb;
  246. f->thread_local_quarantine_size_kb = thread_local_quarantine_size_kb;
  247. f->redzone = min_redzone;
  248. f->max_redzone = max_redzone;
  249. cf->allocator_may_return_null = may_return_null;
  250. f->alloc_dealloc_mismatch = alloc_dealloc_mismatch;
  251. cf->allocator_release_to_os_interval_ms = release_to_os_interval_ms;
  252. }
  253. struct Allocator {
  254. static const uptr kMaxAllowedMallocSize =
  255. FIRST_32_SECOND_64(3UL << 30, 1ULL << 40);
  256. AsanAllocator allocator;
  257. AsanQuarantine quarantine;
  258. StaticSpinMutex fallback_mutex;
  259. AllocatorCache fallback_allocator_cache;
  260. QuarantineCache fallback_quarantine_cache;
  261. uptr max_user_defined_malloc_size;
  262. // ------------------- Options --------------------------
  263. atomic_uint16_t min_redzone;
  264. atomic_uint16_t max_redzone;
  265. atomic_uint8_t alloc_dealloc_mismatch;
  266. // ------------------- Initialization ------------------------
  267. explicit Allocator(LinkerInitialized)
  268. : quarantine(LINKER_INITIALIZED),
  269. fallback_quarantine_cache(LINKER_INITIALIZED) {}
  270. void CheckOptions(const AllocatorOptions &options) const {
  271. CHECK_GE(options.min_redzone, 16);
  272. CHECK_GE(options.max_redzone, options.min_redzone);
  273. CHECK_LE(options.max_redzone, 2048);
  274. CHECK(IsPowerOfTwo(options.min_redzone));
  275. CHECK(IsPowerOfTwo(options.max_redzone));
  276. }
  277. void SharedInitCode(const AllocatorOptions &options) {
  278. CheckOptions(options);
  279. quarantine.Init((uptr)options.quarantine_size_mb << 20,
  280. (uptr)options.thread_local_quarantine_size_kb << 10);
  281. atomic_store(&alloc_dealloc_mismatch, options.alloc_dealloc_mismatch,
  282. memory_order_release);
  283. atomic_store(&min_redzone, options.min_redzone, memory_order_release);
  284. atomic_store(&max_redzone, options.max_redzone, memory_order_release);
  285. }
  286. void InitLinkerInitialized(const AllocatorOptions &options) {
  287. SetAllocatorMayReturnNull(options.may_return_null);
  288. allocator.InitLinkerInitialized(options.release_to_os_interval_ms);
  289. SharedInitCode(options);
  290. max_user_defined_malloc_size = common_flags()->max_allocation_size_mb
  291. ? common_flags()->max_allocation_size_mb
  292. << 20
  293. : kMaxAllowedMallocSize;
  294. }
  295. void RePoisonChunk(uptr chunk) {
  296. // This could be a user-facing chunk (with redzones), or some internal
  297. // housekeeping chunk, like TransferBatch. Start by assuming the former.
  298. AsanChunk *ac = GetAsanChunk((void *)chunk);
  299. uptr allocated_size = allocator.GetActuallyAllocatedSize((void *)chunk);
  300. if (ac && atomic_load(&ac->chunk_state, memory_order_acquire) ==
  301. CHUNK_ALLOCATED) {
  302. uptr beg = ac->Beg();
  303. uptr end = ac->Beg() + ac->UsedSize();
  304. uptr chunk_end = chunk + allocated_size;
  305. if (chunk < beg && beg < end && end <= chunk_end) {
  306. // Looks like a valid AsanChunk in use, poison redzones only.
  307. PoisonShadow(chunk, beg - chunk, kAsanHeapLeftRedzoneMagic);
  308. uptr end_aligned_down = RoundDownTo(end, ASAN_SHADOW_GRANULARITY);
  309. FastPoisonShadowPartialRightRedzone(
  310. end_aligned_down, end - end_aligned_down,
  311. chunk_end - end_aligned_down, kAsanHeapLeftRedzoneMagic);
  312. return;
  313. }
  314. }
  315. // This is either not an AsanChunk or freed or quarantined AsanChunk.
  316. // In either case, poison everything.
  317. PoisonShadow(chunk, allocated_size, kAsanHeapLeftRedzoneMagic);
  318. }
  319. void ReInitialize(const AllocatorOptions &options) {
  320. SetAllocatorMayReturnNull(options.may_return_null);
  321. allocator.SetReleaseToOSIntervalMs(options.release_to_os_interval_ms);
  322. SharedInitCode(options);
  323. // Poison all existing allocation's redzones.
  324. if (CanPoisonMemory()) {
  325. allocator.ForceLock();
  326. allocator.ForEachChunk(
  327. [](uptr chunk, void *alloc) {
  328. ((Allocator *)alloc)->RePoisonChunk(chunk);
  329. },
  330. this);
  331. allocator.ForceUnlock();
  332. }
  333. }
  334. void GetOptions(AllocatorOptions *options) const {
  335. options->quarantine_size_mb = quarantine.GetSize() >> 20;
  336. options->thread_local_quarantine_size_kb = quarantine.GetCacheSize() >> 10;
  337. options->min_redzone = atomic_load(&min_redzone, memory_order_acquire);
  338. options->max_redzone = atomic_load(&max_redzone, memory_order_acquire);
  339. options->may_return_null = AllocatorMayReturnNull();
  340. options->alloc_dealloc_mismatch =
  341. atomic_load(&alloc_dealloc_mismatch, memory_order_acquire);
  342. options->release_to_os_interval_ms = allocator.ReleaseToOSIntervalMs();
  343. }
  344. // -------------------- Helper methods. -------------------------
  345. uptr ComputeRZLog(uptr user_requested_size) {
  346. u32 rz_log = user_requested_size <= 64 - 16 ? 0
  347. : user_requested_size <= 128 - 32 ? 1
  348. : user_requested_size <= 512 - 64 ? 2
  349. : user_requested_size <= 4096 - 128 ? 3
  350. : user_requested_size <= (1 << 14) - 256 ? 4
  351. : user_requested_size <= (1 << 15) - 512 ? 5
  352. : user_requested_size <= (1 << 16) - 1024 ? 6
  353. : 7;
  354. u32 hdr_log = RZSize2Log(RoundUpToPowerOfTwo(sizeof(ChunkHeader)));
  355. u32 min_log = RZSize2Log(atomic_load(&min_redzone, memory_order_acquire));
  356. u32 max_log = RZSize2Log(atomic_load(&max_redzone, memory_order_acquire));
  357. return Min(Max(rz_log, Max(min_log, hdr_log)), Max(max_log, hdr_log));
  358. }
  359. static uptr ComputeUserRequestedAlignmentLog(uptr user_requested_alignment) {
  360. if (user_requested_alignment < 8)
  361. return 0;
  362. if (user_requested_alignment > 512)
  363. user_requested_alignment = 512;
  364. return Log2(user_requested_alignment) - 2;
  365. }
  366. static uptr ComputeUserAlignment(uptr user_requested_alignment_log) {
  367. if (user_requested_alignment_log == 0)
  368. return 0;
  369. return 1LL << (user_requested_alignment_log + 2);
  370. }
  371. // We have an address between two chunks, and we want to report just one.
  372. AsanChunk *ChooseChunk(uptr addr, AsanChunk *left_chunk,
  373. AsanChunk *right_chunk) {
  374. if (!left_chunk)
  375. return right_chunk;
  376. if (!right_chunk)
  377. return left_chunk;
  378. // Prefer an allocated chunk over freed chunk and freed chunk
  379. // over available chunk.
  380. u8 left_state = atomic_load(&left_chunk->chunk_state, memory_order_relaxed);
  381. u8 right_state =
  382. atomic_load(&right_chunk->chunk_state, memory_order_relaxed);
  383. if (left_state != right_state) {
  384. if (left_state == CHUNK_ALLOCATED)
  385. return left_chunk;
  386. if (right_state == CHUNK_ALLOCATED)
  387. return right_chunk;
  388. if (left_state == CHUNK_QUARANTINE)
  389. return left_chunk;
  390. if (right_state == CHUNK_QUARANTINE)
  391. return right_chunk;
  392. }
  393. // Same chunk_state: choose based on offset.
  394. sptr l_offset = 0, r_offset = 0;
  395. CHECK(AsanChunkView(left_chunk).AddrIsAtRight(addr, 1, &l_offset));
  396. CHECK(AsanChunkView(right_chunk).AddrIsAtLeft(addr, 1, &r_offset));
  397. if (l_offset < r_offset)
  398. return left_chunk;
  399. return right_chunk;
  400. }
  401. bool UpdateAllocationStack(uptr addr, BufferedStackTrace *stack) {
  402. AsanChunk *m = GetAsanChunkByAddr(addr);
  403. if (!m) return false;
  404. if (atomic_load(&m->chunk_state, memory_order_acquire) != CHUNK_ALLOCATED)
  405. return false;
  406. if (m->Beg() != addr) return false;
  407. AsanThread *t = GetCurrentThread();
  408. m->SetAllocContext(t ? t->tid() : kMainTid, StackDepotPut(*stack));
  409. return true;
  410. }
  411. // -------------------- Allocation/Deallocation routines ---------------
  412. void *Allocate(uptr size, uptr alignment, BufferedStackTrace *stack,
  413. AllocType alloc_type, bool can_fill) {
  414. if (UNLIKELY(!asan_inited))
  415. AsanInitFromRtl();
  416. if (UNLIKELY(IsRssLimitExceeded())) {
  417. if (AllocatorMayReturnNull())
  418. return nullptr;
  419. ReportRssLimitExceeded(stack);
  420. }
  421. Flags &fl = *flags();
  422. CHECK(stack);
  423. const uptr min_alignment = ASAN_SHADOW_GRANULARITY;
  424. const uptr user_requested_alignment_log =
  425. ComputeUserRequestedAlignmentLog(alignment);
  426. if (alignment < min_alignment)
  427. alignment = min_alignment;
  428. if (size == 0) {
  429. // We'd be happy to avoid allocating memory for zero-size requests, but
  430. // some programs/tests depend on this behavior and assume that malloc
  431. // would not return NULL even for zero-size allocations. Moreover, it
  432. // looks like operator new should never return NULL, and results of
  433. // consecutive "new" calls must be different even if the allocated size
  434. // is zero.
  435. size = 1;
  436. }
  437. CHECK(IsPowerOfTwo(alignment));
  438. uptr rz_log = ComputeRZLog(size);
  439. uptr rz_size = RZLog2Size(rz_log);
  440. uptr rounded_size = RoundUpTo(Max(size, kChunkHeader2Size), alignment);
  441. uptr needed_size = rounded_size + rz_size;
  442. if (alignment > min_alignment)
  443. needed_size += alignment;
  444. // If we are allocating from the secondary allocator, there will be no
  445. // automatic right redzone, so add the right redzone manually.
  446. if (!PrimaryAllocator::CanAllocate(needed_size, alignment))
  447. needed_size += rz_size;
  448. CHECK(IsAligned(needed_size, min_alignment));
  449. if (size > kMaxAllowedMallocSize || needed_size > kMaxAllowedMallocSize ||
  450. size > max_user_defined_malloc_size) {
  451. if (AllocatorMayReturnNull()) {
  452. Report("WARNING: AddressSanitizer failed to allocate 0x%zx bytes\n",
  453. size);
  454. return nullptr;
  455. }
  456. uptr malloc_limit =
  457. Min(kMaxAllowedMallocSize, max_user_defined_malloc_size);
  458. ReportAllocationSizeTooBig(size, needed_size, malloc_limit, stack);
  459. }
  460. AsanThread *t = GetCurrentThread();
  461. void *allocated;
  462. if (t) {
  463. AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
  464. allocated = allocator.Allocate(cache, needed_size, 8);
  465. } else {
  466. SpinMutexLock l(&fallback_mutex);
  467. AllocatorCache *cache = &fallback_allocator_cache;
  468. allocated = allocator.Allocate(cache, needed_size, 8);
  469. }
  470. if (UNLIKELY(!allocated)) {
  471. SetAllocatorOutOfMemory();
  472. if (AllocatorMayReturnNull())
  473. return nullptr;
  474. ReportOutOfMemory(size, stack);
  475. }
  476. if (*(u8 *)MEM_TO_SHADOW((uptr)allocated) == 0 && CanPoisonMemory()) {
  477. // Heap poisoning is enabled, but the allocator provides an unpoisoned
  478. // chunk. This is possible if CanPoisonMemory() was false for some
  479. // time, for example, due to flags()->start_disabled.
  480. // Anyway, poison the block before using it for anything else.
  481. uptr allocated_size = allocator.GetActuallyAllocatedSize(allocated);
  482. PoisonShadow((uptr)allocated, allocated_size, kAsanHeapLeftRedzoneMagic);
  483. }
  484. uptr alloc_beg = reinterpret_cast<uptr>(allocated);
  485. uptr alloc_end = alloc_beg + needed_size;
  486. uptr user_beg = alloc_beg + rz_size;
  487. if (!IsAligned(user_beg, alignment))
  488. user_beg = RoundUpTo(user_beg, alignment);
  489. uptr user_end = user_beg + size;
  490. CHECK_LE(user_end, alloc_end);
  491. uptr chunk_beg = user_beg - kChunkHeaderSize;
  492. AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
  493. m->alloc_type = alloc_type;
  494. CHECK(size);
  495. m->SetUsedSize(size);
  496. m->user_requested_alignment_log = user_requested_alignment_log;
  497. m->SetAllocContext(t ? t->tid() : kMainTid, StackDepotPut(*stack));
  498. uptr size_rounded_down_to_granularity =
  499. RoundDownTo(size, ASAN_SHADOW_GRANULARITY);
  500. // Unpoison the bulk of the memory region.
  501. if (size_rounded_down_to_granularity)
  502. PoisonShadow(user_beg, size_rounded_down_to_granularity, 0);
  503. // Deal with the end of the region if size is not aligned to granularity.
  504. if (size != size_rounded_down_to_granularity && CanPoisonMemory()) {
  505. u8 *shadow =
  506. (u8 *)MemToShadow(user_beg + size_rounded_down_to_granularity);
  507. *shadow = fl.poison_partial ? (size & (ASAN_SHADOW_GRANULARITY - 1)) : 0;
  508. }
  509. AsanStats &thread_stats = GetCurrentThreadStats();
  510. thread_stats.mallocs++;
  511. thread_stats.malloced += size;
  512. thread_stats.malloced_redzones += needed_size - size;
  513. if (needed_size > SizeClassMap::kMaxSize)
  514. thread_stats.malloc_large++;
  515. else
  516. thread_stats.malloced_by_size[SizeClassMap::ClassID(needed_size)]++;
  517. void *res = reinterpret_cast<void *>(user_beg);
  518. if (can_fill && fl.max_malloc_fill_size) {
  519. uptr fill_size = Min(size, (uptr)fl.max_malloc_fill_size);
  520. REAL(memset)(res, fl.malloc_fill_byte, fill_size);
  521. }
  522. #if CAN_SANITIZE_LEAKS
  523. m->lsan_tag = __lsan::DisabledInThisThread() ? __lsan::kIgnored
  524. : __lsan::kDirectlyLeaked;
  525. #endif
  526. // Must be the last mutation of metadata in this function.
  527. atomic_store(&m->chunk_state, CHUNK_ALLOCATED, memory_order_release);
  528. if (alloc_beg != chunk_beg) {
  529. CHECK_LE(alloc_beg + sizeof(LargeChunkHeader), chunk_beg);
  530. reinterpret_cast<LargeChunkHeader *>(alloc_beg)->Set(m);
  531. }
  532. ASAN_MALLOC_HOOK(res, size);
  533. return res;
  534. }
  535. // Set quarantine flag if chunk is allocated, issue ASan error report on
  536. // available and quarantined chunks. Return true on success, false otherwise.
  537. bool AtomicallySetQuarantineFlagIfAllocated(AsanChunk *m, void *ptr,
  538. BufferedStackTrace *stack) {
  539. u8 old_chunk_state = CHUNK_ALLOCATED;
  540. // Flip the chunk_state atomically to avoid race on double-free.
  541. if (!atomic_compare_exchange_strong(&m->chunk_state, &old_chunk_state,
  542. CHUNK_QUARANTINE,
  543. memory_order_acquire)) {
  544. ReportInvalidFree(ptr, old_chunk_state, stack);
  545. // It's not safe to push a chunk in quarantine on invalid free.
  546. return false;
  547. }
  548. CHECK_EQ(CHUNK_ALLOCATED, old_chunk_state);
  549. // It was a user data.
  550. m->SetFreeContext(kInvalidTid, 0);
  551. return true;
  552. }
  553. // Expects the chunk to already be marked as quarantined by using
  554. // AtomicallySetQuarantineFlagIfAllocated.
  555. void QuarantineChunk(AsanChunk *m, void *ptr, BufferedStackTrace *stack) {
  556. CHECK_EQ(atomic_load(&m->chunk_state, memory_order_relaxed),
  557. CHUNK_QUARANTINE);
  558. AsanThread *t = GetCurrentThread();
  559. m->SetFreeContext(t ? t->tid() : 0, StackDepotPut(*stack));
  560. Flags &fl = *flags();
  561. if (fl.max_free_fill_size > 0) {
  562. // We have to skip the chunk header, it contains free_context_id.
  563. uptr scribble_start = (uptr)m + kChunkHeaderSize + kChunkHeader2Size;
  564. if (m->UsedSize() >= kChunkHeader2Size) { // Skip Header2 in user area.
  565. uptr size_to_fill = m->UsedSize() - kChunkHeader2Size;
  566. size_to_fill = Min(size_to_fill, (uptr)fl.max_free_fill_size);
  567. REAL(memset)((void *)scribble_start, fl.free_fill_byte, size_to_fill);
  568. }
  569. }
  570. // Poison the region.
  571. PoisonShadow(m->Beg(), RoundUpTo(m->UsedSize(), ASAN_SHADOW_GRANULARITY),
  572. kAsanHeapFreeMagic);
  573. AsanStats &thread_stats = GetCurrentThreadStats();
  574. thread_stats.frees++;
  575. thread_stats.freed += m->UsedSize();
  576. // Push into quarantine.
  577. if (t) {
  578. AsanThreadLocalMallocStorage *ms = &t->malloc_storage();
  579. AllocatorCache *ac = GetAllocatorCache(ms);
  580. quarantine.Put(GetQuarantineCache(ms), QuarantineCallback(ac, stack), m,
  581. m->UsedSize());
  582. } else {
  583. SpinMutexLock l(&fallback_mutex);
  584. AllocatorCache *ac = &fallback_allocator_cache;
  585. quarantine.Put(&fallback_quarantine_cache, QuarantineCallback(ac, stack),
  586. m, m->UsedSize());
  587. }
  588. }
  589. void Deallocate(void *ptr, uptr delete_size, uptr delete_alignment,
  590. BufferedStackTrace *stack, AllocType alloc_type) {
  591. uptr p = reinterpret_cast<uptr>(ptr);
  592. if (p == 0) return;
  593. uptr chunk_beg = p - kChunkHeaderSize;
  594. AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
  595. // On Windows, uninstrumented DLLs may allocate memory before ASan hooks
  596. // malloc. Don't report an invalid free in this case.
  597. if (SANITIZER_WINDOWS &&
  598. !get_allocator().PointerIsMine(ptr)) {
  599. if (!IsSystemHeapAddress(p))
  600. ReportFreeNotMalloced(p, stack);
  601. return;
  602. }
  603. ASAN_FREE_HOOK(ptr);
  604. // Must mark the chunk as quarantined before any changes to its metadata.
  605. // Do not quarantine given chunk if we failed to set CHUNK_QUARANTINE flag.
  606. if (!AtomicallySetQuarantineFlagIfAllocated(m, ptr, stack)) return;
  607. if (m->alloc_type != alloc_type) {
  608. if (atomic_load(&alloc_dealloc_mismatch, memory_order_acquire)) {
  609. ReportAllocTypeMismatch((uptr)ptr, stack, (AllocType)m->alloc_type,
  610. (AllocType)alloc_type);
  611. }
  612. } else {
  613. if (flags()->new_delete_type_mismatch &&
  614. (alloc_type == FROM_NEW || alloc_type == FROM_NEW_BR) &&
  615. ((delete_size && delete_size != m->UsedSize()) ||
  616. ComputeUserRequestedAlignmentLog(delete_alignment) !=
  617. m->user_requested_alignment_log)) {
  618. ReportNewDeleteTypeMismatch(p, delete_size, delete_alignment, stack);
  619. }
  620. }
  621. QuarantineChunk(m, ptr, stack);
  622. }
  623. void *Reallocate(void *old_ptr, uptr new_size, BufferedStackTrace *stack) {
  624. CHECK(old_ptr && new_size);
  625. uptr p = reinterpret_cast<uptr>(old_ptr);
  626. uptr chunk_beg = p - kChunkHeaderSize;
  627. AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
  628. AsanStats &thread_stats = GetCurrentThreadStats();
  629. thread_stats.reallocs++;
  630. thread_stats.realloced += new_size;
  631. void *new_ptr = Allocate(new_size, 8, stack, FROM_MALLOC, true);
  632. if (new_ptr) {
  633. u8 chunk_state = atomic_load(&m->chunk_state, memory_order_acquire);
  634. if (chunk_state != CHUNK_ALLOCATED)
  635. ReportInvalidFree(old_ptr, chunk_state, stack);
  636. CHECK_NE(REAL(memcpy), nullptr);
  637. uptr memcpy_size = Min(new_size, m->UsedSize());
  638. // If realloc() races with free(), we may start copying freed memory.
  639. // However, we will report racy double-free later anyway.
  640. REAL(memcpy)(new_ptr, old_ptr, memcpy_size);
  641. Deallocate(old_ptr, 0, 0, stack, FROM_MALLOC);
  642. }
  643. return new_ptr;
  644. }
  645. void *Calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) {
  646. if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
  647. if (AllocatorMayReturnNull())
  648. return nullptr;
  649. ReportCallocOverflow(nmemb, size, stack);
  650. }
  651. void *ptr = Allocate(nmemb * size, 8, stack, FROM_MALLOC, false);
  652. // If the memory comes from the secondary allocator no need to clear it
  653. // as it comes directly from mmap.
  654. if (ptr && allocator.FromPrimary(ptr))
  655. REAL(memset)(ptr, 0, nmemb * size);
  656. return ptr;
  657. }
  658. void ReportInvalidFree(void *ptr, u8 chunk_state, BufferedStackTrace *stack) {
  659. if (chunk_state == CHUNK_QUARANTINE)
  660. ReportDoubleFree((uptr)ptr, stack);
  661. else
  662. ReportFreeNotMalloced((uptr)ptr, stack);
  663. }
  664. void CommitBack(AsanThreadLocalMallocStorage *ms, BufferedStackTrace *stack) {
  665. AllocatorCache *ac = GetAllocatorCache(ms);
  666. quarantine.Drain(GetQuarantineCache(ms), QuarantineCallback(ac, stack));
  667. allocator.SwallowCache(ac);
  668. }
  669. // -------------------------- Chunk lookup ----------------------
  670. // Assumes alloc_beg == allocator.GetBlockBegin(alloc_beg).
  671. // Returns nullptr if AsanChunk is not yet initialized just after
  672. // get_allocator().Allocate(), or is being destroyed just before
  673. // get_allocator().Deallocate().
  674. AsanChunk *GetAsanChunk(void *alloc_beg) {
  675. if (!alloc_beg)
  676. return nullptr;
  677. AsanChunk *p = reinterpret_cast<LargeChunkHeader *>(alloc_beg)->Get();
  678. if (!p) {
  679. if (!allocator.FromPrimary(alloc_beg))
  680. return nullptr;
  681. p = reinterpret_cast<AsanChunk *>(alloc_beg);
  682. }
  683. u8 state = atomic_load(&p->chunk_state, memory_order_relaxed);
  684. // It does not guaranty that Chunk is initialized, but it's
  685. // definitely not for any other value.
  686. if (state == CHUNK_ALLOCATED || state == CHUNK_QUARANTINE)
  687. return p;
  688. return nullptr;
  689. }
  690. AsanChunk *GetAsanChunkByAddr(uptr p) {
  691. void *alloc_beg = allocator.GetBlockBegin(reinterpret_cast<void *>(p));
  692. return GetAsanChunk(alloc_beg);
  693. }
  694. // Allocator must be locked when this function is called.
  695. AsanChunk *GetAsanChunkByAddrFastLocked(uptr p) {
  696. void *alloc_beg =
  697. allocator.GetBlockBeginFastLocked(reinterpret_cast<void *>(p));
  698. return GetAsanChunk(alloc_beg);
  699. }
  700. uptr AllocationSize(uptr p) {
  701. AsanChunk *m = GetAsanChunkByAddr(p);
  702. if (!m) return 0;
  703. if (atomic_load(&m->chunk_state, memory_order_acquire) != CHUNK_ALLOCATED)
  704. return 0;
  705. if (m->Beg() != p) return 0;
  706. return m->UsedSize();
  707. }
  708. AsanChunkView FindHeapChunkByAddress(uptr addr) {
  709. AsanChunk *m1 = GetAsanChunkByAddr(addr);
  710. sptr offset = 0;
  711. if (!m1 || AsanChunkView(m1).AddrIsAtLeft(addr, 1, &offset)) {
  712. // The address is in the chunk's left redzone, so maybe it is actually
  713. // a right buffer overflow from the other chunk to the left.
  714. // Search a bit to the left to see if there is another chunk.
  715. AsanChunk *m2 = nullptr;
  716. for (uptr l = 1; l < GetPageSizeCached(); l++) {
  717. m2 = GetAsanChunkByAddr(addr - l);
  718. if (m2 == m1) continue; // Still the same chunk.
  719. break;
  720. }
  721. if (m2 && AsanChunkView(m2).AddrIsAtRight(addr, 1, &offset))
  722. m1 = ChooseChunk(addr, m2, m1);
  723. }
  724. return AsanChunkView(m1);
  725. }
  726. void Purge(BufferedStackTrace *stack) {
  727. AsanThread *t = GetCurrentThread();
  728. if (t) {
  729. AsanThreadLocalMallocStorage *ms = &t->malloc_storage();
  730. quarantine.DrainAndRecycle(GetQuarantineCache(ms),
  731. QuarantineCallback(GetAllocatorCache(ms),
  732. stack));
  733. }
  734. {
  735. SpinMutexLock l(&fallback_mutex);
  736. quarantine.DrainAndRecycle(&fallback_quarantine_cache,
  737. QuarantineCallback(&fallback_allocator_cache,
  738. stack));
  739. }
  740. allocator.ForceReleaseToOS();
  741. }
  742. void PrintStats() {
  743. allocator.PrintStats();
  744. quarantine.PrintStats();
  745. }
  746. void ForceLock() SANITIZER_ACQUIRE(fallback_mutex) {
  747. allocator.ForceLock();
  748. fallback_mutex.Lock();
  749. }
  750. void ForceUnlock() SANITIZER_RELEASE(fallback_mutex) {
  751. fallback_mutex.Unlock();
  752. allocator.ForceUnlock();
  753. }
  754. };
  755. static Allocator instance(LINKER_INITIALIZED);
  756. static AsanAllocator &get_allocator() {
  757. return instance.allocator;
  758. }
  759. bool AsanChunkView::IsValid() const {
  760. return chunk_ && atomic_load(&chunk_->chunk_state, memory_order_relaxed) !=
  761. CHUNK_INVALID;
  762. }
  763. bool AsanChunkView::IsAllocated() const {
  764. return chunk_ && atomic_load(&chunk_->chunk_state, memory_order_relaxed) ==
  765. CHUNK_ALLOCATED;
  766. }
  767. bool AsanChunkView::IsQuarantined() const {
  768. return chunk_ && atomic_load(&chunk_->chunk_state, memory_order_relaxed) ==
  769. CHUNK_QUARANTINE;
  770. }
  771. uptr AsanChunkView::Beg() const { return chunk_->Beg(); }
  772. uptr AsanChunkView::End() const { return Beg() + UsedSize(); }
  773. uptr AsanChunkView::UsedSize() const { return chunk_->UsedSize(); }
  774. u32 AsanChunkView::UserRequestedAlignment() const {
  775. return Allocator::ComputeUserAlignment(chunk_->user_requested_alignment_log);
  776. }
  777. uptr AsanChunkView::AllocTid() const {
  778. u32 tid = 0;
  779. u32 stack = 0;
  780. chunk_->GetAllocContext(tid, stack);
  781. return tid;
  782. }
  783. uptr AsanChunkView::FreeTid() const {
  784. if (!IsQuarantined())
  785. return kInvalidTid;
  786. u32 tid = 0;
  787. u32 stack = 0;
  788. chunk_->GetFreeContext(tid, stack);
  789. return tid;
  790. }
  791. AllocType AsanChunkView::GetAllocType() const {
  792. return (AllocType)chunk_->alloc_type;
  793. }
  794. u32 AsanChunkView::GetAllocStackId() const {
  795. u32 tid = 0;
  796. u32 stack = 0;
  797. chunk_->GetAllocContext(tid, stack);
  798. return stack;
  799. }
  800. u32 AsanChunkView::GetFreeStackId() const {
  801. if (!IsQuarantined())
  802. return 0;
  803. u32 tid = 0;
  804. u32 stack = 0;
  805. chunk_->GetFreeContext(tid, stack);
  806. return stack;
  807. }
  808. void InitializeAllocator(const AllocatorOptions &options) {
  809. instance.InitLinkerInitialized(options);
  810. }
  811. void ReInitializeAllocator(const AllocatorOptions &options) {
  812. instance.ReInitialize(options);
  813. }
  814. void GetAllocatorOptions(AllocatorOptions *options) {
  815. instance.GetOptions(options);
  816. }
  817. AsanChunkView FindHeapChunkByAddress(uptr addr) {
  818. return instance.FindHeapChunkByAddress(addr);
  819. }
  820. AsanChunkView FindHeapChunkByAllocBeg(uptr addr) {
  821. return AsanChunkView(instance.GetAsanChunk(reinterpret_cast<void*>(addr)));
  822. }
  823. void AsanThreadLocalMallocStorage::CommitBack() {
  824. GET_STACK_TRACE_MALLOC;
  825. instance.CommitBack(this, &stack);
  826. }
  827. void PrintInternalAllocatorStats() {
  828. instance.PrintStats();
  829. }
  830. void asan_free(void *ptr, BufferedStackTrace *stack, AllocType alloc_type) {
  831. instance.Deallocate(ptr, 0, 0, stack, alloc_type);
  832. }
  833. void asan_delete(void *ptr, uptr size, uptr alignment,
  834. BufferedStackTrace *stack, AllocType alloc_type) {
  835. instance.Deallocate(ptr, size, alignment, stack, alloc_type);
  836. }
  837. void *asan_malloc(uptr size, BufferedStackTrace *stack) {
  838. return SetErrnoOnNull(instance.Allocate(size, 8, stack, FROM_MALLOC, true));
  839. }
  840. void *asan_calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) {
  841. return SetErrnoOnNull(instance.Calloc(nmemb, size, stack));
  842. }
  843. void *asan_reallocarray(void *p, uptr nmemb, uptr size,
  844. BufferedStackTrace *stack) {
  845. if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
  846. errno = errno_ENOMEM;
  847. if (AllocatorMayReturnNull())
  848. return nullptr;
  849. ReportReallocArrayOverflow(nmemb, size, stack);
  850. }
  851. return asan_realloc(p, nmemb * size, stack);
  852. }
  853. void *asan_realloc(void *p, uptr size, BufferedStackTrace *stack) {
  854. if (!p)
  855. return SetErrnoOnNull(instance.Allocate(size, 8, stack, FROM_MALLOC, true));
  856. if (size == 0) {
  857. if (flags()->allocator_frees_and_returns_null_on_realloc_zero) {
  858. instance.Deallocate(p, 0, 0, stack, FROM_MALLOC);
  859. return nullptr;
  860. }
  861. // Allocate a size of 1 if we shouldn't free() on Realloc to 0
  862. size = 1;
  863. }
  864. return SetErrnoOnNull(instance.Reallocate(p, size, stack));
  865. }
  866. void *asan_valloc(uptr size, BufferedStackTrace *stack) {
  867. return SetErrnoOnNull(
  868. instance.Allocate(size, GetPageSizeCached(), stack, FROM_MALLOC, true));
  869. }
  870. void *asan_pvalloc(uptr size, BufferedStackTrace *stack) {
  871. uptr PageSize = GetPageSizeCached();
  872. if (UNLIKELY(CheckForPvallocOverflow(size, PageSize))) {
  873. errno = errno_ENOMEM;
  874. if (AllocatorMayReturnNull())
  875. return nullptr;
  876. ReportPvallocOverflow(size, stack);
  877. }
  878. // pvalloc(0) should allocate one page.
  879. size = size ? RoundUpTo(size, PageSize) : PageSize;
  880. return SetErrnoOnNull(
  881. instance.Allocate(size, PageSize, stack, FROM_MALLOC, true));
  882. }
  883. void *asan_memalign(uptr alignment, uptr size, BufferedStackTrace *stack,
  884. AllocType alloc_type) {
  885. if (UNLIKELY(!IsPowerOfTwo(alignment))) {
  886. errno = errno_EINVAL;
  887. if (AllocatorMayReturnNull())
  888. return nullptr;
  889. ReportInvalidAllocationAlignment(alignment, stack);
  890. }
  891. return SetErrnoOnNull(
  892. instance.Allocate(size, alignment, stack, alloc_type, true));
  893. }
  894. void *asan_aligned_alloc(uptr alignment, uptr size, BufferedStackTrace *stack) {
  895. if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(alignment, size))) {
  896. errno = errno_EINVAL;
  897. if (AllocatorMayReturnNull())
  898. return nullptr;
  899. ReportInvalidAlignedAllocAlignment(size, alignment, stack);
  900. }
  901. return SetErrnoOnNull(
  902. instance.Allocate(size, alignment, stack, FROM_MALLOC, true));
  903. }
  904. int asan_posix_memalign(void **memptr, uptr alignment, uptr size,
  905. BufferedStackTrace *stack) {
  906. if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) {
  907. if (AllocatorMayReturnNull())
  908. return errno_EINVAL;
  909. ReportInvalidPosixMemalignAlignment(alignment, stack);
  910. }
  911. void *ptr = instance.Allocate(size, alignment, stack, FROM_MALLOC, true);
  912. if (UNLIKELY(!ptr))
  913. // OOM error is already taken care of by Allocate.
  914. return errno_ENOMEM;
  915. CHECK(IsAligned((uptr)ptr, alignment));
  916. *memptr = ptr;
  917. return 0;
  918. }
  919. uptr asan_malloc_usable_size(const void *ptr, uptr pc, uptr bp) {
  920. if (!ptr) return 0;
  921. uptr usable_size = instance.AllocationSize(reinterpret_cast<uptr>(ptr));
  922. if (flags()->check_malloc_usable_size && (usable_size == 0)) {
  923. GET_STACK_TRACE_FATAL(pc, bp);
  924. ReportMallocUsableSizeNotOwned((uptr)ptr, &stack);
  925. }
  926. return usable_size;
  927. }
  928. uptr asan_mz_size(const void *ptr) {
  929. return instance.AllocationSize(reinterpret_cast<uptr>(ptr));
  930. }
  931. void asan_mz_force_lock() SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
  932. instance.ForceLock();
  933. }
  934. void asan_mz_force_unlock() SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
  935. instance.ForceUnlock();
  936. }
  937. } // namespace __asan
  938. // --- Implementation of LSan-specific functions --- {{{1
  939. namespace __lsan {
  940. void LockAllocator() {
  941. __asan::get_allocator().ForceLock();
  942. }
  943. void UnlockAllocator() {
  944. __asan::get_allocator().ForceUnlock();
  945. }
  946. void GetAllocatorGlobalRange(uptr *begin, uptr *end) {
  947. *begin = (uptr)&__asan::get_allocator();
  948. *end = *begin + sizeof(__asan::get_allocator());
  949. }
  950. uptr PointsIntoChunk(void *p) {
  951. uptr addr = reinterpret_cast<uptr>(p);
  952. __asan::AsanChunk *m = __asan::instance.GetAsanChunkByAddrFastLocked(addr);
  953. if (!m || atomic_load(&m->chunk_state, memory_order_acquire) !=
  954. __asan::CHUNK_ALLOCATED)
  955. return 0;
  956. uptr chunk = m->Beg();
  957. if (m->AddrIsInside(addr))
  958. return chunk;
  959. if (IsSpecialCaseOfOperatorNew0(chunk, m->UsedSize(), addr))
  960. return chunk;
  961. return 0;
  962. }
  963. uptr GetUserBegin(uptr chunk) {
  964. __asan::AsanChunk *m = __asan::instance.GetAsanChunkByAddrFastLocked(chunk);
  965. return m ? m->Beg() : 0;
  966. }
  967. LsanMetadata::LsanMetadata(uptr chunk) {
  968. metadata_ = chunk ? reinterpret_cast<void *>(chunk - __asan::kChunkHeaderSize)
  969. : nullptr;
  970. }
  971. bool LsanMetadata::allocated() const {
  972. if (!metadata_)
  973. return false;
  974. __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
  975. return atomic_load(&m->chunk_state, memory_order_relaxed) ==
  976. __asan::CHUNK_ALLOCATED;
  977. }
  978. ChunkTag LsanMetadata::tag() const {
  979. __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
  980. return static_cast<ChunkTag>(m->lsan_tag);
  981. }
  982. void LsanMetadata::set_tag(ChunkTag value) {
  983. __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
  984. m->lsan_tag = value;
  985. }
  986. uptr LsanMetadata::requested_size() const {
  987. __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
  988. return m->UsedSize();
  989. }
  990. u32 LsanMetadata::stack_trace_id() const {
  991. __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
  992. u32 tid = 0;
  993. u32 stack = 0;
  994. m->GetAllocContext(tid, stack);
  995. return stack;
  996. }
  997. void ForEachChunk(ForEachChunkCallback callback, void *arg) {
  998. __asan::get_allocator().ForEachChunk(callback, arg);
  999. }
  1000. IgnoreObjectResult IgnoreObjectLocked(const void *p) {
  1001. uptr addr = reinterpret_cast<uptr>(p);
  1002. __asan::AsanChunk *m = __asan::instance.GetAsanChunkByAddr(addr);
  1003. if (!m ||
  1004. (atomic_load(&m->chunk_state, memory_order_acquire) !=
  1005. __asan::CHUNK_ALLOCATED) ||
  1006. !m->AddrIsInside(addr)) {
  1007. return kIgnoreObjectInvalid;
  1008. }
  1009. if (m->lsan_tag == kIgnored)
  1010. return kIgnoreObjectAlreadyIgnored;
  1011. m->lsan_tag = __lsan::kIgnored;
  1012. return kIgnoreObjectSuccess;
  1013. }
  1014. void GetAdditionalThreadContextPtrs(ThreadContextBase *tctx, void *ptrs) {
  1015. // Look for the arg pointer of threads that have been created or are running.
  1016. // This is necessary to prevent false positive leaks due to the AsanThread
  1017. // holding the only live reference to a heap object. This can happen because
  1018. // the `pthread_create()` interceptor doesn't wait for the child thread to
  1019. // start before returning and thus loosing the the only live reference to the
  1020. // heap object on the stack.
  1021. __asan::AsanThreadContext *atctx =
  1022. reinterpret_cast<__asan::AsanThreadContext *>(tctx);
  1023. __asan::AsanThread *asan_thread = atctx->thread;
  1024. // Note ThreadStatusRunning is required because there is a small window where
  1025. // the thread status switches to `ThreadStatusRunning` but the `arg` pointer
  1026. // still isn't on the stack yet.
  1027. if (atctx->status != ThreadStatusCreated &&
  1028. atctx->status != ThreadStatusRunning)
  1029. return;
  1030. uptr thread_arg = reinterpret_cast<uptr>(asan_thread->get_arg());
  1031. if (!thread_arg)
  1032. return;
  1033. auto ptrsVec = reinterpret_cast<InternalMmapVector<uptr> *>(ptrs);
  1034. ptrsVec->push_back(thread_arg);
  1035. }
  1036. } // namespace __lsan
  1037. // ---------------------- Interface ---------------- {{{1
  1038. using namespace __asan;
  1039. // ASan allocator doesn't reserve extra bytes, so normally we would
  1040. // just return "size". We don't want to expose our redzone sizes, etc here.
  1041. uptr __sanitizer_get_estimated_allocated_size(uptr size) {
  1042. return size;
  1043. }
  1044. int __sanitizer_get_ownership(const void *p) {
  1045. uptr ptr = reinterpret_cast<uptr>(p);
  1046. return instance.AllocationSize(ptr) > 0;
  1047. }
  1048. uptr __sanitizer_get_allocated_size(const void *p) {
  1049. if (!p) return 0;
  1050. uptr ptr = reinterpret_cast<uptr>(p);
  1051. uptr allocated_size = instance.AllocationSize(ptr);
  1052. // Die if p is not malloced or if it is already freed.
  1053. if (allocated_size == 0) {
  1054. GET_STACK_TRACE_FATAL_HERE;
  1055. ReportSanitizerGetAllocatedSizeNotOwned(ptr, &stack);
  1056. }
  1057. return allocated_size;
  1058. }
  1059. void __sanitizer_purge_allocator() {
  1060. GET_STACK_TRACE_MALLOC;
  1061. instance.Purge(&stack);
  1062. }
  1063. int __asan_update_allocation_context(void* addr) {
  1064. GET_STACK_TRACE_MALLOC;
  1065. return instance.UpdateAllocationStack((uptr)addr, &stack);
  1066. }
  1067. #if !SANITIZER_SUPPORTS_WEAK_HOOKS
  1068. // Provide default (no-op) implementation of malloc hooks.
  1069. SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_malloc_hook,
  1070. void *ptr, uptr size) {
  1071. (void)ptr;
  1072. (void)size;
  1073. }
  1074. SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_free_hook, void *ptr) {
  1075. (void)ptr;
  1076. }
  1077. #endif