1 //===-- asan_allocator.cc -------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of AddressSanitizer, an address sanity checker.
12 // Implementation of ASan's memory allocator, 2-nd version.
13 // This variant uses the allocator from sanitizer_common, i.e. the one shared
14 // with ThreadSanitizer and MemorySanitizer.
16 //===----------------------------------------------------------------------===//
18 #include "asan_allocator.h"
19 #include "asan_mapping.h"
20 #include "asan_poisoning.h"
21 #include "asan_report.h"
22 #include "asan_stack.h"
23 #include "asan_thread.h"
24 #include "sanitizer_common/sanitizer_allocator_checks.h"
25 #include "sanitizer_common/sanitizer_allocator_interface.h"
26 #include "sanitizer_common/sanitizer_errno.h"
27 #include "sanitizer_common/sanitizer_flags.h"
28 #include "sanitizer_common/sanitizer_internal_defs.h"
29 #include "sanitizer_common/sanitizer_list.h"
30 #include "sanitizer_common/sanitizer_stackdepot.h"
31 #include "sanitizer_common/sanitizer_quarantine.h"
32 #include "lsan/lsan_common.h"
36 // Valid redzone sizes are 16, 32, 64, ... 2048, so we encode them in 3 bits.
37 // We use adaptive redzones: for larger allocation larger redzones are used.
38 static u32 RZLog2Size(u32 rz_log) {
43 static u32 RZSize2Log(u32 rz_size) {
44 CHECK_GE(rz_size, 16);
45 CHECK_LE(rz_size, 2048);
46 CHECK(IsPowerOfTwo(rz_size));
47 u32 res = Log2(rz_size) - 4;
48 CHECK_EQ(rz_size, RZLog2Size(res));
52 static AsanAllocator &get_allocator();
54 // The memory chunk allocated from the underlying allocator looks like this:
55 // L L L L L L H H U U U U U U R R
56 // L -- left redzone words (0 or more bytes)
57 // H -- ChunkHeader (16 bytes), which is also a part of the left redzone.
59 // R -- right redzone (0 or more bytes)
60 // ChunkBase consists of ChunkHeader and other bytes that overlap with user
63 // If the left redzone is greater than the ChunkHeader size we store a magic
64 // value in the first uptr word of the memory block and store the address of
65 // ChunkBase in the next uptr.
66 // M B L L L L L L L L L H H U U U U U U
68 // ---------------------|
69 // M -- magic value kAllocBegMagic
70 // B -- address of ChunkHeader pointing to the first 'H'
71 static const uptr kAllocBegMagic = 0xCC6E96B9;
75 u32 chunk_state : 8; // Must be first.
79 u32 from_memalign : 1;
84 // This field is used for small sizes. For large sizes it is equal to
85 // SizeClassMap::kMaxSize and the actual size is stored in the
86 // SecondaryAllocator's metadata.
87 u32 user_requested_size : 29;
89 // else -> log2(min(align, 512)) - 2
90 u32 user_requested_alignment_log : 3;
94 struct ChunkBase : ChunkHeader {
95 // Header2, intersects with user memory.
99 static const uptr kChunkHeaderSize = sizeof(ChunkHeader);
100 static const uptr kChunkHeader2Size = sizeof(ChunkBase) - kChunkHeaderSize;
101 COMPILER_CHECK(kChunkHeaderSize == 16);
102 COMPILER_CHECK(kChunkHeader2Size <= 16);
104 // Every chunk of memory allocated by this allocator can be in one of 3 states:
105 // CHUNK_AVAILABLE: the chunk is in the free list and ready to be allocated.
106 // CHUNK_ALLOCATED: the chunk is allocated and not yet freed.
107 // CHUNK_QUARANTINE: the chunk was freed and put into quarantine zone.
109 CHUNK_AVAILABLE = 0, // 0 is the default value even if we didn't set it.
114 struct AsanChunk: ChunkBase {
115 uptr Beg() { return reinterpret_cast<uptr>(this) + kChunkHeaderSize; }
116 uptr UsedSize(bool locked_version = false) {
117 if (user_requested_size != SizeClassMap::kMaxSize)
118 return user_requested_size;
119 return *reinterpret_cast<uptr *>(
120 get_allocator().GetMetaData(AllocBeg(locked_version)));
122 void *AllocBeg(bool locked_version = false) {
125 return get_allocator().GetBlockBeginFastLocked(
126 reinterpret_cast<void *>(this));
127 return get_allocator().GetBlockBegin(reinterpret_cast<void *>(this));
129 return reinterpret_cast<void*>(Beg() - RZLog2Size(rz_log));
131 bool AddrIsInside(uptr addr, bool locked_version = false) {
132 return (addr >= Beg()) && (addr < Beg() + UsedSize(locked_version));
136 struct QuarantineCallback {
137 explicit QuarantineCallback(AllocatorCache *cache)
141 void Recycle(AsanChunk *m) {
142 CHECK_EQ(m->chunk_state, CHUNK_QUARANTINE);
143 atomic_store((atomic_uint8_t*)m, CHUNK_AVAILABLE, memory_order_relaxed);
144 CHECK_NE(m->alloc_tid, kInvalidTid);
145 CHECK_NE(m->free_tid, kInvalidTid);
146 PoisonShadow(m->Beg(),
147 RoundUpTo(m->UsedSize(), SHADOW_GRANULARITY),
148 kAsanHeapLeftRedzoneMagic);
149 void *p = reinterpret_cast<void *>(m->AllocBeg());
151 uptr *alloc_magic = reinterpret_cast<uptr *>(p);
152 CHECK_EQ(alloc_magic[0], kAllocBegMagic);
153 // Clear the magic value, as allocator internals may overwrite the
154 // contents of deallocated chunk, confusing GetAsanChunk lookup.
156 CHECK_EQ(alloc_magic[1], reinterpret_cast<uptr>(m));
160 AsanStats &thread_stats = GetCurrentThreadStats();
161 thread_stats.real_frees++;
162 thread_stats.really_freed += m->UsedSize();
164 get_allocator().Deallocate(cache_, p);
167 void *Allocate(uptr size) {
168 void *res = get_allocator().Allocate(cache_, size, 1);
169 // TODO(alekseys): Consider making quarantine OOM-friendly.
171 return DieOnFailure::OnOOM();
175 void Deallocate(void *p) {
176 get_allocator().Deallocate(cache_, p);
179 AllocatorCache *cache_;
182 typedef Quarantine<QuarantineCallback, AsanChunk> AsanQuarantine;
183 typedef AsanQuarantine::Cache QuarantineCache;
185 void AsanMapUnmapCallback::OnMap(uptr p, uptr size) const {
186 PoisonShadow(p, size, kAsanHeapLeftRedzoneMagic);
188 AsanStats &thread_stats = GetCurrentThreadStats();
189 thread_stats.mmaps++;
190 thread_stats.mmaped += size;
192 void AsanMapUnmapCallback::OnUnmap(uptr p, uptr size) const {
193 PoisonShadow(p, size, 0);
194 // We are about to unmap a chunk of user memory.
195 // Mark the corresponding shadow memory as not needed.
196 FlushUnneededASanShadowMemory(p, size);
198 AsanStats &thread_stats = GetCurrentThreadStats();
199 thread_stats.munmaps++;
200 thread_stats.munmaped += size;
203 // We can not use THREADLOCAL because it is not supported on some of the
204 // platforms we care about (OSX 10.6, Android).
205 // static THREADLOCAL AllocatorCache cache;
206 AllocatorCache *GetAllocatorCache(AsanThreadLocalMallocStorage *ms) {
208 return &ms->allocator_cache;
211 QuarantineCache *GetQuarantineCache(AsanThreadLocalMallocStorage *ms) {
213 CHECK_LE(sizeof(QuarantineCache), sizeof(ms->quarantine_cache));
214 return reinterpret_cast<QuarantineCache *>(ms->quarantine_cache);
217 void AllocatorOptions::SetFrom(const Flags *f, const CommonFlags *cf) {
218 quarantine_size_mb = f->quarantine_size_mb;
219 thread_local_quarantine_size_kb = f->thread_local_quarantine_size_kb;
220 min_redzone = f->redzone;
221 max_redzone = f->max_redzone;
222 may_return_null = cf->allocator_may_return_null;
223 alloc_dealloc_mismatch = f->alloc_dealloc_mismatch;
224 release_to_os_interval_ms = cf->allocator_release_to_os_interval_ms;
227 void AllocatorOptions::CopyTo(Flags *f, CommonFlags *cf) {
228 f->quarantine_size_mb = quarantine_size_mb;
229 f->thread_local_quarantine_size_kb = thread_local_quarantine_size_kb;
230 f->redzone = min_redzone;
231 f->max_redzone = max_redzone;
232 cf->allocator_may_return_null = may_return_null;
233 f->alloc_dealloc_mismatch = alloc_dealloc_mismatch;
234 cf->allocator_release_to_os_interval_ms = release_to_os_interval_ms;
238 static const uptr kMaxAllowedMallocSize =
239 FIRST_32_SECOND_64(3UL << 30, 1ULL << 40);
241 AsanAllocator allocator;
242 AsanQuarantine quarantine;
243 StaticSpinMutex fallback_mutex;
244 AllocatorCache fallback_allocator_cache;
245 QuarantineCache fallback_quarantine_cache;
247 atomic_uint8_t rss_limit_exceeded;
249 // ------------------- Options --------------------------
250 atomic_uint16_t min_redzone;
251 atomic_uint16_t max_redzone;
252 atomic_uint8_t alloc_dealloc_mismatch;
254 // ------------------- Initialization ------------------------
255 explicit Allocator(LinkerInitialized)
256 : quarantine(LINKER_INITIALIZED),
257 fallback_quarantine_cache(LINKER_INITIALIZED) {}
259 void CheckOptions(const AllocatorOptions &options) const {
260 CHECK_GE(options.min_redzone, 16);
261 CHECK_GE(options.max_redzone, options.min_redzone);
262 CHECK_LE(options.max_redzone, 2048);
263 CHECK(IsPowerOfTwo(options.min_redzone));
264 CHECK(IsPowerOfTwo(options.max_redzone));
267 void SharedInitCode(const AllocatorOptions &options) {
268 CheckOptions(options);
269 quarantine.Init((uptr)options.quarantine_size_mb << 20,
270 (uptr)options.thread_local_quarantine_size_kb << 10);
271 atomic_store(&alloc_dealloc_mismatch, options.alloc_dealloc_mismatch,
272 memory_order_release);
273 atomic_store(&min_redzone, options.min_redzone, memory_order_release);
274 atomic_store(&max_redzone, options.max_redzone, memory_order_release);
277 void InitLinkerInitialized(const AllocatorOptions &options) {
278 SetAllocatorMayReturnNull(options.may_return_null);
279 allocator.InitLinkerInitialized(options.release_to_os_interval_ms);
280 SharedInitCode(options);
283 bool RssLimitExceeded() {
284 return atomic_load(&rss_limit_exceeded, memory_order_relaxed);
287 void SetRssLimitExceeded(bool limit_exceeded) {
288 atomic_store(&rss_limit_exceeded, limit_exceeded, memory_order_relaxed);
291 void RePoisonChunk(uptr chunk) {
292 // This could be a user-facing chunk (with redzones), or some internal
293 // housekeeping chunk, like TransferBatch. Start by assuming the former.
294 AsanChunk *ac = GetAsanChunk((void *)chunk);
295 uptr allocated_size = allocator.GetActuallyAllocatedSize((void *)ac);
296 uptr beg = ac->Beg();
297 uptr end = ac->Beg() + ac->UsedSize(true);
298 uptr chunk_end = chunk + allocated_size;
299 if (chunk < beg && beg < end && end <= chunk_end &&
300 ac->chunk_state == CHUNK_ALLOCATED) {
301 // Looks like a valid AsanChunk in use, poison redzones only.
302 PoisonShadow(chunk, beg - chunk, kAsanHeapLeftRedzoneMagic);
303 uptr end_aligned_down = RoundDownTo(end, SHADOW_GRANULARITY);
304 FastPoisonShadowPartialRightRedzone(
305 end_aligned_down, end - end_aligned_down,
306 chunk_end - end_aligned_down, kAsanHeapLeftRedzoneMagic);
308 // This is either not an AsanChunk or freed or quarantined AsanChunk.
309 // In either case, poison everything.
310 PoisonShadow(chunk, allocated_size, kAsanHeapLeftRedzoneMagic);
314 void ReInitialize(const AllocatorOptions &options) {
315 SetAllocatorMayReturnNull(options.may_return_null);
316 allocator.SetReleaseToOSIntervalMs(options.release_to_os_interval_ms);
317 SharedInitCode(options);
319 // Poison all existing allocation's redzones.
320 if (CanPoisonMemory()) {
321 allocator.ForceLock();
322 allocator.ForEachChunk(
323 [](uptr chunk, void *alloc) {
324 ((Allocator *)alloc)->RePoisonChunk(chunk);
327 allocator.ForceUnlock();
331 void GetOptions(AllocatorOptions *options) const {
332 options->quarantine_size_mb = quarantine.GetSize() >> 20;
333 options->thread_local_quarantine_size_kb = quarantine.GetCacheSize() >> 10;
334 options->min_redzone = atomic_load(&min_redzone, memory_order_acquire);
335 options->max_redzone = atomic_load(&max_redzone, memory_order_acquire);
336 options->may_return_null = AllocatorMayReturnNull();
337 options->alloc_dealloc_mismatch =
338 atomic_load(&alloc_dealloc_mismatch, memory_order_acquire);
339 options->release_to_os_interval_ms = allocator.ReleaseToOSIntervalMs();
342 // -------------------- Helper methods. -------------------------
343 uptr ComputeRZLog(uptr user_requested_size) {
345 user_requested_size <= 64 - 16 ? 0 :
346 user_requested_size <= 128 - 32 ? 1 :
347 user_requested_size <= 512 - 64 ? 2 :
348 user_requested_size <= 4096 - 128 ? 3 :
349 user_requested_size <= (1 << 14) - 256 ? 4 :
350 user_requested_size <= (1 << 15) - 512 ? 5 :
351 user_requested_size <= (1 << 16) - 1024 ? 6 : 7;
352 u32 min_rz = atomic_load(&min_redzone, memory_order_acquire);
353 u32 max_rz = atomic_load(&max_redzone, memory_order_acquire);
354 return Min(Max(rz_log, RZSize2Log(min_rz)), RZSize2Log(max_rz));
357 static uptr ComputeUserRequestedAlignmentLog(uptr user_requested_alignment) {
358 if (user_requested_alignment < 8)
360 if (user_requested_alignment > 512)
361 user_requested_alignment = 512;
362 return Log2(user_requested_alignment) - 2;
365 static uptr ComputeUserAlignment(uptr user_requested_alignment_log) {
366 if (user_requested_alignment_log == 0)
368 return 1LL << (user_requested_alignment_log + 2);
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 // Prefer an allocated chunk over freed chunk and freed chunk
375 // over available chunk.
376 if (left_chunk->chunk_state != right_chunk->chunk_state) {
377 if (left_chunk->chunk_state == CHUNK_ALLOCATED)
379 if (right_chunk->chunk_state == CHUNK_ALLOCATED)
381 if (left_chunk->chunk_state == CHUNK_QUARANTINE)
383 if (right_chunk->chunk_state == CHUNK_QUARANTINE)
386 // Same chunk_state: choose based on offset.
387 sptr l_offset = 0, r_offset = 0;
388 CHECK(AsanChunkView(left_chunk).AddrIsAtRight(addr, 1, &l_offset));
389 CHECK(AsanChunkView(right_chunk).AddrIsAtLeft(addr, 1, &r_offset));
390 if (l_offset < r_offset)
395 // -------------------- Allocation/Deallocation routines ---------------
396 void *Allocate(uptr size, uptr alignment, BufferedStackTrace *stack,
397 AllocType alloc_type, bool can_fill) {
398 if (UNLIKELY(!asan_inited))
400 if (RssLimitExceeded())
401 return AsanAllocator::FailureHandler::OnOOM();
402 Flags &fl = *flags();
404 const uptr min_alignment = SHADOW_GRANULARITY;
405 const uptr user_requested_alignment_log =
406 ComputeUserRequestedAlignmentLog(alignment);
407 if (alignment < min_alignment)
408 alignment = min_alignment;
410 // We'd be happy to avoid allocating memory for zero-size requests, but
411 // some programs/tests depend on this behavior and assume that malloc
412 // would not return NULL even for zero-size allocations. Moreover, it
413 // looks like operator new should never return NULL, and results of
414 // consecutive "new" calls must be different even if the allocated size
418 CHECK(IsPowerOfTwo(alignment));
419 uptr rz_log = ComputeRZLog(size);
420 uptr rz_size = RZLog2Size(rz_log);
421 uptr rounded_size = RoundUpTo(Max(size, kChunkHeader2Size), alignment);
422 uptr needed_size = rounded_size + rz_size;
423 if (alignment > min_alignment)
424 needed_size += alignment;
425 bool using_primary_allocator = true;
426 // If we are allocating from the secondary allocator, there will be no
427 // automatic right redzone, so add the right redzone manually.
428 if (!PrimaryAllocator::CanAllocate(needed_size, alignment)) {
429 needed_size += rz_size;
430 using_primary_allocator = false;
432 CHECK(IsAligned(needed_size, min_alignment));
433 if (size > kMaxAllowedMallocSize || needed_size > kMaxAllowedMallocSize) {
434 Report("WARNING: AddressSanitizer failed to allocate 0x%zx bytes\n",
436 return AsanAllocator::FailureHandler::OnBadRequest();
439 AsanThread *t = GetCurrentThread();
442 AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
443 allocated = allocator.Allocate(cache, needed_size, 8);
445 SpinMutexLock l(&fallback_mutex);
446 AllocatorCache *cache = &fallback_allocator_cache;
447 allocated = allocator.Allocate(cache, needed_size, 8);
452 if (*(u8 *)MEM_TO_SHADOW((uptr)allocated) == 0 && CanPoisonMemory()) {
453 // Heap poisoning is enabled, but the allocator provides an unpoisoned
454 // chunk. This is possible if CanPoisonMemory() was false for some
455 // time, for example, due to flags()->start_disabled.
456 // Anyway, poison the block before using it for anything else.
457 uptr allocated_size = allocator.GetActuallyAllocatedSize(allocated);
458 PoisonShadow((uptr)allocated, allocated_size, kAsanHeapLeftRedzoneMagic);
461 uptr alloc_beg = reinterpret_cast<uptr>(allocated);
462 uptr alloc_end = alloc_beg + needed_size;
463 uptr beg_plus_redzone = alloc_beg + rz_size;
464 uptr user_beg = beg_plus_redzone;
465 if (!IsAligned(user_beg, alignment))
466 user_beg = RoundUpTo(user_beg, alignment);
467 uptr user_end = user_beg + size;
468 CHECK_LE(user_end, alloc_end);
469 uptr chunk_beg = user_beg - kChunkHeaderSize;
470 AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
471 m->alloc_type = alloc_type;
473 u32 alloc_tid = t ? t->tid() : 0;
474 m->alloc_tid = alloc_tid;
475 CHECK_EQ(alloc_tid, m->alloc_tid); // Does alloc_tid fit into the bitfield?
476 m->free_tid = kInvalidTid;
477 m->from_memalign = user_beg != beg_plus_redzone;
478 if (alloc_beg != chunk_beg) {
479 CHECK_LE(alloc_beg+ 2 * sizeof(uptr), chunk_beg);
480 reinterpret_cast<uptr *>(alloc_beg)[0] = kAllocBegMagic;
481 reinterpret_cast<uptr *>(alloc_beg)[1] = chunk_beg;
483 if (using_primary_allocator) {
485 m->user_requested_size = size;
486 CHECK(allocator.FromPrimary(allocated));
488 CHECK(!allocator.FromPrimary(allocated));
489 m->user_requested_size = SizeClassMap::kMaxSize;
490 uptr *meta = reinterpret_cast<uptr *>(allocator.GetMetaData(allocated));
494 m->user_requested_alignment_log = user_requested_alignment_log;
496 m->alloc_context_id = StackDepotPut(*stack);
498 uptr size_rounded_down_to_granularity =
499 RoundDownTo(size, 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()) {
506 (u8 *)MemToShadow(user_beg + size_rounded_down_to_granularity);
507 *shadow = fl.poison_partial ? (size & (SHADOW_GRANULARITY - 1)) : 0;
510 AsanStats &thread_stats = GetCurrentThreadStats();
511 thread_stats.mallocs++;
512 thread_stats.malloced += size;
513 thread_stats.malloced_redzones += needed_size - size;
514 if (needed_size > SizeClassMap::kMaxSize)
515 thread_stats.malloc_large++;
517 thread_stats.malloced_by_size[SizeClassMap::ClassID(needed_size)]++;
519 void *res = reinterpret_cast<void *>(user_beg);
520 if (can_fill && fl.max_malloc_fill_size) {
521 uptr fill_size = Min(size, (uptr)fl.max_malloc_fill_size);
522 REAL(memset)(res, fl.malloc_fill_byte, fill_size);
524 #if CAN_SANITIZE_LEAKS
525 m->lsan_tag = __lsan::DisabledInThisThread() ? __lsan::kIgnored
526 : __lsan::kDirectlyLeaked;
528 // Must be the last mutation of metadata in this function.
529 atomic_store((atomic_uint8_t *)m, CHUNK_ALLOCATED, memory_order_release);
530 ASAN_MALLOC_HOOK(res, size);
534 // Set quarantine flag if chunk is allocated, issue ASan error report on
535 // available and quarantined chunks. Return true on success, false otherwise.
536 bool AtomicallySetQuarantineFlagIfAllocated(AsanChunk *m, void *ptr,
537 BufferedStackTrace *stack) {
538 u8 old_chunk_state = CHUNK_ALLOCATED;
539 // Flip the chunk_state atomically to avoid race on double-free.
540 if (!atomic_compare_exchange_strong((atomic_uint8_t *)m, &old_chunk_state,
542 memory_order_acquire)) {
543 ReportInvalidFree(ptr, old_chunk_state, stack);
544 // It's not safe to push a chunk in quarantine on invalid free.
547 CHECK_EQ(CHUNK_ALLOCATED, old_chunk_state);
551 // Expects the chunk to already be marked as quarantined by using
552 // AtomicallySetQuarantineFlagIfAllocated.
553 void QuarantineChunk(AsanChunk *m, void *ptr, BufferedStackTrace *stack) {
554 CHECK_EQ(m->chunk_state, CHUNK_QUARANTINE);
555 CHECK_GE(m->alloc_tid, 0);
556 if (SANITIZER_WORDSIZE == 64) // On 32-bits this resides in user area.
557 CHECK_EQ(m->free_tid, kInvalidTid);
558 AsanThread *t = GetCurrentThread();
559 m->free_tid = t ? t->tid() : 0;
560 m->free_context_id = StackDepotPut(*stack);
562 Flags &fl = *flags();
563 if (fl.max_free_fill_size > 0) {
564 // We have to skip the chunk header, it contains free_context_id.
565 uptr scribble_start = (uptr)m + kChunkHeaderSize + kChunkHeader2Size;
566 if (m->UsedSize() >= kChunkHeader2Size) { // Skip Header2 in user area.
567 uptr size_to_fill = m->UsedSize() - kChunkHeader2Size;
568 size_to_fill = Min(size_to_fill, (uptr)fl.max_free_fill_size);
569 REAL(memset)((void *)scribble_start, fl.free_fill_byte, size_to_fill);
573 // Poison the region.
574 PoisonShadow(m->Beg(),
575 RoundUpTo(m->UsedSize(), SHADOW_GRANULARITY),
578 AsanStats &thread_stats = GetCurrentThreadStats();
579 thread_stats.frees++;
580 thread_stats.freed += m->UsedSize();
582 // Push into quarantine.
584 AsanThreadLocalMallocStorage *ms = &t->malloc_storage();
585 AllocatorCache *ac = GetAllocatorCache(ms);
586 quarantine.Put(GetQuarantineCache(ms), QuarantineCallback(ac), m,
589 SpinMutexLock l(&fallback_mutex);
590 AllocatorCache *ac = &fallback_allocator_cache;
591 quarantine.Put(&fallback_quarantine_cache, QuarantineCallback(ac), m,
596 void Deallocate(void *ptr, uptr delete_size, uptr delete_alignment,
597 BufferedStackTrace *stack, AllocType alloc_type) {
598 uptr p = reinterpret_cast<uptr>(ptr);
601 uptr chunk_beg = p - kChunkHeaderSize;
602 AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
604 // On Windows, uninstrumented DLLs may allocate memory before ASan hooks
605 // malloc. Don't report an invalid free in this case.
606 if (SANITIZER_WINDOWS &&
607 !get_allocator().PointerIsMine(ptr)) {
608 if (!IsSystemHeapAddress(p))
609 ReportFreeNotMalloced(p, stack);
615 // Must mark the chunk as quarantined before any changes to its metadata.
616 // Do not quarantine given chunk if we failed to set CHUNK_QUARANTINE flag.
617 if (!AtomicallySetQuarantineFlagIfAllocated(m, ptr, stack)) return;
619 if (m->alloc_type != alloc_type) {
620 if (atomic_load(&alloc_dealloc_mismatch, memory_order_acquire)) {
621 ReportAllocTypeMismatch((uptr)ptr, stack, (AllocType)m->alloc_type,
622 (AllocType)alloc_type);
625 if (flags()->new_delete_type_mismatch &&
626 (alloc_type == FROM_NEW || alloc_type == FROM_NEW_BR) &&
627 ((delete_size && delete_size != m->UsedSize()) ||
628 ComputeUserRequestedAlignmentLog(delete_alignment) !=
629 m->user_requested_alignment_log)) {
630 ReportNewDeleteTypeMismatch(p, delete_size, delete_alignment, stack);
634 QuarantineChunk(m, ptr, stack);
637 void *Reallocate(void *old_ptr, uptr new_size, BufferedStackTrace *stack) {
638 CHECK(old_ptr && new_size);
639 uptr p = reinterpret_cast<uptr>(old_ptr);
640 uptr chunk_beg = p - kChunkHeaderSize;
641 AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
643 AsanStats &thread_stats = GetCurrentThreadStats();
644 thread_stats.reallocs++;
645 thread_stats.realloced += new_size;
647 void *new_ptr = Allocate(new_size, 8, stack, FROM_MALLOC, true);
649 u8 chunk_state = m->chunk_state;
650 if (chunk_state != CHUNK_ALLOCATED)
651 ReportInvalidFree(old_ptr, chunk_state, stack);
652 CHECK_NE(REAL(memcpy), nullptr);
653 uptr memcpy_size = Min(new_size, m->UsedSize());
654 // If realloc() races with free(), we may start copying freed memory.
655 // However, we will report racy double-free later anyway.
656 REAL(memcpy)(new_ptr, old_ptr, memcpy_size);
657 Deallocate(old_ptr, 0, 0, stack, FROM_MALLOC);
662 void *Calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) {
663 if (CheckForCallocOverflow(size, nmemb))
664 return AsanAllocator::FailureHandler::OnBadRequest();
665 void *ptr = Allocate(nmemb * size, 8, stack, FROM_MALLOC, false);
666 // If the memory comes from the secondary allocator no need to clear it
667 // as it comes directly from mmap.
668 if (ptr && allocator.FromPrimary(ptr))
669 REAL(memset)(ptr, 0, nmemb * size);
673 void ReportInvalidFree(void *ptr, u8 chunk_state, BufferedStackTrace *stack) {
674 if (chunk_state == CHUNK_QUARANTINE)
675 ReportDoubleFree((uptr)ptr, stack);
677 ReportFreeNotMalloced((uptr)ptr, stack);
680 void CommitBack(AsanThreadLocalMallocStorage *ms) {
681 AllocatorCache *ac = GetAllocatorCache(ms);
682 quarantine.Drain(GetQuarantineCache(ms), QuarantineCallback(ac));
683 allocator.SwallowCache(ac);
686 // -------------------------- Chunk lookup ----------------------
688 // Assumes alloc_beg == allocator.GetBlockBegin(alloc_beg).
689 AsanChunk *GetAsanChunk(void *alloc_beg) {
690 if (!alloc_beg) return nullptr;
691 if (!allocator.FromPrimary(alloc_beg)) {
692 uptr *meta = reinterpret_cast<uptr *>(allocator.GetMetaData(alloc_beg));
693 AsanChunk *m = reinterpret_cast<AsanChunk *>(meta[1]);
696 uptr *alloc_magic = reinterpret_cast<uptr *>(alloc_beg);
697 if (alloc_magic[0] == kAllocBegMagic)
698 return reinterpret_cast<AsanChunk *>(alloc_magic[1]);
699 return reinterpret_cast<AsanChunk *>(alloc_beg);
702 AsanChunk *GetAsanChunkByAddr(uptr p) {
703 void *alloc_beg = allocator.GetBlockBegin(reinterpret_cast<void *>(p));
704 return GetAsanChunk(alloc_beg);
707 // Allocator must be locked when this function is called.
708 AsanChunk *GetAsanChunkByAddrFastLocked(uptr p) {
710 allocator.GetBlockBeginFastLocked(reinterpret_cast<void *>(p));
711 return GetAsanChunk(alloc_beg);
714 uptr AllocationSize(uptr p) {
715 AsanChunk *m = GetAsanChunkByAddr(p);
717 if (m->chunk_state != CHUNK_ALLOCATED) return 0;
718 if (m->Beg() != p) return 0;
719 return m->UsedSize();
722 AsanChunkView FindHeapChunkByAddress(uptr addr) {
723 AsanChunk *m1 = GetAsanChunkByAddr(addr);
724 if (!m1) return AsanChunkView(m1);
726 if (AsanChunkView(m1).AddrIsAtLeft(addr, 1, &offset)) {
727 // The address is in the chunk's left redzone, so maybe it is actually
728 // a right buffer overflow from the other chunk to the left.
729 // Search a bit to the left to see if there is another chunk.
730 AsanChunk *m2 = nullptr;
731 for (uptr l = 1; l < GetPageSizeCached(); l++) {
732 m2 = GetAsanChunkByAddr(addr - l);
733 if (m2 == m1) continue; // Still the same chunk.
736 if (m2 && AsanChunkView(m2).AddrIsAtRight(addr, 1, &offset))
737 m1 = ChooseChunk(addr, m2, m1);
739 return AsanChunkView(m1);
743 AsanThread *t = GetCurrentThread();
745 AsanThreadLocalMallocStorage *ms = &t->malloc_storage();
746 quarantine.DrainAndRecycle(GetQuarantineCache(ms),
747 QuarantineCallback(GetAllocatorCache(ms)));
750 SpinMutexLock l(&fallback_mutex);
751 quarantine.DrainAndRecycle(&fallback_quarantine_cache,
752 QuarantineCallback(&fallback_allocator_cache));
755 allocator.ForceReleaseToOS();
759 allocator.PrintStats();
760 quarantine.PrintStats();
764 allocator.ForceLock();
765 fallback_mutex.Lock();
769 fallback_mutex.Unlock();
770 allocator.ForceUnlock();
774 static Allocator instance(LINKER_INITIALIZED);
776 static AsanAllocator &get_allocator() {
777 return instance.allocator;
780 bool AsanChunkView::IsValid() const {
781 return chunk_ && chunk_->chunk_state != CHUNK_AVAILABLE;
783 bool AsanChunkView::IsAllocated() const {
784 return chunk_ && chunk_->chunk_state == CHUNK_ALLOCATED;
786 bool AsanChunkView::IsQuarantined() const {
787 return chunk_ && chunk_->chunk_state == CHUNK_QUARANTINE;
789 uptr AsanChunkView::Beg() const { return chunk_->Beg(); }
790 uptr AsanChunkView::End() const { return Beg() + UsedSize(); }
791 uptr AsanChunkView::UsedSize() const { return chunk_->UsedSize(); }
792 u32 AsanChunkView::UserRequestedAlignment() const {
793 return Allocator::ComputeUserAlignment(chunk_->user_requested_alignment_log);
795 uptr AsanChunkView::AllocTid() const { return chunk_->alloc_tid; }
796 uptr AsanChunkView::FreeTid() const { return chunk_->free_tid; }
797 AllocType AsanChunkView::GetAllocType() const {
798 return (AllocType)chunk_->alloc_type;
801 static StackTrace GetStackTraceFromId(u32 id) {
803 StackTrace res = StackDepotGet(id);
808 u32 AsanChunkView::GetAllocStackId() const { return chunk_->alloc_context_id; }
809 u32 AsanChunkView::GetFreeStackId() const { return chunk_->free_context_id; }
811 StackTrace AsanChunkView::GetAllocStack() const {
812 return GetStackTraceFromId(GetAllocStackId());
815 StackTrace AsanChunkView::GetFreeStack() const {
816 return GetStackTraceFromId(GetFreeStackId());
819 void InitializeAllocator(const AllocatorOptions &options) {
820 instance.InitLinkerInitialized(options);
823 void ReInitializeAllocator(const AllocatorOptions &options) {
824 instance.ReInitialize(options);
827 void GetAllocatorOptions(AllocatorOptions *options) {
828 instance.GetOptions(options);
831 AsanChunkView FindHeapChunkByAddress(uptr addr) {
832 return instance.FindHeapChunkByAddress(addr);
834 AsanChunkView FindHeapChunkByAllocBeg(uptr addr) {
835 return AsanChunkView(instance.GetAsanChunk(reinterpret_cast<void*>(addr)));
838 void AsanThreadLocalMallocStorage::CommitBack() {
839 instance.CommitBack(this);
842 void PrintInternalAllocatorStats() {
843 instance.PrintStats();
846 void asan_free(void *ptr, BufferedStackTrace *stack, AllocType alloc_type) {
847 instance.Deallocate(ptr, 0, 0, stack, alloc_type);
850 void asan_delete(void *ptr, uptr size, uptr alignment,
851 BufferedStackTrace *stack, AllocType alloc_type) {
852 instance.Deallocate(ptr, size, alignment, stack, alloc_type);
855 void *asan_malloc(uptr size, BufferedStackTrace *stack) {
856 return SetErrnoOnNull(instance.Allocate(size, 8, stack, FROM_MALLOC, true));
859 void *asan_calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) {
860 return SetErrnoOnNull(instance.Calloc(nmemb, size, stack));
863 void *asan_realloc(void *p, uptr size, BufferedStackTrace *stack) {
865 return SetErrnoOnNull(instance.Allocate(size, 8, stack, FROM_MALLOC, true));
867 if (flags()->allocator_frees_and_returns_null_on_realloc_zero) {
868 instance.Deallocate(p, 0, 0, stack, FROM_MALLOC);
871 // Allocate a size of 1 if we shouldn't free() on Realloc to 0
874 return SetErrnoOnNull(instance.Reallocate(p, size, stack));
877 void *asan_valloc(uptr size, BufferedStackTrace *stack) {
878 return SetErrnoOnNull(
879 instance.Allocate(size, GetPageSizeCached(), stack, FROM_MALLOC, true));
882 void *asan_pvalloc(uptr size, BufferedStackTrace *stack) {
883 uptr PageSize = GetPageSizeCached();
884 if (UNLIKELY(CheckForPvallocOverflow(size, PageSize))) {
885 errno = errno_ENOMEM;
886 return AsanAllocator::FailureHandler::OnBadRequest();
888 // pvalloc(0) should allocate one page.
889 size = size ? RoundUpTo(size, PageSize) : PageSize;
890 return SetErrnoOnNull(
891 instance.Allocate(size, PageSize, stack, FROM_MALLOC, true));
894 void *asan_memalign(uptr alignment, uptr size, BufferedStackTrace *stack,
895 AllocType alloc_type) {
896 if (UNLIKELY(!IsPowerOfTwo(alignment))) {
897 errno = errno_EINVAL;
898 return AsanAllocator::FailureHandler::OnBadRequest();
900 return SetErrnoOnNull(
901 instance.Allocate(size, alignment, stack, alloc_type, true));
904 int asan_posix_memalign(void **memptr, uptr alignment, uptr size,
905 BufferedStackTrace *stack) {
906 if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) {
907 AsanAllocator::FailureHandler::OnBadRequest();
910 void *ptr = instance.Allocate(size, alignment, stack, FROM_MALLOC, true);
913 CHECK(IsAligned((uptr)ptr, alignment));
918 uptr asan_malloc_usable_size(const void *ptr, uptr pc, uptr bp) {
920 uptr usable_size = instance.AllocationSize(reinterpret_cast<uptr>(ptr));
921 if (flags()->check_malloc_usable_size && (usable_size == 0)) {
922 GET_STACK_TRACE_FATAL(pc, bp);
923 ReportMallocUsableSizeNotOwned((uptr)ptr, &stack);
928 uptr asan_mz_size(const void *ptr) {
929 return instance.AllocationSize(reinterpret_cast<uptr>(ptr));
932 void asan_mz_force_lock() {
933 instance.ForceLock();
936 void asan_mz_force_unlock() {
937 instance.ForceUnlock();
940 void AsanSoftRssLimitExceededCallback(bool limit_exceeded) {
941 instance.SetRssLimitExceeded(limit_exceeded);
944 } // namespace __asan
946 // --- Implementation of LSan-specific functions --- {{{1
948 void LockAllocator() {
949 __asan::get_allocator().ForceLock();
952 void UnlockAllocator() {
953 __asan::get_allocator().ForceUnlock();
956 void GetAllocatorGlobalRange(uptr *begin, uptr *end) {
957 *begin = (uptr)&__asan::get_allocator();
958 *end = *begin + sizeof(__asan::get_allocator());
961 uptr PointsIntoChunk(void* p) {
962 uptr addr = reinterpret_cast<uptr>(p);
963 __asan::AsanChunk *m = __asan::instance.GetAsanChunkByAddrFastLocked(addr);
965 uptr chunk = m->Beg();
966 if (m->chunk_state != __asan::CHUNK_ALLOCATED)
968 if (m->AddrIsInside(addr, /*locked_version=*/true))
970 if (IsSpecialCaseOfOperatorNew0(chunk, m->UsedSize(/*locked_version*/ true),
976 uptr GetUserBegin(uptr chunk) {
977 __asan::AsanChunk *m = __asan::instance.GetAsanChunkByAddrFastLocked(chunk);
982 LsanMetadata::LsanMetadata(uptr chunk) {
983 metadata_ = reinterpret_cast<void *>(chunk - __asan::kChunkHeaderSize);
986 bool LsanMetadata::allocated() const {
987 __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
988 return m->chunk_state == __asan::CHUNK_ALLOCATED;
991 ChunkTag LsanMetadata::tag() const {
992 __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
993 return static_cast<ChunkTag>(m->lsan_tag);
996 void LsanMetadata::set_tag(ChunkTag value) {
997 __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
1001 uptr LsanMetadata::requested_size() const {
1002 __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
1003 return m->UsedSize(/*locked_version=*/true);
1006 u32 LsanMetadata::stack_trace_id() const {
1007 __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
1008 return m->alloc_context_id;
1011 void ForEachChunk(ForEachChunkCallback callback, void *arg) {
1012 __asan::get_allocator().ForEachChunk(callback, arg);
1015 IgnoreObjectResult IgnoreObjectLocked(const void *p) {
1016 uptr addr = reinterpret_cast<uptr>(p);
1017 __asan::AsanChunk *m = __asan::instance.GetAsanChunkByAddr(addr);
1018 if (!m) return kIgnoreObjectInvalid;
1019 if ((m->chunk_state == __asan::CHUNK_ALLOCATED) && m->AddrIsInside(addr)) {
1020 if (m->lsan_tag == kIgnored)
1021 return kIgnoreObjectAlreadyIgnored;
1022 m->lsan_tag = __lsan::kIgnored;
1023 return kIgnoreObjectSuccess;
1025 return kIgnoreObjectInvalid;
1028 } // namespace __lsan
1030 // ---------------------- Interface ---------------- {{{1
1031 using namespace __asan; // NOLINT
1033 // ASan allocator doesn't reserve extra bytes, so normally we would
1034 // just return "size". We don't want to expose our redzone sizes, etc here.
1035 uptr __sanitizer_get_estimated_allocated_size(uptr size) {
1039 int __sanitizer_get_ownership(const void *p) {
1040 uptr ptr = reinterpret_cast<uptr>(p);
1041 return instance.AllocationSize(ptr) > 0;
1044 uptr __sanitizer_get_allocated_size(const void *p) {
1046 uptr ptr = reinterpret_cast<uptr>(p);
1047 uptr allocated_size = instance.AllocationSize(ptr);
1048 // Die if p is not malloced or if it is already freed.
1049 if (allocated_size == 0) {
1050 GET_STACK_TRACE_FATAL_HERE;
1051 ReportSanitizerGetAllocatedSizeNotOwned(ptr, &stack);
1053 return allocated_size;
1056 void __sanitizer_purge_allocator() {
1060 #if !SANITIZER_SUPPORTS_WEAK_HOOKS
1061 // Provide default (no-op) implementation of malloc hooks.
1062 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_malloc_hook,
1063 void *ptr, uptr size) {
1068 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_free_hook, void *ptr) {