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