xref: /NextBSD/contrib/compiler-rt/lib/msan/msan_allocator.cc (revision 84d351007654069f9643c8e4b4802a7f5f08ee42)
1 //===-- msan_allocator.cc --------------------------- ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file is a part of MemorySanitizer.
11 //
12 // MemorySanitizer allocator.
13 //===----------------------------------------------------------------------===//
14 
15 #include "sanitizer_common/sanitizer_allocator.h"
16 #include "sanitizer_common/sanitizer_allocator_interface.h"
17 #include "msan.h"
18 #include "msan_allocator.h"
19 #include "msan_origin.h"
20 #include "msan_thread.h"
21 #include "msan_poisoning.h"
22 
23 namespace __msan {
24 
25 struct Metadata {
26   uptr requested_size;
27 };
28 
29 struct MsanMapUnmapCallback {
OnMap__msan::MsanMapUnmapCallback30   void OnMap(uptr p, uptr size) const {}
OnUnmap__msan::MsanMapUnmapCallback31   void OnUnmap(uptr p, uptr size) const {
32     __msan_unpoison((void *)p, size);
33 
34     // We are about to unmap a chunk of user memory.
35     // Mark the corresponding shadow memory as not needed.
36     FlushUnneededShadowMemory(MEM_TO_SHADOW(p), size);
37     if (__msan_get_track_origins())
38       FlushUnneededShadowMemory(MEM_TO_ORIGIN(p), size);
39   }
40 };
41 
42 #if defined(__mips64)
43   static const uptr kMaxAllowedMallocSize = 2UL << 30;
44   static const uptr kRegionSizeLog = 20;
45   static const uptr kNumRegions = SANITIZER_MMAP_RANGE_SIZE >> kRegionSizeLog;
46   typedef TwoLevelByteMap<(kNumRegions >> 12), 1 << 12> ByteMap;
47   typedef CompactSizeClassMap SizeClassMap;
48 
49   typedef SizeClassAllocator32<0, SANITIZER_MMAP_RANGE_SIZE, sizeof(Metadata),
50                                SizeClassMap, kRegionSizeLog, ByteMap,
51                                MsanMapUnmapCallback> PrimaryAllocator;
52 #elif defined(__x86_64__)
53   static const uptr kAllocatorSpace = 0x600000000000ULL;
54   static const uptr kAllocatorSize   = 0x80000000000;  // 8T.
55   static const uptr kMetadataSize  = sizeof(Metadata);
56   static const uptr kMaxAllowedMallocSize = 8UL << 30;
57 
58   typedef SizeClassAllocator64<kAllocatorSpace, kAllocatorSize, kMetadataSize,
59                              DefaultSizeClassMap,
60                              MsanMapUnmapCallback> PrimaryAllocator;
61 #elif defined(__powerpc64__)
62   static const uptr kAllocatorSpace = 0x300000000000;
63   static const uptr kAllocatorSize  = 0x020000000000;  // 2T
64   static const uptr kMetadataSize  = sizeof(Metadata);
65   static const uptr kMaxAllowedMallocSize = 2UL << 30;  // 2G
66 
67   typedef SizeClassAllocator64<kAllocatorSpace, kAllocatorSize, kMetadataSize,
68                              DefaultSizeClassMap,
69                              MsanMapUnmapCallback> PrimaryAllocator;
70 #endif
71 typedef SizeClassAllocatorLocalCache<PrimaryAllocator> AllocatorCache;
72 typedef LargeMmapAllocator<MsanMapUnmapCallback> SecondaryAllocator;
73 typedef CombinedAllocator<PrimaryAllocator, AllocatorCache,
74                           SecondaryAllocator> Allocator;
75 
76 static Allocator allocator;
77 static AllocatorCache fallback_allocator_cache;
78 static SpinMutex fallback_mutex;
79 
80 static int inited = 0;
81 
Init()82 static inline void Init() {
83   if (inited) return;
84   __msan_init();
85   inited = true;  // this must happen before any threads are created.
86   allocator.Init(common_flags()->allocator_may_return_null);
87 }
88 
GetAllocatorCache(MsanThreadLocalMallocStorage * ms)89 AllocatorCache *GetAllocatorCache(MsanThreadLocalMallocStorage *ms) {
90   CHECK(ms);
91   CHECK_LE(sizeof(AllocatorCache), sizeof(ms->allocator_cache));
92   return reinterpret_cast<AllocatorCache *>(ms->allocator_cache);
93 }
94 
CommitBack()95 void MsanThreadLocalMallocStorage::CommitBack() {
96   allocator.SwallowCache(GetAllocatorCache(this));
97 }
98 
MsanAllocate(StackTrace * stack,uptr size,uptr alignment,bool zeroise)99 static void *MsanAllocate(StackTrace *stack, uptr size, uptr alignment,
100                           bool zeroise) {
101   Init();
102   if (size > kMaxAllowedMallocSize) {
103     Report("WARNING: MemorySanitizer failed to allocate %p bytes\n",
104            (void *)size);
105     return allocator.ReturnNullOrDie();
106   }
107   MsanThread *t = GetCurrentThread();
108   void *allocated;
109   if (t) {
110     AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
111     allocated = allocator.Allocate(cache, size, alignment, false);
112   } else {
113     SpinMutexLock l(&fallback_mutex);
114     AllocatorCache *cache = &fallback_allocator_cache;
115     allocated = allocator.Allocate(cache, size, alignment, false);
116   }
117   Metadata *meta =
118       reinterpret_cast<Metadata *>(allocator.GetMetaData(allocated));
119   meta->requested_size = size;
120   if (zeroise) {
121     __msan_clear_and_unpoison(allocated, size);
122   } else if (flags()->poison_in_malloc) {
123     __msan_poison(allocated, size);
124     if (__msan_get_track_origins()) {
125       stack->tag = StackTrace::TAG_ALLOC;
126       Origin o = Origin::CreateHeapOrigin(stack);
127       __msan_set_origin(allocated, size, o.raw_id());
128     }
129   }
130   MSAN_MALLOC_HOOK(allocated, size);
131   return allocated;
132 }
133 
MsanDeallocate(StackTrace * stack,void * p)134 void MsanDeallocate(StackTrace *stack, void *p) {
135   CHECK(p);
136   Init();
137   MSAN_FREE_HOOK(p);
138   Metadata *meta = reinterpret_cast<Metadata *>(allocator.GetMetaData(p));
139   uptr size = meta->requested_size;
140   meta->requested_size = 0;
141   // This memory will not be reused by anyone else, so we are free to keep it
142   // poisoned.
143   if (flags()->poison_in_free) {
144     __msan_poison(p, size);
145     if (__msan_get_track_origins()) {
146       stack->tag = StackTrace::TAG_DEALLOC;
147       Origin o = Origin::CreateHeapOrigin(stack);
148       __msan_set_origin(p, size, o.raw_id());
149     }
150   }
151   MsanThread *t = GetCurrentThread();
152   if (t) {
153     AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
154     allocator.Deallocate(cache, p);
155   } else {
156     SpinMutexLock l(&fallback_mutex);
157     AllocatorCache *cache = &fallback_allocator_cache;
158     allocator.Deallocate(cache, p);
159   }
160 }
161 
MsanCalloc(StackTrace * stack,uptr nmemb,uptr size)162 void *MsanCalloc(StackTrace *stack, uptr nmemb, uptr size) {
163   Init();
164   if (CallocShouldReturnNullDueToOverflow(size, nmemb))
165     return allocator.ReturnNullOrDie();
166   return MsanReallocate(stack, 0, nmemb * size, sizeof(u64), true);
167 }
168 
MsanReallocate(StackTrace * stack,void * old_p,uptr new_size,uptr alignment,bool zeroise)169 void *MsanReallocate(StackTrace *stack, void *old_p, uptr new_size,
170                      uptr alignment, bool zeroise) {
171   if (!old_p)
172     return MsanAllocate(stack, new_size, alignment, zeroise);
173   if (!new_size) {
174     MsanDeallocate(stack, old_p);
175     return 0;
176   }
177   Metadata *meta = reinterpret_cast<Metadata*>(allocator.GetMetaData(old_p));
178   uptr old_size = meta->requested_size;
179   uptr actually_allocated_size = allocator.GetActuallyAllocatedSize(old_p);
180   if (new_size <= actually_allocated_size) {
181     // We are not reallocating here.
182     meta->requested_size = new_size;
183     if (new_size > old_size) {
184       if (zeroise) {
185         __msan_clear_and_unpoison((char *)old_p + old_size,
186                                   new_size - old_size);
187       } else if (flags()->poison_in_malloc) {
188         stack->tag = StackTrace::TAG_ALLOC;
189         PoisonMemory((char *)old_p + old_size, new_size - old_size, stack);
190       }
191     }
192     return old_p;
193   }
194   uptr memcpy_size = Min(new_size, old_size);
195   void *new_p = MsanAllocate(stack, new_size, alignment, zeroise);
196   // Printf("realloc: old_size %zd new_size %zd\n", old_size, new_size);
197   if (new_p) {
198     CopyMemory(new_p, old_p, memcpy_size, stack);
199     MsanDeallocate(stack, old_p);
200   }
201   return new_p;
202 }
203 
AllocationSize(const void * p)204 static uptr AllocationSize(const void *p) {
205   if (p == 0) return 0;
206   const void *beg = allocator.GetBlockBegin(p);
207   if (beg != p) return 0;
208   Metadata *b = (Metadata *)allocator.GetMetaData(p);
209   return b->requested_size;
210 }
211 
212 }  // namespace __msan
213 
214 using namespace __msan;
215 
__sanitizer_get_current_allocated_bytes()216 uptr __sanitizer_get_current_allocated_bytes() {
217   uptr stats[AllocatorStatCount];
218   allocator.GetStats(stats);
219   return stats[AllocatorStatAllocated];
220 }
221 
__sanitizer_get_heap_size()222 uptr __sanitizer_get_heap_size() {
223   uptr stats[AllocatorStatCount];
224   allocator.GetStats(stats);
225   return stats[AllocatorStatMapped];
226 }
227 
__sanitizer_get_free_bytes()228 uptr __sanitizer_get_free_bytes() { return 1; }
229 
__sanitizer_get_unmapped_bytes()230 uptr __sanitizer_get_unmapped_bytes() { return 1; }
231 
__sanitizer_get_estimated_allocated_size(uptr size)232 uptr __sanitizer_get_estimated_allocated_size(uptr size) { return size; }
233 
__sanitizer_get_ownership(const void * p)234 int __sanitizer_get_ownership(const void *p) { return AllocationSize(p) != 0; }
235 
__sanitizer_get_allocated_size(const void * p)236 uptr __sanitizer_get_allocated_size(const void *p) { return AllocationSize(p); }
237