]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/msan/msan_allocator.cc
Merge ^/head r318964 through r319164.
[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_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 {
30   void OnMap(uptr p, uptr size) const {}
31   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     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);
41     }
42   }
43 };
44
45 #if defined(__mips64)
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;
50
51   struct AP32 {
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;
60   };
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;
65 #else
66   static const uptr kAllocatorSpace = 0x600000000000ULL;
67 #endif
68   static const uptr kMaxAllowedMallocSize = 8UL << 30;
69
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;
77   };
78
79   typedef SizeClassAllocator64<AP64> PrimaryAllocator;
80
81 #elif defined(__powerpc64__)
82   static const uptr kMaxAllowedMallocSize = 2UL << 30;  // 2G
83
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;
91   };
92
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;
99
100   struct AP32 {
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;
109   };
110   typedef SizeClassAllocator32<AP32> PrimaryAllocator;
111 #endif
112 typedef SizeClassAllocatorLocalCache<PrimaryAllocator> AllocatorCache;
113 typedef LargeMmapAllocator<MsanMapUnmapCallback> SecondaryAllocator;
114 typedef CombinedAllocator<PrimaryAllocator, AllocatorCache,
115                           SecondaryAllocator> Allocator;
116
117 static Allocator allocator;
118 static AllocatorCache fallback_allocator_cache;
119 static SpinMutex fallback_mutex;
120
121 void MsanAllocatorInit() {
122   allocator.Init(
123       common_flags()->allocator_may_return_null,
124       common_flags()->allocator_release_to_os_interval_ms);
125 }
126
127 AllocatorCache *GetAllocatorCache(MsanThreadLocalMallocStorage *ms) {
128   CHECK(ms);
129   CHECK_LE(sizeof(AllocatorCache), sizeof(ms->allocator_cache));
130   return reinterpret_cast<AllocatorCache *>(ms->allocator_cache);
131 }
132
133 void MsanThreadLocalMallocStorage::CommitBack() {
134   allocator.SwallowCache(GetAllocatorCache(this));
135 }
136
137 static void *MsanAllocate(StackTrace *stack, uptr size, uptr alignment,
138                           bool zeroise) {
139   if (size > kMaxAllowedMallocSize) {
140     Report("WARNING: MemorySanitizer failed to allocate %p bytes\n",
141            (void *)size);
142     return allocator.ReturnNullOrDieOnBadRequest();
143   }
144   MsanThread *t = GetCurrentThread();
145   void *allocated;
146   if (t) {
147     AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
148     allocated = allocator.Allocate(cache, size, alignment, false);
149   } else {
150     SpinMutexLock l(&fallback_mutex);
151     AllocatorCache *cache = &fallback_allocator_cache;
152     allocated = allocator.Allocate(cache, size, alignment, false);
153   }
154   Metadata *meta =
155       reinterpret_cast<Metadata *>(allocator.GetMetaData(allocated));
156   meta->requested_size = size;
157   if (zeroise) {
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());
165     }
166   }
167   MSAN_MALLOC_HOOK(allocated, size);
168   return allocated;
169 }
170
171 void MsanDeallocate(StackTrace *stack, void *p) {
172   CHECK(p);
173   MSAN_FREE_HOOK(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
178   // poisoned.
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());
185     }
186   }
187   MsanThread *t = GetCurrentThread();
188   if (t) {
189     AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
190     allocator.Deallocate(cache, p);
191   } else {
192     SpinMutexLock l(&fallback_mutex);
193     AllocatorCache *cache = &fallback_allocator_cache;
194     allocator.Deallocate(cache, p);
195   }
196 }
197
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);
202 }
203
204 void *MsanReallocate(StackTrace *stack, void *old_p, uptr new_size,
205                      uptr alignment, bool zeroise) {
206   if (!old_p)
207     return MsanAllocate(stack, new_size, alignment, zeroise);
208   if (!new_size) {
209     MsanDeallocate(stack, old_p);
210     return nullptr;
211   }
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) {
219       if (zeroise) {
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);
225       }
226     }
227     return old_p;
228   }
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);
232   if (new_p) {
233     CopyMemory(new_p, old_p, memcpy_size, stack);
234     MsanDeallocate(stack, old_p);
235   }
236   return new_p;
237 }
238
239 static uptr AllocationSize(const void *p) {
240   if (!p) return 0;
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;
245 }
246
247 } // namespace __msan
248
249 using namespace __msan;
250
251 uptr __sanitizer_get_current_allocated_bytes() {
252   uptr stats[AllocatorStatCount];
253   allocator.GetStats(stats);
254   return stats[AllocatorStatAllocated];
255 }
256
257 uptr __sanitizer_get_heap_size() {
258   uptr stats[AllocatorStatCount];
259   allocator.GetStats(stats);
260   return stats[AllocatorStatMapped];
261 }
262
263 uptr __sanitizer_get_free_bytes() { return 1; }
264
265 uptr __sanitizer_get_unmapped_bytes() { return 1; }
266
267 uptr __sanitizer_get_estimated_allocated_size(uptr size) { return size; }
268
269 int __sanitizer_get_ownership(const void *p) { return AllocationSize(p) != 0; }
270
271 uptr __sanitizer_get_allocated_size(const void *p) { return AllocationSize(p); }