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