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