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;
91 struct ChunkBase : ChunkHeader {
92 // Header2, intersects with user memory.
96 static const uptr kChunkHeaderSize = sizeof(ChunkHeader);
97 static const uptr kChunkHeader2Size = sizeof(ChunkBase) - kChunkHeaderSize;
98 COMPILER_CHECK(kChunkHeaderSize == 16);
99 COMPILER_CHECK(kChunkHeader2Size <= 16);
101 // Every chunk of memory allocated by this allocator can be in one of 3 states:
102 // CHUNK_AVAILABLE: the chunk is in the free list and ready to be allocated.
103 // CHUNK_ALLOCATED: the chunk is allocated and not yet freed.
104 // CHUNK_QUARANTINE: the chunk was freed and put into quarantine zone.
106 CHUNK_AVAILABLE = 0, // 0 is the default value even if we didn't set it.
111 struct AsanChunk: ChunkBase {
112 uptr Beg() { return reinterpret_cast<uptr>(this) + kChunkHeaderSize; }
113 uptr UsedSize(bool locked_version = false) {
114 if (user_requested_size != SizeClassMap::kMaxSize)
115 return user_requested_size;
116 return *reinterpret_cast<uptr *>(
117 get_allocator().GetMetaData(AllocBeg(locked_version)));
119 void *AllocBeg(bool locked_version = false) {
122 return get_allocator().GetBlockBeginFastLocked(
123 reinterpret_cast<void *>(this));
124 return get_allocator().GetBlockBegin(reinterpret_cast<void *>(this));
126 return reinterpret_cast<void*>(Beg() - RZLog2Size(rz_log));
128 bool AddrIsInside(uptr addr, bool locked_version = false) {
129 return (addr >= Beg()) && (addr < Beg() + UsedSize(locked_version));
133 struct QuarantineCallback {
134 explicit QuarantineCallback(AllocatorCache *cache)
138 void Recycle(AsanChunk *m) {
139 CHECK_EQ(m->chunk_state, CHUNK_QUARANTINE);
140 atomic_store((atomic_uint8_t*)m, CHUNK_AVAILABLE, memory_order_relaxed);
141 CHECK_NE(m->alloc_tid, kInvalidTid);
142 CHECK_NE(m->free_tid, kInvalidTid);
143 PoisonShadow(m->Beg(),
144 RoundUpTo(m->UsedSize(), SHADOW_GRANULARITY),
145 kAsanHeapLeftRedzoneMagic);
146 void *p = reinterpret_cast<void *>(m->AllocBeg());
148 uptr *alloc_magic = reinterpret_cast<uptr *>(p);
149 CHECK_EQ(alloc_magic[0], kAllocBegMagic);
150 // Clear the magic value, as allocator internals may overwrite the
151 // contents of deallocated chunk, confusing GetAsanChunk lookup.
153 CHECK_EQ(alloc_magic[1], reinterpret_cast<uptr>(m));
157 AsanStats &thread_stats = GetCurrentThreadStats();
158 thread_stats.real_frees++;
159 thread_stats.really_freed += m->UsedSize();
161 get_allocator().Deallocate(cache_, p);
164 void *Allocate(uptr size) {
165 void *res = get_allocator().Allocate(cache_, size, 1);
166 // TODO(alekseys): Consider making quarantine OOM-friendly.
168 return DieOnFailure::OnOOM();
172 void Deallocate(void *p) {
173 get_allocator().Deallocate(cache_, p);
176 AllocatorCache *cache_;
179 typedef Quarantine<QuarantineCallback, AsanChunk> AsanQuarantine;
180 typedef AsanQuarantine::Cache QuarantineCache;
182 void AsanMapUnmapCallback::OnMap(uptr p, uptr size) const {
183 PoisonShadow(p, size, kAsanHeapLeftRedzoneMagic);
185 AsanStats &thread_stats = GetCurrentThreadStats();
186 thread_stats.mmaps++;
187 thread_stats.mmaped += size;
189 void AsanMapUnmapCallback::OnUnmap(uptr p, uptr size) const {
190 PoisonShadow(p, size, 0);
191 // We are about to unmap a chunk of user memory.
192 // Mark the corresponding shadow memory as not needed.
193 FlushUnneededASanShadowMemory(p, size);
195 AsanStats &thread_stats = GetCurrentThreadStats();
196 thread_stats.munmaps++;
197 thread_stats.munmaped += size;
200 // We can not use THREADLOCAL because it is not supported on some of the
201 // platforms we care about (OSX 10.6, Android).
202 // static THREADLOCAL AllocatorCache cache;
203 AllocatorCache *GetAllocatorCache(AsanThreadLocalMallocStorage *ms) {
205 return &ms->allocator_cache;
208 QuarantineCache *GetQuarantineCache(AsanThreadLocalMallocStorage *ms) {
210 CHECK_LE(sizeof(QuarantineCache), sizeof(ms->quarantine_cache));
211 return reinterpret_cast<QuarantineCache *>(ms->quarantine_cache);
214 void AllocatorOptions::SetFrom(const Flags *f, const CommonFlags *cf) {
215 quarantine_size_mb = f->quarantine_size_mb;
216 thread_local_quarantine_size_kb = f->thread_local_quarantine_size_kb;
217 min_redzone = f->redzone;
218 max_redzone = f->max_redzone;
219 may_return_null = cf->allocator_may_return_null;
220 alloc_dealloc_mismatch = f->alloc_dealloc_mismatch;
221 release_to_os_interval_ms = cf->allocator_release_to_os_interval_ms;
224 void AllocatorOptions::CopyTo(Flags *f, CommonFlags *cf) {
225 f->quarantine_size_mb = quarantine_size_mb;
226 f->thread_local_quarantine_size_kb = thread_local_quarantine_size_kb;
227 f->redzone = min_redzone;
228 f->max_redzone = max_redzone;
229 cf->allocator_may_return_null = may_return_null;
230 f->alloc_dealloc_mismatch = alloc_dealloc_mismatch;
231 cf->allocator_release_to_os_interval_ms = release_to_os_interval_ms;
235 static const uptr kMaxAllowedMallocSize =
236 FIRST_32_SECOND_64(3UL << 30, 1ULL << 40);
238 AsanAllocator allocator;
239 AsanQuarantine quarantine;
240 StaticSpinMutex fallback_mutex;
241 AllocatorCache fallback_allocator_cache;
242 QuarantineCache fallback_quarantine_cache;
244 atomic_uint8_t rss_limit_exceeded;
246 // ------------------- Options --------------------------
247 atomic_uint16_t min_redzone;
248 atomic_uint16_t max_redzone;
249 atomic_uint8_t alloc_dealloc_mismatch;
251 // ------------------- Initialization ------------------------
252 explicit Allocator(LinkerInitialized)
253 : quarantine(LINKER_INITIALIZED),
254 fallback_quarantine_cache(LINKER_INITIALIZED) {}
256 void CheckOptions(const AllocatorOptions &options) const {
257 CHECK_GE(options.min_redzone, 16);
258 CHECK_GE(options.max_redzone, options.min_redzone);
259 CHECK_LE(options.max_redzone, 2048);
260 CHECK(IsPowerOfTwo(options.min_redzone));
261 CHECK(IsPowerOfTwo(options.max_redzone));
264 void SharedInitCode(const AllocatorOptions &options) {
265 CheckOptions(options);
266 quarantine.Init((uptr)options.quarantine_size_mb << 20,
267 (uptr)options.thread_local_quarantine_size_kb << 10);
268 atomic_store(&alloc_dealloc_mismatch, options.alloc_dealloc_mismatch,
269 memory_order_release);
270 atomic_store(&min_redzone, options.min_redzone, memory_order_release);
271 atomic_store(&max_redzone, options.max_redzone, memory_order_release);
274 void Initialize(const AllocatorOptions &options) {
275 SetAllocatorMayReturnNull(options.may_return_null);
276 allocator.Init(options.release_to_os_interval_ms);
277 SharedInitCode(options);
280 bool RssLimitExceeded() {
281 return atomic_load(&rss_limit_exceeded, memory_order_relaxed);
284 void SetRssLimitExceeded(bool limit_exceeded) {
285 atomic_store(&rss_limit_exceeded, limit_exceeded, memory_order_relaxed);
288 void RePoisonChunk(uptr chunk) {
289 // This could be a user-facing chunk (with redzones), or some internal
290 // housekeeping chunk, like TransferBatch. Start by assuming the former.
291 AsanChunk *ac = GetAsanChunk((void *)chunk);
292 uptr allocated_size = allocator.GetActuallyAllocatedSize((void *)ac);
293 uptr beg = ac->Beg();
294 uptr end = ac->Beg() + ac->UsedSize(true);
295 uptr chunk_end = chunk + allocated_size;
296 if (chunk < beg && beg < end && end <= chunk_end &&
297 ac->chunk_state == CHUNK_ALLOCATED) {
298 // Looks like a valid AsanChunk in use, poison redzones only.
299 PoisonShadow(chunk, beg - chunk, kAsanHeapLeftRedzoneMagic);
300 uptr end_aligned_down = RoundDownTo(end, SHADOW_GRANULARITY);
301 FastPoisonShadowPartialRightRedzone(
302 end_aligned_down, end - end_aligned_down,
303 chunk_end - end_aligned_down, kAsanHeapLeftRedzoneMagic);
305 // This is either not an AsanChunk or freed or quarantined AsanChunk.
306 // In either case, poison everything.
307 PoisonShadow(chunk, allocated_size, kAsanHeapLeftRedzoneMagic);
311 void ReInitialize(const AllocatorOptions &options) {
312 SetAllocatorMayReturnNull(options.may_return_null);
313 allocator.SetReleaseToOSIntervalMs(options.release_to_os_interval_ms);
314 SharedInitCode(options);
316 // Poison all existing allocation's redzones.
317 if (CanPoisonMemory()) {
318 allocator.ForceLock();
319 allocator.ForEachChunk(
320 [](uptr chunk, void *alloc) {
321 ((Allocator *)alloc)->RePoisonChunk(chunk);
324 allocator.ForceUnlock();
328 void GetOptions(AllocatorOptions *options) const {
329 options->quarantine_size_mb = quarantine.GetSize() >> 20;
330 options->thread_local_quarantine_size_kb = quarantine.GetCacheSize() >> 10;
331 options->min_redzone = atomic_load(&min_redzone, memory_order_acquire);
332 options->max_redzone = atomic_load(&max_redzone, memory_order_acquire);
333 options->may_return_null = AllocatorMayReturnNull();
334 options->alloc_dealloc_mismatch =
335 atomic_load(&alloc_dealloc_mismatch, memory_order_acquire);
336 options->release_to_os_interval_ms = allocator.ReleaseToOSIntervalMs();
339 // -------------------- Helper methods. -------------------------
340 uptr ComputeRZLog(uptr user_requested_size) {
342 user_requested_size <= 64 - 16 ? 0 :
343 user_requested_size <= 128 - 32 ? 1 :
344 user_requested_size <= 512 - 64 ? 2 :
345 user_requested_size <= 4096 - 128 ? 3 :
346 user_requested_size <= (1 << 14) - 256 ? 4 :
347 user_requested_size <= (1 << 15) - 512 ? 5 :
348 user_requested_size <= (1 << 16) - 1024 ? 6 : 7;
349 u32 min_rz = atomic_load(&min_redzone, memory_order_acquire);
350 u32 max_rz = atomic_load(&max_redzone, memory_order_acquire);
351 return Min(Max(rz_log, RZSize2Log(min_rz)), RZSize2Log(max_rz));
354 // We have an address between two chunks, and we want to report just one.
355 AsanChunk *ChooseChunk(uptr addr, AsanChunk *left_chunk,
356 AsanChunk *right_chunk) {
357 // Prefer an allocated chunk over freed chunk and freed chunk
358 // over available chunk.
359 if (left_chunk->chunk_state != right_chunk->chunk_state) {
360 if (left_chunk->chunk_state == CHUNK_ALLOCATED)
362 if (right_chunk->chunk_state == CHUNK_ALLOCATED)
364 if (left_chunk->chunk_state == CHUNK_QUARANTINE)
366 if (right_chunk->chunk_state == CHUNK_QUARANTINE)
369 // Same chunk_state: choose based on offset.
370 sptr l_offset = 0, r_offset = 0;
371 CHECK(AsanChunkView(left_chunk).AddrIsAtRight(addr, 1, &l_offset));
372 CHECK(AsanChunkView(right_chunk).AddrIsAtLeft(addr, 1, &r_offset));
373 if (l_offset < r_offset)
378 // -------------------- Allocation/Deallocation routines ---------------
379 void *Allocate(uptr size, uptr alignment, BufferedStackTrace *stack,
380 AllocType alloc_type, bool can_fill) {
381 if (UNLIKELY(!asan_inited))
383 if (RssLimitExceeded())
384 return AsanAllocator::FailureHandler::OnOOM();
385 Flags &fl = *flags();
387 const uptr min_alignment = SHADOW_GRANULARITY;
388 if (alignment < min_alignment)
389 alignment = min_alignment;
391 // We'd be happy to avoid allocating memory for zero-size requests, but
392 // some programs/tests depend on this behavior and assume that malloc
393 // would not return NULL even for zero-size allocations. Moreover, it
394 // looks like operator new should never return NULL, and results of
395 // consecutive "new" calls must be different even if the allocated size
399 CHECK(IsPowerOfTwo(alignment));
400 uptr rz_log = ComputeRZLog(size);
401 uptr rz_size = RZLog2Size(rz_log);
402 uptr rounded_size = RoundUpTo(Max(size, kChunkHeader2Size), alignment);
403 uptr needed_size = rounded_size + rz_size;
404 if (alignment > min_alignment)
405 needed_size += alignment;
406 bool using_primary_allocator = true;
407 // If we are allocating from the secondary allocator, there will be no
408 // automatic right redzone, so add the right redzone manually.
409 if (!PrimaryAllocator::CanAllocate(needed_size, alignment)) {
410 needed_size += rz_size;
411 using_primary_allocator = false;
413 CHECK(IsAligned(needed_size, min_alignment));
414 if (size > kMaxAllowedMallocSize || needed_size > kMaxAllowedMallocSize) {
415 Report("WARNING: AddressSanitizer failed to allocate 0x%zx bytes\n",
417 return AsanAllocator::FailureHandler::OnBadRequest();
420 AsanThread *t = GetCurrentThread();
423 AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
424 allocated = allocator.Allocate(cache, needed_size, 8);
426 SpinMutexLock l(&fallback_mutex);
427 AllocatorCache *cache = &fallback_allocator_cache;
428 allocated = allocator.Allocate(cache, needed_size, 8);
433 if (*(u8 *)MEM_TO_SHADOW((uptr)allocated) == 0 && CanPoisonMemory()) {
434 // Heap poisoning is enabled, but the allocator provides an unpoisoned
435 // chunk. This is possible if CanPoisonMemory() was false for some
436 // time, for example, due to flags()->start_disabled.
437 // Anyway, poison the block before using it for anything else.
438 uptr allocated_size = allocator.GetActuallyAllocatedSize(allocated);
439 PoisonShadow((uptr)allocated, allocated_size, kAsanHeapLeftRedzoneMagic);
442 uptr alloc_beg = reinterpret_cast<uptr>(allocated);
443 uptr alloc_end = alloc_beg + needed_size;
444 uptr beg_plus_redzone = alloc_beg + rz_size;
445 uptr user_beg = beg_plus_redzone;
446 if (!IsAligned(user_beg, alignment))
447 user_beg = RoundUpTo(user_beg, alignment);
448 uptr user_end = user_beg + size;
449 CHECK_LE(user_end, alloc_end);
450 uptr chunk_beg = user_beg - kChunkHeaderSize;
451 AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
452 m->alloc_type = alloc_type;
454 u32 alloc_tid = t ? t->tid() : 0;
455 m->alloc_tid = alloc_tid;
456 CHECK_EQ(alloc_tid, m->alloc_tid); // Does alloc_tid fit into the bitfield?
457 m->free_tid = kInvalidTid;
458 m->from_memalign = user_beg != beg_plus_redzone;
459 if (alloc_beg != chunk_beg) {
460 CHECK_LE(alloc_beg+ 2 * sizeof(uptr), chunk_beg);
461 reinterpret_cast<uptr *>(alloc_beg)[0] = kAllocBegMagic;
462 reinterpret_cast<uptr *>(alloc_beg)[1] = chunk_beg;
464 if (using_primary_allocator) {
466 m->user_requested_size = size;
467 CHECK(allocator.FromPrimary(allocated));
469 CHECK(!allocator.FromPrimary(allocated));
470 m->user_requested_size = SizeClassMap::kMaxSize;
471 uptr *meta = reinterpret_cast<uptr *>(allocator.GetMetaData(allocated));
476 m->alloc_context_id = StackDepotPut(*stack);
478 uptr size_rounded_down_to_granularity =
479 RoundDownTo(size, SHADOW_GRANULARITY);
480 // Unpoison the bulk of the memory region.
481 if (size_rounded_down_to_granularity)
482 PoisonShadow(user_beg, size_rounded_down_to_granularity, 0);
483 // Deal with the end of the region if size is not aligned to granularity.
484 if (size != size_rounded_down_to_granularity && CanPoisonMemory()) {
486 (u8 *)MemToShadow(user_beg + size_rounded_down_to_granularity);
487 *shadow = fl.poison_partial ? (size & (SHADOW_GRANULARITY - 1)) : 0;
490 AsanStats &thread_stats = GetCurrentThreadStats();
491 thread_stats.mallocs++;
492 thread_stats.malloced += size;
493 thread_stats.malloced_redzones += needed_size - size;
494 if (needed_size > SizeClassMap::kMaxSize)
495 thread_stats.malloc_large++;
497 thread_stats.malloced_by_size[SizeClassMap::ClassID(needed_size)]++;
499 void *res = reinterpret_cast<void *>(user_beg);
500 if (can_fill && fl.max_malloc_fill_size) {
501 uptr fill_size = Min(size, (uptr)fl.max_malloc_fill_size);
502 REAL(memset)(res, fl.malloc_fill_byte, fill_size);
504 #if CAN_SANITIZE_LEAKS
505 m->lsan_tag = __lsan::DisabledInThisThread() ? __lsan::kIgnored
506 : __lsan::kDirectlyLeaked;
508 // Must be the last mutation of metadata in this function.
509 atomic_store((atomic_uint8_t *)m, CHUNK_ALLOCATED, memory_order_release);
510 ASAN_MALLOC_HOOK(res, size);
514 // Set quarantine flag if chunk is allocated, issue ASan error report on
515 // available and quarantined chunks. Return true on success, false otherwise.
516 bool AtomicallySetQuarantineFlagIfAllocated(AsanChunk *m, void *ptr,
517 BufferedStackTrace *stack) {
518 u8 old_chunk_state = CHUNK_ALLOCATED;
519 // Flip the chunk_state atomically to avoid race on double-free.
520 if (!atomic_compare_exchange_strong((atomic_uint8_t *)m, &old_chunk_state,
522 memory_order_acquire)) {
523 ReportInvalidFree(ptr, old_chunk_state, stack);
524 // It's not safe to push a chunk in quarantine on invalid free.
527 CHECK_EQ(CHUNK_ALLOCATED, old_chunk_state);
531 // Expects the chunk to already be marked as quarantined by using
532 // AtomicallySetQuarantineFlagIfAllocated.
533 void QuarantineChunk(AsanChunk *m, void *ptr, BufferedStackTrace *stack) {
534 CHECK_EQ(m->chunk_state, CHUNK_QUARANTINE);
535 CHECK_GE(m->alloc_tid, 0);
536 if (SANITIZER_WORDSIZE == 64) // On 32-bits this resides in user area.
537 CHECK_EQ(m->free_tid, kInvalidTid);
538 AsanThread *t = GetCurrentThread();
539 m->free_tid = t ? t->tid() : 0;
540 m->free_context_id = StackDepotPut(*stack);
542 Flags &fl = *flags();
543 if (fl.max_free_fill_size > 0) {
544 // We have to skip the chunk header, it contains free_context_id.
545 uptr scribble_start = (uptr)m + kChunkHeaderSize + kChunkHeader2Size;
546 if (m->UsedSize() >= kChunkHeader2Size) { // Skip Header2 in user area.
547 uptr size_to_fill = m->UsedSize() - kChunkHeader2Size;
548 size_to_fill = Min(size_to_fill, (uptr)fl.max_free_fill_size);
549 REAL(memset)((void *)scribble_start, fl.free_fill_byte, size_to_fill);
553 // Poison the region.
554 PoisonShadow(m->Beg(),
555 RoundUpTo(m->UsedSize(), SHADOW_GRANULARITY),
558 AsanStats &thread_stats = GetCurrentThreadStats();
559 thread_stats.frees++;
560 thread_stats.freed += m->UsedSize();
562 // Push into quarantine.
564 AsanThreadLocalMallocStorage *ms = &t->malloc_storage();
565 AllocatorCache *ac = GetAllocatorCache(ms);
566 quarantine.Put(GetQuarantineCache(ms), QuarantineCallback(ac), m,
569 SpinMutexLock l(&fallback_mutex);
570 AllocatorCache *ac = &fallback_allocator_cache;
571 quarantine.Put(&fallback_quarantine_cache, QuarantineCallback(ac), m,
576 void Deallocate(void *ptr, uptr delete_size, BufferedStackTrace *stack,
577 AllocType alloc_type) {
578 uptr p = reinterpret_cast<uptr>(ptr);
581 uptr chunk_beg = p - kChunkHeaderSize;
582 AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
584 // On Windows, uninstrumented DLLs may allocate memory before ASan hooks
585 // malloc. Don't report an invalid free in this case.
586 if (SANITIZER_WINDOWS &&
587 !get_allocator().PointerIsMine(ptr)) {
588 if (!IsSystemHeapAddress(p))
589 ReportFreeNotMalloced(p, stack);
595 // Must mark the chunk as quarantined before any changes to its metadata.
596 // Do not quarantine given chunk if we failed to set CHUNK_QUARANTINE flag.
597 if (!AtomicallySetQuarantineFlagIfAllocated(m, ptr, stack)) return;
599 if (m->alloc_type != alloc_type) {
600 if (atomic_load(&alloc_dealloc_mismatch, memory_order_acquire)) {
601 ReportAllocTypeMismatch((uptr)ptr, stack, (AllocType)m->alloc_type,
602 (AllocType)alloc_type);
606 if (delete_size && flags()->new_delete_type_mismatch &&
607 delete_size != m->UsedSize()) {
608 ReportNewDeleteSizeMismatch(p, delete_size, stack);
611 QuarantineChunk(m, ptr, stack);
614 void *Reallocate(void *old_ptr, uptr new_size, BufferedStackTrace *stack) {
615 CHECK(old_ptr && new_size);
616 uptr p = reinterpret_cast<uptr>(old_ptr);
617 uptr chunk_beg = p - kChunkHeaderSize;
618 AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
620 AsanStats &thread_stats = GetCurrentThreadStats();
621 thread_stats.reallocs++;
622 thread_stats.realloced += new_size;
624 void *new_ptr = Allocate(new_size, 8, stack, FROM_MALLOC, true);
626 u8 chunk_state = m->chunk_state;
627 if (chunk_state != CHUNK_ALLOCATED)
628 ReportInvalidFree(old_ptr, chunk_state, stack);
629 CHECK_NE(REAL(memcpy), nullptr);
630 uptr memcpy_size = Min(new_size, m->UsedSize());
631 // If realloc() races with free(), we may start copying freed memory.
632 // However, we will report racy double-free later anyway.
633 REAL(memcpy)(new_ptr, old_ptr, memcpy_size);
634 Deallocate(old_ptr, 0, stack, FROM_MALLOC);
639 void *Calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) {
640 if (CheckForCallocOverflow(size, nmemb))
641 return AsanAllocator::FailureHandler::OnBadRequest();
642 void *ptr = Allocate(nmemb * size, 8, stack, FROM_MALLOC, false);
643 // If the memory comes from the secondary allocator no need to clear it
644 // as it comes directly from mmap.
645 if (ptr && allocator.FromPrimary(ptr))
646 REAL(memset)(ptr, 0, nmemb * size);
650 void ReportInvalidFree(void *ptr, u8 chunk_state, BufferedStackTrace *stack) {
651 if (chunk_state == CHUNK_QUARANTINE)
652 ReportDoubleFree((uptr)ptr, stack);
654 ReportFreeNotMalloced((uptr)ptr, stack);
657 void CommitBack(AsanThreadLocalMallocStorage *ms) {
658 AllocatorCache *ac = GetAllocatorCache(ms);
659 quarantine.Drain(GetQuarantineCache(ms), QuarantineCallback(ac));
660 allocator.SwallowCache(ac);
663 // -------------------------- Chunk lookup ----------------------
665 // Assumes alloc_beg == allocator.GetBlockBegin(alloc_beg).
666 AsanChunk *GetAsanChunk(void *alloc_beg) {
667 if (!alloc_beg) return nullptr;
668 if (!allocator.FromPrimary(alloc_beg)) {
669 uptr *meta = reinterpret_cast<uptr *>(allocator.GetMetaData(alloc_beg));
670 AsanChunk *m = reinterpret_cast<AsanChunk *>(meta[1]);
673 uptr *alloc_magic = reinterpret_cast<uptr *>(alloc_beg);
674 if (alloc_magic[0] == kAllocBegMagic)
675 return reinterpret_cast<AsanChunk *>(alloc_magic[1]);
676 return reinterpret_cast<AsanChunk *>(alloc_beg);
679 AsanChunk *GetAsanChunkByAddr(uptr p) {
680 void *alloc_beg = allocator.GetBlockBegin(reinterpret_cast<void *>(p));
681 return GetAsanChunk(alloc_beg);
684 // Allocator must be locked when this function is called.
685 AsanChunk *GetAsanChunkByAddrFastLocked(uptr p) {
687 allocator.GetBlockBeginFastLocked(reinterpret_cast<void *>(p));
688 return GetAsanChunk(alloc_beg);
691 uptr AllocationSize(uptr p) {
692 AsanChunk *m = GetAsanChunkByAddr(p);
694 if (m->chunk_state != CHUNK_ALLOCATED) return 0;
695 if (m->Beg() != p) return 0;
696 return m->UsedSize();
699 AsanChunkView FindHeapChunkByAddress(uptr addr) {
700 AsanChunk *m1 = GetAsanChunkByAddr(addr);
701 if (!m1) return AsanChunkView(m1);
703 if (AsanChunkView(m1).AddrIsAtLeft(addr, 1, &offset)) {
704 // The address is in the chunk's left redzone, so maybe it is actually
705 // a right buffer overflow from the other chunk to the left.
706 // Search a bit to the left to see if there is another chunk.
707 AsanChunk *m2 = nullptr;
708 for (uptr l = 1; l < GetPageSizeCached(); l++) {
709 m2 = GetAsanChunkByAddr(addr - l);
710 if (m2 == m1) continue; // Still the same chunk.
713 if (m2 && AsanChunkView(m2).AddrIsAtRight(addr, 1, &offset))
714 m1 = ChooseChunk(addr, m2, m1);
716 return AsanChunkView(m1);
720 allocator.PrintStats();
721 quarantine.PrintStats();
725 allocator.ForceLock();
726 fallback_mutex.Lock();
730 fallback_mutex.Unlock();
731 allocator.ForceUnlock();
735 static Allocator instance(LINKER_INITIALIZED);
737 static AsanAllocator &get_allocator() {
738 return instance.allocator;
741 bool AsanChunkView::IsValid() const {
742 return chunk_ && chunk_->chunk_state != CHUNK_AVAILABLE;
744 bool AsanChunkView::IsAllocated() const {
745 return chunk_ && chunk_->chunk_state == CHUNK_ALLOCATED;
747 bool AsanChunkView::IsQuarantined() const {
748 return chunk_ && chunk_->chunk_state == CHUNK_QUARANTINE;
750 uptr AsanChunkView::Beg() const { return chunk_->Beg(); }
751 uptr AsanChunkView::End() const { return Beg() + UsedSize(); }
752 uptr AsanChunkView::UsedSize() const { return chunk_->UsedSize(); }
753 uptr AsanChunkView::AllocTid() const { return chunk_->alloc_tid; }
754 uptr AsanChunkView::FreeTid() const { return chunk_->free_tid; }
755 AllocType AsanChunkView::GetAllocType() const {
756 return (AllocType)chunk_->alloc_type;
759 static StackTrace GetStackTraceFromId(u32 id) {
761 StackTrace res = StackDepotGet(id);
766 u32 AsanChunkView::GetAllocStackId() const { return chunk_->alloc_context_id; }
767 u32 AsanChunkView::GetFreeStackId() const { return chunk_->free_context_id; }
769 StackTrace AsanChunkView::GetAllocStack() const {
770 return GetStackTraceFromId(GetAllocStackId());
773 StackTrace AsanChunkView::GetFreeStack() const {
774 return GetStackTraceFromId(GetFreeStackId());
777 void InitializeAllocator(const AllocatorOptions &options) {
778 instance.Initialize(options);
781 void ReInitializeAllocator(const AllocatorOptions &options) {
782 instance.ReInitialize(options);
785 void GetAllocatorOptions(AllocatorOptions *options) {
786 instance.GetOptions(options);
789 AsanChunkView FindHeapChunkByAddress(uptr addr) {
790 return instance.FindHeapChunkByAddress(addr);
792 AsanChunkView FindHeapChunkByAllocBeg(uptr addr) {
793 return AsanChunkView(instance.GetAsanChunk(reinterpret_cast<void*>(addr)));
796 void AsanThreadLocalMallocStorage::CommitBack() {
797 instance.CommitBack(this);
800 void PrintInternalAllocatorStats() {
801 instance.PrintStats();
804 void asan_free(void *ptr, BufferedStackTrace *stack, AllocType alloc_type) {
805 instance.Deallocate(ptr, 0, stack, alloc_type);
808 void asan_sized_free(void *ptr, uptr size, BufferedStackTrace *stack,
809 AllocType alloc_type) {
810 instance.Deallocate(ptr, size, stack, alloc_type);
813 void *asan_malloc(uptr size, BufferedStackTrace *stack) {
814 return SetErrnoOnNull(instance.Allocate(size, 8, stack, FROM_MALLOC, true));
817 void *asan_calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) {
818 return SetErrnoOnNull(instance.Calloc(nmemb, size, stack));
821 void *asan_realloc(void *p, uptr size, BufferedStackTrace *stack) {
823 return SetErrnoOnNull(instance.Allocate(size, 8, stack, FROM_MALLOC, true));
825 if (flags()->allocator_frees_and_returns_null_on_realloc_zero) {
826 instance.Deallocate(p, 0, stack, FROM_MALLOC);
829 // Allocate a size of 1 if we shouldn't free() on Realloc to 0
832 return SetErrnoOnNull(instance.Reallocate(p, size, stack));
835 void *asan_valloc(uptr size, BufferedStackTrace *stack) {
836 return SetErrnoOnNull(
837 instance.Allocate(size, GetPageSizeCached(), stack, FROM_MALLOC, true));
840 void *asan_pvalloc(uptr size, BufferedStackTrace *stack) {
841 uptr PageSize = GetPageSizeCached();
842 // pvalloc(0) should allocate one page.
843 size = size ? RoundUpTo(size, PageSize) : PageSize;
844 return SetErrnoOnNull(
845 instance.Allocate(size, PageSize, stack, FROM_MALLOC, true));
848 void *asan_memalign(uptr alignment, uptr size, BufferedStackTrace *stack,
849 AllocType alloc_type) {
850 if (UNLIKELY(!IsPowerOfTwo(alignment))) {
851 errno = errno_EINVAL;
852 return AsanAllocator::FailureHandler::OnBadRequest();
854 return SetErrnoOnNull(
855 instance.Allocate(size, alignment, stack, alloc_type, true));
858 int asan_posix_memalign(void **memptr, uptr alignment, uptr size,
859 BufferedStackTrace *stack) {
860 if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) {
861 AsanAllocator::FailureHandler::OnBadRequest();
864 void *ptr = instance.Allocate(size, alignment, stack, FROM_MALLOC, true);
867 CHECK(IsAligned((uptr)ptr, alignment));
872 uptr asan_malloc_usable_size(const void *ptr, uptr pc, uptr bp) {
874 uptr usable_size = instance.AllocationSize(reinterpret_cast<uptr>(ptr));
875 if (flags()->check_malloc_usable_size && (usable_size == 0)) {
876 GET_STACK_TRACE_FATAL(pc, bp);
877 ReportMallocUsableSizeNotOwned((uptr)ptr, &stack);
882 uptr asan_mz_size(const void *ptr) {
883 return instance.AllocationSize(reinterpret_cast<uptr>(ptr));
886 void asan_mz_force_lock() {
887 instance.ForceLock();
890 void asan_mz_force_unlock() {
891 instance.ForceUnlock();
894 void AsanSoftRssLimitExceededCallback(bool limit_exceeded) {
895 instance.SetRssLimitExceeded(limit_exceeded);
898 } // namespace __asan
900 // --- Implementation of LSan-specific functions --- {{{1
902 void LockAllocator() {
903 __asan::get_allocator().ForceLock();
906 void UnlockAllocator() {
907 __asan::get_allocator().ForceUnlock();
910 void GetAllocatorGlobalRange(uptr *begin, uptr *end) {
911 *begin = (uptr)&__asan::get_allocator();
912 *end = *begin + sizeof(__asan::get_allocator());
915 uptr PointsIntoChunk(void* p) {
916 uptr addr = reinterpret_cast<uptr>(p);
917 __asan::AsanChunk *m = __asan::instance.GetAsanChunkByAddrFastLocked(addr);
919 uptr chunk = m->Beg();
920 if (m->chunk_state != __asan::CHUNK_ALLOCATED)
922 if (m->AddrIsInside(addr, /*locked_version=*/true))
924 if (IsSpecialCaseOfOperatorNew0(chunk, m->UsedSize(/*locked_version*/ true),
930 uptr GetUserBegin(uptr chunk) {
931 __asan::AsanChunk *m = __asan::instance.GetAsanChunkByAddrFastLocked(chunk);
936 LsanMetadata::LsanMetadata(uptr chunk) {
937 metadata_ = reinterpret_cast<void *>(chunk - __asan::kChunkHeaderSize);
940 bool LsanMetadata::allocated() const {
941 __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
942 return m->chunk_state == __asan::CHUNK_ALLOCATED;
945 ChunkTag LsanMetadata::tag() const {
946 __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
947 return static_cast<ChunkTag>(m->lsan_tag);
950 void LsanMetadata::set_tag(ChunkTag value) {
951 __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
955 uptr LsanMetadata::requested_size() const {
956 __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
957 return m->UsedSize(/*locked_version=*/true);
960 u32 LsanMetadata::stack_trace_id() const {
961 __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
962 return m->alloc_context_id;
965 void ForEachChunk(ForEachChunkCallback callback, void *arg) {
966 __asan::get_allocator().ForEachChunk(callback, arg);
969 IgnoreObjectResult IgnoreObjectLocked(const void *p) {
970 uptr addr = reinterpret_cast<uptr>(p);
971 __asan::AsanChunk *m = __asan::instance.GetAsanChunkByAddr(addr);
972 if (!m) return kIgnoreObjectInvalid;
973 if ((m->chunk_state == __asan::CHUNK_ALLOCATED) && m->AddrIsInside(addr)) {
974 if (m->lsan_tag == kIgnored)
975 return kIgnoreObjectAlreadyIgnored;
976 m->lsan_tag = __lsan::kIgnored;
977 return kIgnoreObjectSuccess;
979 return kIgnoreObjectInvalid;
982 } // namespace __lsan
984 // ---------------------- Interface ---------------- {{{1
985 using namespace __asan; // NOLINT
987 // ASan allocator doesn't reserve extra bytes, so normally we would
988 // just return "size". We don't want to expose our redzone sizes, etc here.
989 uptr __sanitizer_get_estimated_allocated_size(uptr size) {
993 int __sanitizer_get_ownership(const void *p) {
994 uptr ptr = reinterpret_cast<uptr>(p);
995 return instance.AllocationSize(ptr) > 0;
998 uptr __sanitizer_get_allocated_size(const void *p) {
1000 uptr ptr = reinterpret_cast<uptr>(p);
1001 uptr allocated_size = instance.AllocationSize(ptr);
1002 // Die if p is not malloced or if it is already freed.
1003 if (allocated_size == 0) {
1004 GET_STACK_TRACE_FATAL_HERE;
1005 ReportSanitizerGetAllocatedSizeNotOwned(ptr, &stack);
1007 return allocated_size;
1010 #if !SANITIZER_SUPPORTS_WEAK_HOOKS
1011 // Provide default (no-op) implementation of malloc hooks.
1012 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_malloc_hook,
1013 void *ptr, uptr size) {
1018 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_free_hook, void *ptr) {