common.h 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. //===-- common.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. // This file contains code that is common between the crash handler and the
  9. // GuardedPoolAllocator.
  10. #ifndef GWP_ASAN_COMMON_H_
  11. #define GWP_ASAN_COMMON_H_
  12. #include "gwp_asan/definitions.h"
  13. #include "gwp_asan/options.h"
  14. #include <stddef.h>
  15. #include <stdint.h>
  16. namespace gwp_asan {
  17. // Magic header that resides in the AllocatorState so that GWP-ASan bugreports
  18. // can be understood by tools at different versions. Out-of-process crash
  19. // handlers, like crashpad on Fuchsia, take the raw contents of the
  20. // AllocationMetatada array and the AllocatorState, and shove them into the
  21. // minidump. Online unpacking of these structs needs to know from which version
  22. // of GWP-ASan it's extracting the information, as the structures are not
  23. // stable.
  24. struct AllocatorVersionMagic {
  25. // The values are copied into the structure at runtime, during
  26. // `GuardedPoolAllocator::init()` so that GWP-ASan remains completely in the
  27. // `.bss` segment.
  28. static constexpr uint8_t kAllocatorVersionMagic[4] = {'A', 'S', 'A', 'N'};
  29. uint8_t Magic[4] = {};
  30. // Update the version number when the AllocatorState or AllocationMetadata
  31. // change.
  32. static constexpr uint16_t kAllocatorVersion = 1;
  33. uint16_t Version = 0;
  34. uint16_t Reserved = 0;
  35. };
  36. enum class Error : uint8_t {
  37. UNKNOWN,
  38. USE_AFTER_FREE,
  39. DOUBLE_FREE,
  40. INVALID_FREE,
  41. BUFFER_OVERFLOW,
  42. BUFFER_UNDERFLOW
  43. };
  44. const char *ErrorToString(const Error &E);
  45. static constexpr uint64_t kInvalidThreadID = UINT64_MAX;
  46. // Get the current thread ID, or kInvalidThreadID if failure. Note: This
  47. // implementation is platform-specific.
  48. uint64_t getThreadID();
  49. // This struct contains all the metadata recorded about a single allocation made
  50. // by GWP-ASan. If `AllocationMetadata.Addr` is zero, the metadata is non-valid.
  51. struct AllocationMetadata {
  52. // The number of bytes used to store a compressed stack frame. On 64-bit
  53. // platforms, assuming a compression ratio of 50%, this should allow us to
  54. // store ~64 frames per trace.
  55. static constexpr size_t kStackFrameStorageBytes = 256;
  56. // Maximum number of stack frames to collect on allocation/deallocation. The
  57. // actual number of collected frames may be less than this as the stack
  58. // frames are compressed into a fixed memory range.
  59. static constexpr size_t kMaxTraceLengthToCollect = 128;
  60. // Records the given allocation metadata into this struct.
  61. void RecordAllocation(uintptr_t Addr, size_t RequestedSize);
  62. // Record that this allocation is now deallocated.
  63. void RecordDeallocation();
  64. struct CallSiteInfo {
  65. // Record the current backtrace to this callsite.
  66. void RecordBacktrace(options::Backtrace_t Backtrace);
  67. // The compressed backtrace to the allocation/deallocation.
  68. uint8_t CompressedTrace[kStackFrameStorageBytes];
  69. // The thread ID for this trace, or kInvalidThreadID if not available.
  70. uint64_t ThreadID = kInvalidThreadID;
  71. // The size of the compressed trace (in bytes). Zero indicates that no
  72. // trace was collected.
  73. size_t TraceSize = 0;
  74. };
  75. // The address of this allocation. If zero, the rest of this struct isn't
  76. // valid, as the allocation has never occurred.
  77. uintptr_t Addr = 0;
  78. // Represents the actual size of the allocation.
  79. size_t RequestedSize = 0;
  80. CallSiteInfo AllocationTrace;
  81. CallSiteInfo DeallocationTrace;
  82. // Whether this allocation has been deallocated yet.
  83. bool IsDeallocated = false;
  84. };
  85. // This holds the state that's shared between the GWP-ASan allocator and the
  86. // crash handler. This, in conjunction with the Metadata array, forms the entire
  87. // set of information required for understanding a GWP-ASan crash.
  88. struct AllocatorState {
  89. constexpr AllocatorState() {}
  90. AllocatorVersionMagic VersionMagic{};
  91. // Returns whether the provided pointer is a current sampled allocation that
  92. // is owned by this pool.
  93. GWP_ASAN_ALWAYS_INLINE bool pointerIsMine(const void *Ptr) const {
  94. uintptr_t P = reinterpret_cast<uintptr_t>(Ptr);
  95. return P < GuardedPagePoolEnd && GuardedPagePool <= P;
  96. }
  97. // Returns the address of the N-th guarded slot.
  98. uintptr_t slotToAddr(size_t N) const;
  99. // Returns the largest allocation that is supported by this pool.
  100. size_t maximumAllocationSize() const;
  101. // Gets the nearest slot to the provided address.
  102. size_t getNearestSlot(uintptr_t Ptr) const;
  103. // Returns whether the provided pointer is a guard page or not. The pointer
  104. // must be within memory owned by this pool, else the result is undefined.
  105. bool isGuardPage(uintptr_t Ptr) const;
  106. // The number of guarded slots that this pool holds.
  107. size_t MaxSimultaneousAllocations = 0;
  108. // Pointer to the pool of guarded slots. Note that this points to the start of
  109. // the pool (which is a guard page), not a pointer to the first guarded page.
  110. uintptr_t GuardedPagePool = 0;
  111. uintptr_t GuardedPagePoolEnd = 0;
  112. // Cached page size for this system in bytes.
  113. size_t PageSize = 0;
  114. // The type and address of an internally-detected failure. For INVALID_FREE
  115. // and DOUBLE_FREE, these errors are detected in GWP-ASan, which will set
  116. // these values and terminate the process.
  117. Error FailureType = Error::UNKNOWN;
  118. uintptr_t FailureAddress = 0;
  119. };
  120. // Below are various compile-time checks that the layout of the internal
  121. // GWP-ASan structures are undisturbed. If they are disturbed, the version magic
  122. // number needs to be increased by one, and the asserts need to be updated.
  123. // Out-of-process crash handlers, like breakpad/crashpad, may copy the internal
  124. // GWP-ASan structures into a minidump for offline reconstruction of the crash.
  125. // In order to accomplish this, the offline reconstructor needs to know the
  126. // version of GWP-ASan internal structures that it's unpacking (along with the
  127. // architecture-specific layout info, which is left as an exercise to the crash
  128. // handler).
  129. static_assert(offsetof(AllocatorState, VersionMagic) == 0, "");
  130. static_assert(sizeof(AllocatorVersionMagic) == 8, "");
  131. #if defined(__x86_64__)
  132. static_assert(sizeof(AllocatorState) == 56, "");
  133. static_assert(offsetof(AllocatorState, FailureAddress) == 48, "");
  134. static_assert(sizeof(AllocationMetadata) == 568, "");
  135. static_assert(offsetof(AllocationMetadata, IsDeallocated) == 560, "");
  136. #elif defined(__aarch64__)
  137. static_assert(sizeof(AllocatorState) == 56, "");
  138. static_assert(offsetof(AllocatorState, FailureAddress) == 48, "");
  139. static_assert(sizeof(AllocationMetadata) == 568, "");
  140. static_assert(offsetof(AllocationMetadata, IsDeallocated) == 560, "");
  141. #elif defined(__i386__)
  142. static_assert(sizeof(AllocatorState) == 32, "");
  143. static_assert(offsetof(AllocatorState, FailureAddress) == 28, "");
  144. static_assert(sizeof(AllocationMetadata) == 548, "");
  145. static_assert(offsetof(AllocationMetadata, IsDeallocated) == 544, "");
  146. #elif defined(__arm__)
  147. static_assert(sizeof(AllocatorState) == 32, "");
  148. static_assert(offsetof(AllocatorState, FailureAddress) == 28, "");
  149. static_assert(sizeof(AllocationMetadata) == 560, "");
  150. static_assert(offsetof(AllocationMetadata, IsDeallocated) == 552, "");
  151. #endif // defined($ARCHITECTURE)
  152. } // namespace gwp_asan
  153. #endif // GWP_ASAN_COMMON_H_