1 //===-- guarded_pool_allocator.cpp ------------------------------*- C++ -*-===// 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 #include "gwp_asan/guarded_pool_allocator.h" 10 11 #include "gwp_asan/options.h" 12 13 // RHEL creates the PRIu64 format macro (for printing uint64_t's) only when this 14 // macro is defined before including <inttypes.h>. 15 #ifndef __STDC_FORMAT_MACROS 16 #define __STDC_FORMAT_MACROS 1 17 #endif 18 19 #include <assert.h> 20 #include <inttypes.h> 21 #include <stdio.h> 22 #include <stdlib.h> 23 #include <string.h> 24 #include <time.h> 25 26 using AllocationMetadata = gwp_asan::GuardedPoolAllocator::AllocationMetadata; 27 using Error = gwp_asan::GuardedPoolAllocator::Error; 28 29 namespace gwp_asan { 30 namespace { 31 // Forward declare the pointer to the singleton version of this class. 32 // Instantiated during initialisation, this allows the signal handler 33 // to find this class in order to deduce the root cause of failures. Must not be 34 // referenced by users outside this translation unit, in order to avoid 35 // init-order-fiasco. 36 GuardedPoolAllocator *SingletonPtr = nullptr; 37 38 class ScopedBoolean { 39 public: 40 ScopedBoolean(bool &B) : Bool(B) { Bool = true; } 41 ~ScopedBoolean() { Bool = false; } 42 43 private: 44 bool &Bool; 45 }; 46 47 void defaultPrintStackTrace(uintptr_t *Trace, size_t TraceLength, 48 options::Printf_t Printf) { 49 if (TraceLength == 0) 50 Printf(" <unknown (does your allocator support backtracing?)>\n"); 51 52 for (size_t i = 0; i < TraceLength; ++i) { 53 Printf(" #%zu 0x%zx in <unknown>\n", i, Trace[i]); 54 } 55 Printf("\n"); 56 } 57 } // anonymous namespace 58 59 // Gets the singleton implementation of this class. Thread-compatible until 60 // init() is called, thread-safe afterwards. 61 GuardedPoolAllocator *getSingleton() { return SingletonPtr; } 62 63 void GuardedPoolAllocator::AllocationMetadata::RecordAllocation( 64 uintptr_t AllocAddr, size_t AllocSize, options::Backtrace_t Backtrace) { 65 Addr = AllocAddr; 66 Size = AllocSize; 67 IsDeallocated = false; 68 69 // TODO(hctim): Ask the caller to provide the thread ID, so we don't waste 70 // other thread's time getting the thread ID under lock. 71 AllocationTrace.ThreadID = getThreadID(); 72 AllocationTrace.TraceSize = 0; 73 DeallocationTrace.TraceSize = 0; 74 DeallocationTrace.ThreadID = kInvalidThreadID; 75 76 if (Backtrace) { 77 uintptr_t UncompressedBuffer[kMaxTraceLengthToCollect]; 78 size_t BacktraceLength = 79 Backtrace(UncompressedBuffer, kMaxTraceLengthToCollect); 80 AllocationTrace.TraceSize = compression::pack( 81 UncompressedBuffer, BacktraceLength, AllocationTrace.CompressedTrace, 82 kStackFrameStorageBytes); 83 } 84 } 85 86 void GuardedPoolAllocator::AllocationMetadata::RecordDeallocation( 87 options::Backtrace_t Backtrace) { 88 IsDeallocated = true; 89 // Ensure that the unwinder is not called if the recursive flag is set, 90 // otherwise non-reentrant unwinders may deadlock. 91 DeallocationTrace.TraceSize = 0; 92 if (Backtrace && !ThreadLocals.RecursiveGuard) { 93 ScopedBoolean B(ThreadLocals.RecursiveGuard); 94 95 uintptr_t UncompressedBuffer[kMaxTraceLengthToCollect]; 96 size_t BacktraceLength = 97 Backtrace(UncompressedBuffer, kMaxTraceLengthToCollect); 98 DeallocationTrace.TraceSize = compression::pack( 99 UncompressedBuffer, BacktraceLength, DeallocationTrace.CompressedTrace, 100 kStackFrameStorageBytes); 101 } 102 DeallocationTrace.ThreadID = getThreadID(); 103 } 104 105 void GuardedPoolAllocator::init(const options::Options &Opts) { 106 // Note: We return from the constructor here if GWP-ASan is not available. 107 // This will stop heap-allocation of class members, as well as mmap() of the 108 // guarded slots. 109 if (!Opts.Enabled || Opts.SampleRate == 0 || 110 Opts.MaxSimultaneousAllocations == 0) 111 return; 112 113 // TODO(hctim): Add a death unit test for this. 114 if (SingletonPtr) { 115 (*SingletonPtr->Printf)( 116 "GWP-ASan Error: init() has already been called.\n"); 117 exit(EXIT_FAILURE); 118 } 119 120 if (Opts.SampleRate < 0) { 121 Opts.Printf("GWP-ASan Error: SampleRate is < 0.\n"); 122 exit(EXIT_FAILURE); 123 } 124 125 if (Opts.SampleRate > INT32_MAX) { 126 Opts.Printf("GWP-ASan Error: SampleRate is > 2^31.\n"); 127 exit(EXIT_FAILURE); 128 } 129 130 if (Opts.MaxSimultaneousAllocations < 0) { 131 Opts.Printf("GWP-ASan Error: MaxSimultaneousAllocations is < 0.\n"); 132 exit(EXIT_FAILURE); 133 } 134 135 SingletonPtr = this; 136 137 MaxSimultaneousAllocations = Opts.MaxSimultaneousAllocations; 138 139 PageSize = getPlatformPageSize(); 140 141 PerfectlyRightAlign = Opts.PerfectlyRightAlign; 142 Printf = Opts.Printf; 143 Backtrace = Opts.Backtrace; 144 if (Opts.PrintBacktrace) 145 PrintBacktrace = Opts.PrintBacktrace; 146 else 147 PrintBacktrace = defaultPrintStackTrace; 148 149 size_t PoolBytesRequired = 150 PageSize * (1 + MaxSimultaneousAllocations) + 151 MaxSimultaneousAllocations * maximumAllocationSize(); 152 void *GuardedPoolMemory = mapMemory(PoolBytesRequired); 153 154 size_t BytesRequired = MaxSimultaneousAllocations * sizeof(*Metadata); 155 Metadata = reinterpret_cast<AllocationMetadata *>(mapMemory(BytesRequired)); 156 markReadWrite(Metadata, BytesRequired); 157 158 // Allocate memory and set up the free pages queue. 159 BytesRequired = MaxSimultaneousAllocations * sizeof(*FreeSlots); 160 FreeSlots = reinterpret_cast<size_t *>(mapMemory(BytesRequired)); 161 markReadWrite(FreeSlots, BytesRequired); 162 163 // Multiply the sample rate by 2 to give a good, fast approximation for (1 / 164 // SampleRate) chance of sampling. 165 if (Opts.SampleRate != 1) 166 AdjustedSampleRate = static_cast<uint32_t>(Opts.SampleRate) * 2; 167 else 168 AdjustedSampleRate = 1; 169 170 GuardedPagePool = reinterpret_cast<uintptr_t>(GuardedPoolMemory); 171 GuardedPagePoolEnd = 172 reinterpret_cast<uintptr_t>(GuardedPoolMemory) + PoolBytesRequired; 173 174 // Ensure that signal handlers are installed as late as possible, as the class 175 // is not thread-safe until init() is finished, and thus a SIGSEGV may cause a 176 // race to members if received during init(). 177 if (Opts.InstallSignalHandlers) 178 installSignalHandlers(); 179 } 180 181 void *GuardedPoolAllocator::allocate(size_t Size) { 182 // GuardedPagePoolEnd == 0 when GWP-ASan is disabled. If we are disabled, fall 183 // back to the supporting allocator. 184 if (GuardedPagePoolEnd == 0) 185 return nullptr; 186 187 // Protect against recursivity. 188 if (ThreadLocals.RecursiveGuard) 189 return nullptr; 190 ScopedBoolean SB(ThreadLocals.RecursiveGuard); 191 192 if (Size == 0 || Size > maximumAllocationSize()) 193 return nullptr; 194 195 size_t Index; 196 { 197 ScopedLock L(PoolMutex); 198 Index = reserveSlot(); 199 } 200 201 if (Index == kInvalidSlotID) 202 return nullptr; 203 204 uintptr_t Ptr = slotToAddr(Index); 205 Ptr += allocationSlotOffset(Size); 206 AllocationMetadata *Meta = addrToMetadata(Ptr); 207 208 // If a slot is multiple pages in size, and the allocation takes up a single 209 // page, we can improve overflow detection by leaving the unused pages as 210 // unmapped. 211 markReadWrite(reinterpret_cast<void *>(getPageAddr(Ptr)), Size); 212 213 Meta->RecordAllocation(Ptr, Size, Backtrace); 214 215 return reinterpret_cast<void *>(Ptr); 216 } 217 218 void GuardedPoolAllocator::deallocate(void *Ptr) { 219 assert(pointerIsMine(Ptr) && "Pointer is not mine!"); 220 uintptr_t UPtr = reinterpret_cast<uintptr_t>(Ptr); 221 uintptr_t SlotStart = slotToAddr(addrToSlot(UPtr)); 222 AllocationMetadata *Meta = addrToMetadata(UPtr); 223 if (Meta->Addr != UPtr) { 224 reportError(UPtr, Error::INVALID_FREE); 225 exit(EXIT_FAILURE); 226 } 227 228 // Intentionally scope the mutex here, so that other threads can access the 229 // pool during the expensive markInaccessible() call. 230 { 231 ScopedLock L(PoolMutex); 232 if (Meta->IsDeallocated) { 233 reportError(UPtr, Error::DOUBLE_FREE); 234 exit(EXIT_FAILURE); 235 } 236 237 // Ensure that the deallocation is recorded before marking the page as 238 // inaccessible. Otherwise, a racy use-after-free will have inconsistent 239 // metadata. 240 Meta->RecordDeallocation(Backtrace); 241 } 242 243 markInaccessible(reinterpret_cast<void *>(SlotStart), 244 maximumAllocationSize()); 245 246 // And finally, lock again to release the slot back into the pool. 247 ScopedLock L(PoolMutex); 248 freeSlot(addrToSlot(UPtr)); 249 } 250 251 size_t GuardedPoolAllocator::getSize(const void *Ptr) { 252 assert(pointerIsMine(Ptr)); 253 ScopedLock L(PoolMutex); 254 AllocationMetadata *Meta = addrToMetadata(reinterpret_cast<uintptr_t>(Ptr)); 255 assert(Meta->Addr == reinterpret_cast<uintptr_t>(Ptr)); 256 return Meta->Size; 257 } 258 259 size_t GuardedPoolAllocator::maximumAllocationSize() const { return PageSize; } 260 261 AllocationMetadata *GuardedPoolAllocator::addrToMetadata(uintptr_t Ptr) const { 262 return &Metadata[addrToSlot(Ptr)]; 263 } 264 265 size_t GuardedPoolAllocator::addrToSlot(uintptr_t Ptr) const { 266 assert(pointerIsMine(reinterpret_cast<void *>(Ptr))); 267 size_t ByteOffsetFromPoolStart = Ptr - GuardedPagePool; 268 return ByteOffsetFromPoolStart / (maximumAllocationSize() + PageSize); 269 } 270 271 uintptr_t GuardedPoolAllocator::slotToAddr(size_t N) const { 272 return GuardedPagePool + (PageSize * (1 + N)) + (maximumAllocationSize() * N); 273 } 274 275 uintptr_t GuardedPoolAllocator::getPageAddr(uintptr_t Ptr) const { 276 assert(pointerIsMine(reinterpret_cast<void *>(Ptr))); 277 return Ptr & ~(static_cast<uintptr_t>(PageSize) - 1); 278 } 279 280 bool GuardedPoolAllocator::isGuardPage(uintptr_t Ptr) const { 281 assert(pointerIsMine(reinterpret_cast<void *>(Ptr))); 282 size_t PageOffsetFromPoolStart = (Ptr - GuardedPagePool) / PageSize; 283 size_t PagesPerSlot = maximumAllocationSize() / PageSize; 284 return (PageOffsetFromPoolStart % (PagesPerSlot + 1)) == 0; 285 } 286 287 size_t GuardedPoolAllocator::reserveSlot() { 288 // Avoid potential reuse of a slot before we have made at least a single 289 // allocation in each slot. Helps with our use-after-free detection. 290 if (NumSampledAllocations < MaxSimultaneousAllocations) 291 return NumSampledAllocations++; 292 293 if (FreeSlotsLength == 0) 294 return kInvalidSlotID; 295 296 size_t ReservedIndex = getRandomUnsigned32() % FreeSlotsLength; 297 size_t SlotIndex = FreeSlots[ReservedIndex]; 298 FreeSlots[ReservedIndex] = FreeSlots[--FreeSlotsLength]; 299 return SlotIndex; 300 } 301 302 void GuardedPoolAllocator::freeSlot(size_t SlotIndex) { 303 assert(FreeSlotsLength < MaxSimultaneousAllocations); 304 FreeSlots[FreeSlotsLength++] = SlotIndex; 305 } 306 307 uintptr_t GuardedPoolAllocator::allocationSlotOffset(size_t Size) const { 308 assert(Size > 0); 309 310 bool ShouldRightAlign = getRandomUnsigned32() % 2 == 0; 311 if (!ShouldRightAlign) 312 return 0; 313 314 uintptr_t Offset = maximumAllocationSize(); 315 if (!PerfectlyRightAlign) { 316 if (Size == 3) 317 Size = 4; 318 else if (Size > 4 && Size <= 8) 319 Size = 8; 320 else if (Size > 8 && (Size % 16) != 0) 321 Size += 16 - (Size % 16); 322 } 323 Offset -= Size; 324 return Offset; 325 } 326 327 void GuardedPoolAllocator::reportError(uintptr_t AccessPtr, Error E) { 328 if (SingletonPtr) 329 SingletonPtr->reportErrorInternal(AccessPtr, E); 330 } 331 332 size_t GuardedPoolAllocator::getNearestSlot(uintptr_t Ptr) const { 333 if (Ptr <= GuardedPagePool + PageSize) 334 return 0; 335 if (Ptr > GuardedPagePoolEnd - PageSize) 336 return MaxSimultaneousAllocations - 1; 337 338 if (!isGuardPage(Ptr)) 339 return addrToSlot(Ptr); 340 341 if (Ptr % PageSize <= PageSize / 2) 342 return addrToSlot(Ptr - PageSize); // Round down. 343 return addrToSlot(Ptr + PageSize); // Round up. 344 } 345 346 Error GuardedPoolAllocator::diagnoseUnknownError(uintptr_t AccessPtr, 347 AllocationMetadata **Meta) { 348 // Let's try and figure out what the source of this error is. 349 if (isGuardPage(AccessPtr)) { 350 size_t Slot = getNearestSlot(AccessPtr); 351 AllocationMetadata *SlotMeta = addrToMetadata(slotToAddr(Slot)); 352 353 // Ensure that this slot was allocated once upon a time. 354 if (!SlotMeta->Addr) 355 return Error::UNKNOWN; 356 *Meta = SlotMeta; 357 358 if (SlotMeta->Addr < AccessPtr) 359 return Error::BUFFER_OVERFLOW; 360 return Error::BUFFER_UNDERFLOW; 361 } 362 363 // Access wasn't a guard page, check for use-after-free. 364 AllocationMetadata *SlotMeta = addrToMetadata(AccessPtr); 365 if (SlotMeta->IsDeallocated) { 366 *Meta = SlotMeta; 367 return Error::USE_AFTER_FREE; 368 } 369 370 // If we have reached here, the error is still unknown. There is no metadata 371 // available. 372 *Meta = nullptr; 373 return Error::UNKNOWN; 374 } 375 376 namespace { 377 // Prints the provided error and metadata information. 378 void printErrorType(Error E, uintptr_t AccessPtr, AllocationMetadata *Meta, 379 options::Printf_t Printf, uint64_t ThreadID) { 380 // Print using intermediate strings. Platforms like Android don't like when 381 // you print multiple times to the same line, as there may be a newline 382 // appended to a log file automatically per Printf() call. 383 const char *ErrorString; 384 switch (E) { 385 case Error::UNKNOWN: 386 ErrorString = "GWP-ASan couldn't automatically determine the source of " 387 "the memory error. It was likely caused by a wild memory " 388 "access into the GWP-ASan pool. The error occurred"; 389 break; 390 case Error::USE_AFTER_FREE: 391 ErrorString = "Use after free"; 392 break; 393 case Error::DOUBLE_FREE: 394 ErrorString = "Double free"; 395 break; 396 case Error::INVALID_FREE: 397 ErrorString = "Invalid (wild) free"; 398 break; 399 case Error::BUFFER_OVERFLOW: 400 ErrorString = "Buffer overflow"; 401 break; 402 case Error::BUFFER_UNDERFLOW: 403 ErrorString = "Buffer underflow"; 404 break; 405 } 406 407 constexpr size_t kDescriptionBufferLen = 128; 408 char DescriptionBuffer[kDescriptionBufferLen]; 409 if (Meta) { 410 if (E == Error::USE_AFTER_FREE) { 411 snprintf(DescriptionBuffer, kDescriptionBufferLen, 412 "(%zu byte%s into a %zu-byte allocation at 0x%zx)", 413 AccessPtr - Meta->Addr, (AccessPtr - Meta->Addr == 1) ? "" : "s", 414 Meta->Size, Meta->Addr); 415 } else if (AccessPtr < Meta->Addr) { 416 snprintf(DescriptionBuffer, kDescriptionBufferLen, 417 "(%zu byte%s to the left of a %zu-byte allocation at 0x%zx)", 418 Meta->Addr - AccessPtr, (Meta->Addr - AccessPtr == 1) ? "" : "s", 419 Meta->Size, Meta->Addr); 420 } else if (AccessPtr > Meta->Addr) { 421 snprintf(DescriptionBuffer, kDescriptionBufferLen, 422 "(%zu byte%s to the right of a %zu-byte allocation at 0x%zx)", 423 AccessPtr - Meta->Addr, (AccessPtr - Meta->Addr == 1) ? "" : "s", 424 Meta->Size, Meta->Addr); 425 } else { 426 snprintf(DescriptionBuffer, kDescriptionBufferLen, 427 "(a %zu-byte allocation)", Meta->Size); 428 } 429 } 430 431 // Possible number of digits of a 64-bit number: ceil(log10(2^64)) == 20. Add 432 // a null terminator, and round to the nearest 8-byte boundary. 433 constexpr size_t kThreadBufferLen = 24; 434 char ThreadBuffer[kThreadBufferLen]; 435 if (ThreadID == GuardedPoolAllocator::kInvalidThreadID) 436 snprintf(ThreadBuffer, kThreadBufferLen, "<unknown>"); 437 else 438 snprintf(ThreadBuffer, kThreadBufferLen, "%" PRIu64, ThreadID); 439 440 Printf("%s at 0x%zx %s by thread %s here:\n", ErrorString, AccessPtr, 441 DescriptionBuffer, ThreadBuffer); 442 } 443 444 void printAllocDeallocTraces(uintptr_t AccessPtr, AllocationMetadata *Meta, 445 options::Printf_t Printf, 446 options::PrintBacktrace_t PrintBacktrace) { 447 assert(Meta != nullptr && "Metadata is non-null for printAllocDeallocTraces"); 448 449 if (Meta->IsDeallocated) { 450 if (Meta->DeallocationTrace.ThreadID == 451 GuardedPoolAllocator::kInvalidThreadID) 452 Printf("0x%zx was deallocated by thread <unknown> here:\n", AccessPtr); 453 else 454 Printf("0x%zx was deallocated by thread %zu here:\n", AccessPtr, 455 Meta->DeallocationTrace.ThreadID); 456 457 uintptr_t UncompressedTrace[AllocationMetadata::kMaxTraceLengthToCollect]; 458 size_t UncompressedLength = compression::unpack( 459 Meta->DeallocationTrace.CompressedTrace, 460 Meta->DeallocationTrace.TraceSize, UncompressedTrace, 461 AllocationMetadata::kMaxTraceLengthToCollect); 462 463 PrintBacktrace(UncompressedTrace, UncompressedLength, Printf); 464 } 465 466 if (Meta->AllocationTrace.ThreadID == GuardedPoolAllocator::kInvalidThreadID) 467 Printf("0x%zx was allocated by thread <unknown> here:\n", Meta->Addr); 468 else 469 Printf("0x%zx was allocated by thread %zu here:\n", Meta->Addr, 470 Meta->AllocationTrace.ThreadID); 471 472 uintptr_t UncompressedTrace[AllocationMetadata::kMaxTraceLengthToCollect]; 473 size_t UncompressedLength = compression::unpack( 474 Meta->AllocationTrace.CompressedTrace, Meta->AllocationTrace.TraceSize, 475 UncompressedTrace, AllocationMetadata::kMaxTraceLengthToCollect); 476 477 PrintBacktrace(UncompressedTrace, UncompressedLength, Printf); 478 } 479 480 struct ScopedEndOfReportDecorator { 481 ScopedEndOfReportDecorator(options::Printf_t Printf) : Printf(Printf) {} 482 ~ScopedEndOfReportDecorator() { Printf("*** End GWP-ASan report ***\n"); } 483 options::Printf_t Printf; 484 }; 485 } // anonymous namespace 486 487 void GuardedPoolAllocator::reportErrorInternal(uintptr_t AccessPtr, Error E) { 488 if (!pointerIsMine(reinterpret_cast<void *>(AccessPtr))) { 489 return; 490 } 491 492 // Attempt to prevent races to re-use the same slot that triggered this error. 493 // This does not guarantee that there are no races, because another thread can 494 // take the locks during the time that the signal handler is being called. 495 PoolMutex.tryLock(); 496 ThreadLocals.RecursiveGuard = true; 497 498 Printf("*** GWP-ASan detected a memory error ***\n"); 499 ScopedEndOfReportDecorator Decorator(Printf); 500 501 AllocationMetadata *Meta = nullptr; 502 503 if (E == Error::UNKNOWN) { 504 E = diagnoseUnknownError(AccessPtr, &Meta); 505 } else { 506 size_t Slot = getNearestSlot(AccessPtr); 507 Meta = addrToMetadata(slotToAddr(Slot)); 508 // Ensure that this slot has been previously allocated. 509 if (!Meta->Addr) 510 Meta = nullptr; 511 } 512 513 // Print the error information. 514 uint64_t ThreadID = getThreadID(); 515 printErrorType(E, AccessPtr, Meta, Printf, ThreadID); 516 if (Backtrace) { 517 static constexpr unsigned kMaximumStackFramesForCrashTrace = 512; 518 uintptr_t Trace[kMaximumStackFramesForCrashTrace]; 519 size_t TraceLength = Backtrace(Trace, kMaximumStackFramesForCrashTrace); 520 521 PrintBacktrace(Trace, TraceLength, Printf); 522 } else { 523 Printf(" <unknown (does your allocator support backtracing?)>\n\n"); 524 } 525 526 if (Meta) 527 printAllocDeallocTraces(AccessPtr, Meta, Printf, PrintBacktrace); 528 } 529 530 TLS_INITIAL_EXEC 531 GuardedPoolAllocator::ThreadLocalPackedVariables 532 GuardedPoolAllocator::ThreadLocals; 533 } // namespace gwp_asan 534