guarded_pool_allocator.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. // This function is used to signal the allocator to indefinitely stop
  60. // functioning, as a crash has occurred. This stops the allocator from
  61. // servicing any further allocations permanently.
  62. void stop();
  63. // Return whether the allocation should be randomly chosen for sampling.
  64. GWP_ASAN_ALWAYS_INLINE bool shouldSample() {
  65. // NextSampleCounter == 0 means we "should regenerate the counter".
  66. // == 1 means we "should sample this allocation".
  67. // AdjustedSampleRatePlusOne is designed to intentionally underflow. This
  68. // class must be valid when zero-initialised, and we wish to sample as
  69. // infrequently as possible when this is the case, hence we underflow to
  70. // UINT32_MAX.
  71. if (GWP_ASAN_UNLIKELY(getThreadLocals()->NextSampleCounter == 0))
  72. getThreadLocals()->NextSampleCounter =
  73. ((getRandomUnsigned32() % (AdjustedSampleRatePlusOne - 1)) + 1) &
  74. ThreadLocalPackedVariables::NextSampleCounterMask;
  75. return GWP_ASAN_UNLIKELY(--getThreadLocals()->NextSampleCounter == 0);
  76. }
  77. // Returns whether the provided pointer is a current sampled allocation that
  78. // is owned by this pool.
  79. GWP_ASAN_ALWAYS_INLINE bool pointerIsMine(const void *Ptr) const {
  80. return State.pointerIsMine(Ptr);
  81. }
  82. // Allocate memory in a guarded slot, with the specified `Alignment`. Returns
  83. // nullptr if the pool is empty, if the alignnment is not a power of two, or
  84. // if the size/alignment makes the allocation too large for this pool to
  85. // handle. By default, uses strong alignment (i.e. `max_align_t`), see
  86. // http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2293.htm for discussion of
  87. // alignment issues in the standard.
  88. void *allocate(size_t Size, size_t Alignment = alignof(max_align_t));
  89. // Deallocate memory in a guarded slot. The provided pointer must have been
  90. // allocated using this pool. This will set the guarded slot as inaccessible.
  91. void deallocate(void *Ptr);
  92. // Returns the size of the allocation at Ptr.
  93. size_t getSize(const void *Ptr);
  94. // Returns a pointer to the Metadata region, or nullptr if it doesn't exist.
  95. const AllocationMetadata *getMetadataRegion() const { return Metadata; }
  96. // Returns a pointer to the AllocatorState region.
  97. const AllocatorState *getAllocatorState() const { return &State; }
  98. // Exposed as protected for testing.
  99. protected:
  100. // Returns the actual allocation size required to service an allocation with
  101. // the provided Size and Alignment.
  102. static size_t getRequiredBackingSize(size_t Size, size_t Alignment,
  103. size_t PageSize);
  104. // Returns the provided pointer that meets the specified alignment, depending
  105. // on whether it's left or right aligned.
  106. static uintptr_t alignUp(uintptr_t Ptr, size_t Alignment);
  107. static uintptr_t alignDown(uintptr_t Ptr, size_t Alignment);
  108. private:
  109. // Name of actively-occupied slot mappings.
  110. static constexpr const char *kGwpAsanAliveSlotName = "GWP-ASan Alive Slot";
  111. // Name of the guard pages. This includes all slots that are not actively in
  112. // use (i.e. were never used, or have been free()'d).)
  113. static constexpr const char *kGwpAsanGuardPageName = "GWP-ASan Guard Page";
  114. // Name of the mapping for `FreeSlots`.
  115. static constexpr const char *kGwpAsanFreeSlotsName = "GWP-ASan Metadata";
  116. static constexpr size_t kInvalidSlotID = SIZE_MAX;
  117. // These functions anonymously map memory or change the permissions of mapped
  118. // memory into this process in a platform-specific way. Pointer and size
  119. // arguments are expected to be page-aligned. These functions will never
  120. // return on error, instead electing to kill the calling process on failure.
  121. // The pool memory is initially reserved and inaccessible, and RW mappings are
  122. // subsequently created and destroyed via allocateInGuardedPool() and
  123. // deallocateInGuardedPool(). Each mapping is named on platforms that support
  124. // it, primarily Android. This name must be a statically allocated string, as
  125. // the Android kernel uses the string pointer directly.
  126. void *map(size_t Size, const char *Name) const;
  127. void unmap(void *Ptr, size_t Size) const;
  128. // The pool is managed separately, as some platforms (particularly Fuchsia)
  129. // manage virtual memory regions as a chunk where individual pages can still
  130. // have separate permissions. These platforms maintain metadata about the
  131. // region in order to perform operations. The pool is unique as it's the only
  132. // thing in GWP-ASan that treats pages in a single VM region on an individual
  133. // basis for page protection.
  134. // The pointer returned by reserveGuardedPool() is the reserved address range
  135. // of (at least) Size bytes.
  136. void *reserveGuardedPool(size_t Size);
  137. // allocateInGuardedPool() Ptr and Size must be a subrange of the previously
  138. // reserved pool range.
  139. void allocateInGuardedPool(void *Ptr, size_t Size) const;
  140. // deallocateInGuardedPool() Ptr and Size must be an exact pair previously
  141. // passed to allocateInGuardedPool().
  142. void deallocateInGuardedPool(void *Ptr, size_t Size) const;
  143. void unreserveGuardedPool();
  144. // Get the page size from the platform-specific implementation. Only needs to
  145. // be called once, and the result should be cached in PageSize in this class.
  146. static size_t getPlatformPageSize();
  147. // Returns a pointer to the metadata for the owned pointer. If the pointer is
  148. // not owned by this pool, the result is undefined.
  149. AllocationMetadata *addrToMetadata(uintptr_t Ptr) const;
  150. // Reserve a slot for a new guarded allocation. Returns kInvalidSlotID if no
  151. // slot is available to be reserved.
  152. size_t reserveSlot();
  153. // Unreserve the guarded slot.
  154. void freeSlot(size_t SlotIndex);
  155. // Raise a SEGV and set the corresponding fields in the Allocator's State in
  156. // order to tell the crash handler what happened. Used when errors are
  157. // detected internally (Double Free, Invalid Free).
  158. void trapOnAddress(uintptr_t Address, Error E);
  159. static GuardedPoolAllocator *getSingleton();
  160. // Install a pthread_atfork handler.
  161. void installAtFork();
  162. gwp_asan::AllocatorState State;
  163. // A mutex to protect the guarded slot and metadata pool for this class.
  164. Mutex PoolMutex;
  165. // Some unwinders can grab the libdl lock. In order to provide atfork
  166. // protection, we need to ensure that we allow an unwinding thread to release
  167. // the libdl lock before forking.
  168. Mutex BacktraceMutex;
  169. // Record the number allocations that we've sampled. We store this amount so
  170. // that we don't randomly choose to recycle a slot that previously had an
  171. // allocation before all the slots have been utilised.
  172. size_t NumSampledAllocations = 0;
  173. // Pointer to the allocation metadata (allocation/deallocation stack traces),
  174. // if any.
  175. AllocationMetadata *Metadata = nullptr;
  176. // Pointer to an array of free slot indexes.
  177. size_t *FreeSlots = nullptr;
  178. // The current length of the list of free slots.
  179. size_t FreeSlotsLength = 0;
  180. // See options.{h, inc} for more information.
  181. bool PerfectlyRightAlign = false;
  182. // Backtrace function provided by the supporting allocator. See `options.h`
  183. // for more information.
  184. options::Backtrace_t Backtrace = nullptr;
  185. // The adjusted sample rate for allocation sampling. Default *must* be
  186. // nonzero, as dynamic initialisation may call malloc (e.g. from libstdc++)
  187. // before GPA::init() is called. This would cause an error in shouldSample(),
  188. // where we would calculate modulo zero. This value is set UINT32_MAX, as when
  189. // GWP-ASan is disabled, we wish to never spend wasted cycles recalculating
  190. // the sample rate.
  191. uint32_t AdjustedSampleRatePlusOne = 0;
  192. // Additional platform specific data structure for the guarded pool mapping.
  193. PlatformSpecificMapData GuardedPagePoolPlatformData = {};
  194. class ScopedRecursiveGuard {
  195. public:
  196. ScopedRecursiveGuard() { getThreadLocals()->RecursiveGuard = true; }
  197. ~ScopedRecursiveGuard() { getThreadLocals()->RecursiveGuard = false; }
  198. };
  199. // Initialise the PRNG, platform-specific.
  200. void initPRNG();
  201. // xorshift (32-bit output), extremely fast PRNG that uses arithmetic
  202. // operations only. Seeded using platform-specific mechanisms by initPRNG().
  203. uint32_t getRandomUnsigned32();
  204. };
  205. } // namespace gwp_asan
  206. #endif // GWP_ASAN_GUARDED_POOL_ALLOCATOR_H_