]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/msan/msan_allocator.cc
MFV r328245: 8856 arc_cksum_is_equal() doesn't take into account ABD-logic
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / msan / msan_allocator.cc
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_checks.h"
17 #include "sanitizer_common/sanitizer_allocator_interface.h"
18 #include "sanitizer_common/sanitizer_errno.h"
19 #include "msan.h"
20 #include "msan_allocator.h"
21 #include "msan_origin.h"
22 #include "msan_thread.h"
23 #include "msan_poisoning.h"
24
25 namespace __msan {
26
27 struct Metadata {
28   uptr requested_size;
29 };
30
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);
35
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);
43     }
44   }
45 };
46
47 #if defined(__mips64)
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;
52
53   struct AP32 {
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;
62   };
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;
68 #else
69   static const uptr kAllocatorSpace = 0x600000000000ULL;
70 #endif
71   static const uptr kMaxAllowedMallocSize = 8UL << 30;
72
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;
80   };
81
82   typedef SizeClassAllocator64<AP64> PrimaryAllocator;
83
84 #elif defined(__powerpc64__)
85   static const uptr kMaxAllowedMallocSize = 2UL << 30;  // 2G
86
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;
94   };
95
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;
102
103   struct AP32 {
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;
112   };
113   typedef SizeClassAllocator32<AP32> PrimaryAllocator;
114 #endif
115 typedef SizeClassAllocatorLocalCache<PrimaryAllocator> AllocatorCache;
116 typedef LargeMmapAllocator<MsanMapUnmapCallback> SecondaryAllocator;
117 typedef CombinedAllocator<PrimaryAllocator, AllocatorCache,
118                           SecondaryAllocator> Allocator;
119
120 static Allocator allocator;
121 static AllocatorCache fallback_allocator_cache;
122 static SpinMutex fallback_mutex;
123
124 void MsanAllocatorInit() {
125   SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null);
126   allocator.Init(common_flags()->allocator_release_to_os_interval_ms);
127 }
128
129 AllocatorCache *GetAllocatorCache(MsanThreadLocalMallocStorage *ms) {
130   CHECK(ms);
131   CHECK_LE(sizeof(AllocatorCache), sizeof(ms->allocator_cache));
132   return reinterpret_cast<AllocatorCache *>(ms->allocator_cache);
133 }
134
135 void MsanThreadLocalMallocStorage::CommitBack() {
136   allocator.SwallowCache(GetAllocatorCache(this));
137 }
138
139 static void *MsanAllocate(StackTrace *stack, uptr size, uptr alignment,
140                           bool zeroise) {
141   if (size > kMaxAllowedMallocSize) {
142     Report("WARNING: MemorySanitizer failed to allocate %p bytes\n",
143            (void *)size);
144     return Allocator::FailureHandler::OnBadRequest();
145   }
146   MsanThread *t = GetCurrentThread();
147   void *allocated;
148   if (t) {
149     AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
150     allocated = allocator.Allocate(cache, size, alignment);
151   } else {
152     SpinMutexLock l(&fallback_mutex);
153     AllocatorCache *cache = &fallback_allocator_cache;
154     allocated = allocator.Allocate(cache, size, alignment);
155   }
156   Metadata *meta =
157       reinterpret_cast<Metadata *>(allocator.GetMetaData(allocated));
158   meta->requested_size = size;
159   if (zeroise) {
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());
167     }
168   }
169   MSAN_MALLOC_HOOK(allocated, size);
170   return allocated;
171 }
172
173 void MsanDeallocate(StackTrace *stack, void *p) {
174   CHECK(p);
175   MSAN_FREE_HOOK(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
180   // poisoned.
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());
187     }
188   }
189   MsanThread *t = GetCurrentThread();
190   if (t) {
191     AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
192     allocator.Deallocate(cache, p);
193   } else {
194     SpinMutexLock l(&fallback_mutex);
195     AllocatorCache *cache = &fallback_allocator_cache;
196     allocator.Deallocate(cache, p);
197   }
198 }
199
200 void *MsanReallocate(StackTrace *stack, void *old_p, uptr new_size,
201                      uptr alignment) {
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);
212       }
213     }
214     return old_p;
215   }
216   uptr memcpy_size = Min(new_size, old_size);
217   void *new_p = MsanAllocate(stack, new_size, alignment, false /*zeroise*/);
218   if (new_p) {
219     CopyMemory(new_p, old_p, memcpy_size, stack);
220     MsanDeallocate(stack, old_p);
221   }
222   return new_p;
223 }
224
225 static uptr AllocationSize(const void *p) {
226   if (!p) return 0;
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;
231 }
232
233 void *msan_malloc(uptr size, StackTrace *stack) {
234   return SetErrnoOnNull(MsanAllocate(stack, size, sizeof(u64), false));
235 }
236
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));
241 }
242
243 void *msan_realloc(void *ptr, uptr size, StackTrace *stack) {
244   if (!ptr)
245     return SetErrnoOnNull(MsanAllocate(stack, size, sizeof(u64), false));
246   if (size == 0) {
247     MsanDeallocate(stack, ptr);
248     return nullptr;
249   }
250   return SetErrnoOnNull(MsanReallocate(stack, ptr, size, sizeof(u64)));
251 }
252
253 void *msan_valloc(uptr size, StackTrace *stack) {
254   return SetErrnoOnNull(MsanAllocate(stack, size, GetPageSizeCached(), false));
255 }
256
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();
262   }
263   // pvalloc(0) should allocate one page.
264   size = size ? RoundUpTo(size, PageSize) : PageSize;
265   return SetErrnoOnNull(MsanAllocate(stack, size, PageSize, false));
266 }
267
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();
272   }
273   return SetErrnoOnNull(MsanAllocate(stack, size, alignment, false));
274 }
275
276 void *msan_memalign(uptr alignment, uptr size, StackTrace *stack) {
277   if (UNLIKELY(!IsPowerOfTwo(alignment))) {
278     errno = errno_EINVAL;
279     return Allocator::FailureHandler::OnBadRequest();
280   }
281   return SetErrnoOnNull(MsanAllocate(stack, size, alignment, false));
282 }
283
284 int msan_posix_memalign(void **memptr, uptr alignment, uptr size,
285                         StackTrace *stack) {
286   if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) {
287     Allocator::FailureHandler::OnBadRequest();
288     return errno_EINVAL;
289   }
290   void *ptr = MsanAllocate(stack, size, alignment, false);
291   if (UNLIKELY(!ptr))
292     return errno_ENOMEM;
293   CHECK(IsAligned((uptr)ptr, alignment));
294   *memptr = ptr;
295   return 0;
296 }
297
298 } // namespace __msan
299
300 using namespace __msan;
301
302 uptr __sanitizer_get_current_allocated_bytes() {
303   uptr stats[AllocatorStatCount];
304   allocator.GetStats(stats);
305   return stats[AllocatorStatAllocated];
306 }
307
308 uptr __sanitizer_get_heap_size() {
309   uptr stats[AllocatorStatCount];
310   allocator.GetStats(stats);
311   return stats[AllocatorStatMapped];
312 }
313
314 uptr __sanitizer_get_free_bytes() { return 1; }
315
316 uptr __sanitizer_get_unmapped_bytes() { return 1; }
317
318 uptr __sanitizer_get_estimated_allocated_size(uptr size) { return size; }
319
320 int __sanitizer_get_ownership(const void *p) { return AllocationSize(p) != 0; }
321
322 uptr __sanitizer_get_allocated_size(const void *p) { return AllocationSize(p); }