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_interface.h"
18 #include "msan_allocator.h"
19 #include "msan_origin.h"
20 #include "msan_thread.h"
21 #include "msan_poisoning.h"
29 struct MsanMapUnmapCallback {
30 void OnMap(uptr p, uptr size) const {}
31 void OnUnmap(uptr p, uptr size) const {
32 __msan_unpoison((void *)p, size);
34 // We are about to unmap a chunk of user memory.
35 // Mark the corresponding shadow memory as not needed.
36 uptr shadow_p = MEM_TO_SHADOW(p);
37 ReleaseMemoryPagesToOS(shadow_p, shadow_p + size);
38 if (__msan_get_track_origins()) {
39 uptr origin_p = MEM_TO_ORIGIN(p);
40 ReleaseMemoryPagesToOS(origin_p, origin_p + size);
46 static const uptr kMaxAllowedMallocSize = 2UL << 30;
47 static const uptr kRegionSizeLog = 20;
48 static const uptr kNumRegions = SANITIZER_MMAP_RANGE_SIZE >> kRegionSizeLog;
49 typedef TwoLevelByteMap<(kNumRegions >> 12), 1 << 12> ByteMap;
52 static const uptr kSpaceBeg = 0;
53 static const u64 kSpaceSize = SANITIZER_MMAP_RANGE_SIZE;
54 static const uptr kMetadataSize = sizeof(Metadata);
55 typedef __sanitizer::CompactSizeClassMap SizeClassMap;
56 static const uptr kRegionSizeLog = __msan::kRegionSizeLog;
57 typedef __msan::ByteMap ByteMap;
58 typedef MsanMapUnmapCallback MapUnmapCallback;
59 static const uptr kFlags = 0;
61 typedef SizeClassAllocator32<AP32> PrimaryAllocator;
62 #elif defined(__x86_64__)
63 #if 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;
79 typedef SizeClassAllocator64<AP64> PrimaryAllocator;
81 #elif defined(__powerpc64__)
82 static const uptr kMaxAllowedMallocSize = 2UL << 30; // 2G
84 struct AP64 { // Allocator64 parameters. Deliberately using a short name.
85 static const uptr kSpaceBeg = 0x300000000000;
86 static const uptr kSpaceSize = 0x020000000000; // 2T.
87 static const uptr kMetadataSize = sizeof(Metadata);
88 typedef DefaultSizeClassMap SizeClassMap;
89 typedef MsanMapUnmapCallback MapUnmapCallback;
90 static const uptr kFlags = 0;
93 typedef SizeClassAllocator64<AP64> PrimaryAllocator;
94 #elif defined(__aarch64__)
95 static const uptr kMaxAllowedMallocSize = 2UL << 30; // 2G
96 static const uptr kRegionSizeLog = 20;
97 static const uptr kNumRegions = SANITIZER_MMAP_RANGE_SIZE >> kRegionSizeLog;
98 typedef TwoLevelByteMap<(kNumRegions >> 12), 1 << 12> ByteMap;
101 static const uptr kSpaceBeg = 0;
102 static const u64 kSpaceSize = SANITIZER_MMAP_RANGE_SIZE;
103 static const uptr kMetadataSize = sizeof(Metadata);
104 typedef __sanitizer::CompactSizeClassMap SizeClassMap;
105 static const uptr kRegionSizeLog = __msan::kRegionSizeLog;
106 typedef __msan::ByteMap ByteMap;
107 typedef MsanMapUnmapCallback MapUnmapCallback;
108 static const uptr kFlags = 0;
110 typedef SizeClassAllocator32<AP32> PrimaryAllocator;
112 typedef SizeClassAllocatorLocalCache<PrimaryAllocator> AllocatorCache;
113 typedef LargeMmapAllocator<MsanMapUnmapCallback> SecondaryAllocator;
114 typedef CombinedAllocator<PrimaryAllocator, AllocatorCache,
115 SecondaryAllocator> Allocator;
117 static Allocator allocator;
118 static AllocatorCache fallback_allocator_cache;
119 static SpinMutex fallback_mutex;
121 void MsanAllocatorInit() {
123 common_flags()->allocator_may_return_null,
124 common_flags()->allocator_release_to_os_interval_ms);
127 AllocatorCache *GetAllocatorCache(MsanThreadLocalMallocStorage *ms) {
129 CHECK_LE(sizeof(AllocatorCache), sizeof(ms->allocator_cache));
130 return reinterpret_cast<AllocatorCache *>(ms->allocator_cache);
133 void MsanThreadLocalMallocStorage::CommitBack() {
134 allocator.SwallowCache(GetAllocatorCache(this));
137 static void *MsanAllocate(StackTrace *stack, uptr size, uptr alignment,
139 if (size > kMaxAllowedMallocSize) {
140 Report("WARNING: MemorySanitizer failed to allocate %p bytes\n",
142 return allocator.ReturnNullOrDieOnBadRequest();
144 MsanThread *t = GetCurrentThread();
147 AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
148 allocated = allocator.Allocate(cache, size, alignment, false);
150 SpinMutexLock l(&fallback_mutex);
151 AllocatorCache *cache = &fallback_allocator_cache;
152 allocated = allocator.Allocate(cache, size, alignment, false);
155 reinterpret_cast<Metadata *>(allocator.GetMetaData(allocated));
156 meta->requested_size = size;
158 __msan_clear_and_unpoison(allocated, size);
159 } else if (flags()->poison_in_malloc) {
160 __msan_poison(allocated, size);
161 if (__msan_get_track_origins()) {
162 stack->tag = StackTrace::TAG_ALLOC;
163 Origin o = Origin::CreateHeapOrigin(stack);
164 __msan_set_origin(allocated, size, o.raw_id());
167 MSAN_MALLOC_HOOK(allocated, size);
171 void MsanDeallocate(StackTrace *stack, void *p) {
174 Metadata *meta = reinterpret_cast<Metadata *>(allocator.GetMetaData(p));
175 uptr size = meta->requested_size;
176 meta->requested_size = 0;
177 // This memory will not be reused by anyone else, so we are free to keep it
179 if (flags()->poison_in_free) {
180 __msan_poison(p, size);
181 if (__msan_get_track_origins()) {
182 stack->tag = StackTrace::TAG_DEALLOC;
183 Origin o = Origin::CreateHeapOrigin(stack);
184 __msan_set_origin(p, size, o.raw_id());
187 MsanThread *t = GetCurrentThread();
189 AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
190 allocator.Deallocate(cache, p);
192 SpinMutexLock l(&fallback_mutex);
193 AllocatorCache *cache = &fallback_allocator_cache;
194 allocator.Deallocate(cache, p);
198 void *MsanCalloc(StackTrace *stack, uptr nmemb, uptr size) {
199 if (CallocShouldReturnNullDueToOverflow(size, nmemb))
200 return allocator.ReturnNullOrDieOnBadRequest();
201 return MsanReallocate(stack, nullptr, nmemb * size, sizeof(u64), true);
204 void *MsanReallocate(StackTrace *stack, void *old_p, uptr new_size,
205 uptr alignment, bool zeroise) {
207 return MsanAllocate(stack, new_size, alignment, zeroise);
209 MsanDeallocate(stack, old_p);
212 Metadata *meta = reinterpret_cast<Metadata*>(allocator.GetMetaData(old_p));
213 uptr old_size = meta->requested_size;
214 uptr actually_allocated_size = allocator.GetActuallyAllocatedSize(old_p);
215 if (new_size <= actually_allocated_size) {
216 // We are not reallocating here.
217 meta->requested_size = new_size;
218 if (new_size > old_size) {
220 __msan_clear_and_unpoison((char *)old_p + old_size,
221 new_size - old_size);
222 } else if (flags()->poison_in_malloc) {
223 stack->tag = StackTrace::TAG_ALLOC;
224 PoisonMemory((char *)old_p + old_size, new_size - old_size, stack);
229 uptr memcpy_size = Min(new_size, old_size);
230 void *new_p = MsanAllocate(stack, new_size, alignment, zeroise);
231 // Printf("realloc: old_size %zd new_size %zd\n", old_size, new_size);
233 CopyMemory(new_p, old_p, memcpy_size, stack);
234 MsanDeallocate(stack, old_p);
239 static uptr AllocationSize(const void *p) {
241 const void *beg = allocator.GetBlockBegin(p);
242 if (beg != p) return 0;
243 Metadata *b = (Metadata *)allocator.GetMetaData(p);
244 return b->requested_size;
247 } // namespace __msan
249 using namespace __msan;
251 uptr __sanitizer_get_current_allocated_bytes() {
252 uptr stats[AllocatorStatCount];
253 allocator.GetStats(stats);
254 return stats[AllocatorStatAllocated];
257 uptr __sanitizer_get_heap_size() {
258 uptr stats[AllocatorStatCount];
259 allocator.GetStats(stats);
260 return stats[AllocatorStatMapped];
263 uptr __sanitizer_get_free_bytes() { return 1; }
265 uptr __sanitizer_get_unmapped_bytes() { return 1; }
267 uptr __sanitizer_get_estimated_allocated_size(uptr size) { return size; }
269 int __sanitizer_get_ownership(const void *p) { return AllocationSize(p) != 0; }
271 uptr __sanitizer_get_allocated_size(const void *p) { return AllocationSize(p); }