guarded_pool_allocator.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. //===-- guarded_pool_allocator.h --------------------------------*- 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. #ifndef GWP_ASAN_GUARDED_POOL_ALLOCATOR_H_
  9. #define GWP_ASAN_GUARDED_POOL_ALLOCATOR_H_
  10. #include "gwp_asan/common.h"
  11. #include "gwp_asan/definitions.h"
  12. #include "gwp_asan/mutex.h"
  13. #include "gwp_asan/options.h"
  14. #include "gwp_asan/platform_specific/guarded_pool_allocator_fuchsia.h" // IWYU pragma: keep
  15. #include "gwp_asan/platform_specific/guarded_pool_allocator_posix.h" // IWYU pragma: keep
  16. #include "gwp_asan/platform_specific/guarded_pool_allocator_tls.h"
  17. #include <stddef.h>
  18. #include <stdint.h>
  19. // IWYU pragma: no_include <__stddef_max_align_t.h>
  20. namespace gwp_asan {
  21. // This class is the primary implementation of the allocator portion of GWP-
  22. // ASan. It is the sole owner of the pool of sequentially allocated guarded
  23. // slots. It should always be treated as a singleton.
  24. // Functions in the public interface of this class are thread-compatible until
  25. // init() is called, at which point they become thread-safe (unless specified
  26. // otherwise).
  27. class GuardedPoolAllocator {
  28. public:
  29. // Name of the GWP-ASan mapping that for `Metadata`.
  30. static constexpr const char *kGwpAsanMetadataName = "GWP-ASan Metadata";
  31. // During program startup, we must ensure that memory allocations do not land
  32. // in this allocation pool if the allocator decides to runtime-disable
  33. // GWP-ASan. The constructor value-initialises the class such that if no
  34. // further initialisation takes place, calls to shouldSample() and
  35. // pointerIsMine() will return false.
  36. constexpr GuardedPoolAllocator() {}
  37. GuardedPoolAllocator(const GuardedPoolAllocator &) = delete;
  38. GuardedPoolAllocator &operator=(const GuardedPoolAllocator &) = delete;
  39. // Note: This class is expected to be a singleton for the lifetime of the
  40. // program. If this object is initialised, it will leak the guarded page pool
  41. // and metadata allocations during destruction. We can't clean up these areas
  42. // as this may cause a use-after-free on shutdown.
  43. ~GuardedPoolAllocator() = default;
  44. // Initialise the rest of the members of this class. Create the allocation
  45. // pool using the provided options. See options.inc for runtime configuration
  46. // options.
  47. void init(const options::Options &Opts);
  48. void uninitTestOnly();
  49. // Functions exported for libmemunreachable's use on Android. disable()
  50. // installs a lock in the allocator that prevents any thread from being able
  51. // to allocate memory, until enable() is called.
  52. void disable();
  53. void enable();
  54. typedef void (*iterate_callback)(uintptr_t base, size_t size, void *arg);
  55. // Execute the callback Cb for every allocation the lies in [Base, Base +
  56. // Size). Must be called while the allocator is disabled. The callback can not
  57. // allocate.
  58. void iterate(void *Base, size_t Size, iterate_callback Cb, void *Arg);
  59. // Return whether the allocation should be randomly chosen for sampling.
  60. GWP_ASAN_ALWAYS_INLINE bool shouldSample() {
  61. // NextSampleCounter == 0 means we "should regenerate the counter".
  62. // == 1 means we "should sample this allocation".
  63. // AdjustedSampleRatePlusOne is designed to intentionally underflow. This
  64. // class must be valid when zero-initialised, and we wish to sample as
  65. // infrequently as possible when this is the case, hence we underflow to
  66. // UINT32_MAX.
  67. if (GWP_ASAN_UNLIKELY(getThreadLocals()->NextSampleCounter == 0))
  68. getThreadLocals()->NextSampleCounter =
  69. ((getRandomUnsigned32() % (AdjustedSampleRatePlusOne - 1)) + 1) &
  70. ThreadLocalPackedVariables::NextSampleCounterMask;
  71. return GWP_ASAN_UNLIKELY(--getThreadLocals()->NextSampleCounter == 0);
  72. }
  73. // Returns whether the provided pointer is a current sampled allocation that
  74. // is owned by this pool.
  75. GWP_ASAN_ALWAYS_INLINE bool pointerIsMine(const void *Ptr) const {
  76. return State.pointerIsMine(Ptr);
  77. }
  78. // Allocate memory in a guarded slot, with the specified `Alignment`. Returns
  79. // nullptr if the pool is empty, if the alignnment is not a power of two, or
  80. // if the size/alignment makes the allocation too large for this pool to
  81. // handle. By default, uses strong alignment (i.e. `max_align_t`), see
  82. // http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2293.htm for discussion of
  83. // alignment issues in the standard.
  84. void *allocate(size_t Size, size_t Alignment = alignof(max_align_t));
  85. // Deallocate memory in a guarded slot. The provided pointer must have been
  86. // allocated using this pool. This will set the guarded slot as inaccessible.
  87. void deallocate(void *Ptr);
  88. // Returns the size of the allocation at Ptr.
  89. size_t getSize(const void *Ptr);
  90. // Returns a pointer to the Metadata region, or nullptr if it doesn't exist.
  91. const AllocationMetadata *getMetadataRegion() const { return Metadata; }
  92. // Returns a pointer to the AllocatorState region.
  93. const AllocatorState *getAllocatorState() const { return &State; }
  94. // Functions that the signal handler is responsible for calling, while
  95. // providing the SEGV pointer, prior to dumping the crash, and after dumping
  96. // the crash (in recoverable mode only).
  97. void preCrashReport(void *Ptr);
  98. void postCrashReportRecoverableOnly(void *Ptr);
  99. // Exposed as protected for testing.
  100. protected:
  101. // Returns the actual allocation size required to service an allocation with
  102. // the provided Size and Alignment.
  103. static size_t getRequiredBackingSize(size_t Size, size_t Alignment,
  104. size_t PageSize);
  105. // Returns the provided pointer that meets the specified alignment, depending
  106. // on whether it's left or right aligned.
  107. static uintptr_t alignUp(uintptr_t Ptr, size_t Alignment);
  108. static uintptr_t alignDown(uintptr_t Ptr, size_t Alignment);
  109. private:
  110. // Name of actively-occupied slot mappings.
  111. static constexpr const char *kGwpAsanAliveSlotName = "GWP-ASan Alive Slot";
  112. // Name of the guard pages. This includes all slots that are not actively in
  113. // use (i.e. were never used, or have been free()'d).)
  114. static constexpr const char *kGwpAsanGuardPageName = "GWP-ASan Guard Page";
  115. // Name of the mapping for `FreeSlots`.
  116. static constexpr const char *kGwpAsanFreeSlotsName = "GWP-ASan Metadata";
  117. static constexpr size_t kInvalidSlotID = SIZE_MAX;
  118. // These functions anonymously map memory or change the permissions of mapped
  119. // memory into this process in a platform-specific way. Pointer and size
  120. // arguments are expected to be page-aligned. These functions will never
  121. // return on error, instead electing to kill the calling process on failure.
  122. // The pool memory is initially reserved and inaccessible, and RW mappings are
  123. // subsequently created and destroyed via allocateInGuardedPool() and
  124. // deallocateInGuardedPool(). Each mapping is named on platforms that support
  125. // it, primarily Android. This name must be a statically allocated string, as
  126. // the Android kernel uses the string pointer directly.
  127. void *map(size_t Size, const char *Name) const;
  128. void unmap(void *Ptr, size_t Size) const;
  129. // The pool is managed separately, as some platforms (particularly Fuchsia)
  130. // manage virtual memory regions as a chunk where individual pages can still
  131. // have separate permissions. These platforms maintain metadata about the
  132. // region in order to perform operations. The pool is unique as it's the only
  133. // thing in GWP-ASan that treats pages in a single VM region on an individual
  134. // basis for page protection.
  135. // The pointer returned by reserveGuardedPool() is the reserved address range
  136. // of (at least) Size bytes.
  137. void *reserveGuardedPool(size_t Size);
  138. // allocateInGuardedPool() Ptr and Size must be a subrange of the previously
  139. // reserved pool range.
  140. void allocateInGuardedPool(void *Ptr, size_t Size) const;
  141. // deallocateInGuardedPool() Ptr and Size must be an exact pair previously
  142. // passed to allocateInGuardedPool().
  143. void deallocateInGuardedPool(void *Ptr, size_t Size) const;
  144. void unreserveGuardedPool();
  145. // Get the page size from the platform-specific implementation. Only needs to
  146. // be called once, and the result should be cached in PageSize in this class.
  147. static size_t getPlatformPageSize();
  148. // Returns a pointer to the metadata for the owned pointer. If the pointer is
  149. // not owned by this pool, the result is undefined.
  150. AllocationMetadata *addrToMetadata(uintptr_t Ptr) const;
  151. // Reserve a slot for a new guarded allocation. Returns kInvalidSlotID if no
  152. // slot is available to be reserved.
  153. size_t reserveSlot();
  154. // Unreserve the guarded slot.
  155. void freeSlot(size_t SlotIndex);
  156. // Raise a SEGV and set the corresponding fields in the Allocator's State in
  157. // order to tell the crash handler what happened. Used when errors are
  158. // detected internally (Double Free, Invalid Free).
  159. void raiseInternallyDetectedError(uintptr_t Address, Error E);
  160. static GuardedPoolAllocator *getSingleton();
  161. // Install a pthread_atfork handler.
  162. void installAtFork();
  163. gwp_asan::AllocatorState State;
  164. // A mutex to protect the guarded slot and metadata pool for this class.
  165. Mutex PoolMutex;
  166. // Some unwinders can grab the libdl lock. In order to provide atfork
  167. // protection, we need to ensure that we allow an unwinding thread to release
  168. // the libdl lock before forking.
  169. Mutex BacktraceMutex;
  170. // Record the number allocations that we've sampled. We store this amount so
  171. // that we don't randomly choose to recycle a slot that previously had an
  172. // allocation before all the slots have been utilised.
  173. size_t NumSampledAllocations = 0;
  174. // Pointer to the allocation metadata (allocation/deallocation stack traces),
  175. // if any.
  176. AllocationMetadata *Metadata = nullptr;
  177. // Pointer to an array of free slot indexes.
  178. size_t *FreeSlots = nullptr;
  179. // The current length of the list of free slots.
  180. size_t FreeSlotsLength = 0;
  181. // See options.{h, inc} for more information.
  182. bool PerfectlyRightAlign = false;
  183. // Backtrace function provided by the supporting allocator. See `options.h`
  184. // for more information.
  185. options::Backtrace_t Backtrace = nullptr;
  186. // The adjusted sample rate for allocation sampling. Default *must* be
  187. // nonzero, as dynamic initialisation may call malloc (e.g. from libstdc++)
  188. // before GPA::init() is called. This would cause an error in shouldSample(),
  189. // where we would calculate modulo zero. This value is set UINT32_MAX, as when
  190. // GWP-ASan is disabled, we wish to never spend wasted cycles recalculating
  191. // the sample rate.
  192. uint32_t AdjustedSampleRatePlusOne = 0;
  193. // Additional platform specific data structure for the guarded pool mapping.
  194. PlatformSpecificMapData GuardedPagePoolPlatformData = {};
  195. class ScopedRecursiveGuard {
  196. public:
  197. ScopedRecursiveGuard() { getThreadLocals()->RecursiveGuard = true; }
  198. ~ScopedRecursiveGuard() { getThreadLocals()->RecursiveGuard = false; }
  199. };
  200. // Initialise the PRNG, platform-specific.
  201. void initPRNG();
  202. // xorshift (32-bit output), extremely fast PRNG that uses arithmetic
  203. // operations only. Seeded using platform-specific mechanisms by initPRNG().
  204. uint32_t getRandomUnsigned32();
  205. };
  206. } // namespace gwp_asan
  207. #endif // GWP_ASAN_GUARDED_POOL_ALLOCATOR_H_