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_interface.h"
25 #include "sanitizer_common/sanitizer_flags.h"
26 #include "sanitizer_common/sanitizer_internal_defs.h"
27 #include "sanitizer_common/sanitizer_list.h"
28 #include "sanitizer_common/sanitizer_stackdepot.h"
29 #include "sanitizer_common/sanitizer_quarantine.h"
30 #include "lsan/lsan_common.h"
34 // Valid redzone sizes are 16, 32, 64, ... 2048, so we encode them in 3 bits.
35 // We use adaptive redzones: for larger allocation larger redzones are used.
36 static u32 RZLog2Size(u32 rz_log) {
41 static u32 RZSize2Log(u32 rz_size) {
42 CHECK_GE(rz_size, 16);
43 CHECK_LE(rz_size, 2048);
44 CHECK(IsPowerOfTwo(rz_size));
45 u32 res = Log2(rz_size) - 4;
46 CHECK_EQ(rz_size, RZLog2Size(res));
50 // The memory chunk allocated from the underlying allocator looks like this:
51 // L L L L L L H H U U U U U U R R
52 // L -- left redzone words (0 or more bytes)
53 // H -- ChunkHeader (16 bytes), which is also a part of the left redzone.
55 // R -- right redzone (0 or more bytes)
56 // ChunkBase consists of ChunkHeader and other bytes that overlap with user
59 // If the left redzone is greater than the ChunkHeader size we store a magic
60 // value in the first uptr word of the memory block and store the address of
61 // ChunkBase in the next uptr.
62 // M B L L L L L L L L L H H U U U U U U
64 // ---------------------|
65 // M -- magic value kAllocBegMagic
66 // B -- address of ChunkHeader pointing to the first 'H'
67 static const uptr kAllocBegMagic = 0xCC6E96B9;
71 u32 chunk_state : 8; // Must be first.
75 u32 from_memalign : 1;
80 // This field is used for small sizes. For large sizes it is equal to
81 // SizeClassMap::kMaxSize and the actual size is stored in the
82 // SecondaryAllocator's metadata.
83 u32 user_requested_size;
87 struct ChunkBase : ChunkHeader {
88 // Header2, intersects with user memory.
92 static const uptr kChunkHeaderSize = sizeof(ChunkHeader);
93 static const uptr kChunkHeader2Size = sizeof(ChunkBase) - kChunkHeaderSize;
94 COMPILER_CHECK(kChunkHeaderSize == 16);
95 COMPILER_CHECK(kChunkHeader2Size <= 16);
97 // Every chunk of memory allocated by this allocator can be in one of 3 states:
98 // CHUNK_AVAILABLE: the chunk is in the free list and ready to be allocated.
99 // CHUNK_ALLOCATED: the chunk is allocated and not yet freed.
100 // CHUNK_QUARANTINE: the chunk was freed and put into quarantine zone.
102 CHUNK_AVAILABLE = 0, // 0 is the default value even if we didn't set it.
107 struct AsanChunk: ChunkBase {
108 uptr Beg() { return reinterpret_cast<uptr>(this) + kChunkHeaderSize; }
109 uptr UsedSize(bool locked_version = false) {
110 if (user_requested_size != SizeClassMap::kMaxSize)
111 return user_requested_size;
112 return *reinterpret_cast<uptr *>(
113 get_allocator().GetMetaData(AllocBeg(locked_version)));
115 void *AllocBeg(bool locked_version = false) {
118 return get_allocator().GetBlockBeginFastLocked(
119 reinterpret_cast<void *>(this));
120 return get_allocator().GetBlockBegin(reinterpret_cast<void *>(this));
122 return reinterpret_cast<void*>(Beg() - RZLog2Size(rz_log));
124 bool AddrIsInside(uptr addr, bool locked_version = false) {
125 return (addr >= Beg()) && (addr < Beg() + UsedSize(locked_version));
129 struct QuarantineCallback {
130 explicit QuarantineCallback(AllocatorCache *cache)
134 void Recycle(AsanChunk *m) {
135 CHECK_EQ(m->chunk_state, CHUNK_QUARANTINE);
136 atomic_store((atomic_uint8_t*)m, CHUNK_AVAILABLE, memory_order_relaxed);
137 CHECK_NE(m->alloc_tid, kInvalidTid);
138 CHECK_NE(m->free_tid, kInvalidTid);
139 PoisonShadow(m->Beg(),
140 RoundUpTo(m->UsedSize(), SHADOW_GRANULARITY),
141 kAsanHeapLeftRedzoneMagic);
142 void *p = reinterpret_cast<void *>(m->AllocBeg());
144 uptr *alloc_magic = reinterpret_cast<uptr *>(p);
145 CHECK_EQ(alloc_magic[0], kAllocBegMagic);
146 // Clear the magic value, as allocator internals may overwrite the
147 // contents of deallocated chunk, confusing GetAsanChunk lookup.
149 CHECK_EQ(alloc_magic[1], reinterpret_cast<uptr>(m));
153 AsanStats &thread_stats = GetCurrentThreadStats();
154 thread_stats.real_frees++;
155 thread_stats.really_freed += m->UsedSize();
157 get_allocator().Deallocate(cache_, p);
160 void *Allocate(uptr size) {
161 return get_allocator().Allocate(cache_, size, 1, false);
164 void Deallocate(void *p) {
165 get_allocator().Deallocate(cache_, p);
168 AllocatorCache *cache_;
171 typedef Quarantine<QuarantineCallback, AsanChunk> AsanQuarantine;
172 typedef AsanQuarantine::Cache QuarantineCache;
174 void AsanMapUnmapCallback::OnMap(uptr p, uptr size) const {
175 PoisonShadow(p, size, kAsanHeapLeftRedzoneMagic);
177 AsanStats &thread_stats = GetCurrentThreadStats();
178 thread_stats.mmaps++;
179 thread_stats.mmaped += size;
181 void AsanMapUnmapCallback::OnUnmap(uptr p, uptr size) const {
182 PoisonShadow(p, size, 0);
183 // We are about to unmap a chunk of user memory.
184 // Mark the corresponding shadow memory as not needed.
185 FlushUnneededASanShadowMemory(p, size);
187 AsanStats &thread_stats = GetCurrentThreadStats();
188 thread_stats.munmaps++;
189 thread_stats.munmaped += size;
192 // We can not use THREADLOCAL because it is not supported on some of the
193 // platforms we care about (OSX 10.6, Android).
194 // static THREADLOCAL AllocatorCache cache;
195 AllocatorCache *GetAllocatorCache(AsanThreadLocalMallocStorage *ms) {
197 return &ms->allocator_cache;
200 QuarantineCache *GetQuarantineCache(AsanThreadLocalMallocStorage *ms) {
202 CHECK_LE(sizeof(QuarantineCache), sizeof(ms->quarantine_cache));
203 return reinterpret_cast<QuarantineCache *>(ms->quarantine_cache);
206 void AllocatorOptions::SetFrom(const Flags *f, const CommonFlags *cf) {
207 quarantine_size_mb = f->quarantine_size_mb;
208 thread_local_quarantine_size_kb = f->thread_local_quarantine_size_kb;
209 min_redzone = f->redzone;
210 max_redzone = f->max_redzone;
211 may_return_null = cf->allocator_may_return_null;
212 alloc_dealloc_mismatch = f->alloc_dealloc_mismatch;
213 release_to_os_interval_ms = cf->allocator_release_to_os_interval_ms;
216 void AllocatorOptions::CopyTo(Flags *f, CommonFlags *cf) {
217 f->quarantine_size_mb = quarantine_size_mb;
218 f->thread_local_quarantine_size_kb = thread_local_quarantine_size_kb;
219 f->redzone = min_redzone;
220 f->max_redzone = max_redzone;
221 cf->allocator_may_return_null = may_return_null;
222 f->alloc_dealloc_mismatch = alloc_dealloc_mismatch;
223 cf->allocator_release_to_os_interval_ms = release_to_os_interval_ms;
227 static const uptr kMaxAllowedMallocSize =
228 FIRST_32_SECOND_64(3UL << 30, 1ULL << 40);
230 AsanAllocator allocator;
231 AsanQuarantine quarantine;
232 StaticSpinMutex fallback_mutex;
233 AllocatorCache fallback_allocator_cache;
234 QuarantineCache fallback_quarantine_cache;
236 // ------------------- Options --------------------------
237 atomic_uint16_t min_redzone;
238 atomic_uint16_t max_redzone;
239 atomic_uint8_t alloc_dealloc_mismatch;
241 // ------------------- Initialization ------------------------
242 explicit Allocator(LinkerInitialized)
243 : quarantine(LINKER_INITIALIZED),
244 fallback_quarantine_cache(LINKER_INITIALIZED) {}
246 void CheckOptions(const AllocatorOptions &options) const {
247 CHECK_GE(options.min_redzone, 16);
248 CHECK_GE(options.max_redzone, options.min_redzone);
249 CHECK_LE(options.max_redzone, 2048);
250 CHECK(IsPowerOfTwo(options.min_redzone));
251 CHECK(IsPowerOfTwo(options.max_redzone));
254 void SharedInitCode(const AllocatorOptions &options) {
255 CheckOptions(options);
256 quarantine.Init((uptr)options.quarantine_size_mb << 20,
257 (uptr)options.thread_local_quarantine_size_kb << 10);
258 atomic_store(&alloc_dealloc_mismatch, options.alloc_dealloc_mismatch,
259 memory_order_release);
260 atomic_store(&min_redzone, options.min_redzone, memory_order_release);
261 atomic_store(&max_redzone, options.max_redzone, memory_order_release);
264 void Initialize(const AllocatorOptions &options) {
265 allocator.Init(options.may_return_null, options.release_to_os_interval_ms);
266 SharedInitCode(options);
269 void RePoisonChunk(uptr chunk) {
270 // This could be a user-facing chunk (with redzones), or some internal
271 // housekeeping chunk, like TransferBatch. Start by assuming the former.
272 AsanChunk *ac = GetAsanChunk((void *)chunk);
273 uptr allocated_size = allocator.GetActuallyAllocatedSize((void *)ac);
274 uptr beg = ac->Beg();
275 uptr end = ac->Beg() + ac->UsedSize(true);
276 uptr chunk_end = chunk + allocated_size;
277 if (chunk < beg && beg < end && end <= chunk_end &&
278 ac->chunk_state == CHUNK_ALLOCATED) {
279 // Looks like a valid AsanChunk in use, poison redzones only.
280 PoisonShadow(chunk, beg - chunk, kAsanHeapLeftRedzoneMagic);
281 uptr end_aligned_down = RoundDownTo(end, SHADOW_GRANULARITY);
282 FastPoisonShadowPartialRightRedzone(
283 end_aligned_down, end - end_aligned_down,
284 chunk_end - end_aligned_down, kAsanHeapLeftRedzoneMagic);
286 // This is either not an AsanChunk or freed or quarantined AsanChunk.
287 // In either case, poison everything.
288 PoisonShadow(chunk, allocated_size, kAsanHeapLeftRedzoneMagic);
292 void ReInitialize(const AllocatorOptions &options) {
293 allocator.SetMayReturnNull(options.may_return_null);
294 allocator.SetReleaseToOSIntervalMs(options.release_to_os_interval_ms);
295 SharedInitCode(options);
297 // Poison all existing allocation's redzones.
298 if (CanPoisonMemory()) {
299 allocator.ForceLock();
300 allocator.ForEachChunk(
301 [](uptr chunk, void *alloc) {
302 ((Allocator *)alloc)->RePoisonChunk(chunk);
305 allocator.ForceUnlock();
309 void GetOptions(AllocatorOptions *options) const {
310 options->quarantine_size_mb = quarantine.GetSize() >> 20;
311 options->thread_local_quarantine_size_kb = quarantine.GetCacheSize() >> 10;
312 options->min_redzone = atomic_load(&min_redzone, memory_order_acquire);
313 options->max_redzone = atomic_load(&max_redzone, memory_order_acquire);
314 options->may_return_null = allocator.MayReturnNull();
315 options->alloc_dealloc_mismatch =
316 atomic_load(&alloc_dealloc_mismatch, memory_order_acquire);
317 options->release_to_os_interval_ms = allocator.ReleaseToOSIntervalMs();
320 // -------------------- Helper methods. -------------------------
321 uptr ComputeRZLog(uptr user_requested_size) {
323 user_requested_size <= 64 - 16 ? 0 :
324 user_requested_size <= 128 - 32 ? 1 :
325 user_requested_size <= 512 - 64 ? 2 :
326 user_requested_size <= 4096 - 128 ? 3 :
327 user_requested_size <= (1 << 14) - 256 ? 4 :
328 user_requested_size <= (1 << 15) - 512 ? 5 :
329 user_requested_size <= (1 << 16) - 1024 ? 6 : 7;
330 u32 min_rz = atomic_load(&min_redzone, memory_order_acquire);
331 u32 max_rz = atomic_load(&max_redzone, memory_order_acquire);
332 return Min(Max(rz_log, RZSize2Log(min_rz)), RZSize2Log(max_rz));
335 // We have an address between two chunks, and we want to report just one.
336 AsanChunk *ChooseChunk(uptr addr, AsanChunk *left_chunk,
337 AsanChunk *right_chunk) {
338 // Prefer an allocated chunk over freed chunk and freed chunk
339 // over available chunk.
340 if (left_chunk->chunk_state != right_chunk->chunk_state) {
341 if (left_chunk->chunk_state == CHUNK_ALLOCATED)
343 if (right_chunk->chunk_state == CHUNK_ALLOCATED)
345 if (left_chunk->chunk_state == CHUNK_QUARANTINE)
347 if (right_chunk->chunk_state == CHUNK_QUARANTINE)
350 // Same chunk_state: choose based on offset.
351 sptr l_offset = 0, r_offset = 0;
352 CHECK(AsanChunkView(left_chunk).AddrIsAtRight(addr, 1, &l_offset));
353 CHECK(AsanChunkView(right_chunk).AddrIsAtLeft(addr, 1, &r_offset));
354 if (l_offset < r_offset)
359 // -------------------- Allocation/Deallocation routines ---------------
360 void *Allocate(uptr size, uptr alignment, BufferedStackTrace *stack,
361 AllocType alloc_type, bool can_fill) {
362 if (UNLIKELY(!asan_inited))
364 Flags &fl = *flags();
366 const uptr min_alignment = SHADOW_GRANULARITY;
367 if (alignment < min_alignment)
368 alignment = min_alignment;
370 // We'd be happy to avoid allocating memory for zero-size requests, but
371 // some programs/tests depend on this behavior and assume that malloc
372 // would not return NULL even for zero-size allocations. Moreover, it
373 // looks like operator new should never return NULL, and results of
374 // consecutive "new" calls must be different even if the allocated size
378 CHECK(IsPowerOfTwo(alignment));
379 uptr rz_log = ComputeRZLog(size);
380 uptr rz_size = RZLog2Size(rz_log);
381 uptr rounded_size = RoundUpTo(Max(size, kChunkHeader2Size), alignment);
382 uptr needed_size = rounded_size + rz_size;
383 if (alignment > min_alignment)
384 needed_size += alignment;
385 bool using_primary_allocator = true;
386 // If we are allocating from the secondary allocator, there will be no
387 // automatic right redzone, so add the right redzone manually.
388 if (!PrimaryAllocator::CanAllocate(needed_size, alignment)) {
389 needed_size += rz_size;
390 using_primary_allocator = false;
392 CHECK(IsAligned(needed_size, min_alignment));
393 if (size > kMaxAllowedMallocSize || needed_size > kMaxAllowedMallocSize) {
394 Report("WARNING: AddressSanitizer failed to allocate 0x%zx bytes\n",
396 return allocator.ReturnNullOrDieOnBadRequest();
399 AsanThread *t = GetCurrentThread();
401 bool check_rss_limit = true;
403 AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
405 allocator.Allocate(cache, needed_size, 8, false, check_rss_limit);
407 SpinMutexLock l(&fallback_mutex);
408 AllocatorCache *cache = &fallback_allocator_cache;
410 allocator.Allocate(cache, needed_size, 8, false, check_rss_limit);
413 if (!allocated) return allocator.ReturnNullOrDieOnOOM();
415 if (*(u8 *)MEM_TO_SHADOW((uptr)allocated) == 0 && CanPoisonMemory()) {
416 // Heap poisoning is enabled, but the allocator provides an unpoisoned
417 // chunk. This is possible if CanPoisonMemory() was false for some
418 // time, for example, due to flags()->start_disabled.
419 // Anyway, poison the block before using it for anything else.
420 uptr allocated_size = allocator.GetActuallyAllocatedSize(allocated);
421 PoisonShadow((uptr)allocated, allocated_size, kAsanHeapLeftRedzoneMagic);
424 uptr alloc_beg = reinterpret_cast<uptr>(allocated);
425 uptr alloc_end = alloc_beg + needed_size;
426 uptr beg_plus_redzone = alloc_beg + rz_size;
427 uptr user_beg = beg_plus_redzone;
428 if (!IsAligned(user_beg, alignment))
429 user_beg = RoundUpTo(user_beg, alignment);
430 uptr user_end = user_beg + size;
431 CHECK_LE(user_end, alloc_end);
432 uptr chunk_beg = user_beg - kChunkHeaderSize;
433 AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
434 m->alloc_type = alloc_type;
436 u32 alloc_tid = t ? t->tid() : 0;
437 m->alloc_tid = alloc_tid;
438 CHECK_EQ(alloc_tid, m->alloc_tid); // Does alloc_tid fit into the bitfield?
439 m->free_tid = kInvalidTid;
440 m->from_memalign = user_beg != beg_plus_redzone;
441 if (alloc_beg != chunk_beg) {
442 CHECK_LE(alloc_beg+ 2 * sizeof(uptr), chunk_beg);
443 reinterpret_cast<uptr *>(alloc_beg)[0] = kAllocBegMagic;
444 reinterpret_cast<uptr *>(alloc_beg)[1] = chunk_beg;
446 if (using_primary_allocator) {
448 m->user_requested_size = size;
449 CHECK(allocator.FromPrimary(allocated));
451 CHECK(!allocator.FromPrimary(allocated));
452 m->user_requested_size = SizeClassMap::kMaxSize;
453 uptr *meta = reinterpret_cast<uptr *>(allocator.GetMetaData(allocated));
458 m->alloc_context_id = StackDepotPut(*stack);
460 uptr size_rounded_down_to_granularity =
461 RoundDownTo(size, SHADOW_GRANULARITY);
462 // Unpoison the bulk of the memory region.
463 if (size_rounded_down_to_granularity)
464 PoisonShadow(user_beg, size_rounded_down_to_granularity, 0);
465 // Deal with the end of the region if size is not aligned to granularity.
466 if (size != size_rounded_down_to_granularity && CanPoisonMemory()) {
468 (u8 *)MemToShadow(user_beg + size_rounded_down_to_granularity);
469 *shadow = fl.poison_partial ? (size & (SHADOW_GRANULARITY - 1)) : 0;
472 AsanStats &thread_stats = GetCurrentThreadStats();
473 thread_stats.mallocs++;
474 thread_stats.malloced += size;
475 thread_stats.malloced_redzones += needed_size - size;
476 if (needed_size > SizeClassMap::kMaxSize)
477 thread_stats.malloc_large++;
479 thread_stats.malloced_by_size[SizeClassMap::ClassID(needed_size)]++;
481 void *res = reinterpret_cast<void *>(user_beg);
482 if (can_fill && fl.max_malloc_fill_size) {
483 uptr fill_size = Min(size, (uptr)fl.max_malloc_fill_size);
484 REAL(memset)(res, fl.malloc_fill_byte, fill_size);
486 #if CAN_SANITIZE_LEAKS
487 m->lsan_tag = __lsan::DisabledInThisThread() ? __lsan::kIgnored
488 : __lsan::kDirectlyLeaked;
490 // Must be the last mutation of metadata in this function.
491 atomic_store((atomic_uint8_t *)m, CHUNK_ALLOCATED, memory_order_release);
492 ASAN_MALLOC_HOOK(res, size);
496 // Set quarantine flag if chunk is allocated, issue ASan error report on
497 // available and quarantined chunks. Return true on success, false otherwise.
498 bool AtomicallySetQuarantineFlagIfAllocated(AsanChunk *m, void *ptr,
499 BufferedStackTrace *stack) {
500 u8 old_chunk_state = CHUNK_ALLOCATED;
501 // Flip the chunk_state atomically to avoid race on double-free.
502 if (!atomic_compare_exchange_strong((atomic_uint8_t *)m, &old_chunk_state,
504 memory_order_acquire)) {
505 ReportInvalidFree(ptr, old_chunk_state, stack);
506 // It's not safe to push a chunk in quarantine on invalid free.
509 CHECK_EQ(CHUNK_ALLOCATED, old_chunk_state);
513 // Expects the chunk to already be marked as quarantined by using
514 // AtomicallySetQuarantineFlagIfAllocated.
515 void QuarantineChunk(AsanChunk *m, void *ptr, BufferedStackTrace *stack,
516 AllocType alloc_type) {
517 CHECK_EQ(m->chunk_state, CHUNK_QUARANTINE);
518 CHECK_GE(m->alloc_tid, 0);
519 if (SANITIZER_WORDSIZE == 64) // On 32-bits this resides in user area.
520 CHECK_EQ(m->free_tid, kInvalidTid);
521 AsanThread *t = GetCurrentThread();
522 m->free_tid = t ? t->tid() : 0;
523 m->free_context_id = StackDepotPut(*stack);
525 Flags &fl = *flags();
526 if (fl.max_free_fill_size > 0) {
527 // We have to skip the chunk header, it contains free_context_id.
528 uptr scribble_start = (uptr)m + kChunkHeaderSize + kChunkHeader2Size;
529 if (m->UsedSize() >= kChunkHeader2Size) { // Skip Header2 in user area.
530 uptr size_to_fill = m->UsedSize() - kChunkHeader2Size;
531 size_to_fill = Min(size_to_fill, (uptr)fl.max_free_fill_size);
532 REAL(memset)((void *)scribble_start, fl.free_fill_byte, size_to_fill);
536 // Poison the region.
537 PoisonShadow(m->Beg(),
538 RoundUpTo(m->UsedSize(), SHADOW_GRANULARITY),
541 AsanStats &thread_stats = GetCurrentThreadStats();
542 thread_stats.frees++;
543 thread_stats.freed += m->UsedSize();
545 // Push into quarantine.
547 AsanThreadLocalMallocStorage *ms = &t->malloc_storage();
548 AllocatorCache *ac = GetAllocatorCache(ms);
549 quarantine.Put(GetQuarantineCache(ms), QuarantineCallback(ac), m,
552 SpinMutexLock l(&fallback_mutex);
553 AllocatorCache *ac = &fallback_allocator_cache;
554 quarantine.Put(&fallback_quarantine_cache, QuarantineCallback(ac), m,
559 void Deallocate(void *ptr, uptr delete_size, BufferedStackTrace *stack,
560 AllocType alloc_type) {
561 uptr p = reinterpret_cast<uptr>(ptr);
564 uptr chunk_beg = p - kChunkHeaderSize;
565 AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
567 // On Windows, uninstrumented DLLs may allocate memory before ASan hooks
568 // malloc. Don't report an invalid free in this case.
569 if (SANITIZER_WINDOWS &&
570 !get_allocator().PointerIsMine(ptr)) {
571 if (!IsSystemHeapAddress(p))
572 ReportFreeNotMalloced(p, stack);
578 // Must mark the chunk as quarantined before any changes to its metadata.
579 // Do not quarantine given chunk if we failed to set CHUNK_QUARANTINE flag.
580 if (!AtomicallySetQuarantineFlagIfAllocated(m, ptr, stack)) return;
582 if (m->alloc_type != alloc_type) {
583 if (atomic_load(&alloc_dealloc_mismatch, memory_order_acquire)) {
584 ReportAllocTypeMismatch((uptr)ptr, stack, (AllocType)m->alloc_type,
585 (AllocType)alloc_type);
589 if (delete_size && flags()->new_delete_type_mismatch &&
590 delete_size != m->UsedSize()) {
591 ReportNewDeleteSizeMismatch(p, delete_size, stack);
594 QuarantineChunk(m, ptr, stack, alloc_type);
597 void *Reallocate(void *old_ptr, uptr new_size, BufferedStackTrace *stack) {
598 CHECK(old_ptr && new_size);
599 uptr p = reinterpret_cast<uptr>(old_ptr);
600 uptr chunk_beg = p - kChunkHeaderSize;
601 AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
603 AsanStats &thread_stats = GetCurrentThreadStats();
604 thread_stats.reallocs++;
605 thread_stats.realloced += new_size;
607 void *new_ptr = Allocate(new_size, 8, stack, FROM_MALLOC, true);
609 u8 chunk_state = m->chunk_state;
610 if (chunk_state != CHUNK_ALLOCATED)
611 ReportInvalidFree(old_ptr, chunk_state, stack);
612 CHECK_NE(REAL(memcpy), nullptr);
613 uptr memcpy_size = Min(new_size, m->UsedSize());
614 // If realloc() races with free(), we may start copying freed memory.
615 // However, we will report racy double-free later anyway.
616 REAL(memcpy)(new_ptr, old_ptr, memcpy_size);
617 Deallocate(old_ptr, 0, stack, FROM_MALLOC);
622 void *Calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) {
623 if (CallocShouldReturnNullDueToOverflow(size, nmemb))
624 return allocator.ReturnNullOrDieOnBadRequest();
625 void *ptr = Allocate(nmemb * size, 8, stack, FROM_MALLOC, false);
626 // If the memory comes from the secondary allocator no need to clear it
627 // as it comes directly from mmap.
628 if (ptr && allocator.FromPrimary(ptr))
629 REAL(memset)(ptr, 0, nmemb * size);
633 void ReportInvalidFree(void *ptr, u8 chunk_state, BufferedStackTrace *stack) {
634 if (chunk_state == CHUNK_QUARANTINE)
635 ReportDoubleFree((uptr)ptr, stack);
637 ReportFreeNotMalloced((uptr)ptr, stack);
640 void CommitBack(AsanThreadLocalMallocStorage *ms) {
641 AllocatorCache *ac = GetAllocatorCache(ms);
642 quarantine.Drain(GetQuarantineCache(ms), QuarantineCallback(ac));
643 allocator.SwallowCache(ac);
646 // -------------------------- Chunk lookup ----------------------
648 // Assumes alloc_beg == allocator.GetBlockBegin(alloc_beg).
649 AsanChunk *GetAsanChunk(void *alloc_beg) {
650 if (!alloc_beg) return nullptr;
651 if (!allocator.FromPrimary(alloc_beg)) {
652 uptr *meta = reinterpret_cast<uptr *>(allocator.GetMetaData(alloc_beg));
653 AsanChunk *m = reinterpret_cast<AsanChunk *>(meta[1]);
656 uptr *alloc_magic = reinterpret_cast<uptr *>(alloc_beg);
657 if (alloc_magic[0] == kAllocBegMagic)
658 return reinterpret_cast<AsanChunk *>(alloc_magic[1]);
659 return reinterpret_cast<AsanChunk *>(alloc_beg);
662 AsanChunk *GetAsanChunkByAddr(uptr p) {
663 void *alloc_beg = allocator.GetBlockBegin(reinterpret_cast<void *>(p));
664 return GetAsanChunk(alloc_beg);
667 // Allocator must be locked when this function is called.
668 AsanChunk *GetAsanChunkByAddrFastLocked(uptr p) {
670 allocator.GetBlockBeginFastLocked(reinterpret_cast<void *>(p));
671 return GetAsanChunk(alloc_beg);
674 uptr AllocationSize(uptr p) {
675 AsanChunk *m = GetAsanChunkByAddr(p);
677 if (m->chunk_state != CHUNK_ALLOCATED) return 0;
678 if (m->Beg() != p) return 0;
679 return m->UsedSize();
682 AsanChunkView FindHeapChunkByAddress(uptr addr) {
683 AsanChunk *m1 = GetAsanChunkByAddr(addr);
684 if (!m1) return AsanChunkView(m1);
686 if (AsanChunkView(m1).AddrIsAtLeft(addr, 1, &offset)) {
687 // The address is in the chunk's left redzone, so maybe it is actually
688 // a right buffer overflow from the other chunk to the left.
689 // Search a bit to the left to see if there is another chunk.
690 AsanChunk *m2 = nullptr;
691 for (uptr l = 1; l < GetPageSizeCached(); l++) {
692 m2 = GetAsanChunkByAddr(addr - l);
693 if (m2 == m1) continue; // Still the same chunk.
696 if (m2 && AsanChunkView(m2).AddrIsAtRight(addr, 1, &offset))
697 m1 = ChooseChunk(addr, m2, m1);
699 return AsanChunkView(m1);
703 allocator.PrintStats();
704 quarantine.PrintStats();
708 allocator.ForceLock();
709 fallback_mutex.Lock();
713 fallback_mutex.Unlock();
714 allocator.ForceUnlock();
718 static Allocator instance(LINKER_INITIALIZED);
720 AsanAllocator &get_allocator() {
721 return instance.allocator;
724 bool AsanChunkView::IsValid() const {
725 return chunk_ && chunk_->chunk_state != CHUNK_AVAILABLE;
727 bool AsanChunkView::IsAllocated() const {
728 return chunk_ && chunk_->chunk_state == CHUNK_ALLOCATED;
730 bool AsanChunkView::IsQuarantined() const {
731 return chunk_ && chunk_->chunk_state == CHUNK_QUARANTINE;
733 uptr AsanChunkView::Beg() const { return chunk_->Beg(); }
734 uptr AsanChunkView::End() const { return Beg() + UsedSize(); }
735 uptr AsanChunkView::UsedSize() const { return chunk_->UsedSize(); }
736 uptr AsanChunkView::AllocTid() const { return chunk_->alloc_tid; }
737 uptr AsanChunkView::FreeTid() const { return chunk_->free_tid; }
738 AllocType AsanChunkView::GetAllocType() const {
739 return (AllocType)chunk_->alloc_type;
742 static StackTrace GetStackTraceFromId(u32 id) {
744 StackTrace res = StackDepotGet(id);
749 u32 AsanChunkView::GetAllocStackId() const { return chunk_->alloc_context_id; }
750 u32 AsanChunkView::GetFreeStackId() const { return chunk_->free_context_id; }
752 StackTrace AsanChunkView::GetAllocStack() const {
753 return GetStackTraceFromId(GetAllocStackId());
756 StackTrace AsanChunkView::GetFreeStack() const {
757 return GetStackTraceFromId(GetFreeStackId());
760 void InitializeAllocator(const AllocatorOptions &options) {
761 instance.Initialize(options);
764 void ReInitializeAllocator(const AllocatorOptions &options) {
765 instance.ReInitialize(options);
768 void GetAllocatorOptions(AllocatorOptions *options) {
769 instance.GetOptions(options);
772 AsanChunkView FindHeapChunkByAddress(uptr addr) {
773 return instance.FindHeapChunkByAddress(addr);
775 AsanChunkView FindHeapChunkByAllocBeg(uptr addr) {
776 return AsanChunkView(instance.GetAsanChunk(reinterpret_cast<void*>(addr)));
779 void AsanThreadLocalMallocStorage::CommitBack() {
780 instance.CommitBack(this);
783 void PrintInternalAllocatorStats() {
784 instance.PrintStats();
787 void *asan_memalign(uptr alignment, uptr size, BufferedStackTrace *stack,
788 AllocType alloc_type) {
789 return instance.Allocate(size, alignment, stack, alloc_type, true);
792 void asan_free(void *ptr, BufferedStackTrace *stack, AllocType alloc_type) {
793 instance.Deallocate(ptr, 0, stack, alloc_type);
796 void asan_sized_free(void *ptr, uptr size, BufferedStackTrace *stack,
797 AllocType alloc_type) {
798 instance.Deallocate(ptr, size, stack, alloc_type);
801 void *asan_malloc(uptr size, BufferedStackTrace *stack) {
802 return instance.Allocate(size, 8, stack, FROM_MALLOC, true);
805 void *asan_calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) {
806 return instance.Calloc(nmemb, size, stack);
809 void *asan_realloc(void *p, uptr size, BufferedStackTrace *stack) {
811 return instance.Allocate(size, 8, stack, FROM_MALLOC, true);
813 if (flags()->allocator_frees_and_returns_null_on_realloc_zero) {
814 instance.Deallocate(p, 0, stack, FROM_MALLOC);
817 // Allocate a size of 1 if we shouldn't free() on Realloc to 0
820 return instance.Reallocate(p, size, stack);
823 void *asan_valloc(uptr size, BufferedStackTrace *stack) {
824 return instance.Allocate(size, GetPageSizeCached(), stack, FROM_MALLOC, true);
827 void *asan_pvalloc(uptr size, BufferedStackTrace *stack) {
828 uptr PageSize = GetPageSizeCached();
829 size = RoundUpTo(size, PageSize);
831 // pvalloc(0) should allocate one page.
834 return instance.Allocate(size, PageSize, stack, FROM_MALLOC, true);
837 int asan_posix_memalign(void **memptr, uptr alignment, uptr size,
838 BufferedStackTrace *stack) {
839 void *ptr = instance.Allocate(size, alignment, stack, FROM_MALLOC, true);
840 CHECK(IsAligned((uptr)ptr, alignment));
845 uptr asan_malloc_usable_size(const void *ptr, uptr pc, uptr bp) {
847 uptr usable_size = instance.AllocationSize(reinterpret_cast<uptr>(ptr));
848 if (flags()->check_malloc_usable_size && (usable_size == 0)) {
849 GET_STACK_TRACE_FATAL(pc, bp);
850 ReportMallocUsableSizeNotOwned((uptr)ptr, &stack);
855 uptr asan_mz_size(const void *ptr) {
856 return instance.AllocationSize(reinterpret_cast<uptr>(ptr));
859 void asan_mz_force_lock() {
860 instance.ForceLock();
863 void asan_mz_force_unlock() {
864 instance.ForceUnlock();
867 void AsanSoftRssLimitExceededCallback(bool exceeded) {
868 instance.allocator.SetRssLimitIsExceeded(exceeded);
871 } // namespace __asan
873 // --- Implementation of LSan-specific functions --- {{{1
875 void LockAllocator() {
876 __asan::get_allocator().ForceLock();
879 void UnlockAllocator() {
880 __asan::get_allocator().ForceUnlock();
883 void GetAllocatorGlobalRange(uptr *begin, uptr *end) {
884 *begin = (uptr)&__asan::get_allocator();
885 *end = *begin + sizeof(__asan::get_allocator());
888 uptr PointsIntoChunk(void* p) {
889 uptr addr = reinterpret_cast<uptr>(p);
890 __asan::AsanChunk *m = __asan::instance.GetAsanChunkByAddrFastLocked(addr);
892 uptr chunk = m->Beg();
893 if (m->chunk_state != __asan::CHUNK_ALLOCATED)
895 if (m->AddrIsInside(addr, /*locked_version=*/true))
897 if (IsSpecialCaseOfOperatorNew0(chunk, m->UsedSize(/*locked_version*/ true),
903 uptr GetUserBegin(uptr chunk) {
904 __asan::AsanChunk *m = __asan::instance.GetAsanChunkByAddrFastLocked(chunk);
909 LsanMetadata::LsanMetadata(uptr chunk) {
910 metadata_ = reinterpret_cast<void *>(chunk - __asan::kChunkHeaderSize);
913 bool LsanMetadata::allocated() const {
914 __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
915 return m->chunk_state == __asan::CHUNK_ALLOCATED;
918 ChunkTag LsanMetadata::tag() const {
919 __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
920 return static_cast<ChunkTag>(m->lsan_tag);
923 void LsanMetadata::set_tag(ChunkTag value) {
924 __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
928 uptr LsanMetadata::requested_size() const {
929 __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
930 return m->UsedSize(/*locked_version=*/true);
933 u32 LsanMetadata::stack_trace_id() const {
934 __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
935 return m->alloc_context_id;
938 void ForEachChunk(ForEachChunkCallback callback, void *arg) {
939 __asan::get_allocator().ForEachChunk(callback, arg);
942 IgnoreObjectResult IgnoreObjectLocked(const void *p) {
943 uptr addr = reinterpret_cast<uptr>(p);
944 __asan::AsanChunk *m = __asan::instance.GetAsanChunkByAddr(addr);
945 if (!m) return kIgnoreObjectInvalid;
946 if ((m->chunk_state == __asan::CHUNK_ALLOCATED) && m->AddrIsInside(addr)) {
947 if (m->lsan_tag == kIgnored)
948 return kIgnoreObjectAlreadyIgnored;
949 m->lsan_tag = __lsan::kIgnored;
950 return kIgnoreObjectSuccess;
952 return kIgnoreObjectInvalid;
955 } // namespace __lsan
957 // ---------------------- Interface ---------------- {{{1
958 using namespace __asan; // NOLINT
960 // ASan allocator doesn't reserve extra bytes, so normally we would
961 // just return "size". We don't want to expose our redzone sizes, etc here.
962 uptr __sanitizer_get_estimated_allocated_size(uptr size) {
966 int __sanitizer_get_ownership(const void *p) {
967 uptr ptr = reinterpret_cast<uptr>(p);
968 return instance.AllocationSize(ptr) > 0;
971 uptr __sanitizer_get_allocated_size(const void *p) {
973 uptr ptr = reinterpret_cast<uptr>(p);
974 uptr allocated_size = instance.AllocationSize(ptr);
975 // Die if p is not malloced or if it is already freed.
976 if (allocated_size == 0) {
977 GET_STACK_TRACE_FATAL_HERE;
978 ReportSanitizerGetAllocatedSizeNotOwned(ptr, &stack);
980 return allocated_size;
983 #if !SANITIZER_SUPPORTS_WEAK_HOOKS
984 // Provide default (no-op) implementation of malloc hooks.
985 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_malloc_hook,
986 void *ptr, uptr size) {
991 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_free_hook, void *ptr) {