1 //===-- msan_allocator.cc --------------------------- ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of MemorySanitizer.
12 // MemorySanitizer allocator.
13 //===----------------------------------------------------------------------===//
15 #include "sanitizer_common/sanitizer_allocator.h"
16 #include "sanitizer_common/sanitizer_allocator_checks.h"
17 #include "sanitizer_common/sanitizer_allocator_interface.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;
49 static const uptr kRegionSizeLog = 20;
50 static const uptr kNumRegions = SANITIZER_MMAP_RANGE_SIZE >> kRegionSizeLog;
51 typedef TwoLevelByteMap<(kNumRegions >> 12), 1 << 12> ByteMap;
54 static const uptr kSpaceBeg = 0;
55 static const u64 kSpaceSize = SANITIZER_MMAP_RANGE_SIZE;
56 static const uptr kMetadataSize = sizeof(Metadata);
57 typedef __sanitizer::CompactSizeClassMap SizeClassMap;
58 static const uptr kRegionSizeLog = __msan::kRegionSizeLog;
59 typedef __msan::ByteMap ByteMap;
60 typedef MsanMapUnmapCallback MapUnmapCallback;
61 static const uptr kFlags = 0;
63 typedef SizeClassAllocator32<AP32> PrimaryAllocator;
64 #elif defined(__x86_64__)
65 #if SANITIZER_NETBSD || \
66 (SANITIZER_LINUX && !defined(MSAN_LINUX_X86_64_OLD_MAPPING))
67 static const uptr kAllocatorSpace = 0x700000000000ULL;
69 static const uptr kAllocatorSpace = 0x600000000000ULL;
71 static const uptr kMaxAllowedMallocSize = 8UL << 30;
73 struct AP64 { // Allocator64 parameters. Deliberately using a short name.
74 static const uptr kSpaceBeg = kAllocatorSpace;
75 static const uptr kSpaceSize = 0x40000000000; // 4T.
76 static const uptr kMetadataSize = sizeof(Metadata);
77 typedef DefaultSizeClassMap SizeClassMap;
78 typedef MsanMapUnmapCallback MapUnmapCallback;
79 static const uptr kFlags = 0;
82 typedef SizeClassAllocator64<AP64> PrimaryAllocator;
84 #elif defined(__powerpc64__)
85 static const uptr kMaxAllowedMallocSize = 2UL << 30; // 2G
87 struct AP64 { // Allocator64 parameters. Deliberately using a short name.
88 static const uptr kSpaceBeg = 0x300000000000;
89 static const uptr kSpaceSize = 0x020000000000; // 2T.
90 static const uptr kMetadataSize = sizeof(Metadata);
91 typedef DefaultSizeClassMap SizeClassMap;
92 typedef MsanMapUnmapCallback MapUnmapCallback;
93 static const uptr kFlags = 0;
96 typedef SizeClassAllocator64<AP64> PrimaryAllocator;
97 #elif defined(__aarch64__)
98 static const uptr kMaxAllowedMallocSize = 2UL << 30; // 2G
99 static const uptr kRegionSizeLog = 20;
100 static const uptr kNumRegions = SANITIZER_MMAP_RANGE_SIZE >> kRegionSizeLog;
101 typedef TwoLevelByteMap<(kNumRegions >> 12), 1 << 12> ByteMap;
104 static const uptr kSpaceBeg = 0;
105 static const u64 kSpaceSize = SANITIZER_MMAP_RANGE_SIZE;
106 static const uptr kMetadataSize = sizeof(Metadata);
107 typedef __sanitizer::CompactSizeClassMap SizeClassMap;
108 static const uptr kRegionSizeLog = __msan::kRegionSizeLog;
109 typedef __msan::ByteMap ByteMap;
110 typedef MsanMapUnmapCallback MapUnmapCallback;
111 static const uptr kFlags = 0;
113 typedef SizeClassAllocator32<AP32> PrimaryAllocator;
115 typedef SizeClassAllocatorLocalCache<PrimaryAllocator> AllocatorCache;
116 typedef LargeMmapAllocator<MsanMapUnmapCallback> SecondaryAllocator;
117 typedef CombinedAllocator<PrimaryAllocator, AllocatorCache,
118 SecondaryAllocator> Allocator;
120 static Allocator allocator;
121 static AllocatorCache fallback_allocator_cache;
122 static SpinMutex fallback_mutex;
124 void MsanAllocatorInit() {
125 SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null);
126 allocator.Init(common_flags()->allocator_release_to_os_interval_ms);
129 AllocatorCache *GetAllocatorCache(MsanThreadLocalMallocStorage *ms) {
131 CHECK_LE(sizeof(AllocatorCache), sizeof(ms->allocator_cache));
132 return reinterpret_cast<AllocatorCache *>(ms->allocator_cache);
135 void MsanThreadLocalMallocStorage::CommitBack() {
136 allocator.SwallowCache(GetAllocatorCache(this));
139 static void *MsanAllocate(StackTrace *stack, uptr size, uptr alignment,
141 if (size > kMaxAllowedMallocSize) {
142 Report("WARNING: MemorySanitizer failed to allocate %p bytes\n",
144 return Allocator::FailureHandler::OnBadRequest();
146 MsanThread *t = GetCurrentThread();
149 AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
150 allocated = allocator.Allocate(cache, size, alignment);
152 SpinMutexLock l(&fallback_mutex);
153 AllocatorCache *cache = &fallback_allocator_cache;
154 allocated = allocator.Allocate(cache, size, alignment);
157 reinterpret_cast<Metadata *>(allocator.GetMetaData(allocated));
158 meta->requested_size = size;
160 __msan_clear_and_unpoison(allocated, size);
161 } else if (flags()->poison_in_malloc) {
162 __msan_poison(allocated, size);
163 if (__msan_get_track_origins()) {
164 stack->tag = StackTrace::TAG_ALLOC;
165 Origin o = Origin::CreateHeapOrigin(stack);
166 __msan_set_origin(allocated, size, o.raw_id());
169 MSAN_MALLOC_HOOK(allocated, size);
173 void MsanDeallocate(StackTrace *stack, void *p) {
176 Metadata *meta = reinterpret_cast<Metadata *>(allocator.GetMetaData(p));
177 uptr size = meta->requested_size;
178 meta->requested_size = 0;
179 // This memory will not be reused by anyone else, so we are free to keep it
181 if (flags()->poison_in_free) {
182 __msan_poison(p, size);
183 if (__msan_get_track_origins()) {
184 stack->tag = StackTrace::TAG_DEALLOC;
185 Origin o = Origin::CreateHeapOrigin(stack);
186 __msan_set_origin(p, size, o.raw_id());
189 MsanThread *t = GetCurrentThread();
191 AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
192 allocator.Deallocate(cache, p);
194 SpinMutexLock l(&fallback_mutex);
195 AllocatorCache *cache = &fallback_allocator_cache;
196 allocator.Deallocate(cache, p);
200 void *MsanReallocate(StackTrace *stack, void *old_p, uptr new_size,
202 Metadata *meta = reinterpret_cast<Metadata*>(allocator.GetMetaData(old_p));
203 uptr old_size = meta->requested_size;
204 uptr actually_allocated_size = allocator.GetActuallyAllocatedSize(old_p);
205 if (new_size <= actually_allocated_size) {
206 // We are not reallocating here.
207 meta->requested_size = new_size;
208 if (new_size > old_size) {
209 if (flags()->poison_in_malloc) {
210 stack->tag = StackTrace::TAG_ALLOC;
211 PoisonMemory((char *)old_p + old_size, new_size - old_size, stack);
216 uptr memcpy_size = Min(new_size, old_size);
217 void *new_p = MsanAllocate(stack, new_size, alignment, false /*zeroise*/);
219 CopyMemory(new_p, old_p, memcpy_size, stack);
220 MsanDeallocate(stack, old_p);
225 static uptr AllocationSize(const void *p) {
227 const void *beg = allocator.GetBlockBegin(p);
228 if (beg != p) return 0;
229 Metadata *b = (Metadata *)allocator.GetMetaData(p);
230 return b->requested_size;
233 void *msan_malloc(uptr size, StackTrace *stack) {
234 return SetErrnoOnNull(MsanAllocate(stack, size, sizeof(u64), false));
237 void *msan_calloc(uptr nmemb, uptr size, StackTrace *stack) {
238 if (UNLIKELY(CheckForCallocOverflow(size, nmemb)))
239 return SetErrnoOnNull(Allocator::FailureHandler::OnBadRequest());
240 return SetErrnoOnNull(MsanAllocate(stack, nmemb * size, sizeof(u64), true));
243 void *msan_realloc(void *ptr, uptr size, StackTrace *stack) {
245 return SetErrnoOnNull(MsanAllocate(stack, size, sizeof(u64), false));
247 MsanDeallocate(stack, ptr);
250 return SetErrnoOnNull(MsanReallocate(stack, ptr, size, sizeof(u64)));
253 void *msan_valloc(uptr size, StackTrace *stack) {
254 return SetErrnoOnNull(MsanAllocate(stack, size, GetPageSizeCached(), false));
257 void *msan_pvalloc(uptr size, StackTrace *stack) {
258 uptr PageSize = GetPageSizeCached();
259 if (UNLIKELY(CheckForPvallocOverflow(size, PageSize))) {
260 errno = errno_ENOMEM;
261 return Allocator::FailureHandler::OnBadRequest();
263 // pvalloc(0) should allocate one page.
264 size = size ? RoundUpTo(size, PageSize) : PageSize;
265 return SetErrnoOnNull(MsanAllocate(stack, size, PageSize, false));
268 void *msan_aligned_alloc(uptr alignment, uptr size, StackTrace *stack) {
269 if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(alignment, size))) {
270 errno = errno_EINVAL;
271 return Allocator::FailureHandler::OnBadRequest();
273 return SetErrnoOnNull(MsanAllocate(stack, size, alignment, false));
276 void *msan_memalign(uptr alignment, uptr size, StackTrace *stack) {
277 if (UNLIKELY(!IsPowerOfTwo(alignment))) {
278 errno = errno_EINVAL;
279 return Allocator::FailureHandler::OnBadRequest();
281 return SetErrnoOnNull(MsanAllocate(stack, size, alignment, false));
284 int msan_posix_memalign(void **memptr, uptr alignment, uptr size,
286 if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) {
287 Allocator::FailureHandler::OnBadRequest();
290 void *ptr = MsanAllocate(stack, size, alignment, false);
293 CHECK(IsAligned((uptr)ptr, alignment));
298 } // namespace __msan
300 using namespace __msan;
302 uptr __sanitizer_get_current_allocated_bytes() {
303 uptr stats[AllocatorStatCount];
304 allocator.GetStats(stats);
305 return stats[AllocatorStatAllocated];
308 uptr __sanitizer_get_heap_size() {
309 uptr stats[AllocatorStatCount];
310 allocator.GetStats(stats);
311 return stats[AllocatorStatMapped];
314 uptr __sanitizer_get_free_bytes() { return 1; }
316 uptr __sanitizer_get_unmapped_bytes() { return 1; }
318 uptr __sanitizer_get_estimated_allocated_size(uptr size) { return size; }
320 int __sanitizer_get_ownership(const void *p) { return AllocationSize(p) != 0; }
322 uptr __sanitizer_get_allocated_size(const void *p) { return AllocationSize(p); }