1 //===-- msan_allocator.cc --------------------------- ---------------------===//
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 MemorySanitizer.
11 // MemorySanitizer allocator.
12 //===----------------------------------------------------------------------===//
14 #include "sanitizer_common/sanitizer_allocator.h"
15 #include "sanitizer_common/sanitizer_allocator_checks.h"
16 #include "sanitizer_common/sanitizer_allocator_interface.h"
17 #include "sanitizer_common/sanitizer_allocator_report.h"
18 #include "sanitizer_common/sanitizer_errno.h"
20 #include "msan_allocator.h"
21 #include "msan_origin.h"
22 #include "msan_thread.h"
23 #include "msan_poisoning.h"
31 struct MsanMapUnmapCallback {
32 void OnMap(uptr p, uptr size) const {}
33 void OnUnmap(uptr p, uptr size) const {
34 __msan_unpoison((void *)p, size);
36 // We are about to unmap a chunk of user memory.
37 // Mark the corresponding shadow memory as not needed.
38 uptr shadow_p = MEM_TO_SHADOW(p);
39 ReleaseMemoryPagesToOS(shadow_p, shadow_p + size);
40 if (__msan_get_track_origins()) {
41 uptr origin_p = MEM_TO_ORIGIN(p);
42 ReleaseMemoryPagesToOS(origin_p, origin_p + size);
48 static const uptr kMaxAllowedMallocSize = 2UL << 30;
51 static const uptr kSpaceBeg = 0;
52 static const u64 kSpaceSize = SANITIZER_MMAP_RANGE_SIZE;
53 static const uptr kMetadataSize = sizeof(Metadata);
54 typedef __sanitizer::CompactSizeClassMap SizeClassMap;
55 static const uptr kRegionSizeLog = 20;
56 using AddressSpaceView = LocalAddressSpaceView;
57 typedef MsanMapUnmapCallback MapUnmapCallback;
58 static const uptr kFlags = 0;
60 typedef SizeClassAllocator32<AP32> PrimaryAllocator;
61 #elif defined(__x86_64__)
62 #if SANITIZER_NETBSD || \
63 (SANITIZER_LINUX && !defined(MSAN_LINUX_X86_64_OLD_MAPPING))
64 static const uptr kAllocatorSpace = 0x700000000000ULL;
66 static const uptr kAllocatorSpace = 0x600000000000ULL;
68 static const uptr kMaxAllowedMallocSize = 8UL << 30;
70 struct AP64 { // Allocator64 parameters. Deliberately using a short name.
71 static const uptr kSpaceBeg = kAllocatorSpace;
72 static const uptr kSpaceSize = 0x40000000000; // 4T.
73 static const uptr kMetadataSize = sizeof(Metadata);
74 typedef DefaultSizeClassMap SizeClassMap;
75 typedef MsanMapUnmapCallback MapUnmapCallback;
76 static const uptr kFlags = 0;
77 using AddressSpaceView = LocalAddressSpaceView;
80 typedef SizeClassAllocator64<AP64> PrimaryAllocator;
82 #elif defined(__powerpc64__)
83 static const uptr kMaxAllowedMallocSize = 2UL << 30; // 2G
85 struct AP64 { // Allocator64 parameters. Deliberately using a short name.
86 static const uptr kSpaceBeg = 0x300000000000;
87 static const uptr kSpaceSize = 0x020000000000; // 2T.
88 static const uptr kMetadataSize = sizeof(Metadata);
89 typedef DefaultSizeClassMap SizeClassMap;
90 typedef MsanMapUnmapCallback MapUnmapCallback;
91 static const uptr kFlags = 0;
92 using AddressSpaceView = LocalAddressSpaceView;
95 typedef SizeClassAllocator64<AP64> PrimaryAllocator;
96 #elif defined(__aarch64__)
97 static const uptr kMaxAllowedMallocSize = 2UL << 30; // 2G
100 static const uptr kSpaceBeg = 0;
101 static const u64 kSpaceSize = SANITIZER_MMAP_RANGE_SIZE;
102 static const uptr kMetadataSize = sizeof(Metadata);
103 typedef __sanitizer::CompactSizeClassMap SizeClassMap;
104 static const uptr kRegionSizeLog = 20;
105 using AddressSpaceView = LocalAddressSpaceView;
106 typedef MsanMapUnmapCallback MapUnmapCallback;
107 static const uptr kFlags = 0;
109 typedef SizeClassAllocator32<AP32> PrimaryAllocator;
111 typedef CombinedAllocator<PrimaryAllocator> Allocator;
112 typedef Allocator::AllocatorCache AllocatorCache;
114 static Allocator allocator;
115 static AllocatorCache fallback_allocator_cache;
116 static StaticSpinMutex fallback_mutex;
118 void MsanAllocatorInit() {
119 SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null);
120 allocator.Init(common_flags()->allocator_release_to_os_interval_ms);
123 AllocatorCache *GetAllocatorCache(MsanThreadLocalMallocStorage *ms) {
125 CHECK_LE(sizeof(AllocatorCache), sizeof(ms->allocator_cache));
126 return reinterpret_cast<AllocatorCache *>(ms->allocator_cache);
129 void MsanThreadLocalMallocStorage::CommitBack() {
130 allocator.SwallowCache(GetAllocatorCache(this));
133 static void *MsanAllocate(StackTrace *stack, uptr size, uptr alignment,
135 if (size > kMaxAllowedMallocSize) {
136 if (AllocatorMayReturnNull()) {
137 Report("WARNING: MemorySanitizer failed to allocate 0x%zx bytes\n", size);
140 ReportAllocationSizeTooBig(size, kMaxAllowedMallocSize, stack);
142 MsanThread *t = GetCurrentThread();
145 AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
146 allocated = allocator.Allocate(cache, size, alignment);
148 SpinMutexLock l(&fallback_mutex);
149 AllocatorCache *cache = &fallback_allocator_cache;
150 allocated = allocator.Allocate(cache, size, alignment);
152 if (UNLIKELY(!allocated)) {
153 SetAllocatorOutOfMemory();
154 if (AllocatorMayReturnNull())
156 ReportOutOfMemory(size, stack);
159 reinterpret_cast<Metadata *>(allocator.GetMetaData(allocated));
160 meta->requested_size = size;
162 __msan_clear_and_unpoison(allocated, size);
163 } else if (flags()->poison_in_malloc) {
164 __msan_poison(allocated, size);
165 if (__msan_get_track_origins()) {
166 stack->tag = StackTrace::TAG_ALLOC;
167 Origin o = Origin::CreateHeapOrigin(stack);
168 __msan_set_origin(allocated, size, o.raw_id());
171 MSAN_MALLOC_HOOK(allocated, size);
175 void MsanDeallocate(StackTrace *stack, void *p) {
178 Metadata *meta = reinterpret_cast<Metadata *>(allocator.GetMetaData(p));
179 uptr size = meta->requested_size;
180 meta->requested_size = 0;
181 // This memory will not be reused by anyone else, so we are free to keep it
183 if (flags()->poison_in_free) {
184 __msan_poison(p, size);
185 if (__msan_get_track_origins()) {
186 stack->tag = StackTrace::TAG_DEALLOC;
187 Origin o = Origin::CreateHeapOrigin(stack);
188 __msan_set_origin(p, size, o.raw_id());
191 MsanThread *t = GetCurrentThread();
193 AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
194 allocator.Deallocate(cache, p);
196 SpinMutexLock l(&fallback_mutex);
197 AllocatorCache *cache = &fallback_allocator_cache;
198 allocator.Deallocate(cache, p);
202 void *MsanReallocate(StackTrace *stack, void *old_p, uptr new_size,
204 Metadata *meta = reinterpret_cast<Metadata*>(allocator.GetMetaData(old_p));
205 uptr old_size = meta->requested_size;
206 uptr actually_allocated_size = allocator.GetActuallyAllocatedSize(old_p);
207 if (new_size <= actually_allocated_size) {
208 // We are not reallocating here.
209 meta->requested_size = new_size;
210 if (new_size > old_size) {
211 if (flags()->poison_in_malloc) {
212 stack->tag = StackTrace::TAG_ALLOC;
213 PoisonMemory((char *)old_p + old_size, new_size - old_size, stack);
218 uptr memcpy_size = Min(new_size, old_size);
219 void *new_p = MsanAllocate(stack, new_size, alignment, false /*zeroise*/);
221 CopyMemory(new_p, old_p, memcpy_size, stack);
222 MsanDeallocate(stack, old_p);
227 void *MsanCalloc(StackTrace *stack, uptr nmemb, uptr size) {
228 if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
229 if (AllocatorMayReturnNull())
231 ReportCallocOverflow(nmemb, size, stack);
233 return MsanAllocate(stack, nmemb * size, sizeof(u64), true);
236 static uptr AllocationSize(const void *p) {
238 const void *beg = allocator.GetBlockBegin(p);
239 if (beg != p) return 0;
240 Metadata *b = (Metadata *)allocator.GetMetaData(p);
241 return b->requested_size;
244 void *msan_malloc(uptr size, StackTrace *stack) {
245 return SetErrnoOnNull(MsanAllocate(stack, size, sizeof(u64), false));
248 void *msan_calloc(uptr nmemb, uptr size, StackTrace *stack) {
249 return SetErrnoOnNull(MsanCalloc(stack, nmemb, size));
252 void *msan_realloc(void *ptr, uptr size, StackTrace *stack) {
254 return SetErrnoOnNull(MsanAllocate(stack, size, sizeof(u64), false));
256 MsanDeallocate(stack, ptr);
259 return SetErrnoOnNull(MsanReallocate(stack, ptr, size, sizeof(u64)));
262 void *msan_reallocarray(void *ptr, uptr nmemb, uptr size, StackTrace *stack) {
263 if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
264 errno = errno_ENOMEM;
265 if (AllocatorMayReturnNull())
267 ReportReallocArrayOverflow(nmemb, size, stack);
269 return msan_realloc(ptr, nmemb * size, stack);
272 void *msan_valloc(uptr size, StackTrace *stack) {
273 return SetErrnoOnNull(MsanAllocate(stack, size, GetPageSizeCached(), false));
276 void *msan_pvalloc(uptr size, StackTrace *stack) {
277 uptr PageSize = GetPageSizeCached();
278 if (UNLIKELY(CheckForPvallocOverflow(size, PageSize))) {
279 errno = errno_ENOMEM;
280 if (AllocatorMayReturnNull())
282 ReportPvallocOverflow(size, stack);
284 // pvalloc(0) should allocate one page.
285 size = size ? RoundUpTo(size, PageSize) : PageSize;
286 return SetErrnoOnNull(MsanAllocate(stack, size, PageSize, false));
289 void *msan_aligned_alloc(uptr alignment, uptr size, StackTrace *stack) {
290 if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(alignment, size))) {
291 errno = errno_EINVAL;
292 if (AllocatorMayReturnNull())
294 ReportInvalidAlignedAllocAlignment(size, alignment, stack);
296 return SetErrnoOnNull(MsanAllocate(stack, size, alignment, false));
299 void *msan_memalign(uptr alignment, uptr size, StackTrace *stack) {
300 if (UNLIKELY(!IsPowerOfTwo(alignment))) {
301 errno = errno_EINVAL;
302 if (AllocatorMayReturnNull())
304 ReportInvalidAllocationAlignment(alignment, stack);
306 return SetErrnoOnNull(MsanAllocate(stack, size, alignment, false));
309 int msan_posix_memalign(void **memptr, uptr alignment, uptr size,
311 if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) {
312 if (AllocatorMayReturnNull())
314 ReportInvalidPosixMemalignAlignment(alignment, stack);
316 void *ptr = MsanAllocate(stack, size, alignment, false);
318 // OOM error is already taken care of by MsanAllocate.
320 CHECK(IsAligned((uptr)ptr, alignment));
325 } // namespace __msan
327 using namespace __msan;
329 uptr __sanitizer_get_current_allocated_bytes() {
330 uptr stats[AllocatorStatCount];
331 allocator.GetStats(stats);
332 return stats[AllocatorStatAllocated];
335 uptr __sanitizer_get_heap_size() {
336 uptr stats[AllocatorStatCount];
337 allocator.GetStats(stats);
338 return stats[AllocatorStatMapped];
341 uptr __sanitizer_get_free_bytes() { return 1; }
343 uptr __sanitizer_get_unmapped_bytes() { return 1; }
345 uptr __sanitizer_get_estimated_allocated_size(uptr size) { return size; }
347 int __sanitizer_get_ownership(const void *p) { return AllocationSize(p) != 0; }
349 uptr __sanitizer_get_allocated_size(const void *p) { return AllocationSize(p); }