asan_allocator2.cc revision 5d43b5a695ca6b6dc4eff05e723a7f39643f3266
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//===----------------------------------------------------------------------===//
17#include "asan_allocator.h"
18
19#include "asan_mapping.h"
20#include "asan_poisoning.h"
21#include "asan_report.h"
22#include "asan_thread.h"
23#include "sanitizer_common/sanitizer_allocator.h"
24#include "sanitizer_common/sanitizer_flags.h"
25#include "sanitizer_common/sanitizer_internal_defs.h"
26#include "sanitizer_common/sanitizer_list.h"
27#include "sanitizer_common/sanitizer_stackdepot.h"
28#include "sanitizer_common/sanitizer_quarantine.h"
29#include "lsan/lsan_common.h"
30
31namespace __asan {
32
33struct AsanMapUnmapCallback {
34  void OnMap(uptr p, uptr size) const {
35    PoisonShadow(p, size, kAsanHeapLeftRedzoneMagic);
36    // Statistics.
37    AsanStats &thread_stats = GetCurrentThreadStats();
38    thread_stats.mmaps++;
39    thread_stats.mmaped += size;
40  }
41  void OnUnmap(uptr p, uptr size) const {
42    PoisonShadow(p, size, 0);
43    // We are about to unmap a chunk of user memory.
44    // Mark the corresponding shadow memory as not needed.
45    // Since asan's mapping is compacting, the shadow chunk may be
46    // not page-aligned, so we only flush the page-aligned portion.
47    uptr page_size = GetPageSizeCached();
48    uptr shadow_beg = RoundUpTo(MemToShadow(p), page_size);
49    uptr shadow_end = RoundDownTo(MemToShadow(p + size), page_size);
50    FlushUnneededShadowMemory(shadow_beg, shadow_end - shadow_beg);
51    // Statistics.
52    AsanStats &thread_stats = GetCurrentThreadStats();
53    thread_stats.munmaps++;
54    thread_stats.munmaped += size;
55  }
56};
57
58#if SANITIZER_WORDSIZE == 64
59#if defined(__powerpc64__)
60const uptr kAllocatorSpace =  0xa0000000000ULL;
61const uptr kAllocatorSize  =  0x20000000000ULL;  // 2T.
62#else
63const uptr kAllocatorSpace = 0x600000000000ULL;
64const uptr kAllocatorSize  =  0x40000000000ULL;  // 4T.
65#endif
66typedef DefaultSizeClassMap SizeClassMap;
67typedef SizeClassAllocator64<kAllocatorSpace, kAllocatorSize, 0 /*metadata*/,
68    SizeClassMap, AsanMapUnmapCallback> PrimaryAllocator;
69#elif SANITIZER_WORDSIZE == 32
70static const u64 kAddressSpaceSize = 1ULL << 32;
71typedef CompactSizeClassMap SizeClassMap;
72static const uptr kRegionSizeLog = 20;
73static const uptr kFlatByteMapSize = kAddressSpaceSize >> kRegionSizeLog;
74typedef SizeClassAllocator32<0, kAddressSpaceSize, 16,
75  SizeClassMap, kRegionSizeLog,
76  FlatByteMap<kFlatByteMapSize>,
77  AsanMapUnmapCallback> PrimaryAllocator;
78#endif
79
80typedef SizeClassAllocatorLocalCache<PrimaryAllocator> AllocatorCache;
81typedef LargeMmapAllocator<AsanMapUnmapCallback> SecondaryAllocator;
82typedef CombinedAllocator<PrimaryAllocator, AllocatorCache,
83    SecondaryAllocator> Allocator;
84
85// We can not use THREADLOCAL because it is not supported on some of the
86// platforms we care about (OSX 10.6, Android).
87// static THREADLOCAL AllocatorCache cache;
88AllocatorCache *GetAllocatorCache(AsanThreadLocalMallocStorage *ms) {
89  CHECK(ms);
90  CHECK_LE(sizeof(AllocatorCache), sizeof(ms->allocator2_cache));
91  return reinterpret_cast<AllocatorCache *>(ms->allocator2_cache);
92}
93
94static Allocator allocator;
95
96static const uptr kMaxAllowedMallocSize =
97  FIRST_32_SECOND_64(3UL << 30, 8UL << 30);
98
99static const uptr kMaxThreadLocalQuarantine =
100  FIRST_32_SECOND_64(1 << 18, 1 << 20);
101
102// Every chunk of memory allocated by this allocator can be in one of 3 states:
103// CHUNK_AVAILABLE: the chunk is in the free list and ready to be allocated.
104// CHUNK_ALLOCATED: the chunk is allocated and not yet freed.
105// CHUNK_QUARANTINE: the chunk was freed and put into quarantine zone.
106enum {
107  CHUNK_AVAILABLE  = 0,  // 0 is the default value even if we didn't set it.
108  CHUNK_ALLOCATED  = 2,
109  CHUNK_QUARANTINE = 3
110};
111
112// Valid redzone sizes are 16, 32, 64, ... 2048, so we encode them in 3 bits.
113// We use adaptive redzones: for larger allocation larger redzones are used.
114static u32 RZLog2Size(u32 rz_log) {
115  CHECK_LT(rz_log, 8);
116  return 16 << rz_log;
117}
118
119static u32 RZSize2Log(u32 rz_size) {
120  CHECK_GE(rz_size, 16);
121  CHECK_LE(rz_size, 2048);
122  CHECK(IsPowerOfTwo(rz_size));
123  u32 res = Log2(rz_size) - 4;
124  CHECK_EQ(rz_size, RZLog2Size(res));
125  return res;
126}
127
128static uptr ComputeRZLog(uptr user_requested_size) {
129  u32 rz_log =
130    user_requested_size <= 64        - 16   ? 0 :
131    user_requested_size <= 128       - 32   ? 1 :
132    user_requested_size <= 512       - 64   ? 2 :
133    user_requested_size <= 4096      - 128  ? 3 :
134    user_requested_size <= (1 << 14) - 256  ? 4 :
135    user_requested_size <= (1 << 15) - 512  ? 5 :
136    user_requested_size <= (1 << 16) - 1024 ? 6 : 7;
137  return Max(rz_log, RZSize2Log(flags()->redzone));
138}
139
140// The memory chunk allocated from the underlying allocator looks like this:
141// L L L L L L H H U U U U U U R R
142//   L -- left redzone words (0 or more bytes)
143//   H -- ChunkHeader (16 bytes), which is also a part of the left redzone.
144//   U -- user memory.
145//   R -- right redzone (0 or more bytes)
146// ChunkBase consists of ChunkHeader and other bytes that overlap with user
147// memory.
148
149// If the left redzone is greater than the ChunkHeader size we store a magic
150// value in the first uptr word of the memory block and store the address of
151// ChunkBase in the next uptr.
152// M B L L L L L L L L L  H H U U U U U U
153//   |                    ^
154//   ---------------------|
155//   M -- magic value kAllocBegMagic
156//   B -- address of ChunkHeader pointing to the first 'H'
157static const uptr kAllocBegMagic = 0xCC6E96B9;
158
159struct ChunkHeader {
160  // 1-st 8 bytes.
161  u32 chunk_state       : 8;  // Must be first.
162  u32 alloc_tid         : 24;
163
164  u32 free_tid          : 24;
165  u32 from_memalign     : 1;
166  u32 alloc_type        : 2;
167  u32 rz_log            : 3;
168  u32 lsan_tag          : 2;
169  // 2-nd 8 bytes
170  // This field is used for small sizes. For large sizes it is equal to
171  // SizeClassMap::kMaxSize and the actual size is stored in the
172  // SecondaryAllocator's metadata.
173  u32 user_requested_size;
174  u32 alloc_context_id;
175};
176
177struct ChunkBase : ChunkHeader {
178  // Header2, intersects with user memory.
179  u32 free_context_id;
180};
181
182static const uptr kChunkHeaderSize = sizeof(ChunkHeader);
183static const uptr kChunkHeader2Size = sizeof(ChunkBase) - kChunkHeaderSize;
184COMPILER_CHECK(kChunkHeaderSize == 16);
185COMPILER_CHECK(kChunkHeader2Size <= 16);
186
187struct AsanChunk: ChunkBase {
188  uptr Beg() { return reinterpret_cast<uptr>(this) + kChunkHeaderSize; }
189  uptr UsedSize() {
190    if (user_requested_size != SizeClassMap::kMaxSize)
191      return user_requested_size;
192    return *reinterpret_cast<uptr *>(allocator.GetMetaData(AllocBeg()));
193  }
194  void *AllocBeg() {
195    if (from_memalign)
196      return allocator.GetBlockBegin(reinterpret_cast<void *>(this));
197    return reinterpret_cast<void*>(Beg() - RZLog2Size(rz_log));
198  }
199  // If we don't use stack depot, we store the alloc/free stack traces
200  // in the chunk itself.
201  u32 *AllocStackBeg() {
202    return (u32*)(Beg() - RZLog2Size(rz_log));
203  }
204  uptr AllocStackSize() {
205    CHECK_LE(RZLog2Size(rz_log), kChunkHeaderSize);
206    return (RZLog2Size(rz_log) - kChunkHeaderSize) / sizeof(u32);
207  }
208  u32 *FreeStackBeg() {
209    return (u32*)(Beg() + kChunkHeader2Size);
210  }
211  uptr FreeStackSize() {
212    if (user_requested_size < kChunkHeader2Size) return 0;
213    uptr available = RoundUpTo(user_requested_size, SHADOW_GRANULARITY);
214    return (available - kChunkHeader2Size) / sizeof(u32);
215  }
216  bool AddrIsInside(uptr addr) {
217    return (addr >= Beg()) && (addr < Beg() + UsedSize());
218  }
219};
220
221uptr AsanChunkView::Beg() { return chunk_->Beg(); }
222uptr AsanChunkView::End() { return Beg() + UsedSize(); }
223uptr AsanChunkView::UsedSize() { return chunk_->UsedSize(); }
224uptr AsanChunkView::AllocTid() { return chunk_->alloc_tid; }
225uptr AsanChunkView::FreeTid() { return chunk_->free_tid; }
226
227static void GetStackTraceFromId(u32 id, StackTrace *stack) {
228  CHECK(id);
229  uptr size = 0;
230  const uptr *trace = StackDepotGet(id, &size);
231  CHECK_LT(size, kStackTraceMax);
232  internal_memcpy(stack->trace, trace, sizeof(uptr) * size);
233  stack->size = size;
234}
235
236void AsanChunkView::GetAllocStack(StackTrace *stack) {
237  if (flags()->use_stack_depot)
238    GetStackTraceFromId(chunk_->alloc_context_id, stack);
239  else
240    StackTrace::UncompressStack(stack, chunk_->AllocStackBeg(),
241                                chunk_->AllocStackSize());
242}
243
244void AsanChunkView::GetFreeStack(StackTrace *stack) {
245  if (flags()->use_stack_depot)
246    GetStackTraceFromId(chunk_->free_context_id, stack);
247  else
248    StackTrace::UncompressStack(stack, chunk_->FreeStackBeg(),
249                                chunk_->FreeStackSize());
250}
251
252struct QuarantineCallback;
253typedef Quarantine<QuarantineCallback, AsanChunk> AsanQuarantine;
254typedef AsanQuarantine::Cache QuarantineCache;
255static AsanQuarantine quarantine(LINKER_INITIALIZED);
256static QuarantineCache fallback_quarantine_cache(LINKER_INITIALIZED);
257static AllocatorCache fallback_allocator_cache;
258static SpinMutex fallback_mutex;
259
260QuarantineCache *GetQuarantineCache(AsanThreadLocalMallocStorage *ms) {
261  CHECK(ms);
262  CHECK_LE(sizeof(QuarantineCache), sizeof(ms->quarantine_cache));
263  return reinterpret_cast<QuarantineCache *>(ms->quarantine_cache);
264}
265
266struct QuarantineCallback {
267  explicit QuarantineCallback(AllocatorCache *cache)
268      : cache_(cache) {
269  }
270
271  void Recycle(AsanChunk *m) {
272    CHECK_EQ(m->chunk_state, CHUNK_QUARANTINE);
273    atomic_store((atomic_uint8_t*)m, CHUNK_AVAILABLE, memory_order_relaxed);
274    CHECK_NE(m->alloc_tid, kInvalidTid);
275    CHECK_NE(m->free_tid, kInvalidTid);
276    PoisonShadow(m->Beg(),
277                 RoundUpTo(m->UsedSize(), SHADOW_GRANULARITY),
278                 kAsanHeapLeftRedzoneMagic);
279    void *p = reinterpret_cast<void *>(m->AllocBeg());
280    if (p != m) {
281      uptr *alloc_magic = reinterpret_cast<uptr *>(p);
282      CHECK_EQ(alloc_magic[0], kAllocBegMagic);
283      CHECK_EQ(alloc_magic[1], reinterpret_cast<uptr>(m));
284    }
285
286    // Statistics.
287    AsanStats &thread_stats = GetCurrentThreadStats();
288    thread_stats.real_frees++;
289    thread_stats.really_freed += m->UsedSize();
290
291    allocator.Deallocate(cache_, p);
292  }
293
294  void *Allocate(uptr size) {
295    return allocator.Allocate(cache_, size, 1, false);
296  }
297
298  void Deallocate(void *p) {
299    allocator.Deallocate(cache_, p);
300  }
301
302  AllocatorCache *cache_;
303};
304
305void InitializeAllocator() {
306  allocator.Init();
307  quarantine.Init((uptr)flags()->quarantine_size, kMaxThreadLocalQuarantine);
308}
309
310static void *Allocate(uptr size, uptr alignment, StackTrace *stack,
311                      AllocType alloc_type, bool can_fill) {
312  if (!asan_inited)
313    __asan_init();
314  Flags &fl = *flags();
315  CHECK(stack);
316  const uptr min_alignment = SHADOW_GRANULARITY;
317  if (alignment < min_alignment)
318    alignment = min_alignment;
319  if (size == 0) {
320    // We'd be happy to avoid allocating memory for zero-size requests, but
321    // some programs/tests depend on this behavior and assume that malloc would
322    // not return NULL even for zero-size allocations. Moreover, it looks like
323    // operator new should never return NULL, and results of consecutive "new"
324    // calls must be different even if the allocated size is zero.
325    size = 1;
326  }
327  CHECK(IsPowerOfTwo(alignment));
328  uptr rz_log = ComputeRZLog(size);
329  uptr rz_size = RZLog2Size(rz_log);
330  uptr rounded_size = RoundUpTo(Max(size, kChunkHeader2Size), alignment);
331  uptr needed_size = rounded_size + rz_size;
332  if (alignment > min_alignment)
333    needed_size += alignment;
334  bool using_primary_allocator = true;
335  // If we are allocating from the secondary allocator, there will be no
336  // automatic right redzone, so add the right redzone manually.
337  if (!PrimaryAllocator::CanAllocate(needed_size, alignment)) {
338    needed_size += rz_size;
339    using_primary_allocator = false;
340  }
341  CHECK(IsAligned(needed_size, min_alignment));
342  if (size > kMaxAllowedMallocSize || needed_size > kMaxAllowedMallocSize) {
343    Report("WARNING: AddressSanitizer failed to allocate %p bytes\n",
344           (void*)size);
345    return 0;
346  }
347
348  AsanThread *t = GetCurrentThread();
349  void *allocated;
350  if (t) {
351    AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
352    allocated = allocator.Allocate(cache, needed_size, 8, false);
353  } else {
354    SpinMutexLock l(&fallback_mutex);
355    AllocatorCache *cache = &fallback_allocator_cache;
356    allocated = allocator.Allocate(cache, needed_size, 8, false);
357  }
358  uptr alloc_beg = reinterpret_cast<uptr>(allocated);
359  uptr alloc_end = alloc_beg + needed_size;
360  uptr beg_plus_redzone = alloc_beg + rz_size;
361  uptr user_beg = beg_plus_redzone;
362  if (!IsAligned(user_beg, alignment))
363    user_beg = RoundUpTo(user_beg, alignment);
364  uptr user_end = user_beg + size;
365  CHECK_LE(user_end, alloc_end);
366  uptr chunk_beg = user_beg - kChunkHeaderSize;
367  AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
368  m->alloc_type = alloc_type;
369  m->rz_log = rz_log;
370  u32 alloc_tid = t ? t->tid() : 0;
371  m->alloc_tid = alloc_tid;
372  CHECK_EQ(alloc_tid, m->alloc_tid);  // Does alloc_tid fit into the bitfield?
373  m->free_tid = kInvalidTid;
374  m->from_memalign = user_beg != beg_plus_redzone;
375  if (alloc_beg != chunk_beg) {
376    CHECK_LE(alloc_beg+ 2 * sizeof(uptr), chunk_beg);
377    reinterpret_cast<uptr *>(alloc_beg)[0] = kAllocBegMagic;
378    reinterpret_cast<uptr *>(alloc_beg)[1] = chunk_beg;
379  }
380  if (using_primary_allocator) {
381    CHECK(size);
382    m->user_requested_size = size;
383    CHECK(allocator.FromPrimary(allocated));
384  } else {
385    CHECK(!allocator.FromPrimary(allocated));
386    m->user_requested_size = SizeClassMap::kMaxSize;
387    uptr *meta = reinterpret_cast<uptr *>(allocator.GetMetaData(allocated));
388    meta[0] = size;
389    meta[1] = chunk_beg;
390  }
391
392  if (fl.use_stack_depot) {
393    m->alloc_context_id = StackDepotPut(stack->trace, stack->size);
394  } else {
395    m->alloc_context_id = 0;
396    StackTrace::CompressStack(stack, m->AllocStackBeg(), m->AllocStackSize());
397  }
398
399  uptr size_rounded_down_to_granularity = RoundDownTo(size, SHADOW_GRANULARITY);
400  // Unpoison the bulk of the memory region.
401  if (size_rounded_down_to_granularity)
402    PoisonShadow(user_beg, size_rounded_down_to_granularity, 0);
403  // Deal with the end of the region if size is not aligned to granularity.
404  if (size != size_rounded_down_to_granularity && fl.poison_heap) {
405    u8 *shadow = (u8*)MemToShadow(user_beg + size_rounded_down_to_granularity);
406    *shadow = size & (SHADOW_GRANULARITY - 1);
407  }
408
409  AsanStats &thread_stats = GetCurrentThreadStats();
410  thread_stats.mallocs++;
411  thread_stats.malloced += size;
412  thread_stats.malloced_redzones += needed_size - size;
413  uptr class_id = Min(kNumberOfSizeClasses, SizeClassMap::ClassID(needed_size));
414  thread_stats.malloced_by_size[class_id]++;
415  if (needed_size > SizeClassMap::kMaxSize)
416    thread_stats.malloc_large++;
417
418  void *res = reinterpret_cast<void *>(user_beg);
419  if (can_fill && fl.max_malloc_fill_size) {
420    uptr fill_size = Min(size, (uptr)fl.max_malloc_fill_size);
421    REAL(memset)(res, fl.malloc_fill_byte, fill_size);
422  }
423  if (t && t->lsan_disabled())
424    m->lsan_tag = __lsan::kSuppressed;
425  else
426    m->lsan_tag = __lsan::kDirectlyLeaked;
427  // Must be the last mutation of metadata in this function.
428  atomic_store((atomic_uint8_t *)m, CHUNK_ALLOCATED, memory_order_release);
429  ASAN_MALLOC_HOOK(res, size);
430  return res;
431}
432
433static void ReportInvalidFree(void *ptr, u8 chunk_state, StackTrace *stack) {
434  if (chunk_state == CHUNK_QUARANTINE)
435    ReportDoubleFree((uptr)ptr, stack);
436  else
437    ReportFreeNotMalloced((uptr)ptr, stack);
438}
439
440static void AtomicallySetQuarantineFlag(AsanChunk *m,
441                                        void *ptr, StackTrace *stack) {
442  u8 old_chunk_state = CHUNK_ALLOCATED;
443  // Flip the chunk_state atomically to avoid race on double-free.
444  if (!atomic_compare_exchange_strong((atomic_uint8_t*)m, &old_chunk_state,
445                                      CHUNK_QUARANTINE, memory_order_acquire))
446    ReportInvalidFree(ptr, old_chunk_state, stack);
447  CHECK_EQ(CHUNK_ALLOCATED, old_chunk_state);
448}
449
450// Expects the chunk to already be marked as quarantined by using
451// AtomicallySetQuarantineFlag.
452static void QuarantineChunk(AsanChunk *m, void *ptr,
453                            StackTrace *stack, AllocType alloc_type) {
454  CHECK_EQ(m->chunk_state, CHUNK_QUARANTINE);
455
456  if (m->alloc_type != alloc_type && flags()->alloc_dealloc_mismatch)
457    ReportAllocTypeMismatch((uptr)ptr, stack,
458                            (AllocType)m->alloc_type, (AllocType)alloc_type);
459
460  CHECK_GE(m->alloc_tid, 0);
461  if (SANITIZER_WORDSIZE == 64)  // On 32-bits this resides in user area.
462    CHECK_EQ(m->free_tid, kInvalidTid);
463  AsanThread *t = GetCurrentThread();
464  m->free_tid = t ? t->tid() : 0;
465  if (flags()->use_stack_depot) {
466    m->free_context_id = StackDepotPut(stack->trace, stack->size);
467  } else {
468    m->free_context_id = 0;
469    StackTrace::CompressStack(stack, m->FreeStackBeg(), m->FreeStackSize());
470  }
471  // Poison the region.
472  PoisonShadow(m->Beg(),
473               RoundUpTo(m->UsedSize(), SHADOW_GRANULARITY),
474               kAsanHeapFreeMagic);
475
476  AsanStats &thread_stats = GetCurrentThreadStats();
477  thread_stats.frees++;
478  thread_stats.freed += m->UsedSize();
479
480  // Push into quarantine.
481  if (t) {
482    AsanThreadLocalMallocStorage *ms = &t->malloc_storage();
483    AllocatorCache *ac = GetAllocatorCache(ms);
484    quarantine.Put(GetQuarantineCache(ms), QuarantineCallback(ac),
485                   m, m->UsedSize());
486  } else {
487    SpinMutexLock l(&fallback_mutex);
488    AllocatorCache *ac = &fallback_allocator_cache;
489    quarantine.Put(&fallback_quarantine_cache, QuarantineCallback(ac),
490                   m, m->UsedSize());
491  }
492}
493
494static void Deallocate(void *ptr, StackTrace *stack, AllocType alloc_type) {
495  uptr p = reinterpret_cast<uptr>(ptr);
496  if (p == 0) return;
497
498  uptr chunk_beg = p - kChunkHeaderSize;
499  AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
500  ASAN_FREE_HOOK(ptr);
501  // Must mark the chunk as quarantined before any changes to its metadata.
502  AtomicallySetQuarantineFlag(m, ptr, stack);
503  QuarantineChunk(m, ptr, stack, alloc_type);
504}
505
506static void *Reallocate(void *old_ptr, uptr new_size, StackTrace *stack) {
507  CHECK(old_ptr && new_size);
508  uptr p = reinterpret_cast<uptr>(old_ptr);
509  uptr chunk_beg = p - kChunkHeaderSize;
510  AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
511
512  AsanStats &thread_stats = GetCurrentThreadStats();
513  thread_stats.reallocs++;
514  thread_stats.realloced += new_size;
515
516  void *new_ptr = Allocate(new_size, 8, stack, FROM_MALLOC, true);
517  if (new_ptr) {
518    u8 chunk_state = m->chunk_state;
519    if (chunk_state != CHUNK_ALLOCATED)
520      ReportInvalidFree(old_ptr, chunk_state, stack);
521    CHECK_NE(REAL(memcpy), (void*)0);
522    uptr memcpy_size = Min(new_size, m->UsedSize());
523    // If realloc() races with free(), we may start copying freed memory.
524    // However, we will report racy double-free later anyway.
525    REAL(memcpy)(new_ptr, old_ptr, memcpy_size);
526    Deallocate(old_ptr, stack, FROM_MALLOC);
527  }
528  return new_ptr;
529}
530
531// Assumes alloc_beg == allocator.GetBlockBegin(alloc_beg).
532static AsanChunk *GetAsanChunk(void *alloc_beg) {
533  if (!alloc_beg) return 0;
534  if (!allocator.FromPrimary(alloc_beg)) {
535    uptr *meta = reinterpret_cast<uptr *>(allocator.GetMetaData(alloc_beg));
536    AsanChunk *m = reinterpret_cast<AsanChunk *>(meta[1]);
537    return m;
538  }
539  uptr *alloc_magic = reinterpret_cast<uptr *>(alloc_beg);
540  if (alloc_magic[0] == kAllocBegMagic)
541    return reinterpret_cast<AsanChunk *>(alloc_magic[1]);
542  return reinterpret_cast<AsanChunk *>(alloc_beg);
543}
544
545static AsanChunk *GetAsanChunkByAddr(uptr p) {
546  void *alloc_beg = allocator.GetBlockBegin(reinterpret_cast<void *>(p));
547  return GetAsanChunk(alloc_beg);
548}
549
550// Allocator must be locked when this function is called.
551static AsanChunk *GetAsanChunkByAddrFastLocked(uptr p) {
552  void *alloc_beg =
553      allocator.GetBlockBeginFastLocked(reinterpret_cast<void *>(p));
554  return GetAsanChunk(alloc_beg);
555}
556
557static uptr AllocationSize(uptr p) {
558  AsanChunk *m = GetAsanChunkByAddr(p);
559  if (!m) return 0;
560  if (m->chunk_state != CHUNK_ALLOCATED) return 0;
561  if (m->Beg() != p) return 0;
562  return m->UsedSize();
563}
564
565// We have an address between two chunks, and we want to report just one.
566AsanChunk *ChooseChunk(uptr addr,
567                       AsanChunk *left_chunk, AsanChunk *right_chunk) {
568  // Prefer an allocated chunk over freed chunk and freed chunk
569  // over available chunk.
570  if (left_chunk->chunk_state != right_chunk->chunk_state) {
571    if (left_chunk->chunk_state == CHUNK_ALLOCATED)
572      return left_chunk;
573    if (right_chunk->chunk_state == CHUNK_ALLOCATED)
574      return right_chunk;
575    if (left_chunk->chunk_state == CHUNK_QUARANTINE)
576      return left_chunk;
577    if (right_chunk->chunk_state == CHUNK_QUARANTINE)
578      return right_chunk;
579  }
580  // Same chunk_state: choose based on offset.
581  sptr l_offset = 0, r_offset = 0;
582  CHECK(AsanChunkView(left_chunk).AddrIsAtRight(addr, 1, &l_offset));
583  CHECK(AsanChunkView(right_chunk).AddrIsAtLeft(addr, 1, &r_offset));
584  if (l_offset < r_offset)
585    return left_chunk;
586  return right_chunk;
587}
588
589AsanChunkView FindHeapChunkByAddress(uptr addr) {
590  AsanChunk *m1 = GetAsanChunkByAddr(addr);
591  if (!m1) return AsanChunkView(m1);
592  sptr offset = 0;
593  if (AsanChunkView(m1).AddrIsAtLeft(addr, 1, &offset)) {
594    // The address is in the chunk's left redzone, so maybe it is actually
595    // a right buffer overflow from the other chunk to the left.
596    // Search a bit to the left to see if there is another chunk.
597    AsanChunk *m2 = 0;
598    for (uptr l = 1; l < GetPageSizeCached(); l++) {
599      m2 = GetAsanChunkByAddr(addr - l);
600      if (m2 == m1) continue;  // Still the same chunk.
601      break;
602    }
603    if (m2 && AsanChunkView(m2).AddrIsAtRight(addr, 1, &offset))
604      m1 = ChooseChunk(addr, m2, m1);
605  }
606  return AsanChunkView(m1);
607}
608
609void AsanThreadLocalMallocStorage::CommitBack() {
610  AllocatorCache *ac = GetAllocatorCache(this);
611  quarantine.Drain(GetQuarantineCache(this), QuarantineCallback(ac));
612  allocator.SwallowCache(GetAllocatorCache(this));
613}
614
615void PrintInternalAllocatorStats() {
616  allocator.PrintStats();
617}
618
619SANITIZER_INTERFACE_ATTRIBUTE
620void *asan_memalign(uptr alignment, uptr size, StackTrace *stack,
621                    AllocType alloc_type) {
622  return Allocate(size, alignment, stack, alloc_type, true);
623}
624
625SANITIZER_INTERFACE_ATTRIBUTE
626void asan_free(void *ptr, StackTrace *stack, AllocType alloc_type) {
627  Deallocate(ptr, stack, alloc_type);
628}
629
630SANITIZER_INTERFACE_ATTRIBUTE
631void *asan_malloc(uptr size, StackTrace *stack) {
632  return Allocate(size, 8, stack, FROM_MALLOC, true);
633}
634
635void *asan_calloc(uptr nmemb, uptr size, StackTrace *stack) {
636  if (CallocShouldReturnNullDueToOverflow(size, nmemb)) return 0;
637  void *ptr = Allocate(nmemb * size, 8, stack, FROM_MALLOC, false);
638  // If the memory comes from the secondary allocator no need to clear it
639  // as it comes directly from mmap.
640  if (ptr && allocator.FromPrimary(ptr))
641    REAL(memset)(ptr, 0, nmemb * size);
642  return ptr;
643}
644
645void *asan_realloc(void *p, uptr size, StackTrace *stack) {
646  if (p == 0)
647    return Allocate(size, 8, stack, FROM_MALLOC, true);
648  if (size == 0) {
649    Deallocate(p, stack, FROM_MALLOC);
650    return 0;
651  }
652  return Reallocate(p, size, stack);
653}
654
655void *asan_valloc(uptr size, StackTrace *stack) {
656  return Allocate(size, GetPageSizeCached(), stack, FROM_MALLOC, true);
657}
658
659void *asan_pvalloc(uptr size, StackTrace *stack) {
660  uptr PageSize = GetPageSizeCached();
661  size = RoundUpTo(size, PageSize);
662  if (size == 0) {
663    // pvalloc(0) should allocate one page.
664    size = PageSize;
665  }
666  return Allocate(size, PageSize, stack, FROM_MALLOC, true);
667}
668
669int asan_posix_memalign(void **memptr, uptr alignment, uptr size,
670                        StackTrace *stack) {
671  void *ptr = Allocate(size, alignment, stack, FROM_MALLOC, true);
672  CHECK(IsAligned((uptr)ptr, alignment));
673  *memptr = ptr;
674  return 0;
675}
676
677uptr asan_malloc_usable_size(void *ptr, StackTrace *stack) {
678  CHECK(stack);
679  if (ptr == 0) return 0;
680  uptr usable_size = AllocationSize(reinterpret_cast<uptr>(ptr));
681  if (flags()->check_malloc_usable_size && (usable_size == 0))
682    ReportMallocUsableSizeNotOwned((uptr)ptr, stack);
683  return usable_size;
684}
685
686uptr asan_mz_size(const void *ptr) {
687  return AllocationSize(reinterpret_cast<uptr>(ptr));
688}
689
690void asan_mz_force_lock() {
691  allocator.ForceLock();
692  fallback_mutex.Lock();
693}
694
695void asan_mz_force_unlock() {
696  fallback_mutex.Unlock();
697  allocator.ForceUnlock();
698}
699
700}  // namespace __asan
701
702// --- Implementation of LSan-specific functions --- {{{1
703namespace __lsan {
704void LockAllocator() {
705  __asan::allocator.ForceLock();
706}
707
708void UnlockAllocator() {
709  __asan::allocator.ForceUnlock();
710}
711
712void GetAllocatorGlobalRange(uptr *begin, uptr *end) {
713  *begin = (uptr)&__asan::allocator;
714  *end = *begin + sizeof(__asan::allocator);
715}
716
717void *PointsIntoChunk(void* p) {
718  uptr addr = reinterpret_cast<uptr>(p);
719  __asan::AsanChunk *m = __asan::GetAsanChunkByAddrFastLocked(addr);
720  if (!m) return 0;
721  uptr chunk = m->Beg();
722  if ((m->chunk_state == __asan::CHUNK_ALLOCATED) && m->AddrIsInside(addr))
723    return reinterpret_cast<void *>(chunk);
724  return 0;
725}
726
727void *GetUserBegin(void *p) {
728  __asan::AsanChunk *m =
729      __asan::GetAsanChunkByAddrFastLocked(reinterpret_cast<uptr>(p));
730  CHECK(m);
731  return reinterpret_cast<void *>(m->Beg());
732}
733
734LsanMetadata::LsanMetadata(void *chunk) {
735  uptr addr = reinterpret_cast<uptr>(chunk);
736  metadata_ = reinterpret_cast<void *>(addr - __asan::kChunkHeaderSize);
737}
738
739bool LsanMetadata::allocated() const {
740  __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
741  return m->chunk_state == __asan::CHUNK_ALLOCATED;
742}
743
744ChunkTag LsanMetadata::tag() const {
745  __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
746  return static_cast<ChunkTag>(m->lsan_tag);
747}
748
749void LsanMetadata::set_tag(ChunkTag value) {
750  __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
751  m->lsan_tag = value;
752}
753
754uptr LsanMetadata::requested_size() const {
755  __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
756  return m->UsedSize();
757}
758
759u32 LsanMetadata::stack_trace_id() const {
760  __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
761  return m->alloc_context_id;
762}
763
764template <typename Callable> void ForEachChunk(Callable const &callback) {
765  __asan::allocator.ForEachChunk(callback);
766}
767#if CAN_SANITIZE_LEAKS
768template void ForEachChunk<ProcessPlatformSpecificAllocationsCb>(
769    ProcessPlatformSpecificAllocationsCb const &callback);
770template void ForEachChunk<PrintLeakedCb>(PrintLeakedCb const &callback);
771template void ForEachChunk<CollectLeaksCb>(CollectLeaksCb const &callback);
772template void ForEachChunk<MarkIndirectlyLeakedCb>(
773    MarkIndirectlyLeakedCb const &callback);
774template void ForEachChunk<CollectSuppressedCb>(
775    CollectSuppressedCb const &callback);
776#endif  // CAN_SANITIZE_LEAKS
777
778IgnoreObjectResult IgnoreObjectLocked(const void *p) {
779  uptr addr = reinterpret_cast<uptr>(p);
780  __asan::AsanChunk *m = __asan::GetAsanChunkByAddr(addr);
781  if (!m) return kIgnoreObjectInvalid;
782  if ((m->chunk_state == __asan::CHUNK_ALLOCATED) && m->AddrIsInside(addr)) {
783    if (m->lsan_tag == kSuppressed)
784      return kIgnoreObjectAlreadyIgnored;
785    m->lsan_tag = __lsan::kSuppressed;
786    return kIgnoreObjectSuccess;
787  } else {
788    return kIgnoreObjectInvalid;
789  }
790}
791}  // namespace __lsan
792
793extern "C" {
794SANITIZER_INTERFACE_ATTRIBUTE
795void __lsan_disable() {
796  __asan_init();
797  __asan::AsanThread *t = __asan::GetCurrentThread();
798  CHECK(t);
799  t->disable_lsan();
800}
801
802SANITIZER_INTERFACE_ATTRIBUTE
803void __lsan_enable() {
804  __asan_init();
805  __asan::AsanThread *t = __asan::GetCurrentThread();
806  CHECK(t);
807  t->enable_lsan();
808}
809}  // extern "C"
810
811// ---------------------- Interface ---------------- {{{1
812using namespace __asan;  // NOLINT
813
814// ASan allocator doesn't reserve extra bytes, so normally we would
815// just return "size". We don't want to expose our redzone sizes, etc here.
816uptr __asan_get_estimated_allocated_size(uptr size) {
817  return size;
818}
819
820bool __asan_get_ownership(const void *p) {
821  uptr ptr = reinterpret_cast<uptr>(p);
822  return (AllocationSize(ptr) > 0);
823}
824
825uptr __asan_get_allocated_size(const void *p) {
826  if (p == 0) return 0;
827  uptr ptr = reinterpret_cast<uptr>(p);
828  uptr allocated_size = AllocationSize(ptr);
829  // Die if p is not malloced or if it is already freed.
830  if (allocated_size == 0) {
831    GET_STACK_TRACE_FATAL_HERE;
832    ReportAsanGetAllocatedSizeNotOwned(ptr, &stack);
833  }
834  return allocated_size;
835}
836
837#if !SANITIZER_SUPPORTS_WEAK_HOOKS
838// Provide default (no-op) implementation of malloc hooks.
839extern "C" {
840SANITIZER_WEAK_ATTRIBUTE SANITIZER_INTERFACE_ATTRIBUTE
841void __asan_malloc_hook(void *ptr, uptr size) {
842  (void)ptr;
843  (void)size;
844}
845SANITIZER_WEAK_ATTRIBUTE SANITIZER_INTERFACE_ATTRIBUTE
846void __asan_free_hook(void *ptr) {
847  (void)ptr;
848}
849}  // extern "C"
850#endif
851