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
19#include "asan_internal.h"
20#include "asan_mapping.h"
21#include "asan_poisoning.h"
22#include "asan_report.h"
23#include "asan_stack.h"
24#include "asan_suppressions.h"
25#include "asan_thread.h"
26#include "lsan/lsan_common.h"
27#include "sanitizer_common/sanitizer_allocator_checks.h"
28#include "sanitizer_common/sanitizer_allocator_interface.h"
29#include "sanitizer_common/sanitizer_common.h"
30#include "sanitizer_common/sanitizer_errno.h"
31#include "sanitizer_common/sanitizer_flags.h"
32#include "sanitizer_common/sanitizer_internal_defs.h"
33#include "sanitizer_common/sanitizer_list.h"
34#include "sanitizer_common/sanitizer_quarantine.h"
35#include "sanitizer_common/sanitizer_stackdepot.h"
36
37namespace __asan {
38
39// Valid redzone sizes are 16, 32, 64, ... 2048, so we encode them in 3 bits.
40// We use adaptive redzones: for larger allocation larger redzones are used.
41static u32 RZLog2Size(u32 rz_log) {
42 CHECK_LT(rz_log, 8);
43 return 16 << rz_log;
44}
45
46static u32 RZSize2Log(u32 rz_size) {
47 CHECK_GE(rz_size, 16);
48 CHECK_LE(rz_size, 2048);
49 CHECK(IsPowerOfTwo(rz_size));
50 u32 res = Log2(x: rz_size) - 4;
51 CHECK_EQ(rz_size, RZLog2Size(res));
52 return res;
53}
54
55static AsanAllocator &get_allocator();
56
57static void AtomicContextStore(volatile atomic_uint64_t *atomic_context,
58 u32 tid, u32 stack) {
59 u64 context = tid;
60 context <<= 32;
61 context += stack;
62 atomic_store(a: atomic_context, v: context, mo: memory_order_relaxed);
63}
64
65static void AtomicContextLoad(const volatile atomic_uint64_t *atomic_context,
66 u32 &tid, u32 &stack) {
67 u64 context = atomic_load(a: atomic_context, mo: memory_order_relaxed);
68 stack = context;
69 context >>= 32;
70 tid = context;
71}
72
73// The memory chunk allocated from the underlying allocator looks like this:
74// L L L L L L H H U U U U U U R R
75// L -- left redzone words (0 or more bytes)
76// H -- ChunkHeader (16 bytes), which is also a part of the left redzone.
77// U -- user memory.
78// R -- right redzone (0 or more bytes)
79// ChunkBase consists of ChunkHeader and other bytes that overlap with user
80// memory.
81
82// If the left redzone is greater than the ChunkHeader size we store a magic
83// value in the first uptr word of the memory block and store the address of
84// ChunkBase in the next uptr.
85// M B L L L L L L L L L H H U U U U U U
86// | ^
87// ---------------------|
88// M -- magic value kAllocBegMagic
89// B -- address of ChunkHeader pointing to the first 'H'
90
91class ChunkHeader {
92 public:
93 atomic_uint8_t chunk_state;
94 u8 alloc_type : 2;
95 u8 lsan_tag : 2;
96#if SANITIZER_WINDOWS
97 // True if this was a zero-size allocation upgraded to size 1.
98 // Used to report the original size (0) to the user via HeapSize/RtlSizeHeap.
99 u8 from_zero_alloc : 1;
100#endif
101
102 // align < 8 -> 0
103 // else -> log2(min(align, 512)) - 2
104 u8 user_requested_alignment_log : 3;
105
106 private:
107 u16 user_requested_size_hi;
108 u32 user_requested_size_lo;
109 atomic_uint64_t alloc_context_id;
110
111 public:
112 uptr UsedSize() const {
113 static_assert(sizeof(user_requested_size_lo) == 4,
114 "Expression below requires this");
115 return FIRST_32_SECOND_64(0, ((uptr)user_requested_size_hi << 32)) +
116 user_requested_size_lo;
117 }
118
119 void SetUsedSize(uptr size) {
120 user_requested_size_lo = size;
121 static_assert(sizeof(user_requested_size_lo) == 4,
122 "Expression below requires this");
123 user_requested_size_hi = FIRST_32_SECOND_64(0, size >> 32);
124 CHECK_EQ(UsedSize(), size);
125 }
126
127 void SetAllocContext(u32 tid, u32 stack) {
128 AtomicContextStore(atomic_context: &alloc_context_id, tid, stack);
129 }
130
131 void GetAllocContext(u32 &tid, u32 &stack) const {
132 AtomicContextLoad(atomic_context: &alloc_context_id, tid, stack);
133 }
134};
135
136class ChunkBase : public ChunkHeader {
137 atomic_uint64_t free_context_id;
138
139 public:
140 void SetFreeContext(u32 tid, u32 stack) {
141 AtomicContextStore(atomic_context: &free_context_id, tid, stack);
142 }
143
144 void GetFreeContext(u32 &tid, u32 &stack) const {
145 AtomicContextLoad(atomic_context: &free_context_id, tid, stack);
146 }
147};
148
149static const uptr kChunkHeaderSize = sizeof(ChunkHeader);
150static const uptr kChunkHeader2Size = sizeof(ChunkBase) - kChunkHeaderSize;
151COMPILER_CHECK(kChunkHeaderSize == 16);
152COMPILER_CHECK(kChunkHeader2Size <= 16);
153
154enum {
155 // Either just allocated by underlying allocator, but AsanChunk is not yet
156 // ready, or almost returned to undelying allocator and AsanChunk is already
157 // meaningless.
158 CHUNK_INVALID = 0,
159 // The chunk is allocated and not yet freed.
160 CHUNK_ALLOCATED = 2,
161 // The chunk was freed and put into quarantine zone.
162 CHUNK_QUARANTINE = 3,
163};
164
165class AsanChunk : public ChunkBase {
166 public:
167 uptr Beg() { return reinterpret_cast<uptr>(this) + kChunkHeaderSize; }
168 bool AddrIsInside(uptr addr) {
169 return (addr >= Beg()) && (addr < Beg() + UsedSize());
170 }
171};
172
173class LargeChunkHeader {
174 static constexpr uptr kAllocBegMagic =
175 FIRST_32_SECOND_64(0xCC6E96B9, 0xCC6E96B9CC6E96B9ULL);
176 atomic_uintptr_t magic;
177 AsanChunk *chunk_header;
178
179 public:
180 AsanChunk *Get() const {
181 return atomic_load(a: &magic, mo: memory_order_acquire) == kAllocBegMagic
182 ? chunk_header
183 : nullptr;
184 }
185
186 void Set(AsanChunk *p) {
187 if (p) {
188 chunk_header = p;
189 atomic_store(a: &magic, v: kAllocBegMagic, mo: memory_order_release);
190 return;
191 }
192
193 uptr old = kAllocBegMagic;
194 if (!atomic_compare_exchange_strong(a: &magic, cmp: &old, xchg: 0,
195 mo: memory_order_release)) {
196 CHECK_EQ(old, kAllocBegMagic);
197 }
198 }
199};
200
201static void FillChunk(AsanChunk *m) {
202 // FIXME: Use ReleaseMemoryPagesToOS.
203 Flags &fl = *flags();
204
205 if (fl.max_free_fill_size > 0) {
206 // We have to skip the chunk header, it contains free_context_id.
207 uptr scribble_start = (uptr)m + kChunkHeaderSize + kChunkHeader2Size;
208 if (m->UsedSize() >= kChunkHeader2Size) { // Skip Header2 in user area.
209 uptr size_to_fill = m->UsedSize() - kChunkHeader2Size;
210 size_to_fill = Min(a: size_to_fill, b: (uptr)fl.max_free_fill_size);
211 REAL(memset)((void *)scribble_start, fl.free_fill_byte, size_to_fill);
212 }
213 }
214}
215
216struct QuarantineCallback {
217 QuarantineCallback(AllocatorCache *cache, BufferedStackTrace *stack)
218 : cache_(cache),
219 stack_(stack) {
220 }
221
222 void PreQuarantine(AsanChunk *m) const {
223 FillChunk(m);
224 // Poison the region.
225 PoisonShadow(addr: m->Beg(), size: RoundUpTo(size: m->UsedSize(), ASAN_SHADOW_GRANULARITY),
226 value: kAsanHeapFreeMagic);
227 }
228
229 void Recycle(AsanChunk *m) const {
230 void *p = get_allocator().GetBlockBegin(p: m);
231
232 // The secondary will immediately unpoison and unmap the memory, so this
233 // branch is unnecessary.
234 if (get_allocator().FromPrimary(p)) {
235 if (p != m) {
236 // Clear the magic value, as allocator internals may overwrite the
237 // contents of deallocated chunk, confusing GetAsanChunk lookup.
238 reinterpret_cast<LargeChunkHeader *>(p)->Set(nullptr);
239 }
240
241 u8 old_chunk_state = CHUNK_QUARANTINE;
242 if (!atomic_compare_exchange_strong(a: &m->chunk_state, cmp: &old_chunk_state,
243 xchg: CHUNK_INVALID,
244 mo: memory_order_acquire)) {
245 CHECK_EQ(old_chunk_state, CHUNK_QUARANTINE);
246 }
247
248 PoisonShadow(addr: m->Beg(), size: RoundUpTo(size: m->UsedSize(), ASAN_SHADOW_GRANULARITY),
249 value: kAsanHeapLeftRedzoneMagic);
250 }
251
252 // Statistics.
253 AsanStats &thread_stats = GetCurrentThreadStats();
254 thread_stats.real_frees++;
255 thread_stats.really_freed += m->UsedSize();
256
257 get_allocator().Deallocate(cache: cache_, p);
258 }
259
260 void RecyclePassThrough(AsanChunk *m) const {
261 // Recycle for the secondary will immediately unpoison and unmap the
262 // memory, so quarantine preparation is unnecessary.
263 if (get_allocator().FromPrimary(p: m)) {
264 // The primary allocation may need pattern fill if enabled.
265 FillChunk(m);
266 }
267 Recycle(m);
268 }
269
270 void *Allocate(uptr size) const {
271 void *res = get_allocator().Allocate(cache: cache_, size, alignment: 1);
272 // TODO(alekseys): Consider making quarantine OOM-friendly.
273 if (UNLIKELY(!res))
274 ReportOutOfMemory(requested_size: size, stack: stack_);
275 return res;
276 }
277
278 void Deallocate(void *p) const { get_allocator().Deallocate(cache: cache_, p); }
279
280 private:
281 AllocatorCache* const cache_;
282 BufferedStackTrace* const stack_;
283};
284
285typedef Quarantine<QuarantineCallback, AsanChunk> AsanQuarantine;
286typedef AsanQuarantine::Cache QuarantineCache;
287
288void AsanMapUnmapCallback::OnMap(uptr p, uptr size) const {
289 PoisonShadow(addr: p, size, value: kAsanHeapLeftRedzoneMagic);
290 // Statistics.
291 AsanStats &thread_stats = GetCurrentThreadStats();
292 thread_stats.mmaps++;
293 thread_stats.mmaped += size;
294}
295
296void AsanMapUnmapCallback::OnMapSecondary(uptr p, uptr size, uptr user_begin,
297 uptr user_size) const {
298 uptr user_end = RoundDownTo(x: user_begin + user_size, ASAN_SHADOW_GRANULARITY);
299 user_begin = RoundUpTo(size: user_begin, ASAN_SHADOW_GRANULARITY);
300 // The secondary mapping will be immediately returned to user, no value
301 // poisoning that with non-zero just before unpoisoning by Allocate(). So just
302 // poison head/tail invisible to Allocate().
303 PoisonShadow(addr: p, size: user_begin - p, value: kAsanHeapLeftRedzoneMagic);
304 PoisonShadow(addr: user_end, size: size - (user_end - p), value: kAsanHeapLeftRedzoneMagic);
305 // Statistics.
306 AsanStats &thread_stats = GetCurrentThreadStats();
307 thread_stats.mmaps++;
308 thread_stats.mmaped += size;
309}
310
311void AsanMapUnmapCallback::OnUnmap(uptr p, uptr size) const {
312 PoisonShadow(addr: p, size, value: 0);
313 // We are about to unmap a chunk of user memory.
314 // Mark the corresponding shadow memory as not needed.
315 FlushUnneededASanShadowMemory(p, size);
316 // Statistics.
317 AsanStats &thread_stats = GetCurrentThreadStats();
318 thread_stats.munmaps++;
319 thread_stats.munmaped += size;
320}
321
322// We can not use THREADLOCAL because it is not supported on some of the
323// platforms we care about (OSX 10.6, Android).
324// static THREADLOCAL AllocatorCache cache;
325AllocatorCache *GetAllocatorCache(AsanThreadLocalMallocStorage *ms) {
326 CHECK(ms);
327 return &ms->allocator_cache;
328}
329
330QuarantineCache *GetQuarantineCache(AsanThreadLocalMallocStorage *ms) {
331 CHECK(ms);
332 CHECK_LE(sizeof(QuarantineCache), sizeof(ms->quarantine_cache));
333 return reinterpret_cast<QuarantineCache *>(ms->quarantine_cache);
334}
335
336void AllocatorOptions::SetFrom(const Flags *f, const CommonFlags *cf) {
337 quarantine_size_mb = f->quarantine_size_mb;
338 thread_local_quarantine_size_kb = f->thread_local_quarantine_size_kb;
339 min_redzone = f->redzone;
340 max_redzone = f->max_redzone;
341 may_return_null = cf->allocator_may_return_null;
342 alloc_dealloc_mismatch = f->alloc_dealloc_mismatch;
343 release_to_os_interval_ms = cf->allocator_release_to_os_interval_ms;
344}
345
346void AllocatorOptions::CopyTo(Flags *f, CommonFlags *cf) {
347 f->quarantine_size_mb = quarantine_size_mb;
348 f->thread_local_quarantine_size_kb = thread_local_quarantine_size_kb;
349 f->redzone = min_redzone;
350 f->max_redzone = max_redzone;
351 cf->allocator_may_return_null = may_return_null;
352 f->alloc_dealloc_mismatch = alloc_dealloc_mismatch;
353 cf->allocator_release_to_os_interval_ms = release_to_os_interval_ms;
354}
355
356struct Allocator {
357 static const uptr kMaxAllowedMallocSize =
358 FIRST_32_SECOND_64(3UL << 30, 1ULL << 40);
359
360 AsanAllocator allocator;
361 AsanQuarantine quarantine;
362 StaticSpinMutex fallback_mutex;
363 AllocatorCache fallback_allocator_cache;
364 QuarantineCache fallback_quarantine_cache;
365
366 uptr max_user_defined_malloc_size;
367
368 // ------------------- Options --------------------------
369 atomic_uint16_t min_redzone;
370 atomic_uint16_t max_redzone;
371 atomic_uint8_t alloc_dealloc_mismatch;
372
373 // ------------------- Initialization ------------------------
374 explicit Allocator(LinkerInitialized)
375 : quarantine(LINKER_INITIALIZED),
376 fallback_quarantine_cache(LINKER_INITIALIZED) {}
377
378 void CheckOptions(const AllocatorOptions &options) const {
379 CHECK_GE(options.min_redzone, 16);
380 CHECK_GE(options.max_redzone, options.min_redzone);
381 CHECK_LE(options.max_redzone, 2048);
382 CHECK(IsPowerOfTwo(options.min_redzone));
383 CHECK(IsPowerOfTwo(options.max_redzone));
384 }
385
386 void SharedInitCode(const AllocatorOptions &options) {
387 CheckOptions(options);
388 quarantine.Init(size: (uptr)options.quarantine_size_mb << 20,
389 cache_size: (uptr)options.thread_local_quarantine_size_kb << 10);
390 atomic_store(a: &alloc_dealloc_mismatch, v: options.alloc_dealloc_mismatch,
391 mo: memory_order_release);
392 atomic_store(a: &min_redzone, v: options.min_redzone, mo: memory_order_release);
393 atomic_store(a: &max_redzone, v: options.max_redzone, mo: memory_order_release);
394 }
395
396 void InitLinkerInitialized(const AllocatorOptions &options) {
397 SetAllocatorMayReturnNull(options.may_return_null);
398 allocator.InitLinkerInitialized(release_to_os_interval_ms: options.release_to_os_interval_ms);
399 SharedInitCode(options);
400 max_user_defined_malloc_size = common_flags()->max_allocation_size_mb
401 ? common_flags()->max_allocation_size_mb
402 << 20
403 : kMaxAllowedMallocSize;
404 }
405
406 void RePoisonChunk(uptr chunk) {
407 // This could be a user-facing chunk (with redzones), or some internal
408 // housekeeping chunk, like TransferBatch. Start by assuming the former.
409 AsanChunk *ac = GetAsanChunk(alloc_beg: (void *)chunk);
410 uptr allocated_size = allocator.GetActuallyAllocatedSize(p: (void *)chunk);
411 if (ac && atomic_load(a: &ac->chunk_state, mo: memory_order_acquire) ==
412 CHUNK_ALLOCATED) {
413 uptr beg = ac->Beg();
414 uptr end = ac->Beg() + ac->UsedSize();
415 uptr chunk_end = chunk + allocated_size;
416 if (chunk < beg && beg < end && end <= chunk_end) {
417 // Looks like a valid AsanChunk in use, poison redzones only.
418 PoisonShadow(addr: chunk, size: beg - chunk, value: kAsanHeapLeftRedzoneMagic);
419 uptr end_aligned_down = RoundDownTo(x: end, ASAN_SHADOW_GRANULARITY);
420 FastPoisonShadowPartialRightRedzone(
421 aligned_addr: end_aligned_down, size: end - end_aligned_down,
422 redzone_size: chunk_end - end_aligned_down, value: kAsanHeapLeftRedzoneMagic);
423 return;
424 }
425 }
426
427 // This is either not an AsanChunk or freed or quarantined AsanChunk.
428 // In either case, poison everything.
429 PoisonShadow(addr: chunk, size: allocated_size, value: kAsanHeapLeftRedzoneMagic);
430 }
431
432 // Apply provided AllocatorOptions to an Allocator
433 void ApplyOptions(const AllocatorOptions &options) {
434 SetAllocatorMayReturnNull(options.may_return_null);
435 allocator.SetReleaseToOSIntervalMs(options.release_to_os_interval_ms);
436 SharedInitCode(options);
437 }
438
439 void ReInitialize(const AllocatorOptions &options) {
440 ApplyOptions(options);
441
442 // Poison all existing allocation's redzones.
443 if (CanPoisonMemory()) {
444 allocator.ForceLock();
445 allocator.ForEachChunk(
446 callback: [](uptr chunk, void *alloc) {
447 ((Allocator *)alloc)->RePoisonChunk(chunk);
448 },
449 arg: this);
450 allocator.ForceUnlock();
451 }
452 }
453
454 void GetOptions(AllocatorOptions *options) const {
455 options->quarantine_size_mb = quarantine.GetMaxSize() >> 20;
456 options->thread_local_quarantine_size_kb =
457 quarantine.GetMaxCacheSize() >> 10;
458 options->min_redzone = atomic_load(a: &min_redzone, mo: memory_order_acquire);
459 options->max_redzone = atomic_load(a: &max_redzone, mo: memory_order_acquire);
460 options->may_return_null = AllocatorMayReturnNull();
461 options->alloc_dealloc_mismatch =
462 atomic_load(a: &alloc_dealloc_mismatch, mo: memory_order_acquire);
463 options->release_to_os_interval_ms = allocator.ReleaseToOSIntervalMs();
464 }
465
466 // -------------------- Helper methods. -------------------------
467 uptr ComputeRZLog(uptr user_requested_size) {
468 u32 rz_log = user_requested_size <= 64 - 16 ? 0
469 : user_requested_size <= 128 - 32 ? 1
470 : user_requested_size <= 512 - 64 ? 2
471 : user_requested_size <= 4096 - 128 ? 3
472 : user_requested_size <= (1 << 14) - 256 ? 4
473 : user_requested_size <= (1 << 15) - 512 ? 5
474 : user_requested_size <= (1 << 16) - 1024 ? 6
475 : 7;
476 u32 hdr_log = RZSize2Log(rz_size: RoundUpToPowerOfTwo(size: sizeof(ChunkHeader)));
477 u32 min_log = RZSize2Log(rz_size: atomic_load(a: &min_redzone, mo: memory_order_acquire));
478 u32 max_log = RZSize2Log(rz_size: atomic_load(a: &max_redzone, mo: memory_order_acquire));
479 return Min(a: Max(a: rz_log, b: Max(a: min_log, b: hdr_log)), b: Max(a: max_log, b: hdr_log));
480 }
481
482 static uptr ComputeUserRequestedAlignmentLog(uptr user_requested_alignment) {
483 if (user_requested_alignment < 8)
484 return 0;
485 if (user_requested_alignment > 512)
486 user_requested_alignment = 512;
487 return Log2(x: user_requested_alignment) - 2;
488 }
489
490 static uptr ComputeUserAlignment(uptr user_requested_alignment_log) {
491 if (user_requested_alignment_log == 0)
492 return 0;
493 return 1LL << (user_requested_alignment_log + 2);
494 }
495
496 // We have an address between two chunks, and we want to report just one.
497 AsanChunk *ChooseChunk(uptr addr, AsanChunk *left_chunk,
498 AsanChunk *right_chunk) {
499 if (!left_chunk)
500 return right_chunk;
501 if (!right_chunk)
502 return left_chunk;
503 // Prefer an allocated chunk over freed chunk and freed chunk
504 // over available chunk.
505 u8 left_state = atomic_load(a: &left_chunk->chunk_state, mo: memory_order_relaxed);
506 u8 right_state =
507 atomic_load(a: &right_chunk->chunk_state, mo: memory_order_relaxed);
508 if (left_state != right_state) {
509 if (left_state == CHUNK_ALLOCATED)
510 return left_chunk;
511 if (right_state == CHUNK_ALLOCATED)
512 return right_chunk;
513 if (left_state == CHUNK_QUARANTINE)
514 return left_chunk;
515 if (right_state == CHUNK_QUARANTINE)
516 return right_chunk;
517 }
518 // Same chunk_state: choose based on offset.
519 sptr l_offset = 0, r_offset = 0;
520 CHECK(AsanChunkView(left_chunk).AddrIsAtRight(addr, 1, &l_offset));
521 CHECK(AsanChunkView(right_chunk).AddrIsAtLeft(addr, 1, &r_offset));
522 if (l_offset < r_offset)
523 return left_chunk;
524 return right_chunk;
525 }
526
527 bool UpdateAllocationStack(uptr addr, BufferedStackTrace *stack) {
528 AsanChunk *m = GetAsanChunkByAddr(p: addr);
529 if (!m) return false;
530 if (atomic_load(a: &m->chunk_state, mo: memory_order_acquire) != CHUNK_ALLOCATED)
531 return false;
532 if (m->Beg() != addr) return false;
533 AsanThread *t = GetCurrentThread();
534 m->SetAllocContext(tid: t ? t->tid() : kMainTid, stack: StackDepotPut(stack: *stack));
535 return true;
536 }
537
538 // -------------------- Allocation/Deallocation routines ---------------
539 void *Allocate(uptr size, uptr alignment, BufferedStackTrace *stack,
540 AllocType alloc_type, bool can_fill) {
541 if (UNLIKELY(!AsanInited()))
542 AsanInitFromRtl();
543 if (UNLIKELY(IsRssLimitExceeded())) {
544 if (AllocatorMayReturnNull())
545 return nullptr;
546 ReportRssLimitExceeded(stack);
547 }
548 Flags &fl = *flags();
549 CHECK(stack);
550 const uptr min_alignment = ASAN_SHADOW_GRANULARITY;
551 const uptr user_requested_alignment_log =
552 ComputeUserRequestedAlignmentLog(user_requested_alignment: alignment);
553 if (alignment < min_alignment)
554 alignment = min_alignment;
555 bool upgraded_from_zero = false;
556 if (size == 0) {
557 // We'd be happy to avoid allocating memory for zero-size requests, but
558 // some programs/tests depend on this behavior and assume that malloc
559 // would not return NULL even for zero-size allocations. Moreover, it
560 // looks like operator new should never return NULL, and results of
561 // consecutive "new" calls must be different even if the allocated size
562 // is zero.
563 size = 1;
564 upgraded_from_zero = true;
565 }
566 CHECK(IsPowerOfTwo(alignment));
567 uptr rz_log = ComputeRZLog(user_requested_size: size);
568 uptr rz_size = RZLog2Size(rz_log);
569 uptr rounded_size = RoundUpTo(size: Max(a: size, b: kChunkHeader2Size), boundary: alignment);
570 uptr needed_size = rounded_size + rz_size;
571 if (alignment > min_alignment)
572 needed_size += alignment;
573 bool from_primary = PrimaryAllocator::CanAllocate(size: needed_size, alignment);
574 // If we are allocating from the secondary allocator, there will be no
575 // automatic right redzone, so add the right redzone manually.
576 if (!from_primary)
577 needed_size += rz_size;
578 CHECK(IsAligned(needed_size, min_alignment));
579 if (size > kMaxAllowedMallocSize || needed_size > kMaxAllowedMallocSize ||
580 size > max_user_defined_malloc_size) {
581 if (AllocatorMayReturnNull()) {
582 Report(format: "WARNING: AddressSanitizer failed to allocate 0x%zx bytes\n",
583 size);
584 return nullptr;
585 }
586 uptr malloc_limit =
587 Min(a: kMaxAllowedMallocSize, b: max_user_defined_malloc_size);
588 ReportAllocationSizeTooBig(user_size: size, total_size: needed_size, max_size: malloc_limit, stack);
589 }
590
591 AsanThread *t = GetCurrentThread();
592 void *allocated;
593 if (t) {
594 AllocatorCache *cache = GetAllocatorCache(ms: &t->malloc_storage());
595 allocated = allocator.Allocate(cache, size: needed_size, alignment: 8);
596 } else {
597 SpinMutexLock l(&fallback_mutex);
598 AllocatorCache *cache = &fallback_allocator_cache;
599 allocated = allocator.Allocate(cache, size: needed_size, alignment: 8);
600 }
601 if (UNLIKELY(!allocated)) {
602 SetAllocatorOutOfMemory();
603 if (AllocatorMayReturnNull())
604 return nullptr;
605 ReportOutOfMemory(requested_size: size, stack);
606 }
607
608 uptr alloc_beg = reinterpret_cast<uptr>(allocated);
609 uptr alloc_end = alloc_beg + needed_size;
610 uptr user_beg = alloc_beg + rz_size;
611 if (!IsAligned(a: user_beg, alignment))
612 user_beg = RoundUpTo(size: user_beg, boundary: alignment);
613 uptr user_end = user_beg + size;
614 CHECK_LE(user_end, alloc_end);
615 uptr chunk_beg = user_beg - kChunkHeaderSize;
616 AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
617 m->alloc_type = alloc_type;
618#if SANITIZER_WINDOWS
619 m->from_zero_alloc = upgraded_from_zero;
620#endif
621 CHECK(size);
622 m->SetUsedSize(size);
623 m->user_requested_alignment_log = user_requested_alignment_log;
624
625 m->SetAllocContext(tid: t ? t->tid() : kMainTid, stack: StackDepotPut(stack: *stack));
626
627 if (!from_primary || *(u8 *)MEM_TO_SHADOW((uptr)allocated) == 0) {
628 // The allocator provides an unpoisoned chunk. This is possible for the
629 // secondary allocator, or if CanPoisonMemory() was false for some time,
630 // for example, due to flags()->start_disabled. Anyway, poison left and
631 // right of the block before using it for anything else.
632 uptr tail_beg = RoundUpTo(size: user_end, ASAN_SHADOW_GRANULARITY);
633 uptr tail_end = alloc_beg + allocator.GetActuallyAllocatedSize(p: allocated);
634 PoisonShadow(addr: alloc_beg, size: user_beg - alloc_beg, value: kAsanHeapLeftRedzoneMagic);
635 PoisonShadow(addr: tail_beg, size: tail_end - tail_beg, value: kAsanHeapLeftRedzoneMagic);
636 }
637
638 uptr size_rounded_down_to_granularity =
639 RoundDownTo(x: size, ASAN_SHADOW_GRANULARITY);
640 // Unpoison the bulk of the memory region.
641 if (size_rounded_down_to_granularity)
642 PoisonShadow(addr: user_beg, size: size_rounded_down_to_granularity, value: 0);
643 // Deal with the end of the region if size is not aligned to granularity.
644 if (size != size_rounded_down_to_granularity && CanPoisonMemory()) {
645 u8 *shadow =
646 (u8 *)MemToShadow(p: user_beg + size_rounded_down_to_granularity);
647 *shadow = fl.poison_partial ? (size & (ASAN_SHADOW_GRANULARITY - 1)) : 0;
648 }
649
650 if (upgraded_from_zero)
651 PoisonShadow(addr: user_beg, ASAN_SHADOW_GRANULARITY,
652 value: kAsanHeapLeftRedzoneMagic);
653
654 AsanStats &thread_stats = GetCurrentThreadStats();
655 thread_stats.mallocs++;
656 thread_stats.malloced += size;
657 thread_stats.malloced_redzones += needed_size - size;
658 if (needed_size > SizeClassMap::kMaxSize)
659 thread_stats.malloc_large++;
660 else
661 thread_stats.malloced_by_size[SizeClassMap::ClassID(size: needed_size)]++;
662
663 void *res = reinterpret_cast<void *>(user_beg);
664 if (can_fill && fl.max_malloc_fill_size) {
665 uptr fill_size = Min(a: size, b: (uptr)fl.max_malloc_fill_size);
666 REAL(memset)(res, fl.malloc_fill_byte, fill_size);
667 }
668#if CAN_SANITIZE_LEAKS
669 m->lsan_tag = __lsan::DisabledInThisThread() ? __lsan::kIgnored
670 : __lsan::kDirectlyLeaked;
671#endif
672 // Must be the last mutation of metadata in this function.
673 atomic_store(a: &m->chunk_state, v: CHUNK_ALLOCATED, mo: memory_order_release);
674 if (alloc_beg != chunk_beg) {
675 CHECK_LE(alloc_beg + sizeof(LargeChunkHeader), chunk_beg);
676 reinterpret_cast<LargeChunkHeader *>(alloc_beg)->Set(m);
677 }
678 RunMallocHooks(ptr: res, size);
679 return res;
680 }
681
682 // Set quarantine flag if chunk is allocated, issue ASan error report on
683 // available and quarantined chunks. Return true on success, false otherwise.
684 bool AtomicallySetQuarantineFlagIfAllocated(AsanChunk *m, void *ptr,
685 BufferedStackTrace *stack) {
686 u8 old_chunk_state = CHUNK_ALLOCATED;
687 // Flip the chunk_state atomically to avoid race on double-free.
688 if (!atomic_compare_exchange_strong(a: &m->chunk_state, cmp: &old_chunk_state,
689 xchg: CHUNK_QUARANTINE,
690 mo: memory_order_acquire)) {
691 ReportInvalidFree(ptr, chunk_state: old_chunk_state, stack);
692 // It's not safe to push a chunk in quarantine on invalid free.
693 return false;
694 }
695 CHECK_EQ(CHUNK_ALLOCATED, old_chunk_state);
696 // It was a user data.
697 m->SetFreeContext(tid: kInvalidTid, stack: 0);
698 return true;
699 }
700
701 // Expects the chunk to already be marked as quarantined by using
702 // AtomicallySetQuarantineFlagIfAllocated.
703 void QuarantineChunk(AsanChunk *m, void *ptr, BufferedStackTrace *stack) {
704 CHECK_EQ(atomic_load(&m->chunk_state, memory_order_relaxed),
705 CHUNK_QUARANTINE);
706 AsanThread *t = GetCurrentThread();
707 m->SetFreeContext(tid: t ? t->tid() : 0, stack: StackDepotPut(stack: *stack));
708
709 // Push into quarantine.
710 if (t) {
711 AsanThreadLocalMallocStorage *ms = &t->malloc_storage();
712 AllocatorCache *ac = GetAllocatorCache(ms);
713 quarantine.Put(c: GetQuarantineCache(ms), cb: QuarantineCallback(ac, stack), ptr: m,
714 size: m->UsedSize());
715 } else {
716 SpinMutexLock l(&fallback_mutex);
717 AllocatorCache *ac = &fallback_allocator_cache;
718 quarantine.Put(c: &fallback_quarantine_cache, cb: QuarantineCallback(ac, stack),
719 ptr: m, size: m->UsedSize());
720 }
721 }
722
723 void Deallocate(void *ptr, uptr delete_size, uptr delete_alignment,
724 BufferedStackTrace *stack, AllocType alloc_type) {
725 uptr p = reinterpret_cast<uptr>(ptr);
726 if (p == 0) return;
727
728 uptr chunk_beg = p - kChunkHeaderSize;
729 AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
730
731 // On Windows, uninstrumented DLLs may allocate memory before ASan hooks
732 // malloc. Don't report an invalid free in this case.
733 if (SANITIZER_WINDOWS &&
734 !get_allocator().PointerIsMine(p: ptr)) {
735 if (!IsSystemHeapAddress(addr: p))
736 ReportFreeNotMalloced(addr: p, free_stack: stack);
737 return;
738 }
739
740 if (RunFreeHooks(ptr)) {
741 // Someone used __sanitizer_ignore_free_hook() and decided that they
742 // didn't want the memory to __sanitizer_ignore_free_hook freed right now.
743 // When they call free() on this pointer again at a later time, we should
744 // ignore the alloc-type mismatch and allow them to deallocate the pointer
745 // through free(), rather than the initial alloc type.
746 m->alloc_type = FROM_MALLOC;
747 return;
748 }
749
750 // Must mark the chunk as quarantined before any changes to its metadata.
751 // Do not quarantine given chunk if we failed to set CHUNK_QUARANTINE flag.
752 if (!AtomicallySetQuarantineFlagIfAllocated(m, ptr, stack)) return;
753
754 if (m->alloc_type != alloc_type) {
755 if (atomic_load(a: &alloc_dealloc_mismatch, mo: memory_order_acquire) &&
756 !IsAllocDeallocMismatchSuppressed(stack)) {
757 ReportAllocTypeMismatch(addr: (uptr)ptr, free_stack: stack, alloc_type: (AllocType)m->alloc_type,
758 dealloc_type: (AllocType)alloc_type);
759 }
760 } else {
761 if (flags()->new_delete_type_mismatch &&
762 (alloc_type == FROM_NEW || alloc_type == FROM_NEW_BR) &&
763 ((delete_size && delete_size != m->UsedSize()) ||
764 ComputeUserRequestedAlignmentLog(user_requested_alignment: delete_alignment) !=
765 m->user_requested_alignment_log)) {
766 ReportNewDeleteTypeMismatch(addr: p, delete_size, delete_alignment, free_stack: stack);
767 }
768 }
769
770 AsanStats &thread_stats = GetCurrentThreadStats();
771 thread_stats.frees++;
772 thread_stats.freed += m->UsedSize();
773
774 QuarantineChunk(m, ptr, stack);
775 }
776
777 void *Reallocate(void *old_ptr, uptr new_size, BufferedStackTrace *stack) {
778 CHECK(old_ptr && new_size);
779 uptr p = reinterpret_cast<uptr>(old_ptr);
780 uptr chunk_beg = p - kChunkHeaderSize;
781 AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg);
782
783 AsanStats &thread_stats = GetCurrentThreadStats();
784 thread_stats.reallocs++;
785 thread_stats.realloced += new_size;
786
787 void *new_ptr = Allocate(size: new_size, alignment: 8, stack, alloc_type: FROM_MALLOC, can_fill: true);
788 if (new_ptr) {
789 u8 chunk_state = atomic_load(a: &m->chunk_state, mo: memory_order_acquire);
790 if (chunk_state != CHUNK_ALLOCATED)
791 ReportInvalidFree(ptr: old_ptr, chunk_state, stack);
792 CHECK_NE(REAL(memcpy), nullptr);
793 uptr memcpy_size = Min(a: new_size, b: m->UsedSize());
794 // If realloc() races with free(), we may start copying freed memory.
795 // However, we will report racy double-free later anyway.
796 REAL(memcpy)(new_ptr, old_ptr, memcpy_size);
797 Deallocate(ptr: old_ptr, delete_size: 0, delete_alignment: 0, stack, alloc_type: FROM_MALLOC);
798 }
799 return new_ptr;
800 }
801
802 void* Calloc(uptr nmemb, uptr size, BufferedStackTrace* stack,
803 uptr align = 8) {
804 if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
805 if (AllocatorMayReturnNull())
806 return nullptr;
807 ReportCallocOverflow(count: nmemb, size, stack);
808 }
809 void* ptr = Allocate(size: nmemb * size, alignment: align, stack, alloc_type: FROM_MALLOC, can_fill: false);
810 // If the memory comes from the secondary allocator no need to clear it
811 // as it comes directly from mmap.
812 if (ptr && allocator.FromPrimary(p: ptr))
813 REAL(memset)(ptr, 0, nmemb * size);
814 return ptr;
815 }
816
817 void ReportInvalidFree(void *ptr, u8 chunk_state, BufferedStackTrace *stack) {
818 if (chunk_state == CHUNK_QUARANTINE)
819 ReportDoubleFree(addr: (uptr)ptr, free_stack: stack);
820 else
821 ReportFreeNotMalloced(addr: (uptr)ptr, free_stack: stack);
822 }
823
824 void CommitBack(AsanThreadLocalMallocStorage *ms, BufferedStackTrace *stack) {
825 AllocatorCache *ac = GetAllocatorCache(ms);
826 quarantine.Drain(c: GetQuarantineCache(ms), cb: QuarantineCallback(ac, stack));
827 allocator.SwallowCache(cache: ac);
828 }
829
830 // -------------------------- Chunk lookup ----------------------
831
832 // Assumes alloc_beg == allocator.GetBlockBegin(alloc_beg).
833 // Returns nullptr if AsanChunk is not yet initialized just after
834 // get_allocator().Allocate(), or is being destroyed just before
835 // get_allocator().Deallocate().
836 AsanChunk *GetAsanChunk(void *alloc_beg) {
837 if (!alloc_beg)
838 return nullptr;
839 AsanChunk *p = reinterpret_cast<LargeChunkHeader *>(alloc_beg)->Get();
840 if (!p) {
841 if (!allocator.FromPrimary(p: alloc_beg))
842 return nullptr;
843 p = reinterpret_cast<AsanChunk *>(alloc_beg);
844 }
845 u8 state = atomic_load(a: &p->chunk_state, mo: memory_order_relaxed);
846 // It does not guaranty that Chunk is initialized, but it's
847 // definitely not for any other value.
848 if (state == CHUNK_ALLOCATED || state == CHUNK_QUARANTINE)
849 return p;
850 return nullptr;
851 }
852
853 AsanChunk *GetAsanChunkByAddr(uptr p) {
854 void *alloc_beg = allocator.GetBlockBegin(p: reinterpret_cast<void *>(p));
855 return GetAsanChunk(alloc_beg);
856 }
857
858 // Allocator must be locked when this function is called.
859 AsanChunk *GetAsanChunkByAddrFastLocked(uptr p) {
860 void *alloc_beg =
861 allocator.GetBlockBeginFastLocked(p: reinterpret_cast<void *>(p));
862 return GetAsanChunk(alloc_beg);
863 }
864
865 uptr AllocationSize(uptr p) {
866 AsanChunk *m = GetAsanChunkByAddr(p);
867 if (!m) return 0;
868 if (atomic_load(a: &m->chunk_state, mo: memory_order_acquire) != CHUNK_ALLOCATED)
869 return 0;
870 if (m->Beg() != p) return 0;
871 return m->UsedSize();
872 }
873
874#if SANITIZER_WINDOWS
875 // Returns true if the allocation at p was a zero-size request that was
876 // internally upgraded to size 1.
877 bool FromZeroAllocation(uptr p) {
878 return reinterpret_cast<AsanChunk*>(p - kChunkHeaderSize)->from_zero_alloc;
879 }
880
881 // Marks an existing size 1 allocation as having originally been zero-size.
882 // Used by SharedReAlloc which augments size 0 to 1 before calling
883 // asan_realloc, bypassing Allocate's own zero-size tracking.
884 void MarkAsZeroAllocation(uptr p) {
885 AsanChunk* m = reinterpret_cast<AsanChunk*>(p - kChunkHeaderSize);
886 m->from_zero_alloc = 1;
887 PoisonShadow(p, ASAN_SHADOW_GRANULARITY, kAsanHeapLeftRedzoneMagic);
888 }
889#endif
890
891 uptr AllocationSizeFast(uptr p) {
892 return reinterpret_cast<AsanChunk *>(p - kChunkHeaderSize)->UsedSize();
893 }
894
895 AsanChunkView FindHeapChunkByAddress(uptr addr) {
896 AsanChunk *m1 = GetAsanChunkByAddr(p: addr);
897 sptr offset = 0;
898 if (!m1 || AsanChunkView(m1).AddrIsAtLeft(addr, access_size: 1, offset: &offset)) {
899 // The address is in the chunk's left redzone, so maybe it is actually
900 // a right buffer overflow from the other chunk before.
901 // Search a bit before to see if there is another chunk.
902 AsanChunk *m2 = nullptr;
903 for (uptr l = 1; l < GetPageSizeCached(); l++) {
904 m2 = GetAsanChunkByAddr(p: addr - l);
905 if (m2 == m1) continue; // Still the same chunk.
906 break;
907 }
908 if (m2 && AsanChunkView(m2).AddrIsAtRight(addr, access_size: 1, offset: &offset))
909 m1 = ChooseChunk(addr, left_chunk: m2, right_chunk: m1);
910 }
911 return AsanChunkView(m1);
912 }
913
914 void Purge(BufferedStackTrace *stack) {
915 AsanThread *t = GetCurrentThread();
916 if (t) {
917 AsanThreadLocalMallocStorage *ms = &t->malloc_storage();
918 quarantine.DrainAndRecycle(c: GetQuarantineCache(ms),
919 cb: QuarantineCallback(GetAllocatorCache(ms),
920 stack));
921 }
922 {
923 SpinMutexLock l(&fallback_mutex);
924 quarantine.DrainAndRecycle(c: &fallback_quarantine_cache,
925 cb: QuarantineCallback(&fallback_allocator_cache,
926 stack));
927 }
928
929 allocator.ForceReleaseToOS();
930 }
931
932 void PrintStats() {
933 allocator.PrintStats();
934 quarantine.PrintStats();
935 }
936
937 void ForceLock() SANITIZER_ACQUIRE(fallback_mutex) {
938 allocator.ForceLock();
939 fallback_mutex.Lock();
940 }
941
942 void ForceUnlock() SANITIZER_RELEASE(fallback_mutex) {
943 fallback_mutex.Unlock();
944 allocator.ForceUnlock();
945 }
946};
947
948static Allocator instance(LINKER_INITIALIZED);
949
950static AsanAllocator &get_allocator() {
951 return instance.allocator;
952}
953
954bool AsanChunkView::IsValid() const {
955 return chunk_ && atomic_load(a: &chunk_->chunk_state, mo: memory_order_relaxed) !=
956 CHUNK_INVALID;
957}
958bool AsanChunkView::IsAllocated() const {
959 return chunk_ && atomic_load(a: &chunk_->chunk_state, mo: memory_order_relaxed) ==
960 CHUNK_ALLOCATED;
961}
962bool AsanChunkView::IsQuarantined() const {
963 return chunk_ && atomic_load(a: &chunk_->chunk_state, mo: memory_order_relaxed) ==
964 CHUNK_QUARANTINE;
965}
966uptr AsanChunkView::Beg() const { return chunk_->Beg(); }
967uptr AsanChunkView::End() const { return Beg() + UsedSize(); }
968uptr AsanChunkView::UsedSize() const { return chunk_->UsedSize(); }
969u32 AsanChunkView::UserRequestedAlignment() const {
970 return Allocator::ComputeUserAlignment(user_requested_alignment_log: chunk_->user_requested_alignment_log);
971}
972
973uptr AsanChunkView::AllocTid() const {
974 u32 tid = 0;
975 u32 stack = 0;
976 chunk_->GetAllocContext(tid, stack);
977 return tid;
978}
979
980uptr AsanChunkView::FreeTid() const {
981 if (!IsQuarantined())
982 return kInvalidTid;
983 u32 tid = 0;
984 u32 stack = 0;
985 chunk_->GetFreeContext(tid, stack);
986 return tid;
987}
988
989AllocType AsanChunkView::GetAllocType() const {
990 return (AllocType)chunk_->alloc_type;
991}
992
993u32 AsanChunkView::GetAllocStackId() const {
994 u32 tid = 0;
995 u32 stack = 0;
996 chunk_->GetAllocContext(tid, stack);
997 return stack;
998}
999
1000u32 AsanChunkView::GetFreeStackId() const {
1001 if (!IsQuarantined())
1002 return 0;
1003 u32 tid = 0;
1004 u32 stack = 0;
1005 chunk_->GetFreeContext(tid, stack);
1006 return stack;
1007}
1008
1009void InitializeAllocator(const AllocatorOptions &options) {
1010 instance.InitLinkerInitialized(options);
1011}
1012
1013void ReInitializeAllocator(const AllocatorOptions &options) {
1014 instance.ReInitialize(options);
1015}
1016
1017// Apply provided AllocatorOptions to an Allocator
1018void ApplyAllocatorOptions(const AllocatorOptions &options) {
1019 instance.ApplyOptions(options);
1020}
1021
1022void GetAllocatorOptions(AllocatorOptions *options) {
1023 instance.GetOptions(options);
1024}
1025
1026AsanChunkView FindHeapChunkByAddress(uptr addr) {
1027 return instance.FindHeapChunkByAddress(addr);
1028}
1029AsanChunkView FindHeapChunkByAllocBeg(uptr addr) {
1030 return AsanChunkView(instance.GetAsanChunk(alloc_beg: reinterpret_cast<void*>(addr)));
1031}
1032
1033void AsanThreadLocalMallocStorage::CommitBack() {
1034 GET_STACK_TRACE_MALLOC;
1035 instance.CommitBack(ms: this, stack: &stack);
1036}
1037
1038void PrintInternalAllocatorStats() {
1039 instance.PrintStats();
1040}
1041
1042void asan_free(void *ptr, BufferedStackTrace *stack) {
1043 instance.Deallocate(ptr, delete_size: 0, delete_alignment: 0, stack, alloc_type: FROM_MALLOC);
1044}
1045
1046void *asan_malloc(uptr size, BufferedStackTrace *stack) {
1047 return SetErrnoOnNull(instance.Allocate(size, alignment: 8, stack, alloc_type: FROM_MALLOC, can_fill: true));
1048}
1049
1050void *asan_calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) {
1051 return SetErrnoOnNull(instance.Calloc(nmemb, size, stack));
1052}
1053
1054#if SANITIZER_AIX
1055void* asan_vec_malloc(uptr size, BufferedStackTrace* stack) {
1056 return SetErrnoOnNull(instance.Allocate(size, 16, stack, FROM_MALLOC, true));
1057}
1058
1059void* asan_vec_calloc(uptr nmemb, uptr size, BufferedStackTrace* stack) {
1060 return SetErrnoOnNull(instance.Calloc(nmemb, size, stack, 16));
1061}
1062#endif
1063
1064void *asan_reallocarray(void *p, uptr nmemb, uptr size,
1065 BufferedStackTrace *stack) {
1066 if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
1067 errno = errno_ENOMEM;
1068 if (AllocatorMayReturnNull())
1069 return nullptr;
1070 ReportReallocArrayOverflow(count: nmemb, size, stack);
1071 }
1072 return asan_realloc(p, size: nmemb * size, stack);
1073}
1074
1075void *asan_realloc(void *p, uptr size, BufferedStackTrace *stack) {
1076 if (!p)
1077 return SetErrnoOnNull(instance.Allocate(size, alignment: 8, stack, alloc_type: FROM_MALLOC, can_fill: true));
1078 if (size == 0) {
1079 if (flags()->allocator_frees_and_returns_null_on_realloc_zero) {
1080 instance.Deallocate(ptr: p, delete_size: 0, delete_alignment: 0, stack, alloc_type: FROM_MALLOC);
1081 return nullptr;
1082 }
1083 // Allocate a size of 1 if we shouldn't free() on Realloc to 0
1084 size = 1;
1085 }
1086 return SetErrnoOnNull(instance.Reallocate(old_ptr: p, new_size: size, stack));
1087}
1088
1089void *asan_valloc(uptr size, BufferedStackTrace *stack) {
1090 return SetErrnoOnNull(
1091 instance.Allocate(size, alignment: GetPageSizeCached(), stack, alloc_type: FROM_MALLOC, can_fill: true));
1092}
1093
1094void *asan_pvalloc(uptr size, BufferedStackTrace *stack) {
1095 uptr PageSize = GetPageSizeCached();
1096 if (UNLIKELY(CheckForPvallocOverflow(size, PageSize))) {
1097 errno = errno_ENOMEM;
1098 if (AllocatorMayReturnNull())
1099 return nullptr;
1100 ReportPvallocOverflow(size, stack);
1101 }
1102 // pvalloc(0) should allocate one page.
1103 size = size ? RoundUpTo(size, boundary: PageSize) : PageSize;
1104 return SetErrnoOnNull(
1105 instance.Allocate(size, alignment: PageSize, stack, alloc_type: FROM_MALLOC, can_fill: true));
1106}
1107
1108void *asan_memalign(uptr alignment, uptr size, BufferedStackTrace *stack) {
1109 if (UNLIKELY(!IsPowerOfTwo(alignment))) {
1110 errno = errno_EINVAL;
1111 if (AllocatorMayReturnNull())
1112 return nullptr;
1113 ReportInvalidAllocationAlignment(alignment, stack);
1114 }
1115 return SetErrnoOnNull(
1116 instance.Allocate(size, alignment, stack, alloc_type: FROM_MALLOC, can_fill: true));
1117}
1118
1119void *asan_aligned_alloc(uptr alignment, uptr size, BufferedStackTrace *stack) {
1120 if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(alignment, size))) {
1121 errno = errno_EINVAL;
1122 if (AllocatorMayReturnNull())
1123 return nullptr;
1124 ReportInvalidAlignedAllocAlignment(size, alignment, stack);
1125 }
1126 return SetErrnoOnNull(
1127 instance.Allocate(size, alignment, stack, alloc_type: FROM_MALLOC, can_fill: true));
1128}
1129
1130int asan_posix_memalign(void **memptr, uptr alignment, uptr size,
1131 BufferedStackTrace *stack) {
1132 if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) {
1133 if (AllocatorMayReturnNull())
1134 return errno_EINVAL;
1135 ReportInvalidPosixMemalignAlignment(alignment, stack);
1136 }
1137 void *ptr = instance.Allocate(size, alignment, stack, alloc_type: FROM_MALLOC, can_fill: true);
1138 if (UNLIKELY(!ptr))
1139 // OOM error is already taken care of by Allocate.
1140 return errno_ENOMEM;
1141 CHECK(IsAligned((uptr)ptr, alignment));
1142 *memptr = ptr;
1143 return 0;
1144}
1145
1146uptr asan_malloc_usable_size(const void *ptr, uptr pc, uptr bp) {
1147 if (!ptr) return 0;
1148 uptr usable_size = instance.AllocationSize(p: reinterpret_cast<uptr>(ptr));
1149 if (flags()->check_malloc_usable_size && (usable_size == 0)) {
1150 GET_STACK_TRACE_FATAL(pc, bp);
1151 ReportMallocUsableSizeNotOwned(addr: (uptr)ptr, stack: &stack);
1152 }
1153#if SANITIZER_WINDOWS
1154 // Zero-size allocations are internally upgraded to size 1 so that
1155 // malloc(0)/new(0) return unique non-NULL pointers as required by the
1156 // standard. Windows heap APIs (HeapSize, RtlSizeHeap, _msize) should still
1157 // report the originally requested size (0).
1158 if (usable_size > 0 &&
1159 instance.FromZeroAllocation(reinterpret_cast<uptr>(ptr))) {
1160 DCHECK(usable_size == 1);
1161 return 0;
1162 }
1163#endif
1164 return usable_size;
1165}
1166
1167namespace {
1168
1169void *asan_new(uptr size, BufferedStackTrace *stack, bool array) {
1170 return SetErrnoOnNull(
1171 instance.Allocate(size, alignment: 0, stack, alloc_type: array ? FROM_NEW_BR : FROM_NEW, can_fill: true));
1172}
1173
1174void *asan_new_aligned(uptr size, uptr alignment, BufferedStackTrace *stack,
1175 bool array) {
1176 if (UNLIKELY(alignment == 0 || !IsPowerOfTwo(alignment))) {
1177 errno = errno_EINVAL;
1178 if (AllocatorMayReturnNull())
1179 return nullptr;
1180 ReportInvalidAllocationAlignment(alignment, stack);
1181 }
1182 return SetErrnoOnNull(instance.Allocate(
1183 size, alignment, stack, alloc_type: array ? FROM_NEW_BR : FROM_NEW, can_fill: true));
1184}
1185
1186void asan_delete(void *ptr, BufferedStackTrace *stack, bool array) {
1187 instance.Deallocate(ptr, delete_size: 0, delete_alignment: 0, stack, alloc_type: array ? FROM_NEW_BR : FROM_NEW);
1188}
1189
1190void asan_delete_aligned(void *ptr, uptr alignment, BufferedStackTrace *stack,
1191 bool array) {
1192 instance.Deallocate(ptr, delete_size: 0, delete_alignment: alignment, stack, alloc_type: array ? FROM_NEW_BR : FROM_NEW);
1193}
1194
1195void asan_delete_sized(void *ptr, uptr size, BufferedStackTrace *stack,
1196 bool array) {
1197 instance.Deallocate(ptr, delete_size: size, delete_alignment: 0, stack, alloc_type: array ? FROM_NEW_BR : FROM_NEW);
1198}
1199
1200void asan_delete_sized_aligned(void *ptr, uptr size, uptr alignment,
1201 BufferedStackTrace *stack, bool array) {
1202 instance.Deallocate(ptr, delete_size: size, delete_alignment: alignment, stack,
1203 alloc_type: array ? FROM_NEW_BR : FROM_NEW);
1204}
1205
1206} // namespace
1207
1208void *asan_new(uptr size, BufferedStackTrace *stack) {
1209 return asan_new(size, stack, /*array=*/false);
1210}
1211
1212void *asan_new_aligned(uptr size, uptr alignment, BufferedStackTrace *stack) {
1213 return asan_new_aligned(size, alignment, stack, /*array=*/false);
1214}
1215
1216void *asan_new_array(uptr size, BufferedStackTrace *stack) {
1217 return asan_new(size, stack, /*array=*/true);
1218}
1219
1220void *asan_new_array_aligned(uptr size, uptr alignment,
1221 BufferedStackTrace *stack) {
1222 return asan_new_aligned(size, alignment, stack, /*array=*/true);
1223}
1224
1225void asan_delete(void *ptr, BufferedStackTrace *stack) {
1226 asan_delete(ptr, stack, /*array=*/false);
1227}
1228
1229void asan_delete_aligned(void *ptr, uptr alignment, BufferedStackTrace *stack) {
1230 asan_delete_aligned(ptr, alignment, stack, /*array=*/false);
1231}
1232
1233void asan_delete_sized(void *ptr, uptr size, BufferedStackTrace *stack) {
1234 asan_delete_sized(ptr, size, stack, /*array=*/false);
1235}
1236
1237void asan_delete_sized_aligned(void *ptr, uptr size, uptr alignment,
1238 BufferedStackTrace *stack) {
1239 asan_delete_sized_aligned(ptr, size, alignment, stack, /*array=*/false);
1240}
1241
1242void asan_delete_array(void *ptr, BufferedStackTrace *stack) {
1243 asan_delete(ptr, stack, /*array=*/true);
1244}
1245
1246void asan_delete_array_aligned(void *ptr, uptr alignment,
1247 BufferedStackTrace *stack) {
1248 asan_delete_aligned(ptr, alignment, stack, /*array=*/true);
1249}
1250
1251void asan_delete_array_sized(void *ptr, uptr size, BufferedStackTrace *stack) {
1252 asan_delete_sized(ptr, size, stack, /*array=*/true);
1253}
1254
1255void asan_delete_array_sized_aligned(void *ptr, uptr size, uptr alignment,
1256 BufferedStackTrace *stack) {
1257 asan_delete_sized_aligned(ptr, size, alignment, stack, /*array=*/true);
1258}
1259
1260uptr asan_mz_size(const void* ptr) {
1261 uptr size = instance.AllocationSize(p: reinterpret_cast<uptr>(ptr));
1262
1263#if SANITIZER_WINDOWS
1264 if (size > 0 && instance.FromZeroAllocation(reinterpret_cast<uptr>(ptr))) {
1265 DCHECK(size == 1);
1266 return 0;
1267 }
1268#endif
1269
1270 return size;
1271}
1272
1273#if SANITIZER_WINDOWS
1274void asan_mark_zero_allocation(void* ptr) {
1275 instance.MarkAsZeroAllocation(reinterpret_cast<uptr>(ptr));
1276}
1277#endif
1278
1279void asan_mz_force_lock() SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
1280 instance.ForceLock();
1281}
1282
1283void asan_mz_force_unlock() SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
1284 instance.ForceUnlock();
1285}
1286
1287} // namespace __asan
1288
1289// --- Implementation of LSan-specific functions --- {{{1
1290namespace __lsan {
1291void LockAllocator() {
1292 __asan::get_allocator().ForceLock();
1293}
1294
1295void UnlockAllocator() {
1296 __asan::get_allocator().ForceUnlock();
1297}
1298
1299void GetAllocatorGlobalRange(uptr *begin, uptr *end) {
1300 *begin = (uptr)&__asan::get_allocator();
1301 *end = *begin + sizeof(__asan::get_allocator());
1302}
1303
1304uptr PointsIntoChunk(void *p) {
1305 uptr addr = reinterpret_cast<uptr>(p);
1306 __asan::AsanChunk *m = __asan::instance.GetAsanChunkByAddrFastLocked(p: addr);
1307 if (!m || atomic_load(a: &m->chunk_state, mo: memory_order_acquire) !=
1308 __asan::CHUNK_ALLOCATED)
1309 return 0;
1310 uptr chunk = m->Beg();
1311 if (m->AddrIsInside(addr))
1312 return chunk;
1313 if (IsSpecialCaseOfOperatorNew0(chunk_beg: chunk, chunk_size: m->UsedSize(), addr))
1314 return chunk;
1315 return 0;
1316}
1317
1318uptr GetUserBegin(uptr chunk) {
1319 // FIXME: All usecases provide chunk address, GetAsanChunkByAddrFastLocked is
1320 // not needed.
1321 __asan::AsanChunk *m = __asan::instance.GetAsanChunkByAddrFastLocked(p: chunk);
1322 return m ? m->Beg() : 0;
1323}
1324
1325uptr GetUserAddr(uptr chunk) {
1326 return chunk;
1327}
1328
1329LsanMetadata::LsanMetadata(uptr chunk) {
1330 metadata_ = chunk ? reinterpret_cast<void *>(chunk - __asan::kChunkHeaderSize)
1331 : nullptr;
1332}
1333
1334bool LsanMetadata::allocated() const {
1335 if (!metadata_)
1336 return false;
1337 __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
1338 return atomic_load(a: &m->chunk_state, mo: memory_order_relaxed) ==
1339 __asan::CHUNK_ALLOCATED;
1340}
1341
1342ChunkTag LsanMetadata::tag() const {
1343 __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
1344 return static_cast<ChunkTag>(m->lsan_tag);
1345}
1346
1347void LsanMetadata::set_tag(ChunkTag value) {
1348 __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
1349 m->lsan_tag = value;
1350}
1351
1352uptr LsanMetadata::requested_size() const {
1353 __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
1354 return m->UsedSize();
1355}
1356
1357u32 LsanMetadata::stack_trace_id() const {
1358 __asan::AsanChunk *m = reinterpret_cast<__asan::AsanChunk *>(metadata_);
1359 u32 tid = 0;
1360 u32 stack = 0;
1361 m->GetAllocContext(tid, stack);
1362 return stack;
1363}
1364
1365void ForEachChunk(ForEachChunkCallback callback, void *arg) {
1366 __asan::get_allocator().ForEachChunk(callback, arg);
1367}
1368
1369IgnoreObjectResult IgnoreObject(const void *p) {
1370 uptr addr = reinterpret_cast<uptr>(p);
1371 __asan::AsanChunk *m = __asan::instance.GetAsanChunkByAddr(p: addr);
1372 if (!m ||
1373 (atomic_load(a: &m->chunk_state, mo: memory_order_acquire) !=
1374 __asan::CHUNK_ALLOCATED) ||
1375 !m->AddrIsInside(addr)) {
1376 return kIgnoreObjectInvalid;
1377 }
1378 if (m->lsan_tag == kIgnored)
1379 return kIgnoreObjectAlreadyIgnored;
1380 m->lsan_tag = __lsan::kIgnored;
1381 return kIgnoreObjectSuccess;
1382}
1383
1384} // namespace __lsan
1385
1386// ---------------------- Interface ---------------- {{{1
1387using namespace __asan;
1388
1389static const void *AllocationBegin(const void *p) {
1390 AsanChunk *m = __asan::instance.GetAsanChunkByAddr(p: (uptr)p);
1391 if (!m)
1392 return nullptr;
1393 if (atomic_load(a: &m->chunk_state, mo: memory_order_acquire) != CHUNK_ALLOCATED)
1394 return nullptr;
1395 if (m->UsedSize() == 0)
1396 return nullptr;
1397 return (const void *)(m->Beg());
1398}
1399
1400// ASan allocator doesn't reserve extra bytes, so normally we would
1401// just return "size". We don't want to expose our redzone sizes, etc here.
1402uptr __sanitizer_get_estimated_allocated_size(uptr size) {
1403 return size;
1404}
1405
1406int __sanitizer_get_ownership(const void *p) {
1407 uptr ptr = reinterpret_cast<uptr>(p);
1408 return instance.AllocationSize(p: ptr) > 0;
1409}
1410
1411uptr __sanitizer_get_allocated_size(const void *p) {
1412 if (!p) return 0;
1413 uptr ptr = reinterpret_cast<uptr>(p);
1414 uptr allocated_size = instance.AllocationSize(p: ptr);
1415 // Die if p is not malloced or if it is already freed.
1416 if (allocated_size == 0) {
1417 GET_STACK_TRACE_FATAL_HERE;
1418 ReportSanitizerGetAllocatedSizeNotOwned(addr: ptr, stack: &stack);
1419 }
1420 return allocated_size;
1421}
1422
1423uptr __sanitizer_get_allocated_size_fast(const void *p) {
1424 DCHECK_EQ(p, __sanitizer_get_allocated_begin(p));
1425 uptr ret = instance.AllocationSizeFast(p: reinterpret_cast<uptr>(p));
1426 DCHECK_EQ(ret, __sanitizer_get_allocated_size(p));
1427 return ret;
1428}
1429
1430const void *__sanitizer_get_allocated_begin(const void *p) {
1431 return AllocationBegin(p);
1432}
1433
1434void __sanitizer_purge_allocator() {
1435 GET_STACK_TRACE_MALLOC;
1436 instance.Purge(stack: &stack);
1437}
1438
1439int __asan_update_allocation_context(void* addr) {
1440 GET_STACK_TRACE_MALLOC;
1441 return instance.UpdateAllocationStack(addr: (uptr)addr, stack: &stack);
1442}
1443