1 //=-- lsan_allocator.cpp --------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file is a part of LeakSanitizer.
10 // See lsan_allocator.h for details.
12 //===----------------------------------------------------------------------===//
14 #include "lsan_allocator.h"
16 #include "sanitizer_common/sanitizer_allocator.h"
17 #include "sanitizer_common/sanitizer_allocator_checks.h"
18 #include "sanitizer_common/sanitizer_allocator_interface.h"
19 #include "sanitizer_common/sanitizer_allocator_report.h"
20 #include "sanitizer_common/sanitizer_errno.h"
21 #include "sanitizer_common/sanitizer_internal_defs.h"
22 #include "sanitizer_common/sanitizer_stackdepot.h"
23 #include "sanitizer_common/sanitizer_stacktrace.h"
24 #include "lsan_common.h"
26 extern "C" void *memset(void *ptr
, int value
, uptr num
);
29 #if defined(__i386__) || defined(__arm__)
30 static const uptr kMaxAllowedMallocSize
= 1UL << 30;
31 #elif defined(__mips64) || defined(__aarch64__)
32 static const uptr kMaxAllowedMallocSize
= 4UL << 30;
34 static const uptr kMaxAllowedMallocSize
= 8UL << 30;
37 static Allocator allocator
;
39 static uptr max_malloc_size
;
41 void InitializeAllocator() {
42 SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null
);
43 allocator
.InitLinkerInitialized(
44 common_flags()->allocator_release_to_os_interval_ms
);
45 if (common_flags()->max_allocation_size_mb
)
46 max_malloc_size
= Min(common_flags()->max_allocation_size_mb
<< 20,
47 kMaxAllowedMallocSize
);
49 max_malloc_size
= kMaxAllowedMallocSize
;
52 void AllocatorThreadFinish() {
53 allocator
.SwallowCache(GetAllocatorCache());
56 static ChunkMetadata
*Metadata(const void *p
) {
57 return reinterpret_cast<ChunkMetadata
*>(allocator
.GetMetaData(p
));
60 static void RegisterAllocation(const StackTrace
&stack
, void *p
, uptr size
) {
62 ChunkMetadata
*m
= Metadata(p
);
64 m
->tag
= DisabledInThisThread() ? kIgnored
: kDirectlyLeaked
;
65 m
->stack_trace_id
= StackDepotPut(stack
);
66 m
->requested_size
= size
;
67 atomic_store(reinterpret_cast<atomic_uint8_t
*>(m
), 1, memory_order_relaxed
);
70 static void RegisterDeallocation(void *p
) {
72 ChunkMetadata
*m
= Metadata(p
);
74 atomic_store(reinterpret_cast<atomic_uint8_t
*>(m
), 0, memory_order_relaxed
);
77 static void *ReportAllocationSizeTooBig(uptr size
, const StackTrace
&stack
) {
78 if (AllocatorMayReturnNull()) {
79 Report("WARNING: LeakSanitizer failed to allocate 0x%zx bytes\n", size
);
82 ReportAllocationSizeTooBig(size
, max_malloc_size
, &stack
);
85 void *Allocate(const StackTrace
&stack
, uptr size
, uptr alignment
,
89 if (size
> max_malloc_size
)
90 return ReportAllocationSizeTooBig(size
, stack
);
91 void *p
= allocator
.Allocate(GetAllocatorCache(), size
, alignment
);
93 SetAllocatorOutOfMemory();
94 if (AllocatorMayReturnNull())
96 ReportOutOfMemory(size
, &stack
);
98 // Do not rely on the allocator to clear the memory (it's slow).
99 if (cleared
&& allocator
.FromPrimary(p
))
101 RegisterAllocation(stack
, p
, size
);
102 if (&__sanitizer_malloc_hook
) __sanitizer_malloc_hook(p
, size
);
103 RunMallocHooks(p
, size
);
107 static void *Calloc(uptr nmemb
, uptr size
, const StackTrace
&stack
) {
108 if (UNLIKELY(CheckForCallocOverflow(size
, nmemb
))) {
109 if (AllocatorMayReturnNull())
111 ReportCallocOverflow(nmemb
, size
, &stack
);
114 return Allocate(stack
, size
, 1, true);
117 void Deallocate(void *p
) {
118 if (&__sanitizer_free_hook
) __sanitizer_free_hook(p
);
120 RegisterDeallocation(p
);
121 allocator
.Deallocate(GetAllocatorCache(), p
);
124 void *Reallocate(const StackTrace
&stack
, void *p
, uptr new_size
,
126 RegisterDeallocation(p
);
127 if (new_size
> max_malloc_size
) {
128 allocator
.Deallocate(GetAllocatorCache(), p
);
129 return ReportAllocationSizeTooBig(new_size
, stack
);
131 p
= allocator
.Reallocate(GetAllocatorCache(), p
, new_size
, alignment
);
132 RegisterAllocation(stack
, p
, new_size
);
136 void GetAllocatorCacheRange(uptr
*begin
, uptr
*end
) {
137 *begin
= (uptr
)GetAllocatorCache();
138 *end
= *begin
+ sizeof(AllocatorCache
);
141 uptr
GetMallocUsableSize(const void *p
) {
142 ChunkMetadata
*m
= Metadata(p
);
144 return m
->requested_size
;
147 int lsan_posix_memalign(void **memptr
, uptr alignment
, uptr size
,
148 const StackTrace
&stack
) {
149 if (UNLIKELY(!CheckPosixMemalignAlignment(alignment
))) {
150 if (AllocatorMayReturnNull())
152 ReportInvalidPosixMemalignAlignment(alignment
, &stack
);
154 void *ptr
= Allocate(stack
, size
, alignment
, kAlwaysClearMemory
);
156 // OOM error is already taken care of by Allocate.
158 CHECK(IsAligned((uptr
)ptr
, alignment
));
163 void *lsan_aligned_alloc(uptr alignment
, uptr size
, const StackTrace
&stack
) {
164 if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(alignment
, size
))) {
165 errno
= errno_EINVAL
;
166 if (AllocatorMayReturnNull())
168 ReportInvalidAlignedAllocAlignment(size
, alignment
, &stack
);
170 return SetErrnoOnNull(Allocate(stack
, size
, alignment
, kAlwaysClearMemory
));
173 void *lsan_memalign(uptr alignment
, uptr size
, const StackTrace
&stack
) {
174 if (UNLIKELY(!IsPowerOfTwo(alignment
))) {
175 errno
= errno_EINVAL
;
176 if (AllocatorMayReturnNull())
178 ReportInvalidAllocationAlignment(alignment
, &stack
);
180 return SetErrnoOnNull(Allocate(stack
, size
, alignment
, kAlwaysClearMemory
));
183 void *lsan_malloc(uptr size
, const StackTrace
&stack
) {
184 return SetErrnoOnNull(Allocate(stack
, size
, 1, kAlwaysClearMemory
));
187 void lsan_free(void *p
) {
191 void *lsan_realloc(void *p
, uptr size
, const StackTrace
&stack
) {
192 return SetErrnoOnNull(Reallocate(stack
, p
, size
, 1));
195 void *lsan_reallocarray(void *ptr
, uptr nmemb
, uptr size
,
196 const StackTrace
&stack
) {
197 if (UNLIKELY(CheckForCallocOverflow(size
, nmemb
))) {
198 errno
= errno_ENOMEM
;
199 if (AllocatorMayReturnNull())
201 ReportReallocArrayOverflow(nmemb
, size
, &stack
);
203 return lsan_realloc(ptr
, nmemb
* size
, stack
);
206 void *lsan_calloc(uptr nmemb
, uptr size
, const StackTrace
&stack
) {
207 return SetErrnoOnNull(Calloc(nmemb
, size
, stack
));
210 void *lsan_valloc(uptr size
, const StackTrace
&stack
) {
211 return SetErrnoOnNull(
212 Allocate(stack
, size
, GetPageSizeCached(), kAlwaysClearMemory
));
215 void *lsan_pvalloc(uptr size
, const StackTrace
&stack
) {
216 uptr PageSize
= GetPageSizeCached();
217 if (UNLIKELY(CheckForPvallocOverflow(size
, PageSize
))) {
218 errno
= errno_ENOMEM
;
219 if (AllocatorMayReturnNull())
221 ReportPvallocOverflow(size
, &stack
);
223 // pvalloc(0) should allocate one page.
224 size
= size
? RoundUpTo(size
, PageSize
) : PageSize
;
225 return SetErrnoOnNull(Allocate(stack
, size
, PageSize
, kAlwaysClearMemory
));
228 uptr
lsan_mz_size(const void *p
) {
229 return GetMallocUsableSize(p
);
232 ///// Interface to the common LSan module. /////
234 void LockAllocator() {
235 allocator
.ForceLock();
238 void UnlockAllocator() {
239 allocator
.ForceUnlock();
242 void GetAllocatorGlobalRange(uptr
*begin
, uptr
*end
) {
243 *begin
= (uptr
)&allocator
;
244 *end
= *begin
+ sizeof(allocator
);
247 uptr
PointsIntoChunk(void* p
) {
248 uptr addr
= reinterpret_cast<uptr
>(p
);
249 uptr chunk
= reinterpret_cast<uptr
>(allocator
.GetBlockBeginFastLocked(p
));
250 if (!chunk
) return 0;
251 // LargeMmapAllocator considers pointers to the meta-region of a chunk to be
252 // valid, but we don't want that.
253 if (addr
< chunk
) return 0;
254 ChunkMetadata
*m
= Metadata(reinterpret_cast<void *>(chunk
));
258 if (addr
< chunk
+ m
->requested_size
)
260 if (IsSpecialCaseOfOperatorNew0(chunk
, m
->requested_size
, addr
))
265 uptr
GetUserBegin(uptr chunk
) {
269 LsanMetadata::LsanMetadata(uptr chunk
) {
270 metadata_
= Metadata(reinterpret_cast<void *>(chunk
));
274 bool LsanMetadata::allocated() const {
275 return reinterpret_cast<ChunkMetadata
*>(metadata_
)->allocated
;
278 ChunkTag
LsanMetadata::tag() const {
279 return reinterpret_cast<ChunkMetadata
*>(metadata_
)->tag
;
282 void LsanMetadata::set_tag(ChunkTag value
) {
283 reinterpret_cast<ChunkMetadata
*>(metadata_
)->tag
= value
;
286 uptr
LsanMetadata::requested_size() const {
287 return reinterpret_cast<ChunkMetadata
*>(metadata_
)->requested_size
;
290 u32
LsanMetadata::stack_trace_id() const {
291 return reinterpret_cast<ChunkMetadata
*>(metadata_
)->stack_trace_id
;
294 void ForEachChunk(ForEachChunkCallback callback
, void *arg
) {
295 allocator
.ForEachChunk(callback
, arg
);
298 IgnoreObjectResult
IgnoreObjectLocked(const void *p
) {
299 void *chunk
= allocator
.GetBlockBegin(p
);
300 if (!chunk
|| p
< chunk
) return kIgnoreObjectInvalid
;
301 ChunkMetadata
*m
= Metadata(chunk
);
303 if (m
->allocated
&& (uptr
)p
< (uptr
)chunk
+ m
->requested_size
) {
304 if (m
->tag
== kIgnored
)
305 return kIgnoreObjectAlreadyIgnored
;
307 return kIgnoreObjectSuccess
;
309 return kIgnoreObjectInvalid
;
312 } // namespace __lsan
314 using namespace __lsan
;
317 SANITIZER_INTERFACE_ATTRIBUTE
318 uptr
__sanitizer_get_current_allocated_bytes() {
319 uptr stats
[AllocatorStatCount
];
320 allocator
.GetStats(stats
);
321 return stats
[AllocatorStatAllocated
];
324 SANITIZER_INTERFACE_ATTRIBUTE
325 uptr
__sanitizer_get_heap_size() {
326 uptr stats
[AllocatorStatCount
];
327 allocator
.GetStats(stats
);
328 return stats
[AllocatorStatMapped
];
331 SANITIZER_INTERFACE_ATTRIBUTE
332 uptr
__sanitizer_get_free_bytes() { return 0; }
334 SANITIZER_INTERFACE_ATTRIBUTE
335 uptr
__sanitizer_get_unmapped_bytes() { return 0; }
337 SANITIZER_INTERFACE_ATTRIBUTE
338 uptr
__sanitizer_get_estimated_allocated_size(uptr size
) { return size
; }
340 SANITIZER_INTERFACE_ATTRIBUTE
341 int __sanitizer_get_ownership(const void *p
) { return Metadata(p
) != nullptr; }
343 SANITIZER_INTERFACE_ATTRIBUTE
344 uptr
__sanitizer_get_allocated_size(const void *p
) {
345 return GetMallocUsableSize(p
);
348 #if !SANITIZER_SUPPORTS_WEAK_HOOKS
349 // Provide default (no-op) implementation of malloc hooks.
350 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
351 void __sanitizer_malloc_hook(void *ptr
, uptr size
) {
355 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
356 void __sanitizer_free_hook(void *ptr
) {