]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/asan/asan_allocator.cc
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r308421, and update
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / asan / asan_allocator.cc
1 //===-- asan_allocator.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
18 #include "asan_allocator.h"
19 #include "asan_mapping.h"
20 #include "asan_poisoning.h"
21 #include "asan_report.h"
22 #include "asan_stack.h"
23 #include "asan_thread.h"
24 #include "sanitizer_common/sanitizer_allocator_checks.h"
25 #include "sanitizer_common/sanitizer_allocator_interface.h"
26 #include "sanitizer_common/sanitizer_errno.h"
27 #include "sanitizer_common/sanitizer_flags.h"
28 #include "sanitizer_common/sanitizer_internal_defs.h"
29 #include "sanitizer_common/sanitizer_list.h"
30 #include "sanitizer_common/sanitizer_stackdepot.h"
31 #include "sanitizer_common/sanitizer_quarantine.h"
32 #include "lsan/lsan_common.h"
33
34 namespace __asan {
35
36 // Valid redzone sizes are 16, 32, 64, ... 2048, so we encode them in 3 bits.
37 // We use adaptive redzones: for larger allocation larger redzones are used.
38 static u32 RZLog2Size(u32 rz_log) {
39   CHECK_LT(rz_log, 8);
40   return 16 << rz_log;
41 }
42
43 static u32 RZSize2Log(u32 rz_size) {
44   CHECK_GE(rz_size, 16);
45   CHECK_LE(rz_size, 2048);
46   CHECK(IsPowerOfTwo(rz_size));
47   u32 res = Log2(rz_size) - 4;
48   CHECK_EQ(rz_size, RZLog2Size(res));
49   return res;
50 }
51
52 static AsanAllocator &get_allocator();
53
54 // The memory chunk allocated from the underlying allocator looks like this:
55 // L L L L L L H H U U U U U U R R
56 //   L -- left redzone words (0 or more bytes)
57 //   H -- ChunkHeader (16 bytes), which is also a part of the left redzone.
58 //   U -- user memory.
59 //   R -- right redzone (0 or more bytes)
60 // ChunkBase consists of ChunkHeader and other bytes that overlap with user
61 // memory.
62
63 // If the left redzone is greater than the ChunkHeader size we store a magic
64 // value in the first uptr word of the memory block and store the address of
65 // ChunkBase in the next uptr.
66 // M B L L L L L L L L L  H H U U U U U U
67 //   |                    ^
68 //   ---------------------|
69 //   M -- magic value kAllocBegMagic
70 //   B -- address of ChunkHeader pointing to the first 'H'
71 static const uptr kAllocBegMagic = 0xCC6E96B9;
72
73 struct ChunkHeader {
74   // 1-st 8 bytes.
75   u32 chunk_state       : 8;  // Must be first.
76   u32 alloc_tid         : 24;
77
78   u32 free_tid          : 24;
79   u32 from_memalign     : 1;
80   u32 alloc_type        : 2;
81   u32 rz_log            : 3;
82   u32 lsan_tag          : 2;
83   // 2-nd 8 bytes
84   // This field is used for small sizes. For large sizes it is equal to
85   // SizeClassMap::kMaxSize and the actual size is stored in the
86   // SecondaryAllocator's metadata.
87   u32 user_requested_size;
88   u32 alloc_context_id;
89 };
90
91 struct ChunkBase : ChunkHeader {
92   // Header2, intersects with user memory.
93   u32 free_context_id;
94 };
95
96 static const uptr kChunkHeaderSize = sizeof(ChunkHeader);
97 static const uptr kChunkHeader2Size = sizeof(ChunkBase) - kChunkHeaderSize;
98 COMPILER_CHECK(kChunkHeaderSize == 16);
99 COMPILER_CHECK(kChunkHeader2Size <= 16);
100
101 // Every chunk of memory allocated by this allocator can be in one of 3 states:
102 // CHUNK_AVAILABLE: the chunk is in the free list and ready to be allocated.
103 // CHUNK_ALLOCATED: the chunk is allocated and not yet freed.
104 // CHUNK_QUARANTINE: the chunk was freed and put into quarantine zone.
105 enum {
106   CHUNK_AVAILABLE  = 0,  // 0 is the default value even if we didn't set it.
107   CHUNK_ALLOCATED  = 2,
108   CHUNK_QUARANTINE = 3
109 };
110
111 struct AsanChunk: ChunkBase {
112   uptr Beg() { return reinterpret_cast<uptr>(this) + kChunkHeaderSize; }
113   uptr UsedSize(bool locked_version = false) {
114     if (user_requested_size != SizeClassMap::kMaxSize)
115       return user_requested_size;
116     return *reinterpret_cast<uptr *>(
117                get_allocator().GetMetaData(AllocBeg(locked_version)));
118   }
119   void *AllocBeg(bool locked_version = false) {
120     if (from_memalign) {
121       if (locked_version)
122         return get_allocator().GetBlockBeginFastLocked(
123             reinterpret_cast<void *>(this));
124       return get_allocator().GetBlockBegin(reinterpret_cast<void *>(this));
125     }
126     return reinterpret_cast<void*>(Beg() - RZLog2Size(rz_log));
127   }
128   bool AddrIsInside(uptr addr, bool locked_version = false) {
129     return (addr >= Beg()) && (addr < Beg() + UsedSize(locked_version));
130   }
131 };
132
133 struct QuarantineCallback {
134   explicit QuarantineCallback(AllocatorCache *cache)
135       : cache_(cache) {
136   }
137
138   void Recycle(AsanChunk *m) {
139     CHECK_EQ(m->chunk_state, CHUNK_QUARANTINE);
140     atomic_store((atomic_uint8_t*)m, CHUNK_AVAILABLE, memory_order_relaxed);
141     CHECK_NE(m->alloc_tid, kInvalidTid);
142     CHECK_NE(m->free_tid, kInvalidTid);
143     PoisonShadow(m->Beg(),
144                  RoundUpTo(m->UsedSize(), SHADOW_GRANULARITY),
145                  kAsanHeapLeftRedzoneMagic);
146     void *p = reinterpret_cast<void *>(m->AllocBeg());
147     if (p != m) {
148       uptr *alloc_magic = reinterpret_cast<uptr *>(p);
149       CHECK_EQ(alloc_magic[0], kAllocBegMagic);
150       // Clear the magic value, as allocator internals may overwrite the
151       // contents of deallocated chunk, confusing GetAsanChunk lookup.
152       alloc_magic[0] = 0;
153       CHECK_EQ(alloc_magic[1], reinterpret_cast<uptr>(m));
154     }
155
156     // Statistics.
157     AsanStats &thread_stats = GetCurrentThreadStats();
158     thread_stats.real_frees++;
159     thread_stats.really_freed += m->UsedSize();
160
161     get_allocator().Deallocate(cache_, p);
162   }
163
164   void *Allocate(uptr size) {
165     void *res = get_allocator().Allocate(cache_, size, 1);
166     // TODO(alekseys): Consider making quarantine OOM-friendly.
167     if (UNLIKELY(!res))
168       return DieOnFailure::OnOOM();
169     return res;
170   }
171
172   void Deallocate(void *p) {
173     get_allocator().Deallocate(cache_, p);
174   }
175
176   AllocatorCache *cache_;
177 };
178
179 typedef Quarantine<QuarantineCallback, AsanChunk> AsanQuarantine;
180 typedef AsanQuarantine::Cache QuarantineCache;
181
182 void AsanMapUnmapCallback::OnMap(uptr p, uptr size) const {
183   PoisonShadow(p, size, kAsanHeapLeftRedzoneMagic);
184   // Statistics.
185   AsanStats &thread_stats = GetCurrentThreadStats();
186   thread_stats.mmaps++;
187   thread_stats.mmaped += size;
188 }
189 void AsanMapUnmapCallback::OnUnmap(uptr p, uptr size) const {
190   PoisonShadow(p, size, 0);
191   // We are about to unmap a chunk of user memory.
192   // Mark the corresponding shadow memory as not needed.
193   FlushUnneededASanShadowMemory(p, size);
194   // Statistics.
195   AsanStats &thread_stats = GetCurrentThreadStats();
196   thread_stats.munmaps++;
197   thread_stats.munmaped += size;
198 }
199
200 // We can not use THREADLOCAL because it is not supported on some of the
201 // platforms we care about (OSX 10.6, Android).
202 // static THREADLOCAL AllocatorCache cache;
203 AllocatorCache *GetAllocatorCache(AsanThreadLocalMallocStorage *ms) {
204   CHECK(ms);
205   return &ms->allocator_cache;
206 }
207
208 QuarantineCache *GetQuarantineCache(AsanThreadLocalMallocStorage *ms) {
209   CHECK(ms);
210   CHECK_LE(sizeof(QuarantineCache), sizeof(ms->quarantine_cache));
211   return reinterpret_cast<QuarantineCache *>(ms->quarantine_cache);
212 }
213
214 void AllocatorOptions::SetFrom(const Flags *f, const CommonFlags *cf) {
215   quarantine_size_mb = f->quarantine_size_mb;
216   thread_local_quarantine_size_kb = f->thread_local_quarantine_size_kb;
217   min_redzone = f->redzone;
218   max_redzone = f->max_redzone;
219   may_return_null = cf->allocator_may_return_null;
220   alloc_dealloc_mismatch = f->alloc_dealloc_mismatch;
221   release_to_os_interval_ms = cf->allocator_release_to_os_interval_ms;
222 }
223
224 void AllocatorOptions::CopyTo(Flags *f, CommonFlags *cf) {
225   f->quarantine_size_mb = quarantine_size_mb;
226   f->thread_local_quarantine_size_kb = thread_local_quarantine_size_kb;
227   f->redzone = min_redzone;
228   f->max_redzone = max_redzone;
229   cf->allocator_may_return_null = may_return_null;
230   f->alloc_dealloc_mismatch = alloc_dealloc_mismatch;
231   cf->allocator_release_to_os_interval_ms = release_to_os_interval_ms;
232 }
233
234 struct Allocator {
235   static const uptr kMaxAllowedMallocSize =
236       FIRST_32_SECOND_64(3UL << 30, 1ULL << 40);
237
238   AsanAllocator allocator;
239   AsanQuarantine quarantine;
240   StaticSpinMutex fallback_mutex;
241   AllocatorCache fallback_allocator_cache;
242   QuarantineCache fallback_quarantine_cache;
243
244   atomic_uint8_t rss_limit_exceeded;
245
246   // ------------------- Options --------------------------
247   atomic_uint16_t min_redzone;
248   atomic_uint16_t max_redzone;
249   atomic_uint8_t alloc_dealloc_mismatch;
250
251   // ------------------- Initialization ------------------------
252   explicit Allocator(LinkerInitialized)
253       : quarantine(LINKER_INITIALIZED),
254         fallback_quarantine_cache(LINKER_INITIALIZED) {}
255
256   void CheckOptions(const AllocatorOptions &options) const {
257     CHECK_GE(options.min_redzone, 16);
258     CHECK_GE(options.max_redzone, options.min_redzone);
259     CHECK_LE(options.max_redzone, 2048);
260     CHECK(IsPowerOfTwo(options.min_redzone));
261     CHECK(IsPowerOfTwo(options.max_redzone));
262   }
263
264   void SharedInitCode(const AllocatorOptions &options) {
265     CheckOptions(options);
266     quarantine.Init((uptr)options.quarantine_size_mb << 20,
267                     (uptr)options.thread_local_quarantine_size_kb << 10);
268     atomic_store(&alloc_dealloc_mismatch, options.alloc_dealloc_mismatch,
269                  memory_order_release);
270     atomic_store(&min_redzone, options.min_redzone, memory_order_release);
271     atomic_store(&max_redzone, options.max_redzone, memory_order_release);
272   }
273
274   void Initialize(const AllocatorOptions &options) {
275     SetAllocatorMayReturnNull(options.may_return_null);
276     allocator.Init(options.release_to_os_interval_ms);
277     SharedInitCode(options);
278   }
279
280   bool RssLimitExceeded() {
281     return atomic_load(&rss_limit_exceeded, memory_order_relaxed);
282   }
283
284   void SetRssLimitExceeded(bool limit_exceeded) {
285     atomic_store(&rss_limit_exceeded, limit_exceeded, memory_order_relaxed);
286   }
287
288   void RePoisonChunk(uptr chunk) {
289     // This could be a user-facing chunk (with redzones), or some internal
290     // housekeeping chunk, like TransferBatch. Start by assuming the former.
291     AsanChunk *ac = GetAsanChunk((void *)chunk);
292     uptr allocated_size = allocator.GetActuallyAllocatedSize((void *)ac);
293     uptr beg = ac->Beg();
294     uptr end = ac->Beg() + ac->UsedSize(true);
295     uptr chunk_end = chunk + allocated_size;
296     if (chunk < beg && beg < end && end <= chunk_end &&
297         ac->chunk_state == CHUNK_ALLOCATED) {
298       // Looks like a valid AsanChunk in use, poison redzones only.
299       PoisonShadow(chunk, beg - chunk, kAsanHeapLeftRedzoneMagic);
300       uptr end_aligned_down = RoundDownTo(end, SHADOW_GRANULARITY);
301       FastPoisonShadowPartialRightRedzone(
302           end_aligned_down, end - end_aligned_down,
303           chunk_end - end_aligned_down, kAsanHeapLeftRedzoneMagic);
304     } else {
305       // This is either not an AsanChunk or freed or quarantined AsanChunk.
306       // In either case, poison everything.
307       PoisonShadow(chunk, allocated_size, kAsanHeapLeftRedzoneMagic);
308     }
309   }
310
311   void ReInitialize(const AllocatorOptions &options) {
312     SetAllocatorMayReturnNull(options.may_return_null);
313     allocator.SetReleaseToOSIntervalMs(options.release_to_os_interval_ms);
314     SharedInitCode(options);
315
316     // Poison all existing allocation's redzones.
317     if (CanPoisonMemory()) {
318       allocator.ForceLock();
319       allocator.ForEachChunk(
320           [](uptr chunk, void *alloc) {
321             ((Allocator *)alloc)->RePoisonChunk(chunk);
322           },
323           this);
324       allocator.ForceUnlock();
325     }
326   }
327
328   void GetOptions(AllocatorOptions *options) const {
329     options->quarantine_size_mb = quarantine.GetSize() >> 20;
330     options->thread_local_quarantine_size_kb = quarantine.GetCacheSize() >> 10;
331     options->min_redzone = atomic_load(&min_redzone, memory_order_acquire);
332     options->max_redzone = atomic_load(&max_redzone, memory_order_acquire);
333     options->may_return_null = AllocatorMayReturnNull();
334     options->alloc_dealloc_mismatch =
335         atomic_load(&alloc_dealloc_mismatch, memory_order_acquire);
336     options->release_to_os_interval_ms = allocator.ReleaseToOSIntervalMs();
337   }
338
339   // -------------------- Helper methods. -------------------------
340   uptr ComputeRZLog(uptr user_requested_size) {
341     u32 rz_log =
342       user_requested_size <= 64        - 16   ? 0 :
343       user_requested_size <= 128       - 32   ? 1 :
344       user_requested_size <= 512       - 64   ? 2 :
345       user_requested_size <= 4096      - 128  ? 3 :
346       user_requested_size <= (1 << 14) - 256  ? 4 :
347       user_requested_size <= (1 << 15) - 512  ? 5 :
348       user_requested_size <= (1 << 16) - 1024 ? 6 : 7;
349     u32 min_rz = atomic_load(&min_redzone, memory_order_acquire);
350     u32 max_rz = atomic_load(&max_redzone, memory_order_acquire);
351     return Min(Max(rz_log, RZSize2Log(min_rz)), RZSize2Log(max_rz));
352   }
353
354   // We have an address between two chunks, and we want to report just one.
355   AsanChunk *ChooseChunk(uptr addr, AsanChunk *left_chunk,
356                          AsanChunk *right_chunk) {
357     // Prefer an allocated chunk over freed chunk and freed chunk
358     // over available chunk.
359     if (left_chunk->chunk_state != right_chunk->chunk_state) {
360       if (left_chunk->chunk_state == CHUNK_ALLOCATED)
361         return left_chunk;
362       if (right_chunk->chunk_state == CHUNK_ALLOCATED)
363         return right_chunk;
364       if (left_chunk->chunk_state == CHUNK_QUARANTINE)
365         return left_chunk;
366       if (right_chunk->chunk_state == CHUNK_QUARANTINE)
367         return right_chunk;
368     }
369     // Same chunk_state: choose based on offset.
370     sptr l_offset = 0, r_offset = 0;
371     CHECK(AsanChunkView(left_chunk).AddrIsAtRight(addr, 1, &l_offset));
372     CHECK(AsanChunkView(right_chunk).AddrIsAtLeft(addr, 1, &r_offset));
373     if (l_offset < r_offset)
374       return left_chunk;
375     return right_chunk;
376   }
377
378   // -------------------- Allocation/Deallocation routines ---------------
379   void *Allocate(uptr size, uptr alignment, BufferedStackTrace *stack,
380                  AllocType alloc_type, bool can_fill) {
381     if (UNLIKELY(!asan_inited))
382       AsanInitFromRtl();
383     if (RssLimitExceeded())
384       return AsanAllocator::FailureHandler::OnOOM();
385     Flags &fl = *flags();
386     CHECK(stack);
387     const uptr min_alignment = SHADOW_GRANULARITY;
388     if (alignment < min_alignment)
389       alignment = min_alignment;
390     if (size == 0) {
391       // We'd be happy to avoid allocating memory for zero-size requests, but
392       // some programs/tests depend on this behavior and assume that malloc
393       // would not return NULL even for zero-size allocations. Moreover, it
394       // looks like operator new should never return NULL, and results of
395       // consecutive "new" calls must be different even if the allocated size
396       // is zero.
397       size = 1;
398     }
399     CHECK(IsPowerOfTwo(alignment));
400     uptr rz_log = ComputeRZLog(size);
401     uptr rz_size = RZLog2Size(rz_log);
402     uptr rounded_size = RoundUpTo(Max(size, kChunkHeader2Size), alignment);
403     uptr needed_size = rounded_size + rz_size;
404     if (alignment > min_alignment)
405       needed_size += alignment;
406     bool using_primary_allocator = true;
407     // If we are allocating from the secondary allocator, there will be no
408     // automatic right redzone, so add the right redzone manually.
409     if (!PrimaryAllocator::CanAllocate(needed_size, alignment)) {
410       needed_size += rz_size;
411       using_primary_allocator = false;
412     }
413     CHECK(IsAligned(needed_size, min_alignment));
414     if (size > kMaxAllowedMallocSize || needed_size > kMaxAllowedMallocSize) {
415       Report("WARNING: AddressSanitizer failed to allocate 0x%zx bytes\n",
416              (void*)size);
417       return AsanAllocator::FailureHandler::OnBadRequest();
418     }
419
420     AsanThread *t = GetCurrentThread();
421     void *allocated;
422     if (t) {
423       AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
424       allocated = allocator.Allocate(cache, needed_size, 8);
425     } else {
426       SpinMutexLock l(&fallback_mutex);
427       AllocatorCache *cache = &fallback_allocator_cache;
428       allocated = allocator.Allocate(cache, needed_size, 8);
429     }
430     if (!allocated)
431       return nullptr;
432
433     if (*(u8 *)MEM_TO_SHADOW((uptr)allocated) == 0 && CanPoisonMemory()) {
434       // Heap poisoning is enabled, but the allocator provides an unpoisoned
435       // chunk. This is possible if CanPoisonMemory() was false for some
436       // time, for example, due to flags()->start_disabled.
437       // Anyway, poison the block before using it for anything else.
438       uptr allocated_size = allocator.GetActuallyAllocatedSize(allocated);
439       PoisonShadow((uptr)allocated, allocated_size, kAsanHeapLeftRedzoneMagic);
440     }
441
442     uptr alloc_beg = reinterpret_cast<uptr>(allocated);
443     uptr alloc_end = alloc_beg + needed_size;
444     uptr beg_plus_redzone = alloc_beg + rz_size;
445     uptr user_beg = beg_plus_redzone;
446     if (!IsAligned(user_beg, alignment))
447       user_beg = RoundUpTo(user_beg, alignment);
448     uptr user_end = user_beg + size;
449     CHECK_LE(user_end, alloc_end);
450     uptr chunk_beg = user_beg - kChunkHeaderSize;
451     AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
452     m->alloc_type = alloc_type;
453     m->rz_log = rz_log;
454     u32 alloc_tid = t ? t->tid() : 0;
455     m->alloc_tid = alloc_tid;
456     CHECK_EQ(alloc_tid, m->alloc_tid);  // Does alloc_tid fit into the bitfield?
457     m->free_tid = kInvalidTid;
458     m->from_memalign = user_beg != beg_plus_redzone;
459     if (alloc_beg != chunk_beg) {
460       CHECK_LE(alloc_beg+ 2 * sizeof(uptr), chunk_beg);
461       reinterpret_cast<uptr *>(alloc_beg)[0] = kAllocBegMagic;
462       reinterpret_cast<uptr *>(alloc_beg)[1] = chunk_beg;
463     }
464     if (using_primary_allocator) {
465       CHECK(size);
466       m->user_requested_size = size;
467       CHECK(allocator.FromPrimary(allocated));
468     } else {
469       CHECK(!allocator.FromPrimary(allocated));
470       m->user_requested_size = SizeClassMap::kMaxSize;
471       uptr *meta = reinterpret_cast<uptr *>(allocator.GetMetaData(allocated));
472       meta[0] = size;
473       meta[1] = chunk_beg;
474     }
475
476     m->alloc_context_id = StackDepotPut(*stack);
477
478     uptr size_rounded_down_to_granularity =
479         RoundDownTo(size, SHADOW_GRANULARITY);
480     // Unpoison the bulk of the memory region.
481     if (size_rounded_down_to_granularity)
482       PoisonShadow(user_beg, size_rounded_down_to_granularity, 0);
483     // Deal with the end of the region if size is not aligned to granularity.
484     if (size != size_rounded_down_to_granularity && CanPoisonMemory()) {
485       u8 *shadow =
486           (u8 *)MemToShadow(user_beg + size_rounded_down_to_granularity);
487       *shadow = fl.poison_partial ? (size & (SHADOW_GRANULARITY - 1)) : 0;
488     }
489
490     AsanStats &thread_stats = GetCurrentThreadStats();
491     thread_stats.mallocs++;
492     thread_stats.malloced += size;
493     thread_stats.malloced_redzones += needed_size - size;
494     if (needed_size > SizeClassMap::kMaxSize)
495       thread_stats.malloc_large++;
496     else
497       thread_stats.malloced_by_size[SizeClassMap::ClassID(needed_size)]++;
498
499     void *res = reinterpret_cast<void *>(user_beg);
500     if (can_fill && fl.max_malloc_fill_size) {
501       uptr fill_size = Min(size, (uptr)fl.max_malloc_fill_size);
502       REAL(memset)(res, fl.malloc_fill_byte, fill_size);
503     }
504 #if CAN_SANITIZE_LEAKS
505     m->lsan_tag = __lsan::DisabledInThisThread() ? __lsan::kIgnored
506                                                  : __lsan::kDirectlyLeaked;
507 #endif
508     // Must be the last mutation of metadata in this function.
509     atomic_store((atomic_uint8_t *)m, CHUNK_ALLOCATED, memory_order_release);
510     ASAN_MALLOC_HOOK(res, size);
511     return res;
512   }
513
514   // Set quarantine flag if chunk is allocated, issue ASan error report on
515   // available and quarantined chunks. Return true on success, false otherwise.
516   bool AtomicallySetQuarantineFlagIfAllocated(AsanChunk *m, void *ptr,
517                                    BufferedStackTrace *stack) {
518     u8 old_chunk_state = CHUNK_ALLOCATED;
519     // Flip the chunk_state atomically to avoid race on double-free.
520     if (!atomic_compare_exchange_strong((atomic_uint8_t *)m, &old_chunk_state,
521                                         CHUNK_QUARANTINE,
522                                         memory_order_acquire)) {
523       ReportInvalidFree(ptr, old_chunk_state, stack);
524       // It's not safe to push a chunk in quarantine on invalid free.
525       return false;
526     }
527     CHECK_EQ(CHUNK_ALLOCATED, old_chunk_state);
528     return true;
529   }
530
531   // Expects the chunk to already be marked as quarantined by using
532   // AtomicallySetQuarantineFlagIfAllocated.
533   void QuarantineChunk(AsanChunk *m, void *ptr, BufferedStackTrace *stack) {
534     CHECK_EQ(m->chunk_state, CHUNK_QUARANTINE);
535     CHECK_GE(m->alloc_tid, 0);
536     if (SANITIZER_WORDSIZE == 64)  // On 32-bits this resides in user area.
537       CHECK_EQ(m->free_tid, kInvalidTid);
538     AsanThread *t = GetCurrentThread();
539     m->free_tid = t ? t->tid() : 0;
540     m->free_context_id = StackDepotPut(*stack);
541
542     Flags &fl = *flags();
543     if (fl.max_free_fill_size > 0) {
544       // We have to skip the chunk header, it contains free_context_id.
545       uptr scribble_start = (uptr)m + kChunkHeaderSize + kChunkHeader2Size;
546       if (m->UsedSize() >= kChunkHeader2Size) {  // Skip Header2 in user area.
547         uptr size_to_fill = m->UsedSize() - kChunkHeader2Size;
548         size_to_fill = Min(size_to_fill, (uptr)fl.max_free_fill_size);
549         REAL(memset)((void *)scribble_start, fl.free_fill_byte, size_to_fill);
550       }
551     }
552
553     // Poison the region.
554     PoisonShadow(m->Beg(),
555                  RoundUpTo(m->UsedSize(), SHADOW_GRANULARITY),
556                  kAsanHeapFreeMagic);
557
558     AsanStats &thread_stats = GetCurrentThreadStats();
559     thread_stats.frees++;
560     thread_stats.freed += m->UsedSize();
561
562     // Push into quarantine.
563     if (t) {
564       AsanThreadLocalMallocStorage *ms = &t->malloc_storage();
565       AllocatorCache *ac = GetAllocatorCache(ms);
566       quarantine.Put(GetQuarantineCache(ms), QuarantineCallback(ac), m,
567                            m->UsedSize());
568     } else {
569       SpinMutexLock l(&fallback_mutex);
570       AllocatorCache *ac = &fallback_allocator_cache;
571       quarantine.Put(&fallback_quarantine_cache, QuarantineCallback(ac), m,
572                            m->UsedSize());
573     }
574   }
575
576   void Deallocate(void *ptr, uptr delete_size, BufferedStackTrace *stack,
577                   AllocType alloc_type) {
578     uptr p = reinterpret_cast<uptr>(ptr);
579     if (p == 0) return;
580
581     uptr chunk_beg = p - kChunkHeaderSize;
582     AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
583
584     // On Windows, uninstrumented DLLs may allocate memory before ASan hooks
585     // malloc. Don't report an invalid free in this case.
586     if (SANITIZER_WINDOWS &&
587         !get_allocator().PointerIsMine(ptr)) {
588       if (!IsSystemHeapAddress(p))
589         ReportFreeNotMalloced(p, stack);
590       return;
591     }
592
593     ASAN_FREE_HOOK(ptr);
594
595     // Must mark the chunk as quarantined before any changes to its metadata.
596     // Do not quarantine given chunk if we failed to set CHUNK_QUARANTINE flag.
597     if (!AtomicallySetQuarantineFlagIfAllocated(m, ptr, stack)) return;
598
599     if (m->alloc_type != alloc_type) {
600       if (atomic_load(&alloc_dealloc_mismatch, memory_order_acquire)) {
601         ReportAllocTypeMismatch((uptr)ptr, stack, (AllocType)m->alloc_type,
602                                 (AllocType)alloc_type);
603       }
604     }
605
606     if (delete_size && flags()->new_delete_type_mismatch &&
607         delete_size != m->UsedSize()) {
608       ReportNewDeleteSizeMismatch(p, delete_size, stack);
609     }
610
611     QuarantineChunk(m, ptr, stack);
612   }
613
614   void *Reallocate(void *old_ptr, uptr new_size, BufferedStackTrace *stack) {
615     CHECK(old_ptr && new_size);
616     uptr p = reinterpret_cast<uptr>(old_ptr);
617     uptr chunk_beg = p - kChunkHeaderSize;
618     AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
619
620     AsanStats &thread_stats = GetCurrentThreadStats();
621     thread_stats.reallocs++;
622     thread_stats.realloced += new_size;
623
624     void *new_ptr = Allocate(new_size, 8, stack, FROM_MALLOC, true);
625     if (new_ptr) {
626       u8 chunk_state = m->chunk_state;
627       if (chunk_state != CHUNK_ALLOCATED)
628         ReportInvalidFree(old_ptr, chunk_state, stack);
629       CHECK_NE(REAL(memcpy), nullptr);
630       uptr memcpy_size = Min(new_size, m->UsedSize());
631       // If realloc() races with free(), we may start copying freed memory.
632       // However, we will report racy double-free later anyway.
633       REAL(memcpy)(new_ptr, old_ptr, memcpy_size);
634       Deallocate(old_ptr, 0, stack, FROM_MALLOC);
635     }
636     return new_ptr;
637   }
638
639   void *Calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) {
640     if (CheckForCallocOverflow(size, nmemb))
641       return AsanAllocator::FailureHandler::OnBadRequest();
642     void *ptr = Allocate(nmemb * size, 8, stack, FROM_MALLOC, false);
643     // If the memory comes from the secondary allocator no need to clear it
644     // as it comes directly from mmap.
645     if (ptr && allocator.FromPrimary(ptr))
646       REAL(memset)(ptr, 0, nmemb * size);
647     return ptr;
648   }
649
650   void ReportInvalidFree(void *ptr, u8 chunk_state, BufferedStackTrace *stack) {
651     if (chunk_state == CHUNK_QUARANTINE)
652       ReportDoubleFree((uptr)ptr, stack);
653     else
654       ReportFreeNotMalloced((uptr)ptr, stack);
655   }
656
657   void CommitBack(AsanThreadLocalMallocStorage *ms) {
658     AllocatorCache *ac = GetAllocatorCache(ms);
659     quarantine.Drain(GetQuarantineCache(ms), QuarantineCallback(ac));
660     allocator.SwallowCache(ac);
661   }
662
663   // -------------------------- Chunk lookup ----------------------
664
665   // Assumes alloc_beg == allocator.GetBlockBegin(alloc_beg).
666   AsanChunk *GetAsanChunk(void *alloc_beg) {
667     if (!alloc_beg) return nullptr;
668     if (!allocator.FromPrimary(alloc_beg)) {
669       uptr *meta = reinterpret_cast<uptr *>(allocator.GetMetaData(alloc_beg));
670       AsanChunk *m = reinterpret_cast<AsanChunk *>(meta[1]);
671       return m;
672     }
673     uptr *alloc_magic = reinterpret_cast<uptr *>(alloc_beg);
674     if (alloc_magic[0] == kAllocBegMagic)
675       return reinterpret_cast<AsanChunk *>(alloc_magic[1]);
676     return reinterpret_cast<AsanChunk *>(alloc_beg);
677   }
678
679   AsanChunk *GetAsanChunkByAddr(uptr p) {
680     void *alloc_beg = allocator.GetBlockBegin(reinterpret_cast<void *>(p));
681     return GetAsanChunk(alloc_beg);
682   }
683
684   // Allocator must be locked when this function is called.
685   AsanChunk *GetAsanChunkByAddrFastLocked(uptr p) {
686     void *alloc_beg =
687         allocator.GetBlockBeginFastLocked(reinterpret_cast<void *>(p));
688     return GetAsanChunk(alloc_beg);
689   }
690
691   uptr AllocationSize(uptr p) {
692     AsanChunk *m = GetAsanChunkByAddr(p);
693     if (!m) return 0;
694     if (m->chunk_state != CHUNK_ALLOCATED) return 0;
695     if (m->Beg() != p) return 0;
696     return m->UsedSize();
697   }
698
699   AsanChunkView FindHeapChunkByAddress(uptr addr) {
700     AsanChunk *m1 = GetAsanChunkByAddr(addr);
701     if (!m1) return AsanChunkView(m1);
702     sptr offset = 0;
703     if (AsanChunkView(m1).AddrIsAtLeft(addr, 1, &offset)) {
704       // The address is in the chunk's left redzone, so maybe it is actually
705       // a right buffer overflow from the other chunk to the left.
706       // Search a bit to the left to see if there is another chunk.
707       AsanChunk *m2 = nullptr;
708       for (uptr l = 1; l < GetPageSizeCached(); l++) {
709         m2 = GetAsanChunkByAddr(addr - l);
710         if (m2 == m1) continue;  // Still the same chunk.
711         break;
712       }
713       if (m2 && AsanChunkView(m2).AddrIsAtRight(addr, 1, &offset))
714         m1 = ChooseChunk(addr, m2, m1);
715     }
716     return AsanChunkView(m1);
717   }
718
719   void PrintStats() {
720     allocator.PrintStats();
721     quarantine.PrintStats();
722   }
723
724   void ForceLock() {
725     allocator.ForceLock();
726     fallback_mutex.Lock();
727   }
728
729   void ForceUnlock() {
730     fallback_mutex.Unlock();
731     allocator.ForceUnlock();
732   }
733 };
734
735 static Allocator instance(LINKER_INITIALIZED);
736
737 static AsanAllocator &get_allocator() {
738   return instance.allocator;
739 }
740
741 bool AsanChunkView::IsValid() const {
742   return chunk_ && chunk_->chunk_state != CHUNK_AVAILABLE;
743 }
744 bool AsanChunkView::IsAllocated() const {
745   return chunk_ && chunk_->chunk_state == CHUNK_ALLOCATED;
746 }
747 bool AsanChunkView::IsQuarantined() const {
748   return chunk_ && chunk_->chunk_state == CHUNK_QUARANTINE;
749 }
750 uptr AsanChunkView::Beg() const { return chunk_->Beg(); }
751 uptr AsanChunkView::End() const { return Beg() + UsedSize(); }
752 uptr AsanChunkView::UsedSize() const { return chunk_->UsedSize(); }
753 uptr AsanChunkView::AllocTid() const { return chunk_->alloc_tid; }
754 uptr AsanChunkView::FreeTid() const { return chunk_->free_tid; }
755 AllocType AsanChunkView::GetAllocType() const {
756   return (AllocType)chunk_->alloc_type;
757 }
758
759 static StackTrace GetStackTraceFromId(u32 id) {
760   CHECK(id);
761   StackTrace res = StackDepotGet(id);
762   CHECK(res.trace);
763   return res;
764 }
765
766 u32 AsanChunkView::GetAllocStackId() const { return chunk_->alloc_context_id; }
767 u32 AsanChunkView::GetFreeStackId() const { return chunk_->free_context_id; }
768
769 StackTrace AsanChunkView::GetAllocStack() const {
770   return GetStackTraceFromId(GetAllocStackId());
771 }
772
773 StackTrace AsanChunkView::GetFreeStack() const {
774   return GetStackTraceFromId(GetFreeStackId());
775 }
776
777 void InitializeAllocator(const AllocatorOptions &options) {
778   instance.Initialize(options);
779 }
780
781 void ReInitializeAllocator(const AllocatorOptions &options) {
782   instance.ReInitialize(options);
783 }
784
785 void GetAllocatorOptions(AllocatorOptions *options) {
786   instance.GetOptions(options);
787 }
788
789 AsanChunkView FindHeapChunkByAddress(uptr addr) {
790   return instance.FindHeapChunkByAddress(addr);
791 }
792 AsanChunkView FindHeapChunkByAllocBeg(uptr addr) {
793   return AsanChunkView(instance.GetAsanChunk(reinterpret_cast<void*>(addr)));
794 }
795
796 void AsanThreadLocalMallocStorage::CommitBack() {
797   instance.CommitBack(this);
798 }
799
800 void PrintInternalAllocatorStats() {
801   instance.PrintStats();
802 }
803
804 void asan_free(void *ptr, BufferedStackTrace *stack, AllocType alloc_type) {
805   instance.Deallocate(ptr, 0, stack, alloc_type);
806 }
807
808 void asan_sized_free(void *ptr, uptr size, BufferedStackTrace *stack,
809                      AllocType alloc_type) {
810   instance.Deallocate(ptr, size, stack, alloc_type);
811 }
812
813 void *asan_malloc(uptr size, BufferedStackTrace *stack) {
814   return SetErrnoOnNull(instance.Allocate(size, 8, stack, FROM_MALLOC, true));
815 }
816
817 void *asan_calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) {
818   return SetErrnoOnNull(instance.Calloc(nmemb, size, stack));
819 }
820
821 void *asan_realloc(void *p, uptr size, BufferedStackTrace *stack) {
822   if (!p)
823     return SetErrnoOnNull(instance.Allocate(size, 8, stack, FROM_MALLOC, true));
824   if (size == 0) {
825     if (flags()->allocator_frees_and_returns_null_on_realloc_zero) {
826       instance.Deallocate(p, 0, stack, FROM_MALLOC);
827       return nullptr;
828     }
829     // Allocate a size of 1 if we shouldn't free() on Realloc to 0
830     size = 1;
831   }
832   return SetErrnoOnNull(instance.Reallocate(p, size, stack));
833 }
834
835 void *asan_valloc(uptr size, BufferedStackTrace *stack) {
836   return SetErrnoOnNull(
837       instance.Allocate(size, GetPageSizeCached(), stack, FROM_MALLOC, true));
838 }
839
840 void *asan_pvalloc(uptr size, BufferedStackTrace *stack) {
841   uptr PageSize = GetPageSizeCached();
842   // pvalloc(0) should allocate one page.
843   size = size ? RoundUpTo(size, PageSize) : PageSize;
844   return SetErrnoOnNull(
845       instance.Allocate(size, PageSize, stack, FROM_MALLOC, true));
846 }
847
848 void *asan_memalign(uptr alignment, uptr size, BufferedStackTrace *stack,
849                     AllocType alloc_type) {
850   if (UNLIKELY(!IsPowerOfTwo(alignment))) {
851     errno = errno_EINVAL;
852     return AsanAllocator::FailureHandler::OnBadRequest();
853   }
854   return SetErrnoOnNull(
855       instance.Allocate(size, alignment, stack, alloc_type, true));
856 }
857
858 int asan_posix_memalign(void **memptr, uptr alignment, uptr size,
859                         BufferedStackTrace *stack) {
860   if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) {
861     AsanAllocator::FailureHandler::OnBadRequest();
862     return errno_EINVAL;
863   }
864   void *ptr = instance.Allocate(size, alignment, stack, FROM_MALLOC, true);
865   if (UNLIKELY(!ptr))
866     return errno_ENOMEM;
867   CHECK(IsAligned((uptr)ptr, alignment));
868   *memptr = ptr;
869   return 0;
870 }
871
872 uptr asan_malloc_usable_size(const void *ptr, uptr pc, uptr bp) {
873   if (!ptr) return 0;
874   uptr usable_size = instance.AllocationSize(reinterpret_cast<uptr>(ptr));
875   if (flags()->check_malloc_usable_size && (usable_size == 0)) {
876     GET_STACK_TRACE_FATAL(pc, bp);
877     ReportMallocUsableSizeNotOwned((uptr)ptr, &stack);
878   }
879   return usable_size;
880 }
881
882 uptr asan_mz_size(const void *ptr) {
883   return instance.AllocationSize(reinterpret_cast<uptr>(ptr));
884 }
885
886 void asan_mz_force_lock() {
887   instance.ForceLock();
888 }
889
890 void asan_mz_force_unlock() {
891   instance.ForceUnlock();
892 }
893
894 void AsanSoftRssLimitExceededCallback(bool limit_exceeded) {
895   instance.SetRssLimitExceeded(limit_exceeded);
896 }
897
898 } // namespace __asan
899
900 // --- Implementation of LSan-specific functions --- {{{1
901 namespace __lsan {
902 void LockAllocator() {
903   __asan::get_allocator().ForceLock();
904 }
905
906 void UnlockAllocator() {
907   __asan::get_allocator().ForceUnlock();
908 }
909
910 void GetAllocatorGlobalRange(uptr *begin, uptr *end) {
911   *begin = (uptr)&__asan::get_allocator();
912   *end = *begin + sizeof(__asan::get_allocator());
913 }
914
915 uptr PointsIntoChunk(void* p) {
916   uptr addr = reinterpret_cast<uptr>(p);
917   __asan::AsanChunk *m = __asan::instance.GetAsanChunkByAddrFastLocked(addr);
918   if (!m) return 0;
919   uptr chunk = m->Beg();
920   if (m->chunk_state != __asan::CHUNK_ALLOCATED)
921     return 0;
922   if (m->AddrIsInside(addr, /*locked_version=*/true))
923     return chunk;
924   if (IsSpecialCaseOfOperatorNew0(chunk, m->UsedSize(/*locked_version*/ true),
925                                   addr))
926     return chunk;
927   return 0;
928 }
929
930 uptr GetUserBegin(uptr chunk) {
931   __asan::AsanChunk *m = __asan::instance.GetAsanChunkByAddrFastLocked(chunk);
932   CHECK(m);
933   return m->Beg();
934 }
935
936 LsanMetadata::LsanMetadata(uptr chunk) {
937   metadata_ = reinterpret_cast<void *>(chunk - __asan::kChunkHeaderSize);
938 }
939
940 bool LsanMetadata::allocated() const {
941   __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
942   return m->chunk_state == __asan::CHUNK_ALLOCATED;
943 }
944
945 ChunkTag LsanMetadata::tag() const {
946   __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
947   return static_cast<ChunkTag>(m->lsan_tag);
948 }
949
950 void LsanMetadata::set_tag(ChunkTag value) {
951   __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
952   m->lsan_tag = value;
953 }
954
955 uptr LsanMetadata::requested_size() const {
956   __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
957   return m->UsedSize(/*locked_version=*/true);
958 }
959
960 u32 LsanMetadata::stack_trace_id() const {
961   __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
962   return m->alloc_context_id;
963 }
964
965 void ForEachChunk(ForEachChunkCallback callback, void *arg) {
966   __asan::get_allocator().ForEachChunk(callback, arg);
967 }
968
969 IgnoreObjectResult IgnoreObjectLocked(const void *p) {
970   uptr addr = reinterpret_cast<uptr>(p);
971   __asan::AsanChunk *m = __asan::instance.GetAsanChunkByAddr(addr);
972   if (!m) return kIgnoreObjectInvalid;
973   if ((m->chunk_state == __asan::CHUNK_ALLOCATED) && m->AddrIsInside(addr)) {
974     if (m->lsan_tag == kIgnored)
975       return kIgnoreObjectAlreadyIgnored;
976     m->lsan_tag = __lsan::kIgnored;
977     return kIgnoreObjectSuccess;
978   } else {
979     return kIgnoreObjectInvalid;
980   }
981 }
982 }  // namespace __lsan
983
984 // ---------------------- Interface ---------------- {{{1
985 using namespace __asan;  // NOLINT
986
987 // ASan allocator doesn't reserve extra bytes, so normally we would
988 // just return "size". We don't want to expose our redzone sizes, etc here.
989 uptr __sanitizer_get_estimated_allocated_size(uptr size) {
990   return size;
991 }
992
993 int __sanitizer_get_ownership(const void *p) {
994   uptr ptr = reinterpret_cast<uptr>(p);
995   return instance.AllocationSize(ptr) > 0;
996 }
997
998 uptr __sanitizer_get_allocated_size(const void *p) {
999   if (!p) return 0;
1000   uptr ptr = reinterpret_cast<uptr>(p);
1001   uptr allocated_size = instance.AllocationSize(ptr);
1002   // Die if p is not malloced or if it is already freed.
1003   if (allocated_size == 0) {
1004     GET_STACK_TRACE_FATAL_HERE;
1005     ReportSanitizerGetAllocatedSizeNotOwned(ptr, &stack);
1006   }
1007   return allocated_size;
1008 }
1009
1010 #if !SANITIZER_SUPPORTS_WEAK_HOOKS
1011 // Provide default (no-op) implementation of malloc hooks.
1012 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_malloc_hook,
1013                              void *ptr, uptr size) {
1014   (void)ptr;
1015   (void)size;
1016 }
1017
1018 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_free_hook, void *ptr) {
1019   (void)ptr;
1020 }
1021 #endif