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