asan_allocator2.cc revision a61ec8172611a75d80e86355352c7b2dd3cb8125
1//===-- asan_allocator2.cc ------------------------------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file is a part of AddressSanitizer, an address sanity checker. 11// 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. 15// 16// Status: under development, not enabled by default yet. 17//===----------------------------------------------------------------------===// 18#include "asan_allocator.h" 19#if ASAN_ALLOCATOR_VERSION == 2 20 21#include "asan_mapping.h" 22#include "asan_report.h" 23#include "asan_thread.h" 24#include "asan_thread_registry.h" 25#include "sanitizer/asan_interface.h" 26#include "sanitizer_common/sanitizer_allocator.h" 27#include "sanitizer_common/sanitizer_internal_defs.h" 28#include "sanitizer_common/sanitizer_list.h" 29#include "sanitizer_common/sanitizer_stackdepot.h" 30#include "sanitizer_common/sanitizer_quarantine.h" 31 32namespace __asan { 33 34struct AsanMapUnmapCallback { 35 void OnMap(uptr p, uptr size) const { 36 PoisonShadow(p, size, kAsanHeapLeftRedzoneMagic); 37 // Statistics. 38 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats(); 39 thread_stats.mmaps++; 40 thread_stats.mmaped += size; 41 } 42 void OnUnmap(uptr p, uptr size) const { 43 PoisonShadow(p, size, 0); 44 // We are about to unmap a chunk of user memory. 45 // Mark the corresponding shadow memory as not needed. 46 // Since asan's mapping is compacting, the shadow chunk may be 47 // not page-aligned, so we only flush the page-aligned portion. 48 uptr page_size = GetPageSizeCached(); 49 uptr shadow_beg = RoundUpTo(MemToShadow(p), page_size); 50 uptr shadow_end = RoundDownTo(MemToShadow(p + size), page_size); 51 FlushUnneededShadowMemory(shadow_beg, shadow_end - shadow_beg); 52 // Statistics. 53 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats(); 54 thread_stats.munmaps++; 55 thread_stats.munmaped += size; 56 } 57}; 58 59#if SANITIZER_WORDSIZE == 64 60const uptr kAllocatorSpace = 0x600000000000ULL; 61const uptr kAllocatorSize = 0x10000000000ULL; // 1T. 62typedef DefaultSizeClassMap SizeClassMap; 63typedef SizeClassAllocator64<kAllocatorSpace, kAllocatorSize, 0 /*metadata*/, 64 SizeClassMap, AsanMapUnmapCallback> PrimaryAllocator; 65#elif SANITIZER_WORDSIZE == 32 66static const u64 kAddressSpaceSize = 1ULL << 32; 67typedef CompactSizeClassMap SizeClassMap; 68typedef SizeClassAllocator32<0, kAddressSpaceSize, 16, 69 SizeClassMap, AsanMapUnmapCallback> PrimaryAllocator; 70#endif 71 72typedef SizeClassAllocatorLocalCache<PrimaryAllocator> AllocatorCache; 73typedef LargeMmapAllocator<AsanMapUnmapCallback> SecondaryAllocator; 74typedef CombinedAllocator<PrimaryAllocator, AllocatorCache, 75 SecondaryAllocator> Allocator; 76 77// We can not use THREADLOCAL because it is not supported on some of the 78// platforms we care about (OSX 10.6, Android). 79// static THREADLOCAL AllocatorCache cache; 80AllocatorCache *GetAllocatorCache(AsanThreadLocalMallocStorage *ms) { 81 CHECK(ms); 82 CHECK_LE(sizeof(AllocatorCache), sizeof(ms->allocator2_cache)); 83 return reinterpret_cast<AllocatorCache *>(ms->allocator2_cache); 84} 85 86static Allocator allocator; 87 88static const uptr kMaxAllowedMallocSize = 89 FIRST_32_SECOND_64(3UL << 30, 8UL << 30); 90 91static const uptr kMaxThreadLocalQuarantine = 92 FIRST_32_SECOND_64(1 << 18, 1 << 20); 93 94static const uptr kReturnOnZeroMalloc = 2048; // Zero page is protected. 95 96// Every chunk of memory allocated by this allocator can be in one of 3 states: 97// CHUNK_AVAILABLE: the chunk is in the free list and ready to be allocated. 98// CHUNK_ALLOCATED: the chunk is allocated and not yet freed. 99// CHUNK_QUARANTINE: the chunk was freed and put into quarantine zone. 100enum { 101 CHUNK_AVAILABLE = 0, // 0 is the default value even if we didn't set it. 102 CHUNK_ALLOCATED = 2, 103 CHUNK_QUARANTINE = 3 104}; 105 106// Valid redzone sizes are 16, 32, 64, ... 2048, so we encode them in 3 bits. 107// We use adaptive redzones: for larger allocation larger redzones are used. 108static u32 RZLog2Size(u32 rz_log) { 109 CHECK_LT(rz_log, 8); 110 return 16 << rz_log; 111} 112 113static u32 RZSize2Log(u32 rz_size) { 114 CHECK_GE(rz_size, 16); 115 CHECK_LE(rz_size, 2048); 116 CHECK(IsPowerOfTwo(rz_size)); 117 u32 res = __builtin_ctz(rz_size) - 4; 118 CHECK_EQ(rz_size, RZLog2Size(res)); 119 return res; 120} 121 122static uptr ComputeRZLog(uptr user_requested_size) { 123 u32 rz_log = 124 user_requested_size <= 64 - 16 ? 0 : 125 user_requested_size <= 128 - 32 ? 1 : 126 user_requested_size <= 512 - 64 ? 2 : 127 user_requested_size <= 4096 - 128 ? 3 : 128 user_requested_size <= (1 << 14) - 256 ? 4 : 129 user_requested_size <= (1 << 15) - 512 ? 5 : 130 user_requested_size <= (1 << 16) - 1024 ? 6 : 7; 131 return Max(rz_log, RZSize2Log(flags()->redzone)); 132} 133 134// The memory chunk allocated from the underlying allocator looks like this: 135// L L L L L L H H U U U U U U R R 136// L -- left redzone words (0 or more bytes) 137// H -- ChunkHeader (16 bytes), which is also a part of the left redzone. 138// U -- user memory. 139// R -- right redzone (0 or more bytes) 140// ChunkBase consists of ChunkHeader and other bytes that overlap with user 141// memory. 142 143// If a memory chunk is allocated by memalign and we had to increase the 144// allocation size to achieve the proper alignment, then we store this magic 145// value in the first uptr word of the memory block and store the address of 146// ChunkBase in the next uptr. 147// M B ? ? ? L L L L L L H H U U U U U U 148// M -- magic value kMemalignMagic 149// B -- address of ChunkHeader pointing to the first 'H' 150static const uptr kMemalignMagic = 0xCC6E96B9; 151 152struct ChunkHeader { 153 // 1-st 8 bytes. 154 u32 chunk_state : 8; // Must be first. 155 u32 alloc_tid : 24; 156 157 u32 free_tid : 24; 158 u32 from_memalign : 1; 159 u32 alloc_type : 2; 160 u32 rz_log : 3; 161 // 2-nd 8 bytes 162 // This field is used for small sizes. For large sizes it is equal to 163 // SizeClassMap::kMaxSize and the actual size is stored in the 164 // SecondaryAllocator's metadata. 165 u32 user_requested_size; 166 u32 alloc_context_id; 167}; 168 169struct ChunkBase : ChunkHeader { 170 // Header2, intersects with user memory. 171 AsanChunk *next; 172 u32 free_context_id; 173}; 174 175static const uptr kChunkHeaderSize = sizeof(ChunkHeader); 176static const uptr kChunkHeader2Size = sizeof(ChunkBase) - kChunkHeaderSize; 177COMPILER_CHECK(kChunkHeaderSize == 16); 178COMPILER_CHECK(kChunkHeader2Size <= 16); 179 180struct AsanChunk: ChunkBase { 181 uptr Beg() { return reinterpret_cast<uptr>(this) + kChunkHeaderSize; } 182 uptr UsedSize() { 183 if (user_requested_size != SizeClassMap::kMaxSize) 184 return user_requested_size; 185 return *reinterpret_cast<uptr *>(allocator.GetMetaData(AllocBeg())); 186 } 187 void *AllocBeg() { 188 if (from_memalign) 189 return allocator.GetBlockBegin(reinterpret_cast<void *>(this)); 190 return reinterpret_cast<void*>(Beg() - RZLog2Size(rz_log)); 191 } 192 // We store the alloc/free stack traces in the chunk itself. 193 u32 *AllocStackBeg() { 194 return (u32*)(Beg() - RZLog2Size(rz_log)); 195 } 196 uptr AllocStackSize() { 197 CHECK_LE(RZLog2Size(rz_log), kChunkHeaderSize); 198 return (RZLog2Size(rz_log) - kChunkHeaderSize) / sizeof(u32); 199 } 200 u32 *FreeStackBeg() { 201 return (u32*)(Beg() + kChunkHeader2Size); 202 } 203 uptr FreeStackSize() { 204 if (user_requested_size < kChunkHeader2Size) return 0; 205 uptr available = RoundUpTo(user_requested_size, SHADOW_GRANULARITY); 206 return (available - kChunkHeader2Size) / sizeof(u32); 207 } 208}; 209 210uptr AsanChunkView::Beg() { return chunk_->Beg(); } 211uptr AsanChunkView::End() { return Beg() + UsedSize(); } 212uptr AsanChunkView::UsedSize() { return chunk_->UsedSize(); } 213uptr AsanChunkView::AllocTid() { return chunk_->alloc_tid; } 214uptr AsanChunkView::FreeTid() { return chunk_->free_tid; } 215 216static void GetStackTraceFromId(u32 id, StackTrace *stack) { 217 CHECK(id); 218 uptr size = 0; 219 const uptr *trace = StackDepotGet(id, &size); 220 CHECK_LT(size, kStackTraceMax); 221 internal_memcpy(stack->trace, trace, sizeof(uptr) * size); 222 stack->size = size; 223} 224 225void AsanChunkView::GetAllocStack(StackTrace *stack) { 226 if (flags()->use_stack_depot) 227 GetStackTraceFromId(chunk_->alloc_context_id, stack); 228 else 229 StackTrace::UncompressStack(stack, chunk_->AllocStackBeg(), 230 chunk_->AllocStackSize()); 231} 232 233void AsanChunkView::GetFreeStack(StackTrace *stack) { 234 if (flags()->use_stack_depot) 235 GetStackTraceFromId(chunk_->free_context_id, stack); 236 else 237 StackTrace::UncompressStack(stack, chunk_->FreeStackBeg(), 238 chunk_->FreeStackSize()); 239} 240 241struct QuarantineCallback; 242typedef Quarantine<QuarantineCallback, AsanChunk> AsanQuarantine; 243typedef AsanQuarantine::Cache QuarantineCache; 244static AsanQuarantine quarantine(LINKER_INITIALIZED); 245static QuarantineCache fallback_quarantine_cache(LINKER_INITIALIZED); 246static AllocatorCache fallback_allocator_cache; 247static SpinMutex fallback_mutex; 248 249QuarantineCache *GetQuarantineCache(AsanThreadLocalMallocStorage *ms) { 250 CHECK(ms); 251 CHECK_LE(sizeof(QuarantineCache), sizeof(ms->quarantine_cache)); 252 return reinterpret_cast<QuarantineCache *>(ms->quarantine_cache); 253} 254 255struct QuarantineCallback { 256 explicit QuarantineCallback(AllocatorCache *cache) 257 : cache_(cache) { 258 } 259 260 void Recycle(AsanChunk *m) { 261 CHECK(m->chunk_state == CHUNK_QUARANTINE); 262 m->chunk_state = CHUNK_AVAILABLE; 263 CHECK_NE(m->alloc_tid, kInvalidTid); 264 CHECK_NE(m->free_tid, kInvalidTid); 265 PoisonShadow(m->Beg(), 266 RoundUpTo(m->UsedSize(), SHADOW_GRANULARITY), 267 kAsanHeapLeftRedzoneMagic); 268 void *p = reinterpret_cast<void *>(m->AllocBeg()); 269 if (m->from_memalign) { 270 uptr *memalign_magic = reinterpret_cast<uptr *>(p); 271 CHECK_EQ(memalign_magic[0], kMemalignMagic); 272 CHECK_EQ(memalign_magic[1], reinterpret_cast<uptr>(m)); 273 } 274 275 // Statistics. 276 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats(); 277 thread_stats.real_frees++; 278 thread_stats.really_freed += m->UsedSize(); 279 280 allocator.Deallocate(cache_, p); 281 } 282 283 void *Allocate(uptr size) { 284 return allocator.Allocate(cache_, size, 1, false); 285 } 286 287 void Deallocate(void *p) { 288 allocator.Deallocate(cache_, p); 289 } 290 291 AllocatorCache *cache_; 292}; 293 294static void Init() { 295 static int inited = 0; 296 if (inited) return; 297 __asan_init(); 298 inited = true; // this must happen before any threads are created. 299 allocator.Init(); 300 quarantine.Init((uptr)flags()->quarantine_size, kMaxThreadLocalQuarantine); 301} 302 303static void *Allocate(uptr size, uptr alignment, StackTrace *stack, 304 AllocType alloc_type) { 305 Init(); 306 CHECK(stack); 307 const uptr min_alignment = SHADOW_GRANULARITY; 308 if (alignment < min_alignment) 309 alignment = min_alignment; 310 if (size == 0) { 311 if (alignment <= kReturnOnZeroMalloc) 312 return reinterpret_cast<void *>(kReturnOnZeroMalloc); 313 else 314 return 0; // 0 bytes with large alignment requested. Just return 0. 315 } 316 CHECK(IsPowerOfTwo(alignment)); 317 uptr rz_log = ComputeRZLog(size); 318 uptr rz_size = RZLog2Size(rz_log); 319 uptr rounded_size = RoundUpTo(size, alignment); 320 if (rounded_size < kChunkHeader2Size) 321 rounded_size = kChunkHeader2Size; 322 uptr needed_size = rounded_size + rz_size; 323 if (alignment > min_alignment) 324 needed_size += alignment; 325 bool using_primary_allocator = true; 326 // If we are allocating from the secondary allocator, there will be no 327 // automatic right redzone, so add the right redzone manually. 328 if (!PrimaryAllocator::CanAllocate(needed_size, alignment)) { 329 needed_size += rz_size; 330 using_primary_allocator = false; 331 } 332 CHECK(IsAligned(needed_size, min_alignment)); 333 if (size > kMaxAllowedMallocSize || needed_size > kMaxAllowedMallocSize) { 334 Report("WARNING: AddressSanitizer failed to allocate %p bytes\n", 335 (void*)size); 336 return 0; 337 } 338 339 AsanThread *t = asanThreadRegistry().GetCurrent(); 340 AllocatorCache *cache = t ? GetAllocatorCache(&t->malloc_storage()) : 0; 341 void *allocated = allocator.Allocate(cache, needed_size, 8, false); 342 uptr alloc_beg = reinterpret_cast<uptr>(allocated); 343 uptr alloc_end = alloc_beg + needed_size; 344 uptr beg_plus_redzone = alloc_beg + rz_size; 345 uptr user_beg = beg_plus_redzone; 346 if (!IsAligned(user_beg, alignment)) 347 user_beg = RoundUpTo(user_beg, alignment); 348 uptr user_end = user_beg + size; 349 CHECK_LE(user_end, alloc_end); 350 uptr chunk_beg = user_beg - kChunkHeaderSize; 351 AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg); 352 m->chunk_state = CHUNK_ALLOCATED; 353 m->alloc_type = alloc_type; 354 m->rz_log = rz_log; 355 u32 alloc_tid = t ? t->tid() : 0; 356 m->alloc_tid = alloc_tid; 357 CHECK_EQ(alloc_tid, m->alloc_tid); // Does alloc_tid fit into the bitfield? 358 m->free_tid = kInvalidTid; 359 m->from_memalign = user_beg != beg_plus_redzone; 360 if (m->from_memalign) { 361 CHECK_LE(beg_plus_redzone + 2 * sizeof(uptr), user_beg); 362 uptr *memalign_magic = reinterpret_cast<uptr *>(alloc_beg); 363 memalign_magic[0] = kMemalignMagic; 364 memalign_magic[1] = chunk_beg; 365 } 366 if (using_primary_allocator) { 367 CHECK(size); 368 m->user_requested_size = size; 369 CHECK(allocator.FromPrimary(allocated)); 370 } else { 371 CHECK(!allocator.FromPrimary(allocated)); 372 m->user_requested_size = SizeClassMap::kMaxSize; 373 uptr *meta = reinterpret_cast<uptr *>(allocator.GetMetaData(allocated)); 374 meta[0] = size; 375 meta[1] = chunk_beg; 376 } 377 378 if (flags()->use_stack_depot) { 379 m->alloc_context_id = StackDepotPut(stack->trace, stack->size); 380 } else { 381 m->alloc_context_id = 0; 382 StackTrace::CompressStack(stack, m->AllocStackBeg(), m->AllocStackSize()); 383 } 384 385 uptr size_rounded_down_to_granularity = RoundDownTo(size, SHADOW_GRANULARITY); 386 // Unpoison the bulk of the memory region. 387 if (size_rounded_down_to_granularity) 388 PoisonShadow(user_beg, size_rounded_down_to_granularity, 0); 389 // Deal with the end of the region if size is not aligned to granularity. 390 if (size != size_rounded_down_to_granularity && flags()->poison_heap) { 391 u8 *shadow = (u8*)MemToShadow(user_beg + size_rounded_down_to_granularity); 392 *shadow = size & (SHADOW_GRANULARITY - 1); 393 } 394 395 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats(); 396 thread_stats.mallocs++; 397 thread_stats.malloced += size; 398 thread_stats.malloced_redzones += needed_size - size; 399 uptr class_id = Min(kNumberOfSizeClasses, SizeClassMap::ClassID(needed_size)); 400 thread_stats.malloced_by_size[class_id]++; 401 if (needed_size > SizeClassMap::kMaxSize) 402 thread_stats.malloc_large++; 403 404 void *res = reinterpret_cast<void *>(user_beg); 405 ASAN_MALLOC_HOOK(res, size); 406 return res; 407} 408 409static void Deallocate(void *ptr, StackTrace *stack, AllocType alloc_type) { 410 uptr p = reinterpret_cast<uptr>(ptr); 411 if (p == 0 || p == kReturnOnZeroMalloc) return; 412 uptr chunk_beg = p - kChunkHeaderSize; 413 AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg); 414 415 // Flip the chunk_state atomically to avoid race on double-free. 416 u8 old_chunk_state = atomic_exchange((atomic_uint8_t*)m, CHUNK_QUARANTINE, 417 memory_order_acq_rel); 418 419 if (old_chunk_state == CHUNK_QUARANTINE) 420 ReportDoubleFree((uptr)ptr, stack); 421 else if (old_chunk_state != CHUNK_ALLOCATED) 422 ReportFreeNotMalloced((uptr)ptr, stack); 423 CHECK(old_chunk_state == CHUNK_ALLOCATED); 424 if (m->alloc_type != alloc_type && flags()->alloc_dealloc_mismatch) 425 ReportAllocTypeMismatch((uptr)ptr, stack, 426 (AllocType)m->alloc_type, (AllocType)alloc_type); 427 428 CHECK_GE(m->alloc_tid, 0); 429 if (SANITIZER_WORDSIZE == 64) // On 32-bits this resides in user area. 430 CHECK_EQ(m->free_tid, kInvalidTid); 431 AsanThread *t = asanThreadRegistry().GetCurrent(); 432 m->free_tid = t ? t->tid() : 0; 433 if (flags()->use_stack_depot) { 434 m->free_context_id = StackDepotPut(stack->trace, stack->size); 435 } else { 436 m->free_context_id = 0; 437 StackTrace::CompressStack(stack, m->FreeStackBeg(), m->FreeStackSize()); 438 } 439 CHECK(m->chunk_state == CHUNK_QUARANTINE); 440 // Poison the region. 441 PoisonShadow(m->Beg(), 442 RoundUpTo(m->UsedSize(), SHADOW_GRANULARITY), 443 kAsanHeapFreeMagic); 444 445 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats(); 446 thread_stats.frees++; 447 thread_stats.freed += m->UsedSize(); 448 449 // Push into quarantine. 450 if (t) { 451 AsanThreadLocalMallocStorage *ms = &t->malloc_storage(); 452 AllocatorCache *ac = GetAllocatorCache(ms); 453 quarantine.Put(GetQuarantineCache(ms), QuarantineCallback(ac), 454 m, m->UsedSize()); 455 } else { 456 SpinMutexLock l(&fallback_mutex); 457 AllocatorCache *ac = &fallback_allocator_cache; 458 quarantine.Put(&fallback_quarantine_cache, QuarantineCallback(ac), 459 m, m->UsedSize()); 460 } 461 462 ASAN_FREE_HOOK(ptr); 463} 464 465static void *Reallocate(void *old_ptr, uptr new_size, StackTrace *stack) { 466 CHECK(old_ptr && new_size); 467 uptr p = reinterpret_cast<uptr>(old_ptr); 468 uptr chunk_beg = p - kChunkHeaderSize; 469 AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg); 470 471 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats(); 472 thread_stats.reallocs++; 473 thread_stats.realloced += new_size; 474 475 CHECK(m->chunk_state == CHUNK_ALLOCATED); 476 uptr old_size = m->UsedSize(); 477 uptr memcpy_size = Min(new_size, old_size); 478 void *new_ptr = Allocate(new_size, 8, stack, FROM_MALLOC); 479 if (new_ptr) { 480 CHECK(REAL(memcpy) != 0); 481 REAL(memcpy)(new_ptr, old_ptr, memcpy_size); 482 Deallocate(old_ptr, stack, FROM_MALLOC); 483 } 484 return new_ptr; 485} 486 487static AsanChunk *GetAsanChunkByAddr(uptr p) { 488 void *ptr = reinterpret_cast<void *>(p); 489 uptr alloc_beg = reinterpret_cast<uptr>(allocator.GetBlockBegin(ptr)); 490 if (!alloc_beg) return 0; 491 uptr *memalign_magic = reinterpret_cast<uptr *>(alloc_beg); 492 if (memalign_magic[0] == kMemalignMagic) { 493 AsanChunk *m = reinterpret_cast<AsanChunk *>(memalign_magic[1]); 494 CHECK(m->from_memalign); 495 return m; 496 } 497 if (!allocator.FromPrimary(ptr)) { 498 uptr *meta = reinterpret_cast<uptr *>( 499 allocator.GetMetaData(reinterpret_cast<void *>(alloc_beg))); 500 AsanChunk *m = reinterpret_cast<AsanChunk *>(meta[1]); 501 return m; 502 } 503 uptr actual_size = allocator.GetActuallyAllocatedSize(ptr); 504 CHECK_LE(actual_size, SizeClassMap::kMaxSize); 505 // We know the actually allocted size, but we don't know the redzone size. 506 // Just try all possible redzone sizes. 507 for (u32 rz_log = 0; rz_log < 8; rz_log++) { 508 u32 rz_size = RZLog2Size(rz_log); 509 uptr max_possible_size = actual_size - rz_size; 510 if (ComputeRZLog(max_possible_size) != rz_log) 511 continue; 512 return reinterpret_cast<AsanChunk *>( 513 alloc_beg + rz_size - kChunkHeaderSize); 514 } 515 return 0; 516} 517 518static uptr AllocationSize(uptr p) { 519 AsanChunk *m = GetAsanChunkByAddr(p); 520 if (!m) return 0; 521 if (m->chunk_state != CHUNK_ALLOCATED) return 0; 522 if (m->Beg() != p) return 0; 523 return m->UsedSize(); 524} 525 526// We have an address between two chunks, and we want to report just one. 527AsanChunk *ChooseChunk(uptr addr, 528 AsanChunk *left_chunk, AsanChunk *right_chunk) { 529 // Prefer an allocated chunk over freed chunk and freed chunk 530 // over available chunk. 531 if (left_chunk->chunk_state != right_chunk->chunk_state) { 532 if (left_chunk->chunk_state == CHUNK_ALLOCATED) 533 return left_chunk; 534 if (right_chunk->chunk_state == CHUNK_ALLOCATED) 535 return right_chunk; 536 if (left_chunk->chunk_state == CHUNK_QUARANTINE) 537 return left_chunk; 538 if (right_chunk->chunk_state == CHUNK_QUARANTINE) 539 return right_chunk; 540 } 541 // Same chunk_state: choose based on offset. 542 uptr l_offset = 0, r_offset = 0; 543 CHECK(AsanChunkView(left_chunk).AddrIsAtRight(addr, 1, &l_offset)); 544 CHECK(AsanChunkView(right_chunk).AddrIsAtLeft(addr, 1, &r_offset)); 545 if (l_offset < r_offset) 546 return left_chunk; 547 return right_chunk; 548} 549 550AsanChunkView FindHeapChunkByAddress(uptr addr) { 551 AsanChunk *m1 = GetAsanChunkByAddr(addr); 552 if (!m1) return AsanChunkView(m1); 553 uptr offset = 0; 554 if (AsanChunkView(m1).AddrIsAtLeft(addr, 1, &offset)) { 555 // The address is in the chunk's left redzone, so maybe it is actually 556 // a right buffer overflow from the other chunk to the left. 557 // Search a bit to the left to see if there is another chunk. 558 AsanChunk *m2 = 0; 559 for (uptr l = 1; l < GetPageSizeCached(); l++) { 560 m2 = GetAsanChunkByAddr(addr - l); 561 if (m2 == m1) continue; // Still the same chunk. 562 break; 563 } 564 if (m2 && AsanChunkView(m2).AddrIsAtRight(addr, 1, &offset)) 565 m1 = ChooseChunk(addr, m2, m1); 566 } 567 return AsanChunkView(m1); 568} 569 570void AsanThreadLocalMallocStorage::CommitBack() { 571 AllocatorCache *ac = GetAllocatorCache(this); 572 quarantine.Drain(GetQuarantineCache(this), QuarantineCallback(ac)); 573 allocator.SwallowCache(GetAllocatorCache(this)); 574} 575 576void PrintInternalAllocatorStats() { 577 allocator.PrintStats(); 578} 579 580SANITIZER_INTERFACE_ATTRIBUTE 581void *asan_memalign(uptr alignment, uptr size, StackTrace *stack, 582 AllocType alloc_type) { 583 return Allocate(size, alignment, stack, alloc_type); 584} 585 586SANITIZER_INTERFACE_ATTRIBUTE 587void asan_free(void *ptr, StackTrace *stack, AllocType alloc_type) { 588 Deallocate(ptr, stack, alloc_type); 589} 590 591SANITIZER_INTERFACE_ATTRIBUTE 592void *asan_malloc(uptr size, StackTrace *stack) { 593 return Allocate(size, 8, stack, FROM_MALLOC); 594} 595 596void *asan_calloc(uptr nmemb, uptr size, StackTrace *stack) { 597 void *ptr = Allocate(nmemb * size, 8, stack, FROM_MALLOC); 598 if (ptr) 599 REAL(memset)(ptr, 0, nmemb * size); 600 return ptr; 601} 602 603void *asan_realloc(void *p, uptr size, StackTrace *stack) { 604 if (p == 0) 605 return Allocate(size, 8, stack, FROM_MALLOC); 606 if (size == 0) { 607 Deallocate(p, stack, FROM_MALLOC); 608 return 0; 609 } 610 return Reallocate(p, size, stack); 611} 612 613void *asan_valloc(uptr size, StackTrace *stack) { 614 return Allocate(size, GetPageSizeCached(), stack, FROM_MALLOC); 615} 616 617void *asan_pvalloc(uptr size, StackTrace *stack) { 618 uptr PageSize = GetPageSizeCached(); 619 size = RoundUpTo(size, PageSize); 620 if (size == 0) { 621 // pvalloc(0) should allocate one page. 622 size = PageSize; 623 } 624 return Allocate(size, PageSize, stack, FROM_MALLOC); 625} 626 627int asan_posix_memalign(void **memptr, uptr alignment, uptr size, 628 StackTrace *stack) { 629 void *ptr = Allocate(size, alignment, stack, FROM_MALLOC); 630 CHECK(IsAligned((uptr)ptr, alignment)); 631 *memptr = ptr; 632 return 0; 633} 634 635uptr asan_malloc_usable_size(void *ptr, StackTrace *stack) { 636 CHECK(stack); 637 if (ptr == 0) return 0; 638 uptr usable_size = AllocationSize(reinterpret_cast<uptr>(ptr)); 639 if (flags()->check_malloc_usable_size && (usable_size == 0)) 640 ReportMallocUsableSizeNotOwned((uptr)ptr, stack); 641 return usable_size; 642} 643 644uptr asan_mz_size(const void *ptr) { 645 UNIMPLEMENTED(); 646 return 0; 647} 648 649void asan_mz_force_lock() { 650 UNIMPLEMENTED(); 651} 652 653void asan_mz_force_unlock() { 654 UNIMPLEMENTED(); 655} 656 657} // namespace __asan 658 659// ---------------------- Interface ---------------- {{{1 660using namespace __asan; // NOLINT 661 662// ASan allocator doesn't reserve extra bytes, so normally we would 663// just return "size". We don't want to expose our redzone sizes, etc here. 664uptr __asan_get_estimated_allocated_size(uptr size) { 665 return size; 666} 667 668bool __asan_get_ownership(const void *p) { 669 return AllocationSize(reinterpret_cast<uptr>(p)) > 0; 670} 671 672uptr __asan_get_allocated_size(const void *p) { 673 if (p == 0) return 0; 674 uptr allocated_size = AllocationSize(reinterpret_cast<uptr>(p)); 675 // Die if p is not malloced or if it is already freed. 676 if (allocated_size == 0) { 677 GET_STACK_TRACE_FATAL_HERE; 678 ReportAsanGetAllocatedSizeNotOwned(reinterpret_cast<uptr>(p), &stack); 679 } 680 return allocated_size; 681} 682 683#if !SANITIZER_SUPPORTS_WEAK_HOOKS 684// Provide default (no-op) implementation of malloc hooks. 685extern "C" { 686SANITIZER_WEAK_ATTRIBUTE SANITIZER_INTERFACE_ATTRIBUTE 687void __asan_malloc_hook(void *ptr, uptr size) { 688 (void)ptr; 689 (void)size; 690} 691SANITIZER_WEAK_ATTRIBUTE SANITIZER_INTERFACE_ATTRIBUTE 692void __asan_free_hook(void *ptr) { 693 (void)ptr; 694} 695} // extern "C" 696#endif 697 698 699#endif // ASAN_ALLOCATOR_VERSION 700