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