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