xref: /freebsd/contrib/llvm-project/compiler-rt/lib/msan/msan_allocator.cpp (revision 5f757f3ff9144b609b3c433dfd370cc6bdc191ad)
1 //===-- msan_allocator.cpp -------------------------- ---------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is a part of MemorySanitizer.
10 //
11 // MemorySanitizer allocator.
12 //===----------------------------------------------------------------------===//
13 
14 #include "msan_allocator.h"
15 
16 #include "msan.h"
17 #include "msan_interface_internal.h"
18 #include "msan_origin.h"
19 #include "msan_poisoning.h"
20 #include "msan_thread.h"
21 #include "sanitizer_common/sanitizer_allocator.h"
22 #include "sanitizer_common/sanitizer_allocator_checks.h"
23 #include "sanitizer_common/sanitizer_allocator_interface.h"
24 #include "sanitizer_common/sanitizer_allocator_report.h"
25 #include "sanitizer_common/sanitizer_errno.h"
26 
27 namespace __msan {
28 
29 struct Metadata {
30   uptr requested_size;
31 };
32 
33 struct MsanMapUnmapCallback {
34   void OnMap(uptr p, uptr size) const {}
35   void OnMapSecondary(uptr p, uptr size, uptr user_begin,
36                       uptr user_size) const {}
37   void OnUnmap(uptr p, uptr size) const {
38     __msan_unpoison((void *)p, size);
39 
40     // We are about to unmap a chunk of user memory.
41     // Mark the corresponding shadow memory as not needed.
42     uptr shadow_p = MEM_TO_SHADOW(p);
43     ReleaseMemoryPagesToOS(shadow_p, shadow_p + size);
44     if (__msan_get_track_origins()) {
45       uptr origin_p = MEM_TO_ORIGIN(p);
46       ReleaseMemoryPagesToOS(origin_p, origin_p + size);
47     }
48   }
49 };
50 
51 #if defined(__mips64)
52 static const uptr kMaxAllowedMallocSize = 2UL << 30;
53 
54 struct AP32 {
55   static const uptr kSpaceBeg = 0;
56   static const u64 kSpaceSize = SANITIZER_MMAP_RANGE_SIZE;
57   static const uptr kMetadataSize = sizeof(Metadata);
58   typedef __sanitizer::CompactSizeClassMap SizeClassMap;
59   static const uptr kRegionSizeLog = 20;
60   using AddressSpaceView = LocalAddressSpaceView;
61   typedef MsanMapUnmapCallback MapUnmapCallback;
62   static const uptr kFlags = 0;
63 };
64 typedef SizeClassAllocator32<AP32> PrimaryAllocator;
65 #elif defined(__x86_64__)
66 #if SANITIZER_NETBSD || SANITIZER_LINUX
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   using AddressSpaceView = LocalAddressSpaceView;
81 };
82 
83 typedef SizeClassAllocator64<AP64> PrimaryAllocator;
84 
85 #elif defined(__loongarch_lp64)
86 const uptr kAllocatorSpace = 0x700000000000ULL;
87 const uptr kMaxAllowedMallocSize = 8UL << 30;
88 
89 struct AP64 {  // Allocator64 parameters. Deliberately using a short name.
90   static const uptr kSpaceBeg = kAllocatorSpace;
91   static const uptr kSpaceSize = 0x40000000000;  // 4T.
92   static const uptr kMetadataSize = sizeof(Metadata);
93   typedef DefaultSizeClassMap SizeClassMap;
94   typedef MsanMapUnmapCallback MapUnmapCallback;
95   static const uptr kFlags = 0;
96   using AddressSpaceView = LocalAddressSpaceView;
97 };
98 
99 typedef SizeClassAllocator64<AP64> PrimaryAllocator;
100 
101 #elif defined(__powerpc64__)
102 static const uptr kMaxAllowedMallocSize = 2UL << 30;  // 2G
103 
104 struct AP64 {  // Allocator64 parameters. Deliberately using a short name.
105   static const uptr kSpaceBeg = 0x300000000000;
106   static const uptr kSpaceSize = 0x020000000000;  // 2T.
107   static const uptr kMetadataSize = sizeof(Metadata);
108   typedef DefaultSizeClassMap SizeClassMap;
109   typedef MsanMapUnmapCallback MapUnmapCallback;
110   static const uptr kFlags = 0;
111   using AddressSpaceView = LocalAddressSpaceView;
112 };
113 
114 typedef SizeClassAllocator64<AP64> PrimaryAllocator;
115 #elif defined(__s390x__)
116 static const uptr kMaxAllowedMallocSize = 2UL << 30;  // 2G
117 
118 struct AP64 {  // Allocator64 parameters. Deliberately using a short name.
119   static const uptr kSpaceBeg = 0x440000000000;
120   static const uptr kSpaceSize = 0x020000000000;  // 2T.
121   static const uptr kMetadataSize = sizeof(Metadata);
122   typedef DefaultSizeClassMap SizeClassMap;
123   typedef MsanMapUnmapCallback MapUnmapCallback;
124   static const uptr kFlags = 0;
125   using AddressSpaceView = LocalAddressSpaceView;
126 };
127 
128 typedef SizeClassAllocator64<AP64> PrimaryAllocator;
129 #elif defined(__aarch64__)
130 static const uptr kMaxAllowedMallocSize = 8UL << 30;
131 
132 struct AP64 {
133   static const uptr kSpaceBeg = 0xE00000000000ULL;
134   static const uptr kSpaceSize = 0x40000000000;  // 4T.
135   static const uptr kMetadataSize = sizeof(Metadata);
136   typedef DefaultSizeClassMap SizeClassMap;
137   typedef MsanMapUnmapCallback MapUnmapCallback;
138   static const uptr kFlags = 0;
139   using AddressSpaceView = LocalAddressSpaceView;
140 };
141 typedef SizeClassAllocator64<AP64> PrimaryAllocator;
142 #endif
143 typedef CombinedAllocator<PrimaryAllocator> Allocator;
144 typedef Allocator::AllocatorCache AllocatorCache;
145 
146 static Allocator allocator;
147 static AllocatorCache fallback_allocator_cache;
148 static StaticSpinMutex fallback_mutex;
149 
150 static uptr max_malloc_size;
151 
152 void MsanAllocatorInit() {
153   SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null);
154   allocator.Init(common_flags()->allocator_release_to_os_interval_ms);
155   if (common_flags()->max_allocation_size_mb)
156     max_malloc_size = Min(common_flags()->max_allocation_size_mb << 20,
157                           kMaxAllowedMallocSize);
158   else
159     max_malloc_size = kMaxAllowedMallocSize;
160 }
161 
162 void LockAllocator() { allocator.ForceLock(); }
163 
164 void UnlockAllocator() { allocator.ForceUnlock(); }
165 
166 AllocatorCache *GetAllocatorCache(MsanThreadLocalMallocStorage *ms) {
167   CHECK(ms);
168   CHECK_LE(sizeof(AllocatorCache), sizeof(ms->allocator_cache));
169   return reinterpret_cast<AllocatorCache *>(ms->allocator_cache);
170 }
171 
172 void MsanThreadLocalMallocStorage::Init() {
173   allocator.InitCache(GetAllocatorCache(this));
174 }
175 
176 void MsanThreadLocalMallocStorage::CommitBack() {
177   allocator.SwallowCache(GetAllocatorCache(this));
178   allocator.DestroyCache(GetAllocatorCache(this));
179 }
180 
181 static void *MsanAllocate(StackTrace *stack, uptr size, uptr alignment,
182                           bool zeroise) {
183   if (size > max_malloc_size) {
184     if (AllocatorMayReturnNull()) {
185       Report("WARNING: MemorySanitizer failed to allocate 0x%zx bytes\n", size);
186       return nullptr;
187     }
188     ReportAllocationSizeTooBig(size, max_malloc_size, stack);
189   }
190   if (UNLIKELY(IsRssLimitExceeded())) {
191     if (AllocatorMayReturnNull())
192       return nullptr;
193     ReportRssLimitExceeded(stack);
194   }
195   MsanThread *t = GetCurrentThread();
196   void *allocated;
197   if (t) {
198     AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
199     allocated = allocator.Allocate(cache, size, alignment);
200   } else {
201     SpinMutexLock l(&fallback_mutex);
202     AllocatorCache *cache = &fallback_allocator_cache;
203     allocated = allocator.Allocate(cache, size, alignment);
204   }
205   if (UNLIKELY(!allocated)) {
206     SetAllocatorOutOfMemory();
207     if (AllocatorMayReturnNull())
208       return nullptr;
209     ReportOutOfMemory(size, stack);
210   }
211   Metadata *meta =
212       reinterpret_cast<Metadata *>(allocator.GetMetaData(allocated));
213   meta->requested_size = size;
214   if (zeroise) {
215     if (allocator.FromPrimary(allocated))
216       __msan_clear_and_unpoison(allocated, size);
217     else
218       __msan_unpoison(allocated, size);  // Mem is already zeroed.
219   } else if (flags()->poison_in_malloc) {
220     __msan_poison(allocated, size);
221     if (__msan_get_track_origins()) {
222       stack->tag = StackTrace::TAG_ALLOC;
223       Origin o = Origin::CreateHeapOrigin(stack);
224       __msan_set_origin(allocated, size, o.raw_id());
225     }
226   }
227   UnpoisonParam(2);
228   RunMallocHooks(allocated, size);
229   return allocated;
230 }
231 
232 void MsanDeallocate(StackTrace *stack, void *p) {
233   CHECK(p);
234   UnpoisonParam(1);
235   RunFreeHooks(p);
236 
237   Metadata *meta = reinterpret_cast<Metadata *>(allocator.GetMetaData(p));
238   uptr size = meta->requested_size;
239   meta->requested_size = 0;
240   // This memory will not be reused by anyone else, so we are free to keep it
241   // poisoned. The secondary allocator will unmap and unpoison by
242   // MsanMapUnmapCallback, no need to poison it here.
243   if (flags()->poison_in_free && allocator.FromPrimary(p)) {
244     __msan_poison(p, size);
245     if (__msan_get_track_origins()) {
246       stack->tag = StackTrace::TAG_DEALLOC;
247       Origin o = Origin::CreateHeapOrigin(stack);
248       __msan_set_origin(p, size, o.raw_id());
249     }
250   }
251   MsanThread *t = GetCurrentThread();
252   if (t) {
253     AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
254     allocator.Deallocate(cache, p);
255   } else {
256     SpinMutexLock l(&fallback_mutex);
257     AllocatorCache *cache = &fallback_allocator_cache;
258     allocator.Deallocate(cache, p);
259   }
260 }
261 
262 static void *MsanReallocate(StackTrace *stack, void *old_p, uptr new_size,
263                             uptr alignment) {
264   Metadata *meta = reinterpret_cast<Metadata*>(allocator.GetMetaData(old_p));
265   uptr old_size = meta->requested_size;
266   uptr actually_allocated_size = allocator.GetActuallyAllocatedSize(old_p);
267   if (new_size <= actually_allocated_size) {
268     // We are not reallocating here.
269     meta->requested_size = new_size;
270     if (new_size > old_size) {
271       if (flags()->poison_in_malloc) {
272         stack->tag = StackTrace::TAG_ALLOC;
273         PoisonMemory((char *)old_p + old_size, new_size - old_size, stack);
274       }
275     }
276     return old_p;
277   }
278   uptr memcpy_size = Min(new_size, old_size);
279   void *new_p = MsanAllocate(stack, new_size, alignment, false /*zeroise*/);
280   if (new_p) {
281     CopyMemory(new_p, old_p, memcpy_size, stack);
282     MsanDeallocate(stack, old_p);
283   }
284   return new_p;
285 }
286 
287 static void *MsanCalloc(StackTrace *stack, uptr nmemb, uptr size) {
288   if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
289     if (AllocatorMayReturnNull())
290       return nullptr;
291     ReportCallocOverflow(nmemb, size, stack);
292   }
293   return MsanAllocate(stack, nmemb * size, sizeof(u64), true);
294 }
295 
296 static const void *AllocationBegin(const void *p) {
297   if (!p)
298     return nullptr;
299   void *beg = allocator.GetBlockBegin(p);
300   if (!beg)
301     return nullptr;
302   Metadata *b = (Metadata *)allocator.GetMetaData(beg);
303   if (!b)
304     return nullptr;
305   if (b->requested_size == 0)
306     return nullptr;
307 
308   return (const void *)beg;
309 }
310 
311 static uptr AllocationSize(const void *p) {
312   if (!p) return 0;
313   const void *beg = allocator.GetBlockBegin(p);
314   if (beg != p) return 0;
315   Metadata *b = (Metadata *)allocator.GetMetaData(p);
316   return b->requested_size;
317 }
318 
319 static uptr AllocationSizeFast(const void *p) {
320   return reinterpret_cast<Metadata *>(allocator.GetMetaData(p))->requested_size;
321 }
322 
323 void *msan_malloc(uptr size, StackTrace *stack) {
324   return SetErrnoOnNull(MsanAllocate(stack, size, sizeof(u64), false));
325 }
326 
327 void *msan_calloc(uptr nmemb, uptr size, StackTrace *stack) {
328   return SetErrnoOnNull(MsanCalloc(stack, nmemb, size));
329 }
330 
331 void *msan_realloc(void *ptr, uptr size, StackTrace *stack) {
332   if (!ptr)
333     return SetErrnoOnNull(MsanAllocate(stack, size, sizeof(u64), false));
334   if (size == 0) {
335     MsanDeallocate(stack, ptr);
336     return nullptr;
337   }
338   return SetErrnoOnNull(MsanReallocate(stack, ptr, size, sizeof(u64)));
339 }
340 
341 void *msan_reallocarray(void *ptr, uptr nmemb, uptr size, StackTrace *stack) {
342   if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
343     errno = errno_ENOMEM;
344     if (AllocatorMayReturnNull())
345       return nullptr;
346     ReportReallocArrayOverflow(nmemb, size, stack);
347   }
348   return msan_realloc(ptr, nmemb * size, stack);
349 }
350 
351 void *msan_valloc(uptr size, StackTrace *stack) {
352   return SetErrnoOnNull(MsanAllocate(stack, size, GetPageSizeCached(), false));
353 }
354 
355 void *msan_pvalloc(uptr size, StackTrace *stack) {
356   uptr PageSize = GetPageSizeCached();
357   if (UNLIKELY(CheckForPvallocOverflow(size, PageSize))) {
358     errno = errno_ENOMEM;
359     if (AllocatorMayReturnNull())
360       return nullptr;
361     ReportPvallocOverflow(size, stack);
362   }
363   // pvalloc(0) should allocate one page.
364   size = size ? RoundUpTo(size, PageSize) : PageSize;
365   return SetErrnoOnNull(MsanAllocate(stack, size, PageSize, false));
366 }
367 
368 void *msan_aligned_alloc(uptr alignment, uptr size, StackTrace *stack) {
369   if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(alignment, size))) {
370     errno = errno_EINVAL;
371     if (AllocatorMayReturnNull())
372       return nullptr;
373     ReportInvalidAlignedAllocAlignment(size, alignment, stack);
374   }
375   return SetErrnoOnNull(MsanAllocate(stack, size, alignment, false));
376 }
377 
378 void *msan_memalign(uptr alignment, uptr size, StackTrace *stack) {
379   if (UNLIKELY(!IsPowerOfTwo(alignment))) {
380     errno = errno_EINVAL;
381     if (AllocatorMayReturnNull())
382       return nullptr;
383     ReportInvalidAllocationAlignment(alignment, stack);
384   }
385   return SetErrnoOnNull(MsanAllocate(stack, size, alignment, false));
386 }
387 
388 int msan_posix_memalign(void **memptr, uptr alignment, uptr size,
389                         StackTrace *stack) {
390   if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) {
391     if (AllocatorMayReturnNull())
392       return errno_EINVAL;
393     ReportInvalidPosixMemalignAlignment(alignment, stack);
394   }
395   void *ptr = MsanAllocate(stack, size, alignment, false);
396   if (UNLIKELY(!ptr))
397     // OOM error is already taken care of by MsanAllocate.
398     return errno_ENOMEM;
399   CHECK(IsAligned((uptr)ptr, alignment));
400   *memptr = ptr;
401   return 0;
402 }
403 
404 } // namespace __msan
405 
406 using namespace __msan;
407 
408 uptr __sanitizer_get_current_allocated_bytes() {
409   uptr stats[AllocatorStatCount];
410   allocator.GetStats(stats);
411   return stats[AllocatorStatAllocated];
412 }
413 
414 uptr __sanitizer_get_heap_size() {
415   uptr stats[AllocatorStatCount];
416   allocator.GetStats(stats);
417   return stats[AllocatorStatMapped];
418 }
419 
420 uptr __sanitizer_get_free_bytes() { return 1; }
421 
422 uptr __sanitizer_get_unmapped_bytes() { return 1; }
423 
424 uptr __sanitizer_get_estimated_allocated_size(uptr size) { return size; }
425 
426 int __sanitizer_get_ownership(const void *p) { return AllocationSize(p) != 0; }
427 
428 const void *__sanitizer_get_allocated_begin(const void *p) {
429   return AllocationBegin(p);
430 }
431 
432 uptr __sanitizer_get_allocated_size(const void *p) { return AllocationSize(p); }
433 
434 uptr __sanitizer_get_allocated_size_fast(const void *p) {
435   DCHECK_EQ(p, __sanitizer_get_allocated_begin(p));
436   uptr ret = AllocationSizeFast(p);
437   DCHECK_EQ(ret, __sanitizer_get_allocated_size(p));
438   return ret;
439 }
440 
441 void __sanitizer_purge_allocator() { allocator.ForceReleaseToOS(); }
442