1 //===-- asan_allocator2.cc ------------------------------------------------===//
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
6 //===----------------------------------------------------------------------===//
8 // This file is a part of AddressSanitizer, an address sanity checker.
10 // Implementation of ASan's memory allocator, 2-nd version.
11 // This variant uses the allocator from sanitizer_common, i.e. the one shared
12 // with ThreadSanitizer and MemorySanitizer.
14 //===----------------------------------------------------------------------===//
15 #include "asan_allocator.h"
17 #include "asan_mapping.h"
18 #include "asan_poisoning.h"
19 #include "asan_report.h"
20 #include "asan_stack.h"
21 #include "asan_thread.h"
22 #include "sanitizer_common/sanitizer_allocator_interface.h"
23 #include "sanitizer_common/sanitizer_flags.h"
24 #include "sanitizer_common/sanitizer_internal_defs.h"
25 #include "sanitizer_common/sanitizer_list.h"
26 #include "sanitizer_common/sanitizer_stackdepot.h"
27 #include "sanitizer_common/sanitizer_quarantine.h"
28 #include "lsan/lsan_common.h"
32 void AsanMapUnmapCallback::OnMap(uptr p
, uptr size
) const {
33 PoisonShadow(p
, size
, kAsanHeapLeftRedzoneMagic
);
35 AsanStats
&thread_stats
= GetCurrentThreadStats();
37 thread_stats
.mmaped
+= size
;
39 void AsanMapUnmapCallback::OnUnmap(uptr p
, uptr size
) const {
40 PoisonShadow(p
, size
, 0);
41 // We are about to unmap a chunk of user memory.
42 // Mark the corresponding shadow memory as not needed.
43 FlushUnneededASanShadowMemory(p
, size
);
45 AsanStats
&thread_stats
= GetCurrentThreadStats();
46 thread_stats
.munmaps
++;
47 thread_stats
.munmaped
+= size
;
50 // We can not use THREADLOCAL because it is not supported on some of the
51 // platforms we care about (OSX 10.6, Android).
52 // static THREADLOCAL AllocatorCache cache;
53 AllocatorCache
*GetAllocatorCache(AsanThreadLocalMallocStorage
*ms
) {
55 return &ms
->allocator2_cache
;
58 static Allocator allocator
;
60 static const uptr kMaxAllowedMallocSize
=
61 FIRST_32_SECOND_64(3UL << 30, 64UL << 30);
63 static const uptr kMaxThreadLocalQuarantine
=
64 FIRST_32_SECOND_64(1 << 18, 1 << 20);
66 // Every chunk of memory allocated by this allocator can be in one of 3 states:
67 // CHUNK_AVAILABLE: the chunk is in the free list and ready to be allocated.
68 // CHUNK_ALLOCATED: the chunk is allocated and not yet freed.
69 // CHUNK_QUARANTINE: the chunk was freed and put into quarantine zone.
71 CHUNK_AVAILABLE
= 0, // 0 is the default value even if we didn't set it.
76 // Valid redzone sizes are 16, 32, 64, ... 2048, so we encode them in 3 bits.
77 // We use adaptive redzones: for larger allocation larger redzones are used.
78 static u32
RZLog2Size(u32 rz_log
) {
83 static u32
RZSize2Log(u32 rz_size
) {
84 CHECK_GE(rz_size
, 16);
85 CHECK_LE(rz_size
, 2048);
86 CHECK(IsPowerOfTwo(rz_size
));
87 u32 res
= Log2(rz_size
) - 4;
88 CHECK_EQ(rz_size
, RZLog2Size(res
));
92 static uptr
ComputeRZLog(uptr user_requested_size
) {
94 user_requested_size
<= 64 - 16 ? 0 :
95 user_requested_size
<= 128 - 32 ? 1 :
96 user_requested_size
<= 512 - 64 ? 2 :
97 user_requested_size
<= 4096 - 128 ? 3 :
98 user_requested_size
<= (1 << 14) - 256 ? 4 :
99 user_requested_size
<= (1 << 15) - 512 ? 5 :
100 user_requested_size
<= (1 << 16) - 1024 ? 6 : 7;
101 return Min(Max(rz_log
, RZSize2Log(flags()->redzone
)),
102 RZSize2Log(flags()->max_redzone
));
105 // The memory chunk allocated from the underlying allocator looks like this:
106 // L L L L L L H H U U U U U U R R
107 // L -- left redzone words (0 or more bytes)
108 // H -- ChunkHeader (16 bytes), which is also a part of the left redzone.
110 // R -- right redzone (0 or more bytes)
111 // ChunkBase consists of ChunkHeader and other bytes that overlap with user
114 // If the left redzone is greater than the ChunkHeader size we store a magic
115 // value in the first uptr word of the memory block and store the address of
116 // ChunkBase in the next uptr.
117 // M B L L L L L L L L L H H U U U U U U
119 // ---------------------|
120 // M -- magic value kAllocBegMagic
121 // B -- address of ChunkHeader pointing to the first 'H'
122 static const uptr kAllocBegMagic
= 0xCC6E96B9;
126 u32 chunk_state
: 8; // Must be first.
130 u32 from_memalign
: 1;
135 // This field is used for small sizes. For large sizes it is equal to
136 // SizeClassMap::kMaxSize and the actual size is stored in the
137 // SecondaryAllocator's metadata.
138 u32 user_requested_size
;
139 u32 alloc_context_id
;
142 struct ChunkBase
: ChunkHeader
{
143 // Header2, intersects with user memory.
147 static const uptr kChunkHeaderSize
= sizeof(ChunkHeader
);
148 static const uptr kChunkHeader2Size
= sizeof(ChunkBase
) - kChunkHeaderSize
;
149 COMPILER_CHECK(kChunkHeaderSize
== 16);
150 COMPILER_CHECK(kChunkHeader2Size
<= 16);
152 struct AsanChunk
: ChunkBase
{
153 uptr
Beg() { return reinterpret_cast<uptr
>(this) + kChunkHeaderSize
; }
154 uptr
UsedSize(bool locked_version
= false) {
155 if (user_requested_size
!= SizeClassMap::kMaxSize
)
156 return user_requested_size
;
157 return *reinterpret_cast<uptr
*>(
158 allocator
.GetMetaData(AllocBeg(locked_version
)));
160 void *AllocBeg(bool locked_version
= false) {
163 return allocator
.GetBlockBeginFastLocked(
164 reinterpret_cast<void *>(this));
165 return allocator
.GetBlockBegin(reinterpret_cast<void *>(this));
167 return reinterpret_cast<void*>(Beg() - RZLog2Size(rz_log
));
169 bool AddrIsInside(uptr addr
, bool locked_version
= false) {
170 return (addr
>= Beg()) && (addr
< Beg() + UsedSize(locked_version
));
174 bool AsanChunkView::IsValid() {
175 return chunk_
!= 0 && chunk_
->chunk_state
!= CHUNK_AVAILABLE
;
177 uptr
AsanChunkView::Beg() { return chunk_
->Beg(); }
178 uptr
AsanChunkView::End() { return Beg() + UsedSize(); }
179 uptr
AsanChunkView::UsedSize() { return chunk_
->UsedSize(); }
180 uptr
AsanChunkView::AllocTid() { return chunk_
->alloc_tid
; }
181 uptr
AsanChunkView::FreeTid() { return chunk_
->free_tid
; }
183 static StackTrace
GetStackTraceFromId(u32 id
) {
185 StackTrace res
= StackDepotGet(id
);
190 StackTrace
AsanChunkView::GetAllocStack() {
191 return GetStackTraceFromId(chunk_
->alloc_context_id
);
194 StackTrace
AsanChunkView::GetFreeStack() {
195 return GetStackTraceFromId(chunk_
->free_context_id
);
198 struct QuarantineCallback
;
199 typedef Quarantine
<QuarantineCallback
, AsanChunk
> AsanQuarantine
;
200 typedef AsanQuarantine::Cache QuarantineCache
;
201 static AsanQuarantine
quarantine(LINKER_INITIALIZED
);
202 static QuarantineCache
fallback_quarantine_cache(LINKER_INITIALIZED
);
203 static AllocatorCache fallback_allocator_cache
;
204 static SpinMutex fallback_mutex
;
206 QuarantineCache
*GetQuarantineCache(AsanThreadLocalMallocStorage
*ms
) {
208 CHECK_LE(sizeof(QuarantineCache
), sizeof(ms
->quarantine_cache
));
209 return reinterpret_cast<QuarantineCache
*>(ms
->quarantine_cache
);
212 struct QuarantineCallback
{
213 explicit QuarantineCallback(AllocatorCache
*cache
)
217 void Recycle(AsanChunk
*m
) {
218 CHECK_EQ(m
->chunk_state
, CHUNK_QUARANTINE
);
219 atomic_store((atomic_uint8_t
*)m
, CHUNK_AVAILABLE
, memory_order_relaxed
);
220 CHECK_NE(m
->alloc_tid
, kInvalidTid
);
221 CHECK_NE(m
->free_tid
, kInvalidTid
);
222 PoisonShadow(m
->Beg(),
223 RoundUpTo(m
->UsedSize(), SHADOW_GRANULARITY
),
224 kAsanHeapLeftRedzoneMagic
);
225 void *p
= reinterpret_cast<void *>(m
->AllocBeg());
227 uptr
*alloc_magic
= reinterpret_cast<uptr
*>(p
);
228 CHECK_EQ(alloc_magic
[0], kAllocBegMagic
);
229 // Clear the magic value, as allocator internals may overwrite the
230 // contents of deallocated chunk, confusing GetAsanChunk lookup.
232 CHECK_EQ(alloc_magic
[1], reinterpret_cast<uptr
>(m
));
236 AsanStats
&thread_stats
= GetCurrentThreadStats();
237 thread_stats
.real_frees
++;
238 thread_stats
.really_freed
+= m
->UsedSize();
240 allocator
.Deallocate(cache_
, p
);
243 void *Allocate(uptr size
) {
244 return allocator
.Allocate(cache_
, size
, 1, false);
247 void Deallocate(void *p
) {
248 allocator
.Deallocate(cache_
, p
);
251 AllocatorCache
*cache_
;
254 void InitializeAllocator() {
256 quarantine
.Init((uptr
)flags()->quarantine_size
, kMaxThreadLocalQuarantine
);
259 void ReInitializeAllocator() {
260 quarantine
.Init((uptr
)flags()->quarantine_size
, kMaxThreadLocalQuarantine
);
263 static void *Allocate(uptr size
, uptr alignment
, BufferedStackTrace
*stack
,
264 AllocType alloc_type
, bool can_fill
) {
265 if (UNLIKELY(!asan_inited
))
267 Flags
&fl
= *flags();
269 const uptr min_alignment
= SHADOW_GRANULARITY
;
270 if (alignment
< min_alignment
)
271 alignment
= min_alignment
;
273 // We'd be happy to avoid allocating memory for zero-size requests, but
274 // some programs/tests depend on this behavior and assume that malloc would
275 // not return NULL even for zero-size allocations. Moreover, it looks like
276 // operator new should never return NULL, and results of consecutive "new"
277 // calls must be different even if the allocated size is zero.
280 CHECK(IsPowerOfTwo(alignment
));
281 uptr rz_log
= ComputeRZLog(size
);
282 uptr rz_size
= RZLog2Size(rz_log
);
283 uptr rounded_size
= RoundUpTo(Max(size
, kChunkHeader2Size
), alignment
);
284 uptr needed_size
= rounded_size
+ rz_size
;
285 if (alignment
> min_alignment
)
286 needed_size
+= alignment
;
287 bool using_primary_allocator
= true;
288 // If we are allocating from the secondary allocator, there will be no
289 // automatic right redzone, so add the right redzone manually.
290 if (!PrimaryAllocator::CanAllocate(needed_size
, alignment
)) {
291 needed_size
+= rz_size
;
292 using_primary_allocator
= false;
294 CHECK(IsAligned(needed_size
, min_alignment
));
295 if (size
> kMaxAllowedMallocSize
|| needed_size
> kMaxAllowedMallocSize
) {
296 Report("WARNING: AddressSanitizer failed to allocate %p bytes\n",
298 return AllocatorReturnNull();
301 AsanThread
*t
= GetCurrentThread();
304 AllocatorCache
*cache
= GetAllocatorCache(&t
->malloc_storage());
305 allocated
= allocator
.Allocate(cache
, needed_size
, 8, false);
307 SpinMutexLock
l(&fallback_mutex
);
308 AllocatorCache
*cache
= &fallback_allocator_cache
;
309 allocated
= allocator
.Allocate(cache
, needed_size
, 8, false);
312 if (*(u8
*)MEM_TO_SHADOW((uptr
)allocated
) == 0 && flags()->poison_heap
) {
313 // Heap poisoning is enabled, but the allocator provides an unpoisoned
314 // chunk. This is possible if flags()->poison_heap was disabled for some
315 // time, for example, due to flags()->start_disabled.
316 // Anyway, poison the block before using it for anything else.
317 uptr allocated_size
= allocator
.GetActuallyAllocatedSize(allocated
);
318 PoisonShadow((uptr
)allocated
, allocated_size
, kAsanHeapLeftRedzoneMagic
);
321 uptr alloc_beg
= reinterpret_cast<uptr
>(allocated
);
322 uptr alloc_end
= alloc_beg
+ needed_size
;
323 uptr beg_plus_redzone
= alloc_beg
+ rz_size
;
324 uptr user_beg
= beg_plus_redzone
;
325 if (!IsAligned(user_beg
, alignment
))
326 user_beg
= RoundUpTo(user_beg
, alignment
);
327 uptr user_end
= user_beg
+ size
;
328 CHECK_LE(user_end
, alloc_end
);
329 uptr chunk_beg
= user_beg
- kChunkHeaderSize
;
330 AsanChunk
*m
= reinterpret_cast<AsanChunk
*>(chunk_beg
);
331 m
->alloc_type
= alloc_type
;
333 u32 alloc_tid
= t
? t
->tid() : 0;
334 m
->alloc_tid
= alloc_tid
;
335 CHECK_EQ(alloc_tid
, m
->alloc_tid
); // Does alloc_tid fit into the bitfield?
336 m
->free_tid
= kInvalidTid
;
337 m
->from_memalign
= user_beg
!= beg_plus_redzone
;
338 if (alloc_beg
!= chunk_beg
) {
339 CHECK_LE(alloc_beg
+ 2 * sizeof(uptr
), chunk_beg
);
340 reinterpret_cast<uptr
*>(alloc_beg
)[0] = kAllocBegMagic
;
341 reinterpret_cast<uptr
*>(alloc_beg
)[1] = chunk_beg
;
343 if (using_primary_allocator
) {
345 m
->user_requested_size
= size
;
346 CHECK(allocator
.FromPrimary(allocated
));
348 CHECK(!allocator
.FromPrimary(allocated
));
349 m
->user_requested_size
= SizeClassMap::kMaxSize
;
350 uptr
*meta
= reinterpret_cast<uptr
*>(allocator
.GetMetaData(allocated
));
355 m
->alloc_context_id
= StackDepotPut(*stack
);
357 uptr size_rounded_down_to_granularity
= RoundDownTo(size
, SHADOW_GRANULARITY
);
358 // Unpoison the bulk of the memory region.
359 if (size_rounded_down_to_granularity
)
360 PoisonShadow(user_beg
, size_rounded_down_to_granularity
, 0);
361 // Deal with the end of the region if size is not aligned to granularity.
362 if (size
!= size_rounded_down_to_granularity
&& fl
.poison_heap
) {
363 u8
*shadow
= (u8
*)MemToShadow(user_beg
+ size_rounded_down_to_granularity
);
364 *shadow
= fl
.poison_partial
? (size
& (SHADOW_GRANULARITY
- 1)) : 0;
367 AsanStats
&thread_stats
= GetCurrentThreadStats();
368 thread_stats
.mallocs
++;
369 thread_stats
.malloced
+= size
;
370 thread_stats
.malloced_redzones
+= needed_size
- size
;
371 uptr class_id
= Min(kNumberOfSizeClasses
, SizeClassMap::ClassID(needed_size
));
372 thread_stats
.malloced_by_size
[class_id
]++;
373 if (needed_size
> SizeClassMap::kMaxSize
)
374 thread_stats
.malloc_large
++;
376 void *res
= reinterpret_cast<void *>(user_beg
);
377 if (can_fill
&& fl
.max_malloc_fill_size
) {
378 uptr fill_size
= Min(size
, (uptr
)fl
.max_malloc_fill_size
);
379 REAL(memset
)(res
, fl
.malloc_fill_byte
, fill_size
);
381 #if CAN_SANITIZE_LEAKS
382 m
->lsan_tag
= __lsan::DisabledInThisThread() ? __lsan::kIgnored
383 : __lsan::kDirectlyLeaked
;
385 // Must be the last mutation of metadata in this function.
386 atomic_store((atomic_uint8_t
*)m
, CHUNK_ALLOCATED
, memory_order_release
);
387 ASAN_MALLOC_HOOK(res
, size
);
391 static void ReportInvalidFree(void *ptr
, u8 chunk_state
,
392 BufferedStackTrace
*stack
) {
393 if (chunk_state
== CHUNK_QUARANTINE
)
394 ReportDoubleFree((uptr
)ptr
, stack
);
396 ReportFreeNotMalloced((uptr
)ptr
, stack
);
399 static void AtomicallySetQuarantineFlag(AsanChunk
*m
, void *ptr
,
400 BufferedStackTrace
*stack
) {
401 u8 old_chunk_state
= CHUNK_ALLOCATED
;
402 // Flip the chunk_state atomically to avoid race on double-free.
403 if (!atomic_compare_exchange_strong((atomic_uint8_t
*)m
, &old_chunk_state
,
404 CHUNK_QUARANTINE
, memory_order_acquire
))
405 ReportInvalidFree(ptr
, old_chunk_state
, stack
);
406 CHECK_EQ(CHUNK_ALLOCATED
, old_chunk_state
);
409 // Expects the chunk to already be marked as quarantined by using
410 // AtomicallySetQuarantineFlag.
411 static void QuarantineChunk(AsanChunk
*m
, void *ptr
, BufferedStackTrace
*stack
,
412 AllocType alloc_type
) {
413 CHECK_EQ(m
->chunk_state
, CHUNK_QUARANTINE
);
415 if (m
->alloc_type
!= alloc_type
&& flags()->alloc_dealloc_mismatch
)
416 ReportAllocTypeMismatch((uptr
)ptr
, stack
,
417 (AllocType
)m
->alloc_type
, (AllocType
)alloc_type
);
419 CHECK_GE(m
->alloc_tid
, 0);
420 if (SANITIZER_WORDSIZE
== 64) // On 32-bits this resides in user area.
421 CHECK_EQ(m
->free_tid
, kInvalidTid
);
422 AsanThread
*t
= GetCurrentThread();
423 m
->free_tid
= t
? t
->tid() : 0;
424 m
->free_context_id
= StackDepotPut(*stack
);
425 // Poison the region.
426 PoisonShadow(m
->Beg(),
427 RoundUpTo(m
->UsedSize(), SHADOW_GRANULARITY
),
430 AsanStats
&thread_stats
= GetCurrentThreadStats();
431 thread_stats
.frees
++;
432 thread_stats
.freed
+= m
->UsedSize();
434 // Push into quarantine.
436 AsanThreadLocalMallocStorage
*ms
= &t
->malloc_storage();
437 AllocatorCache
*ac
= GetAllocatorCache(ms
);
438 quarantine
.Put(GetQuarantineCache(ms
), QuarantineCallback(ac
),
441 SpinMutexLock
l(&fallback_mutex
);
442 AllocatorCache
*ac
= &fallback_allocator_cache
;
443 quarantine
.Put(&fallback_quarantine_cache
, QuarantineCallback(ac
),
448 static void Deallocate(void *ptr
, uptr delete_size
, BufferedStackTrace
*stack
,
449 AllocType alloc_type
) {
450 uptr p
= reinterpret_cast<uptr
>(ptr
);
453 uptr chunk_beg
= p
- kChunkHeaderSize
;
454 AsanChunk
*m
= reinterpret_cast<AsanChunk
*>(chunk_beg
);
455 if (delete_size
&& flags()->new_delete_type_mismatch
&&
456 delete_size
!= m
->UsedSize()) {
457 ReportNewDeleteSizeMismatch(p
, delete_size
, stack
);
460 // Must mark the chunk as quarantined before any changes to its metadata.
461 AtomicallySetQuarantineFlag(m
, ptr
, stack
);
462 QuarantineChunk(m
, ptr
, stack
, alloc_type
);
465 static void *Reallocate(void *old_ptr
, uptr new_size
,
466 BufferedStackTrace
*stack
) {
467 CHECK(old_ptr
&& new_size
);
468 uptr p
= reinterpret_cast<uptr
>(old_ptr
);
469 uptr chunk_beg
= p
- kChunkHeaderSize
;
470 AsanChunk
*m
= reinterpret_cast<AsanChunk
*>(chunk_beg
);
472 AsanStats
&thread_stats
= GetCurrentThreadStats();
473 thread_stats
.reallocs
++;
474 thread_stats
.realloced
+= new_size
;
476 void *new_ptr
= Allocate(new_size
, 8, stack
, FROM_MALLOC
, true);
478 u8 chunk_state
= m
->chunk_state
;
479 if (chunk_state
!= CHUNK_ALLOCATED
)
480 ReportInvalidFree(old_ptr
, chunk_state
, stack
);
481 CHECK_NE(REAL(memcpy
), (void*)0);
482 uptr memcpy_size
= Min(new_size
, m
->UsedSize());
483 // If realloc() races with free(), we may start copying freed memory.
484 // However, we will report racy double-free later anyway.
485 REAL(memcpy
)(new_ptr
, old_ptr
, memcpy_size
);
486 Deallocate(old_ptr
, 0, stack
, FROM_MALLOC
);
491 // Assumes alloc_beg == allocator.GetBlockBegin(alloc_beg).
492 static AsanChunk
*GetAsanChunk(void *alloc_beg
) {
493 if (!alloc_beg
) return 0;
494 if (!allocator
.FromPrimary(alloc_beg
)) {
495 uptr
*meta
= reinterpret_cast<uptr
*>(allocator
.GetMetaData(alloc_beg
));
496 AsanChunk
*m
= reinterpret_cast<AsanChunk
*>(meta
[1]);
499 uptr
*alloc_magic
= reinterpret_cast<uptr
*>(alloc_beg
);
500 if (alloc_magic
[0] == kAllocBegMagic
)
501 return reinterpret_cast<AsanChunk
*>(alloc_magic
[1]);
502 return reinterpret_cast<AsanChunk
*>(alloc_beg
);
505 static AsanChunk
*GetAsanChunkByAddr(uptr p
) {
506 void *alloc_beg
= allocator
.GetBlockBegin(reinterpret_cast<void *>(p
));
507 return GetAsanChunk(alloc_beg
);
510 // Allocator must be locked when this function is called.
511 static AsanChunk
*GetAsanChunkByAddrFastLocked(uptr p
) {
513 allocator
.GetBlockBeginFastLocked(reinterpret_cast<void *>(p
));
514 return GetAsanChunk(alloc_beg
);
517 static uptr
AllocationSize(uptr p
) {
518 AsanChunk
*m
= GetAsanChunkByAddr(p
);
520 if (m
->chunk_state
!= CHUNK_ALLOCATED
) return 0;
521 if (m
->Beg() != p
) return 0;
522 return m
->UsedSize();
525 // We have an address between two chunks, and we want to report just one.
526 AsanChunk
*ChooseChunk(uptr addr
,
527 AsanChunk
*left_chunk
, AsanChunk
*right_chunk
) {
528 // Prefer an allocated chunk over freed chunk and freed chunk
529 // over available chunk.
530 if (left_chunk
->chunk_state
!= right_chunk
->chunk_state
) {
531 if (left_chunk
->chunk_state
== CHUNK_ALLOCATED
)
533 if (right_chunk
->chunk_state
== CHUNK_ALLOCATED
)
535 if (left_chunk
->chunk_state
== CHUNK_QUARANTINE
)
537 if (right_chunk
->chunk_state
== CHUNK_QUARANTINE
)
540 // Same chunk_state: choose based on offset.
541 sptr l_offset
= 0, r_offset
= 0;
542 CHECK(AsanChunkView(left_chunk
).AddrIsAtRight(addr
, 1, &l_offset
));
543 CHECK(AsanChunkView(right_chunk
).AddrIsAtLeft(addr
, 1, &r_offset
));
544 if (l_offset
< r_offset
)
549 AsanChunkView
FindHeapChunkByAddress(uptr addr
) {
550 AsanChunk
*m1
= GetAsanChunkByAddr(addr
);
551 if (!m1
) return AsanChunkView(m1
);
553 if (AsanChunkView(m1
).AddrIsAtLeft(addr
, 1, &offset
)) {
554 // The address is in the chunk's left redzone, so maybe it is actually
555 // a right buffer overflow from the other chunk to the left.
556 // Search a bit to the left to see if there is another chunk.
558 for (uptr l
= 1; l
< GetPageSizeCached(); l
++) {
559 m2
= GetAsanChunkByAddr(addr
- l
);
560 if (m2
== m1
) continue; // Still the same chunk.
563 if (m2
&& AsanChunkView(m2
).AddrIsAtRight(addr
, 1, &offset
))
564 m1
= ChooseChunk(addr
, m2
, m1
);
566 return AsanChunkView(m1
);
569 void AsanThreadLocalMallocStorage::CommitBack() {
570 AllocatorCache
*ac
= GetAllocatorCache(this);
571 quarantine
.Drain(GetQuarantineCache(this), QuarantineCallback(ac
));
572 allocator
.SwallowCache(GetAllocatorCache(this));
575 void PrintInternalAllocatorStats() {
576 allocator
.PrintStats();
579 void *asan_memalign(uptr alignment
, uptr size
, BufferedStackTrace
*stack
,
580 AllocType alloc_type
) {
581 return Allocate(size
, alignment
, stack
, alloc_type
, true);
584 void asan_free(void *ptr
, BufferedStackTrace
*stack
, AllocType alloc_type
) {
585 Deallocate(ptr
, 0, stack
, alloc_type
);
588 void asan_sized_free(void *ptr
, uptr size
, BufferedStackTrace
*stack
,
589 AllocType alloc_type
) {
590 Deallocate(ptr
, size
, stack
, alloc_type
);
593 void *asan_malloc(uptr size
, BufferedStackTrace
*stack
) {
594 return Allocate(size
, 8, stack
, FROM_MALLOC
, true);
597 void *asan_calloc(uptr nmemb
, uptr size
, BufferedStackTrace
*stack
) {
598 if (CallocShouldReturnNullDueToOverflow(size
, nmemb
))
599 return AllocatorReturnNull();
600 void *ptr
= Allocate(nmemb
* size
, 8, stack
, FROM_MALLOC
, false);
601 // If the memory comes from the secondary allocator no need to clear it
602 // as it comes directly from mmap.
603 if (ptr
&& allocator
.FromPrimary(ptr
))
604 REAL(memset
)(ptr
, 0, nmemb
* size
);
608 void *asan_realloc(void *p
, uptr size
, BufferedStackTrace
*stack
) {
610 return Allocate(size
, 8, stack
, FROM_MALLOC
, true);
612 Deallocate(p
, 0, stack
, FROM_MALLOC
);
615 return Reallocate(p
, size
, stack
);
618 void *asan_valloc(uptr size
, BufferedStackTrace
*stack
) {
619 return Allocate(size
, GetPageSizeCached(), stack
, FROM_MALLOC
, true);
622 void *asan_pvalloc(uptr size
, BufferedStackTrace
*stack
) {
623 uptr PageSize
= GetPageSizeCached();
624 size
= RoundUpTo(size
, PageSize
);
626 // pvalloc(0) should allocate one page.
629 return Allocate(size
, PageSize
, stack
, FROM_MALLOC
, true);
632 int asan_posix_memalign(void **memptr
, uptr alignment
, uptr size
,
633 BufferedStackTrace
*stack
) {
634 void *ptr
= Allocate(size
, alignment
, stack
, FROM_MALLOC
, true);
635 CHECK(IsAligned((uptr
)ptr
, alignment
));
640 uptr
asan_malloc_usable_size(void *ptr
, uptr pc
, uptr bp
) {
641 if (ptr
== 0) return 0;
642 uptr usable_size
= AllocationSize(reinterpret_cast<uptr
>(ptr
));
643 if (flags()->check_malloc_usable_size
&& (usable_size
== 0)) {
644 GET_STACK_TRACE_FATAL(pc
, bp
);
645 ReportMallocUsableSizeNotOwned((uptr
)ptr
, &stack
);
650 uptr
asan_mz_size(const void *ptr
) {
651 return AllocationSize(reinterpret_cast<uptr
>(ptr
));
654 void asan_mz_force_lock() {
655 allocator
.ForceLock();
656 fallback_mutex
.Lock();
659 void asan_mz_force_unlock() {
660 fallback_mutex
.Unlock();
661 allocator
.ForceUnlock();
664 } // namespace __asan
666 // --- Implementation of LSan-specific functions --- {{{1
668 void LockAllocator() {
669 __asan::allocator
.ForceLock();
672 void UnlockAllocator() {
673 __asan::allocator
.ForceUnlock();
676 void GetAllocatorGlobalRange(uptr
*begin
, uptr
*end
) {
677 *begin
= (uptr
)&__asan::allocator
;
678 *end
= *begin
+ sizeof(__asan::allocator
);
681 uptr
PointsIntoChunk(void* p
) {
682 uptr addr
= reinterpret_cast<uptr
>(p
);
683 __asan::AsanChunk
*m
= __asan::GetAsanChunkByAddrFastLocked(addr
);
685 uptr chunk
= m
->Beg();
686 if (m
->chunk_state
!= __asan::CHUNK_ALLOCATED
)
688 if (m
->AddrIsInside(addr
, /*locked_version=*/true))
690 if (IsSpecialCaseOfOperatorNew0(chunk
, m
->UsedSize(/*locked_version*/ true),
696 uptr
GetUserBegin(uptr chunk
) {
697 __asan::AsanChunk
*m
=
698 __asan::GetAsanChunkByAddrFastLocked(chunk
);
703 LsanMetadata::LsanMetadata(uptr chunk
) {
704 metadata_
= reinterpret_cast<void *>(chunk
- __asan::kChunkHeaderSize
);
707 bool LsanMetadata::allocated() const {
708 __asan::AsanChunk
*m
= reinterpret_cast<__asan::AsanChunk
*>(metadata_
);
709 return m
->chunk_state
== __asan::CHUNK_ALLOCATED
;
712 ChunkTag
LsanMetadata::tag() const {
713 __asan::AsanChunk
*m
= reinterpret_cast<__asan::AsanChunk
*>(metadata_
);
714 return static_cast<ChunkTag
>(m
->lsan_tag
);
717 void LsanMetadata::set_tag(ChunkTag value
) {
718 __asan::AsanChunk
*m
= reinterpret_cast<__asan::AsanChunk
*>(metadata_
);
722 uptr
LsanMetadata::requested_size() const {
723 __asan::AsanChunk
*m
= reinterpret_cast<__asan::AsanChunk
*>(metadata_
);
724 return m
->UsedSize(/*locked_version=*/true);
727 u32
LsanMetadata::stack_trace_id() const {
728 __asan::AsanChunk
*m
= reinterpret_cast<__asan::AsanChunk
*>(metadata_
);
729 return m
->alloc_context_id
;
732 void ForEachChunk(ForEachChunkCallback callback
, void *arg
) {
733 __asan::allocator
.ForEachChunk(callback
, arg
);
736 IgnoreObjectResult
IgnoreObjectLocked(const void *p
) {
737 uptr addr
= reinterpret_cast<uptr
>(p
);
738 __asan::AsanChunk
*m
= __asan::GetAsanChunkByAddr(addr
);
739 if (!m
) return kIgnoreObjectInvalid
;
740 if ((m
->chunk_state
== __asan::CHUNK_ALLOCATED
) && m
->AddrIsInside(addr
)) {
741 if (m
->lsan_tag
== kIgnored
)
742 return kIgnoreObjectAlreadyIgnored
;
743 m
->lsan_tag
= __lsan::kIgnored
;
744 return kIgnoreObjectSuccess
;
746 return kIgnoreObjectInvalid
;
749 } // namespace __lsan
751 // ---------------------- Interface ---------------- {{{1
752 using namespace __asan
; // NOLINT
754 // ASan allocator doesn't reserve extra bytes, so normally we would
755 // just return "size". We don't want to expose our redzone sizes, etc here.
756 uptr
__sanitizer_get_estimated_allocated_size(uptr size
) {
760 int __sanitizer_get_ownership(const void *p
) {
761 uptr ptr
= reinterpret_cast<uptr
>(p
);
762 return (AllocationSize(ptr
) > 0);
765 uptr
__sanitizer_get_allocated_size(const void *p
) {
766 if (p
== 0) return 0;
767 uptr ptr
= reinterpret_cast<uptr
>(p
);
768 uptr allocated_size
= AllocationSize(ptr
);
769 // Die if p is not malloced or if it is already freed.
770 if (allocated_size
== 0) {
771 GET_STACK_TRACE_FATAL_HERE
;
772 ReportSanitizerGetAllocatedSizeNotOwned(ptr
, &stack
);
774 return allocated_size
;
777 #if !SANITIZER_SUPPORTS_WEAK_HOOKS
778 // Provide default (no-op) implementation of malloc hooks.
780 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
781 void __sanitizer_malloc_hook(void *ptr
, uptr size
) {
785 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
786 void __sanitizer_free_hook(void *ptr
) {