Newer
Older
Kostya Serebryany
committed
//===-- asan_allocator2.cc ------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
// Implementation of ASan's memory allocator, 2-nd version.
// This variant uses the allocator from sanitizer_common, i.e. the one shared
// with ThreadSanitizer and MemorySanitizer.
//
// Status: under development, not enabled by default yet.
//===----------------------------------------------------------------------===//
#include "asan_allocator.h"
#if ASAN_ALLOCATOR_VERSION == 2
Kostya Serebryany
committed
#include "asan_mapping.h"
#include "asan_report.h"
#include "asan_thread.h"
#include "asan_thread_registry.h"
#include "sanitizer/asan_interface.h"
Kostya Serebryany
committed
#include "sanitizer_common/sanitizer_allocator.h"
#include "sanitizer_common/sanitizer_internal_defs.h"
#include "sanitizer_common/sanitizer_list.h"
Kostya Serebryany
committed
#include "sanitizer_common/sanitizer_stackdepot.h"
Kostya Serebryany
committed
namespace __asan {
Kostya Serebryany
committed
struct AsanMapUnmapCallback {
void OnMap(uptr p, uptr size) const {
PoisonShadow(p, size, kAsanHeapLeftRedzoneMagic);
// Statistics.
AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
thread_stats.mmaps++;
thread_stats.mmaped += size;
// thread_stats.mmaped_by_size[size_class] += n_chunks;
Kostya Serebryany
committed
}
void OnUnmap(uptr p, uptr size) const {
PoisonShadow(p, size, 0);
// Statistics.
AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
thread_stats.munmaps++;
thread_stats.munmaped += size;
Kostya Serebryany
committed
}
};
Kostya Serebryany
committed
#if SANITIZER_WORDSIZE == 64
const uptr kAllocatorSpace = 0x600000000000ULL;
const uptr kAllocatorSize = 0x10000000000ULL; // 1T.
typedef DefaultSizeClassMap SizeClassMap;
Kostya Serebryany
committed
typedef SizeClassAllocator64<kAllocatorSpace, kAllocatorSize, 0 /*metadata*/,
SizeClassMap, AsanMapUnmapCallback> PrimaryAllocator;
Kostya Serebryany
committed
#elif SANITIZER_WORDSIZE == 32
static const u64 kAddressSpaceSize = 1ULL << 32;
typedef CompactSizeClassMap SizeClassMap;
Kostya Serebryany
committed
typedef SizeClassAllocator32<0, kAddressSpaceSize, 16,
SizeClassMap, AsanMapUnmapCallback> PrimaryAllocator;
Kostya Serebryany
committed
#endif
typedef SizeClassAllocatorLocalCache<PrimaryAllocator> AllocatorCache;
Kostya Serebryany
committed
typedef LargeMmapAllocator<AsanMapUnmapCallback> SecondaryAllocator;
Kostya Serebryany
committed
typedef CombinedAllocator<PrimaryAllocator, AllocatorCache,
SecondaryAllocator> Allocator;
// We can not use THREADLOCAL because it is not supported on some of the
// platforms we care about (OSX 10.6, Android).
// static THREADLOCAL AllocatorCache cache;
AllocatorCache *GetAllocatorCache(AsanThreadLocalMallocStorage *ms) {
CHECK(ms);
CHECK_LE(sizeof(AllocatorCache), sizeof(ms->allocator2_cache));
return reinterpret_cast<AllocatorCache *>(ms->allocator2_cache);
}
static Allocator allocator;
Kostya Serebryany
committed
static const uptr kMaxAllowedMallocSize =
FIRST_32_SECOND_64(3UL << 30, 8UL << 30);
static const uptr kMaxThreadLocalQuarantine =
FIRST_32_SECOND_64(1 << 18, 1 << 20);
Kostya Serebryany
committed
static const uptr kReturnOnZeroMalloc = 2048; // Zero page is protected.
static int inited = 0;
static void Init() {
if (inited) return;
__asan_init();
inited = true; // this must happen before any threads are created.
allocator.Init();
}
// Every chunk of memory allocated by this allocator can be in one of 3 states:
// CHUNK_AVAILABLE: the chunk is in the free list and ready to be allocated.
// CHUNK_ALLOCATED: the chunk is allocated and not yet freed.
// CHUNK_QUARANTINE: the chunk was freed and put into quarantine zone.
enum {
Kostya Serebryany
committed
CHUNK_AVAILABLE = 0, // 0 is the default value even if we didn't set it.
CHUNK_ALLOCATED = 2,
CHUNK_QUARANTINE = 3
};
Kostya Serebryany
committed
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
// Valid redzone sizes are 16, 32, 64, ... 2048, so we encode them in 3 bits.
// We use adaptive redzones: for larger allocation larger redzones are used.
static u32 RZLog2Size(u32 rz_log) {
CHECK_LT(rz_log, 8);
return 16 << rz_log;
}
static u32 RZSize2Log(u32 rz_size) {
CHECK_GE(rz_size, 16);
CHECK_LE(rz_size, 2048);
CHECK(IsPowerOfTwo(rz_size));
u32 res = __builtin_ctz(rz_size) - 4;
CHECK_EQ(rz_size, RZLog2Size(res));
return res;
}
static uptr ComputeRZLog(uptr user_requested_size) {
u32 rz_log =
user_requested_size <= 64 - 16 ? 0 :
user_requested_size <= 128 - 32 ? 1 :
user_requested_size <= 512 - 64 ? 2 :
user_requested_size <= 4096 - 128 ? 3 :
user_requested_size <= (1 << 14) - 256 ? 4 :
user_requested_size <= (1 << 15) - 512 ? 5 :
user_requested_size <= (1 << 16) - 1024 ? 6 : 7;
return Max(rz_log, RZSize2Log(flags()->redzone));
}
// The memory chunk allocated from the underlying allocator looks like this:
// L L L L L L H H U U U U U U R R
// L -- left redzone words (0 or more bytes)
// H -- ChunkHeader (16 bytes), which is also a part of the left redzone.
// U -- user memory.
// R -- right redzone (0 or more bytes)
// ChunkBase consists of ChunkHeader and other bytes that overlap with user
// memory.
// If a memory chunk is allocated by memalign and we had to increase the
// allocation size to achieve the proper alignment, then we store this magic
// value in the first uptr word of the memory block and store the address of
// ChunkBase in the next uptr.
// M B ? ? ? L L L L L L H H U U U U U U
// M -- magic value kMemalignMagic
// B -- address of ChunkHeader pointing to the first 'H'
static const uptr kMemalignMagic = 0xCC6E96B9;
Kostya Serebryany
committed
struct ChunkHeader {
// 1-st 8 bytes.
Kostya Serebryany
committed
u32 chunk_state : 8; // Must be first.
u32 alloc_tid : 24;
Kostya Serebryany
committed
Kostya Serebryany
committed
u32 free_tid : 24;
u32 from_memalign : 1;
u32 alloc_type : 2;
Kostya Serebryany
committed
u32 rz_log : 3;
// 2-nd 8 bytes
Kostya Serebryany
committed
// This field is used for small sizes. For large sizes it is equal to
// SizeClassMap::kMaxSize and the actual size is stored in the
// SecondaryAllocator's metadata.
u32 user_requested_size;
u32 alloc_context_id;
};
Kostya Serebryany
committed
struct ChunkBase : ChunkHeader {
// Header2, intersects with user memory.
AsanChunk *next;
Kostya Serebryany
committed
u32 free_context_id;
};
Kostya Serebryany
committed
static const uptr kChunkHeaderSize = sizeof(ChunkHeader);
static const uptr kChunkHeader2Size = sizeof(ChunkBase) - kChunkHeaderSize;
COMPILER_CHECK(kChunkHeaderSize == 16);
COMPILER_CHECK(kChunkHeader2Size <= 16);
struct AsanChunk: ChunkBase {
uptr Beg() { return reinterpret_cast<uptr>(this) + kChunkHeaderSize; }
Kostya Serebryany
committed
uptr UsedSize() {
if (user_requested_size != SizeClassMap::kMaxSize)
return user_requested_size;
return *reinterpret_cast<uptr *>(allocator.GetMetaData(AllocBeg()));
}
void *AllocBeg() {
if (from_memalign)
Kostya Serebryany
committed
return allocator.GetBlockBegin(reinterpret_cast<void *>(this));
Kostya Serebryany
committed
return reinterpret_cast<void*>(Beg() - RZLog2Size(rz_log));
Kostya Serebryany
committed
}
Kostya Serebryany
committed
// We store the alloc/free stack traces in the chunk itself.
Kostya Serebryany
committed
u32 *AllocStackBeg() {
Kostya Serebryany
committed
return (u32*)(Beg() - RZLog2Size(rz_log));
Kostya Serebryany
committed
}
uptr AllocStackSize() {
Kostya Serebryany
committed
CHECK_LE(RZLog2Size(rz_log), kChunkHeaderSize);
return (RZLog2Size(rz_log) - kChunkHeaderSize) / sizeof(u32);
Kostya Serebryany
committed
}
u32 *FreeStackBeg() {
return (u32*)(Beg() + kChunkHeader2Size);
}
uptr FreeStackSize() {
uptr available = Max(RoundUpTo(UsedSize(), SHADOW_GRANULARITY),
Kostya Serebryany
committed
(uptr)RZLog2Size(rz_log));
Kostya Serebryany
committed
return (available - kChunkHeader2Size) / sizeof(u32);
Kostya Serebryany
committed
}
};
uptr AsanChunkView::Beg() { return chunk_->Beg(); }
uptr AsanChunkView::End() { return Beg() + UsedSize(); }
uptr AsanChunkView::UsedSize() { return chunk_->UsedSize(); }
uptr AsanChunkView::AllocTid() { return chunk_->alloc_tid; }
uptr AsanChunkView::FreeTid() { return chunk_->free_tid; }
Kostya Serebryany
committed
static void GetStackTraceFromId(u32 id, StackTrace *stack) {
CHECK(id);
uptr size = 0;
const uptr *trace = StackDepotGet(id, &size);
CHECK_LT(size, kStackTraceMax);
internal_memcpy(stack->trace, trace, sizeof(uptr) * size);
stack->size = size;
}
void AsanChunkView::GetAllocStack(StackTrace *stack) {
Kostya Serebryany
committed
if (flags()->use_stack_depot)
GetStackTraceFromId(chunk_->alloc_context_id, stack);
else
StackTrace::UncompressStack(stack, chunk_->AllocStackBeg(),
chunk_->AllocStackSize());
}
void AsanChunkView::GetFreeStack(StackTrace *stack) {
Kostya Serebryany
committed
if (flags()->use_stack_depot)
GetStackTraceFromId(chunk_->free_context_id, stack);
else
StackTrace::UncompressStack(stack, chunk_->FreeStackBeg(),
chunk_->FreeStackSize());
}
class Quarantine: public AsanChunkFifoList {
public:
void SwallowThreadLocalQuarantine(AsanThreadLocalMallocStorage *ms) {
AsanChunkFifoList *q = &ms->quarantine_;
if (!q->size()) return;
SpinMutexLock l(&mutex_);
PushList(q);
PopAndDeallocateLoop(ms);
void BypassThreadLocalQuarantine(AsanChunk *m) {
SpinMutexLock l(&mutex_);
Push(m);
}
private:
void PopAndDeallocateLoop(AsanThreadLocalMallocStorage *ms) {
while (size() > (uptr)flags()->quarantine_size) {
PopAndDeallocate(ms);
void PopAndDeallocate(AsanThreadLocalMallocStorage *ms) {
CHECK_GT(size(), 0);
AsanChunk *m = Pop();
CHECK(m);
CHECK(m->chunk_state == CHUNK_QUARANTINE);
m->chunk_state = CHUNK_AVAILABLE;
CHECK_NE(m->alloc_tid, kInvalidTid);
CHECK_NE(m->free_tid, kInvalidTid);
PoisonShadow(m->Beg(),
Kostya Serebryany
committed
RoundUpTo(m->UsedSize(), SHADOW_GRANULARITY),
kAsanHeapLeftRedzoneMagic);
Kostya Serebryany
committed
void *p = reinterpret_cast<void *>(m->AllocBeg());
if (m->from_memalign) {
uptr *memalign_magic = reinterpret_cast<uptr *>(p);
CHECK_EQ(memalign_magic[0], kMemalignMagic);
CHECK_EQ(memalign_magic[1], reinterpret_cast<uptr>(m));
}
// Statistics.
AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
thread_stats.real_frees++;
thread_stats.really_freed += m->UsedSize();
allocator.Deallocate(GetAllocatorCache(ms), p);
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
}
SpinMutex mutex_;
};
static Quarantine quarantine;
void AsanChunkFifoList::PushList(AsanChunkFifoList *q) {
CHECK(q->size() > 0);
size_ += q->size();
append_back(q);
q->clear();
}
void AsanChunkFifoList::Push(AsanChunk *n) {
push_back(n);
size_ += n->UsedSize();
}
// Interesting performance observation: this function takes up to 15% of overal
// allocator time. That's because *first_ has been evicted from cache long time
// ago. Not sure if we can or want to do anything with this.
AsanChunk *AsanChunkFifoList::Pop() {
CHECK(first_);
AsanChunk *res = front();
size_ -= res->UsedSize();
pop_front();
return res;
}
Kostya Serebryany
committed
static void *Allocate(uptr size, uptr alignment, StackTrace *stack,
AllocType alloc_type) {
Init();
CHECK(stack);
if (alignment < 8) alignment = 8;
Kostya Serebryany
committed
if (size == 0) {
if (alignment <= kReturnOnZeroMalloc)
return reinterpret_cast<void *>(kReturnOnZeroMalloc);
else
return 0; // 0 bytes with large alignment requested. Just return 0.
}
CHECK(IsPowerOfTwo(alignment));
Kostya Serebryany
committed
uptr rz_log = ComputeRZLog(size);
uptr rz_size = RZLog2Size(rz_log);
uptr rounded_size = RoundUpTo(size, rz_size);
uptr needed_size = rounded_size + rz_size;
if (alignment > rz_size)
needed_size += alignment;
Kostya Serebryany
committed
bool using_primary_allocator = true;
Kostya Serebryany
committed
// If we are allocating from the secondary allocator, there will be no
// automatic right redzone, so add the right redzone manually.
Kostya Serebryany
committed
if (!PrimaryAllocator::CanAllocate(needed_size, alignment)) {
Kostya Serebryany
committed
needed_size += rz_size;
Kostya Serebryany
committed
using_primary_allocator = false;
}
CHECK(IsAligned(needed_size, rz_size));
if (size > kMaxAllowedMallocSize || needed_size > kMaxAllowedMallocSize) {
Report("WARNING: AddressSanitizer failed to allocate %p bytes\n",
(void*)size);
return 0;
}
AsanThread *t = asanThreadRegistry().GetCurrent();
Kostya Serebryany
committed
AllocatorCache *cache = t ? GetAllocatorCache(&t->malloc_storage()) : 0;
void *allocated = allocator.Allocate(cache, needed_size, 8, false);
uptr alloc_beg = reinterpret_cast<uptr>(allocated);
uptr alloc_end = alloc_beg + needed_size;
uptr beg_plus_redzone = alloc_beg + rz_size;
uptr user_beg = beg_plus_redzone;
if (!IsAligned(user_beg, alignment))
user_beg = RoundUpTo(user_beg, alignment);
uptr user_end = user_beg + size;
CHECK_LE(user_end, alloc_end);
uptr chunk_beg = user_beg - kChunkHeaderSize;
AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
m->chunk_state = CHUNK_ALLOCATED;
Kostya Serebryany
committed
m->alloc_type = alloc_type;
Kostya Serebryany
committed
m->rz_log = rz_log;
u32 alloc_tid = t ? t->tid() : 0;
m->alloc_tid = alloc_tid;
CHECK_EQ(alloc_tid, m->alloc_tid); // Does alloc_tid fit into the bitfield?
Kostya Serebryany
committed
m->free_tid = kInvalidTid;
m->from_memalign = user_beg != beg_plus_redzone;
if (m->from_memalign) {
CHECK_LE(beg_plus_redzone + 2 * sizeof(uptr), user_beg);
uptr *memalign_magic = reinterpret_cast<uptr *>(alloc_beg);
memalign_magic[0] = kMemalignMagic;
memalign_magic[1] = chunk_beg;
}
Kostya Serebryany
committed
if (using_primary_allocator) {
CHECK(size);
m->user_requested_size = size;
CHECK(allocator.FromPrimary(allocated));
} else {
CHECK(!allocator.FromPrimary(allocated));
m->user_requested_size = SizeClassMap::kMaxSize;
Kostya Serebryany
committed
uptr *meta = reinterpret_cast<uptr *>(allocator.GetMetaData(allocated));
meta[0] = size;
meta[1] = chunk_beg;
Kostya Serebryany
committed
}
Kostya Serebryany
committed
if (flags()->use_stack_depot) {
m->alloc_context_id = StackDepotPut(stack->trace, stack->size);
} else {
m->alloc_context_id = 0;
StackTrace::CompressStack(stack, m->AllocStackBeg(), m->AllocStackSize());
}
Kostya Serebryany
committed
uptr size_rounded_down_to_granularity = RoundDownTo(size, SHADOW_GRANULARITY);
// Unpoison the bulk of the memory region.
if (size_rounded_down_to_granularity)
PoisonShadow(user_beg, size_rounded_down_to_granularity, 0);
// Deal with the end of the region if size is not aligned to granularity.
Kostya Serebryany
committed
if (size != size_rounded_down_to_granularity && flags()->poison_heap) {
Kostya Serebryany
committed
u8 *shadow = (u8*)MemToShadow(user_beg + size_rounded_down_to_granularity);
*shadow = size & (SHADOW_GRANULARITY - 1);
}
AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
thread_stats.mallocs++;
thread_stats.malloced += size;
thread_stats.malloced_redzones += needed_size - size;
uptr class_id = Min(kNumberOfSizeClasses, SizeClassMap::ClassID(needed_size));
thread_stats.malloced_by_size[class_id]++;
if (needed_size > SizeClassMap::kMaxSize)
thread_stats.malloc_large++;
void *res = reinterpret_cast<void *>(user_beg);
ASAN_MALLOC_HOOK(res, size);
return res;
}
Kostya Serebryany
committed
static void Deallocate(void *ptr, StackTrace *stack, AllocType alloc_type) {
uptr p = reinterpret_cast<uptr>(ptr);
if (p == 0 || p == kReturnOnZeroMalloc) return;
uptr chunk_beg = p - kChunkHeaderSize;
AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
// Flip the chunk_state atomically to avoid race on double-free.
u8 old_chunk_state = atomic_exchange((atomic_uint8_t*)m, CHUNK_QUARANTINE,
memory_order_acq_rel);
if (old_chunk_state == CHUNK_QUARANTINE)
ReportDoubleFree((uptr)ptr, stack);
else if (old_chunk_state != CHUNK_ALLOCATED)
ReportFreeNotMalloced((uptr)ptr, stack);
CHECK(old_chunk_state == CHUNK_ALLOCATED);
Kostya Serebryany
committed
if (m->alloc_type != alloc_type && flags()->alloc_dealloc_mismatch)
ReportAllocTypeMismatch((uptr)ptr, stack,
(AllocType)m->alloc_type, (AllocType)alloc_type);
Kostya Serebryany
committed
CHECK_GE(m->alloc_tid, 0);
if (SANITIZER_WORDSIZE == 64) // On 32-bits this resides in user area.
CHECK_EQ(m->free_tid, kInvalidTid);
Kostya Serebryany
committed
AsanThread *t = asanThreadRegistry().GetCurrent();
m->free_tid = t ? t->tid() : 0;
Kostya Serebryany
committed
if (flags()->use_stack_depot) {
m->free_context_id = StackDepotPut(stack->trace, stack->size);
} else {
m->free_context_id = 0;
StackTrace::CompressStack(stack, m->FreeStackBeg(), m->FreeStackSize());
}
CHECK(m->chunk_state == CHUNK_QUARANTINE);
Kostya Serebryany
committed
// Poison the region.
PoisonShadow(m->Beg(),
Kostya Serebryany
committed
RoundUpTo(m->UsedSize(), SHADOW_GRANULARITY),
Kostya Serebryany
committed
kAsanHeapFreeMagic);
AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
thread_stats.frees++;
thread_stats.freed += m->UsedSize();
// Push into quarantine.
if (t) {
AsanChunkFifoList &q = t->malloc_storage().quarantine_;
q.Push(m);
if (q.size() > kMaxThreadLocalQuarantine)
quarantine.SwallowThreadLocalQuarantine(&t->malloc_storage());
} else {
quarantine.BypassThreadLocalQuarantine(m);
}
ASAN_FREE_HOOK(ptr);
}
static void *Reallocate(void *old_ptr, uptr new_size, StackTrace *stack) {
CHECK(old_ptr && new_size);
uptr p = reinterpret_cast<uptr>(old_ptr);
uptr chunk_beg = p - kChunkHeaderSize;
AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
thread_stats.reallocs++;
thread_stats.realloced += new_size;
CHECK(m->chunk_state == CHUNK_ALLOCATED);
uptr old_size = m->UsedSize();
uptr memcpy_size = Min(new_size, old_size);
Kostya Serebryany
committed
void *new_ptr = Allocate(new_size, 8, stack, FROM_MALLOC);
if (new_ptr) {
CHECK(REAL(memcpy) != 0);
REAL(memcpy)(new_ptr, old_ptr, memcpy_size);
Kostya Serebryany
committed
Deallocate(old_ptr, stack, FROM_MALLOC);
}
return new_ptr;
}
static AsanChunk *GetAsanChunkByAddr(uptr p) {
Kostya Serebryany
committed
void *ptr = reinterpret_cast<void *>(p);
uptr alloc_beg = reinterpret_cast<uptr>(allocator.GetBlockBegin(ptr));
if (!alloc_beg) return 0;
uptr *memalign_magic = reinterpret_cast<uptr *>(alloc_beg);
if (memalign_magic[0] == kMemalignMagic) {
Kostya Serebryany
committed
AsanChunk *m = reinterpret_cast<AsanChunk *>(memalign_magic[1]);
CHECK(m->from_memalign);
return m;
}
if (!allocator.FromPrimary(ptr)) {
uptr *meta = reinterpret_cast<uptr *>(
allocator.GetMetaData(reinterpret_cast<void *>(alloc_beg)));
AsanChunk *m = reinterpret_cast<AsanChunk *>(meta[1]);
return m;
Kostya Serebryany
committed
uptr actual_size = allocator.GetActuallyAllocatedSize(ptr);
CHECK_LE(actual_size, SizeClassMap::kMaxSize);
// We know the actually allocted size, but we don't know the redzone size.
// Just try all possible redzone sizes.
for (u32 rz_log = 0; rz_log < 8; rz_log++) {
u32 rz_size = RZLog2Size(rz_log);
uptr max_possible_size = actual_size - rz_size;
if (ComputeRZLog(max_possible_size) != rz_log)
continue;
return reinterpret_cast<AsanChunk *>(
alloc_beg + rz_size - kChunkHeaderSize);
}
return 0;
}
static uptr AllocationSize(uptr p) {
AsanChunk *m = GetAsanChunkByAddr(p);
if (!m) return 0;
if (m->chunk_state != CHUNK_ALLOCATED) return 0;
if (m->Beg() != p) return 0;
return m->UsedSize();
}
Kostya Serebryany
committed
// We have an address between two chunks, and we want to report just one.
AsanChunk *ChooseChunk(uptr addr,
AsanChunk *left_chunk, AsanChunk *right_chunk) {
Kostya Serebryany
committed
// Prefer an allocated chunk over freed chunk and freed chunk
// over available chunk.
if (left_chunk->chunk_state != right_chunk->chunk_state) {
if (left_chunk->chunk_state == CHUNK_ALLOCATED)
return left_chunk;
if (right_chunk->chunk_state == CHUNK_ALLOCATED)
return right_chunk;
if (left_chunk->chunk_state == CHUNK_QUARANTINE)
return left_chunk;
if (right_chunk->chunk_state == CHUNK_QUARANTINE)
return right_chunk;
}
// Same chunk_state: choose based on offset.
Kostya Serebryany
committed
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
uptr l_offset = 0, r_offset = 0;
CHECK(AsanChunkView(left_chunk).AddrIsAtRight(addr, 1, &l_offset));
CHECK(AsanChunkView(right_chunk).AddrIsAtLeft(addr, 1, &r_offset));
if (l_offset < r_offset)
return left_chunk;
return right_chunk;
}
AsanChunkView FindHeapChunkByAddress(uptr addr) {
AsanChunk *m1 = GetAsanChunkByAddr(addr);
if (!m1) return AsanChunkView(m1);
uptr offset = 0;
if (AsanChunkView(m1).AddrIsAtLeft(addr, 1, &offset)) {
// The address is in the chunk's left redzone, so maybe it is actually
// a right buffer overflow from the other chunk to the left.
// Search a bit to the left to see if there is another chunk.
AsanChunk *m2 = 0;
for (uptr l = 1; l < GetPageSizeCached(); l++) {
m2 = GetAsanChunkByAddr(addr - l);
if (m2 == m1) continue; // Still the same chunk.
break;
}
if (m2 && AsanChunkView(m2).AddrIsAtRight(addr, 1, &offset))
m1 = ChooseChunk(addr, m2, m1);
}
return AsanChunkView(m1);
}
void AsanThreadLocalMallocStorage::CommitBack() {
quarantine.SwallowThreadLocalQuarantine(this);
allocator.SwallowCache(GetAllocatorCache(this));
}
SANITIZER_INTERFACE_ATTRIBUTE
Kostya Serebryany
committed
void *asan_memalign(uptr alignment, uptr size, StackTrace *stack,
AllocType alloc_type) {
return Allocate(size, alignment, stack, alloc_type);
}
SANITIZER_INTERFACE_ATTRIBUTE
Kostya Serebryany
committed
void asan_free(void *ptr, StackTrace *stack, AllocType alloc_type) {
Deallocate(ptr, stack, alloc_type);
}
SANITIZER_INTERFACE_ATTRIBUTE
void *asan_malloc(uptr size, StackTrace *stack) {
Kostya Serebryany
committed
return Allocate(size, 8, stack, FROM_MALLOC);
}
void *asan_calloc(uptr nmemb, uptr size, StackTrace *stack) {
Kostya Serebryany
committed
void *ptr = Allocate(nmemb * size, 8, stack, FROM_MALLOC);
Kostya Serebryany
committed
if (ptr)
REAL(memset)(ptr, 0, nmemb * size);
}
void *asan_realloc(void *p, uptr size, StackTrace *stack) {
Kostya Serebryany
committed
if (p == 0)
Kostya Serebryany
committed
return Allocate(size, 8, stack, FROM_MALLOC);
Kostya Serebryany
committed
if (size == 0) {
Kostya Serebryany
committed
Deallocate(p, stack, FROM_MALLOC);
Kostya Serebryany
committed
return 0;
}
return Reallocate(p, size, stack);
}
void *asan_valloc(uptr size, StackTrace *stack) {
Kostya Serebryany
committed
return Allocate(size, GetPageSizeCached(), stack, FROM_MALLOC);
}
void *asan_pvalloc(uptr size, StackTrace *stack) {
Kostya Serebryany
committed
uptr PageSize = GetPageSizeCached();
size = RoundUpTo(size, PageSize);
if (size == 0) {
// pvalloc(0) should allocate one page.
size = PageSize;
}
Kostya Serebryany
committed
return Allocate(size, PageSize, stack, FROM_MALLOC);
}
int asan_posix_memalign(void **memptr, uptr alignment, uptr size,
Kostya Serebryany
committed
StackTrace *stack) {
Kostya Serebryany
committed
void *ptr = Allocate(size, alignment, stack, FROM_MALLOC);
Kostya Serebryany
committed
CHECK(IsAligned((uptr)ptr, alignment));
*memptr = ptr;
return 0;
}
uptr asan_malloc_usable_size(void *ptr, StackTrace *stack) {
CHECK(stack);
if (ptr == 0) return 0;
uptr usable_size = AllocationSize(reinterpret_cast<uptr>(ptr));
if (flags()->check_malloc_usable_size && (usable_size == 0))
ReportMallocUsableSizeNotOwned((uptr)ptr, stack);
return usable_size;
}
uptr asan_mz_size(const void *ptr) {
UNIMPLEMENTED();
return 0;
}
void asan_mz_force_lock() {
UNIMPLEMENTED();
}
void asan_mz_force_unlock() {
UNIMPLEMENTED();
}
Kostya Serebryany
committed
} // namespace __asan
// ---------------------- Interface ---------------- {{{1
using namespace __asan; // NOLINT
// ASan allocator doesn't reserve extra bytes, so normally we would
// just return "size". We don't want to expose our redzone sizes, etc here.
uptr __asan_get_estimated_allocated_size(uptr size) {
}
bool __asan_get_ownership(const void *p) {
return AllocationSize(reinterpret_cast<uptr>(p)) > 0;
}
uptr __asan_get_allocated_size(const void *p) {
if (p == 0) return 0;
uptr allocated_size = AllocationSize(reinterpret_cast<uptr>(p));
// Die if p is not malloced or if it is already freed.
if (allocated_size == 0) {
GET_STACK_TRACE_FATAL_HERE;
ReportAsanGetAllocatedSizeNotOwned(reinterpret_cast<uptr>(p), &stack);
}
return allocated_size;
}
#if !SANITIZER_SUPPORTS_WEAK_HOOKS
// Provide default (no-op) implementation of malloc hooks.
extern "C" {
SANITIZER_WEAK_ATTRIBUTE SANITIZER_INTERFACE_ATTRIBUTE
void __asan_malloc_hook(void *ptr, uptr size) {
(void)ptr;
(void)size;
}
SANITIZER_WEAK_ATTRIBUTE SANITIZER_INTERFACE_ATTRIBUTE
void __asan_free_hook(void *ptr) {
(void)ptr;
}
} // extern "C"
#endif
Kostya Serebryany
committed
#endif // ASAN_ALLOCATOR_VERSION