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 "sanitizer_common/sanitizer_allocator.h" 15 #include "sanitizer_common/sanitizer_allocator_checks.h" 16 #include "sanitizer_common/sanitizer_allocator_interface.h" 17 #include "sanitizer_common/sanitizer_allocator_report.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 50 struct AP32 { 51 static const uptr kSpaceBeg = 0; 52 static const u64 kSpaceSize = SANITIZER_MMAP_RANGE_SIZE; 53 static const uptr kMetadataSize = sizeof(Metadata); 54 typedef __sanitizer::CompactSizeClassMap SizeClassMap; 55 static const uptr kRegionSizeLog = 20; 56 using AddressSpaceView = LocalAddressSpaceView; 57 typedef MsanMapUnmapCallback MapUnmapCallback; 58 static const uptr kFlags = 0; 59 }; 60 typedef SizeClassAllocator32<AP32> PrimaryAllocator; 61 #elif defined(__x86_64__) 62 #if SANITIZER_NETBSD || \ 63 (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 using AddressSpaceView = LocalAddressSpaceView; 78 }; 79 80 typedef SizeClassAllocator64<AP64> PrimaryAllocator; 81 82 #elif defined(__powerpc64__) 83 static const uptr kMaxAllowedMallocSize = 2UL << 30; // 2G 84 85 struct AP64 { // Allocator64 parameters. Deliberately using a short name. 86 static const uptr kSpaceBeg = 0x300000000000; 87 static const uptr kSpaceSize = 0x020000000000; // 2T. 88 static const uptr kMetadataSize = sizeof(Metadata); 89 typedef DefaultSizeClassMap SizeClassMap; 90 typedef MsanMapUnmapCallback MapUnmapCallback; 91 static const uptr kFlags = 0; 92 using AddressSpaceView = LocalAddressSpaceView; 93 }; 94 95 typedef SizeClassAllocator64<AP64> PrimaryAllocator; 96 #elif defined(__aarch64__) 97 static const uptr kMaxAllowedMallocSize = 2UL << 30; // 2G 98 99 struct AP32 { 100 static const uptr kSpaceBeg = 0; 101 static const u64 kSpaceSize = SANITIZER_MMAP_RANGE_SIZE; 102 static const uptr kMetadataSize = sizeof(Metadata); 103 typedef __sanitizer::CompactSizeClassMap SizeClassMap; 104 static const uptr kRegionSizeLog = 20; 105 using AddressSpaceView = LocalAddressSpaceView; 106 typedef MsanMapUnmapCallback MapUnmapCallback; 107 static const uptr kFlags = 0; 108 }; 109 typedef SizeClassAllocator32<AP32> PrimaryAllocator; 110 #endif 111 typedef CombinedAllocator<PrimaryAllocator> Allocator; 112 typedef Allocator::AllocatorCache AllocatorCache; 113 114 static Allocator allocator; 115 static AllocatorCache fallback_allocator_cache; 116 static StaticSpinMutex fallback_mutex; 117 118 void MsanAllocatorInit() { 119 SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null); 120 allocator.Init(common_flags()->allocator_release_to_os_interval_ms); 121 } 122 123 AllocatorCache *GetAllocatorCache(MsanThreadLocalMallocStorage *ms) { 124 CHECK(ms); 125 CHECK_LE(sizeof(AllocatorCache), sizeof(ms->allocator_cache)); 126 return reinterpret_cast<AllocatorCache *>(ms->allocator_cache); 127 } 128 129 void MsanThreadLocalMallocStorage::CommitBack() { 130 allocator.SwallowCache(GetAllocatorCache(this)); 131 } 132 133 static void *MsanAllocate(StackTrace *stack, uptr size, uptr alignment, 134 bool zeroise) { 135 if (size > kMaxAllowedMallocSize) { 136 if (AllocatorMayReturnNull()) { 137 Report("WARNING: MemorySanitizer failed to allocate 0x%zx bytes\n", size); 138 return nullptr; 139 } 140 ReportAllocationSizeTooBig(size, kMaxAllowedMallocSize, stack); 141 } 142 MsanThread *t = GetCurrentThread(); 143 void *allocated; 144 if (t) { 145 AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage()); 146 allocated = allocator.Allocate(cache, size, alignment); 147 } else { 148 SpinMutexLock l(&fallback_mutex); 149 AllocatorCache *cache = &fallback_allocator_cache; 150 allocated = allocator.Allocate(cache, size, alignment); 151 } 152 if (UNLIKELY(!allocated)) { 153 SetAllocatorOutOfMemory(); 154 if (AllocatorMayReturnNull()) 155 return nullptr; 156 ReportOutOfMemory(size, stack); 157 } 158 Metadata *meta = 159 reinterpret_cast<Metadata *>(allocator.GetMetaData(allocated)); 160 meta->requested_size = size; 161 if (zeroise) { 162 __msan_clear_and_unpoison(allocated, size); 163 } else if (flags()->poison_in_malloc) { 164 __msan_poison(allocated, size); 165 if (__msan_get_track_origins()) { 166 stack->tag = StackTrace::TAG_ALLOC; 167 Origin o = Origin::CreateHeapOrigin(stack); 168 __msan_set_origin(allocated, size, o.raw_id()); 169 } 170 } 171 MSAN_MALLOC_HOOK(allocated, size); 172 return allocated; 173 } 174 175 void MsanDeallocate(StackTrace *stack, void *p) { 176 CHECK(p); 177 MSAN_FREE_HOOK(p); 178 Metadata *meta = reinterpret_cast<Metadata *>(allocator.GetMetaData(p)); 179 uptr size = meta->requested_size; 180 meta->requested_size = 0; 181 // This memory will not be reused by anyone else, so we are free to keep it 182 // poisoned. 183 if (flags()->poison_in_free) { 184 __msan_poison(p, size); 185 if (__msan_get_track_origins()) { 186 stack->tag = StackTrace::TAG_DEALLOC; 187 Origin o = Origin::CreateHeapOrigin(stack); 188 __msan_set_origin(p, size, o.raw_id()); 189 } 190 } 191 MsanThread *t = GetCurrentThread(); 192 if (t) { 193 AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage()); 194 allocator.Deallocate(cache, p); 195 } else { 196 SpinMutexLock l(&fallback_mutex); 197 AllocatorCache *cache = &fallback_allocator_cache; 198 allocator.Deallocate(cache, p); 199 } 200 } 201 202 void *MsanReallocate(StackTrace *stack, void *old_p, uptr new_size, 203 uptr alignment) { 204 Metadata *meta = reinterpret_cast<Metadata*>(allocator.GetMetaData(old_p)); 205 uptr old_size = meta->requested_size; 206 uptr actually_allocated_size = allocator.GetActuallyAllocatedSize(old_p); 207 if (new_size <= actually_allocated_size) { 208 // We are not reallocating here. 209 meta->requested_size = new_size; 210 if (new_size > old_size) { 211 if (flags()->poison_in_malloc) { 212 stack->tag = StackTrace::TAG_ALLOC; 213 PoisonMemory((char *)old_p + old_size, new_size - old_size, stack); 214 } 215 } 216 return old_p; 217 } 218 uptr memcpy_size = Min(new_size, old_size); 219 void *new_p = MsanAllocate(stack, new_size, alignment, false /*zeroise*/); 220 if (new_p) { 221 CopyMemory(new_p, old_p, memcpy_size, stack); 222 MsanDeallocate(stack, old_p); 223 } 224 return new_p; 225 } 226 227 void *MsanCalloc(StackTrace *stack, uptr nmemb, uptr size) { 228 if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) { 229 if (AllocatorMayReturnNull()) 230 return nullptr; 231 ReportCallocOverflow(nmemb, size, stack); 232 } 233 return MsanAllocate(stack, nmemb * size, sizeof(u64), true); 234 } 235 236 static uptr AllocationSize(const void *p) { 237 if (!p) return 0; 238 const void *beg = allocator.GetBlockBegin(p); 239 if (beg != p) return 0; 240 Metadata *b = (Metadata *)allocator.GetMetaData(p); 241 return b->requested_size; 242 } 243 244 void *msan_malloc(uptr size, StackTrace *stack) { 245 return SetErrnoOnNull(MsanAllocate(stack, size, sizeof(u64), false)); 246 } 247 248 void *msan_calloc(uptr nmemb, uptr size, StackTrace *stack) { 249 return SetErrnoOnNull(MsanCalloc(stack, nmemb, size)); 250 } 251 252 void *msan_realloc(void *ptr, uptr size, StackTrace *stack) { 253 if (!ptr) 254 return SetErrnoOnNull(MsanAllocate(stack, size, sizeof(u64), false)); 255 if (size == 0) { 256 MsanDeallocate(stack, ptr); 257 return nullptr; 258 } 259 return SetErrnoOnNull(MsanReallocate(stack, ptr, size, sizeof(u64))); 260 } 261 262 void *msan_reallocarray(void *ptr, uptr nmemb, uptr size, StackTrace *stack) { 263 if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) { 264 errno = errno_ENOMEM; 265 if (AllocatorMayReturnNull()) 266 return nullptr; 267 ReportReallocArrayOverflow(nmemb, size, stack); 268 } 269 return msan_realloc(ptr, nmemb * size, stack); 270 } 271 272 void *msan_valloc(uptr size, StackTrace *stack) { 273 return SetErrnoOnNull(MsanAllocate(stack, size, GetPageSizeCached(), false)); 274 } 275 276 void *msan_pvalloc(uptr size, StackTrace *stack) { 277 uptr PageSize = GetPageSizeCached(); 278 if (UNLIKELY(CheckForPvallocOverflow(size, PageSize))) { 279 errno = errno_ENOMEM; 280 if (AllocatorMayReturnNull()) 281 return nullptr; 282 ReportPvallocOverflow(size, stack); 283 } 284 // pvalloc(0) should allocate one page. 285 size = size ? RoundUpTo(size, PageSize) : PageSize; 286 return SetErrnoOnNull(MsanAllocate(stack, size, PageSize, false)); 287 } 288 289 void *msan_aligned_alloc(uptr alignment, uptr size, StackTrace *stack) { 290 if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(alignment, size))) { 291 errno = errno_EINVAL; 292 if (AllocatorMayReturnNull()) 293 return nullptr; 294 ReportInvalidAlignedAllocAlignment(size, alignment, stack); 295 } 296 return SetErrnoOnNull(MsanAllocate(stack, size, alignment, false)); 297 } 298 299 void *msan_memalign(uptr alignment, uptr size, StackTrace *stack) { 300 if (UNLIKELY(!IsPowerOfTwo(alignment))) { 301 errno = errno_EINVAL; 302 if (AllocatorMayReturnNull()) 303 return nullptr; 304 ReportInvalidAllocationAlignment(alignment, stack); 305 } 306 return SetErrnoOnNull(MsanAllocate(stack, size, alignment, false)); 307 } 308 309 int msan_posix_memalign(void **memptr, uptr alignment, uptr size, 310 StackTrace *stack) { 311 if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) { 312 if (AllocatorMayReturnNull()) 313 return errno_EINVAL; 314 ReportInvalidPosixMemalignAlignment(alignment, stack); 315 } 316 void *ptr = MsanAllocate(stack, size, alignment, false); 317 if (UNLIKELY(!ptr)) 318 // OOM error is already taken care of by MsanAllocate. 319 return errno_ENOMEM; 320 CHECK(IsAligned((uptr)ptr, alignment)); 321 *memptr = ptr; 322 return 0; 323 } 324 325 } // namespace __msan 326 327 using namespace __msan; 328 329 uptr __sanitizer_get_current_allocated_bytes() { 330 uptr stats[AllocatorStatCount]; 331 allocator.GetStats(stats); 332 return stats[AllocatorStatAllocated]; 333 } 334 335 uptr __sanitizer_get_heap_size() { 336 uptr stats[AllocatorStatCount]; 337 allocator.GetStats(stats); 338 return stats[AllocatorStatMapped]; 339 } 340 341 uptr __sanitizer_get_free_bytes() { return 1; } 342 343 uptr __sanitizer_get_unmapped_bytes() { return 1; } 344 345 uptr __sanitizer_get_estimated_allocated_size(uptr size) { return size; } 346 347 int __sanitizer_get_ownership(const void *p) { return AllocationSize(p) != 0; } 348 349 uptr __sanitizer_get_allocated_size(const void *p) { return AllocationSize(p); } 350