segv_handler_posix.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. //===-- segv_handler_posix.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. #include "gwp_asan/common.h"
  9. #include "gwp_asan/crash_handler.h"
  10. #include "gwp_asan/guarded_pool_allocator.h"
  11. #include "gwp_asan/optional/segv_handler.h"
  12. #include "gwp_asan/options.h"
  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. #include <assert.h>
  19. #include <inttypes.h>
  20. #include <signal.h>
  21. #include <stdio.h>
  22. using gwp_asan::AllocationMetadata;
  23. using gwp_asan::Error;
  24. using gwp_asan::GuardedPoolAllocator;
  25. using gwp_asan::Printf_t;
  26. using gwp_asan::backtrace::PrintBacktrace_t;
  27. using gwp_asan::backtrace::SegvBacktrace_t;
  28. namespace {
  29. struct ScopedEndOfReportDecorator {
  30. ScopedEndOfReportDecorator(gwp_asan::Printf_t Printf) : Printf(Printf) {}
  31. ~ScopedEndOfReportDecorator() { Printf("*** End GWP-ASan report ***\n"); }
  32. gwp_asan::Printf_t Printf;
  33. };
  34. // Prints the provided error and metadata information.
  35. void printHeader(Error E, uintptr_t AccessPtr,
  36. const gwp_asan::AllocationMetadata *Metadata,
  37. Printf_t Printf) {
  38. // Print using intermediate strings. Platforms like Android don't like when
  39. // you print multiple times to the same line, as there may be a newline
  40. // appended to a log file automatically per Printf() call.
  41. constexpr size_t kDescriptionBufferLen = 128;
  42. char DescriptionBuffer[kDescriptionBufferLen] = "";
  43. bool AccessWasInBounds = false;
  44. if (E != Error::UNKNOWN && Metadata != nullptr) {
  45. uintptr_t Address = __gwp_asan_get_allocation_address(Metadata);
  46. size_t Size = __gwp_asan_get_allocation_size(Metadata);
  47. if (AccessPtr < Address) {
  48. snprintf(DescriptionBuffer, kDescriptionBufferLen,
  49. "(%zu byte%s to the left of a %zu-byte allocation at 0x%zx) ",
  50. Address - AccessPtr, (Address - AccessPtr == 1) ? "" : "s", Size,
  51. Address);
  52. } else if (AccessPtr > Address) {
  53. snprintf(DescriptionBuffer, kDescriptionBufferLen,
  54. "(%zu byte%s to the right of a %zu-byte allocation at 0x%zx) ",
  55. AccessPtr - Address, (AccessPtr - Address == 1) ? "" : "s", Size,
  56. Address);
  57. } else if (E == Error::DOUBLE_FREE) {
  58. snprintf(DescriptionBuffer, kDescriptionBufferLen,
  59. "(a %zu-byte allocation) ", Size);
  60. } else {
  61. AccessWasInBounds = true;
  62. snprintf(DescriptionBuffer, kDescriptionBufferLen,
  63. "(%zu byte%s into a %zu-byte allocation at 0x%zx) ",
  64. AccessPtr - Address, (AccessPtr - Address == 1) ? "" : "s", Size,
  65. Address);
  66. }
  67. }
  68. // Possible number of digits of a 64-bit number: ceil(log10(2^64)) == 20. Add
  69. // a null terminator, and round to the nearest 8-byte boundary.
  70. uint64_t ThreadID = gwp_asan::getThreadID();
  71. constexpr size_t kThreadBufferLen = 24;
  72. char ThreadBuffer[kThreadBufferLen];
  73. if (ThreadID == gwp_asan::kInvalidThreadID)
  74. snprintf(ThreadBuffer, kThreadBufferLen, "<unknown>");
  75. else
  76. snprintf(ThreadBuffer, kThreadBufferLen, "%" PRIu64, ThreadID);
  77. const char *OutOfBoundsAndUseAfterFreeWarning = "";
  78. if (E == Error::USE_AFTER_FREE && !AccessWasInBounds) {
  79. OutOfBoundsAndUseAfterFreeWarning =
  80. " (warning: buffer overflow/underflow detected on a free()'d "
  81. "allocation. This either means you have a buffer-overflow and a "
  82. "use-after-free at the same time, or you have a long-lived "
  83. "use-after-free bug where the allocation/deallocation metadata below "
  84. "has already been overwritten and is likely bogus)";
  85. }
  86. Printf("%s%s at 0x%zx %sby thread %s here:\n", gwp_asan::ErrorToString(E),
  87. OutOfBoundsAndUseAfterFreeWarning, AccessPtr, DescriptionBuffer,
  88. ThreadBuffer);
  89. }
  90. void dumpReport(uintptr_t ErrorPtr, const gwp_asan::AllocatorState *State,
  91. const gwp_asan::AllocationMetadata *Metadata,
  92. SegvBacktrace_t SegvBacktrace, Printf_t Printf,
  93. PrintBacktrace_t PrintBacktrace, void *Context) {
  94. assert(State && "dumpReport missing Allocator State.");
  95. assert(Metadata && "dumpReport missing Metadata.");
  96. assert(Printf && "dumpReport missing Printf.");
  97. assert(__gwp_asan_error_is_mine(State, ErrorPtr) &&
  98. "dumpReport() called on a non-GWP-ASan error.");
  99. uintptr_t InternalErrorPtr =
  100. __gwp_asan_get_internal_crash_address(State, ErrorPtr);
  101. if (InternalErrorPtr)
  102. ErrorPtr = InternalErrorPtr;
  103. const gwp_asan::AllocationMetadata *AllocMeta =
  104. __gwp_asan_get_metadata(State, Metadata, ErrorPtr);
  105. // It's unusual for a signal handler to be invoked multiple times for the same
  106. // allocation, but it's possible in various scenarios, like:
  107. // 1. A double-free or invalid-free was invoked in one thread at the same
  108. // time as a buffer-overflow or use-after-free in another thread, or
  109. // 2. Two threads do a use-after-free or buffer-overflow at the same time.
  110. // In these instances, we've already dumped a report for this allocation, so
  111. // skip dumping this issue as well.
  112. if (AllocMeta->HasCrashed)
  113. return;
  114. Printf("*** GWP-ASan detected a memory error ***\n");
  115. ScopedEndOfReportDecorator Decorator(Printf);
  116. Error E = __gwp_asan_diagnose_error(State, Metadata, ErrorPtr);
  117. if (E == Error::UNKNOWN) {
  118. Printf("GWP-ASan cannot provide any more information about this error. "
  119. "This may occur due to a wild memory access into the GWP-ASan pool, "
  120. "or an overflow/underflow that is > 512B in length.\n");
  121. return;
  122. }
  123. // Print the error header.
  124. printHeader(E, ErrorPtr, AllocMeta, Printf);
  125. // Print the fault backtrace.
  126. static constexpr unsigned kMaximumStackFramesForCrashTrace = 512;
  127. uintptr_t Trace[kMaximumStackFramesForCrashTrace];
  128. size_t TraceLength =
  129. SegvBacktrace(Trace, kMaximumStackFramesForCrashTrace, Context);
  130. PrintBacktrace(Trace, TraceLength, Printf);
  131. if (AllocMeta == nullptr)
  132. return;
  133. // Maybe print the deallocation trace.
  134. if (__gwp_asan_is_deallocated(AllocMeta)) {
  135. uint64_t ThreadID = __gwp_asan_get_deallocation_thread_id(AllocMeta);
  136. if (ThreadID == gwp_asan::kInvalidThreadID)
  137. Printf("0x%zx was deallocated by thread <unknown> here:\n", ErrorPtr);
  138. else
  139. Printf("0x%zx was deallocated by thread %zu here:\n", ErrorPtr, ThreadID);
  140. TraceLength = __gwp_asan_get_deallocation_trace(
  141. AllocMeta, Trace, kMaximumStackFramesForCrashTrace);
  142. PrintBacktrace(Trace, TraceLength, Printf);
  143. }
  144. // Print the allocation trace.
  145. uint64_t ThreadID = __gwp_asan_get_allocation_thread_id(AllocMeta);
  146. if (ThreadID == gwp_asan::kInvalidThreadID)
  147. Printf("0x%zx was allocated by thread <unknown> here:\n", ErrorPtr);
  148. else
  149. Printf("0x%zx was allocated by thread %zu here:\n", ErrorPtr, ThreadID);
  150. TraceLength = __gwp_asan_get_allocation_trace(
  151. AllocMeta, Trace, kMaximumStackFramesForCrashTrace);
  152. PrintBacktrace(Trace, TraceLength, Printf);
  153. }
  154. struct sigaction PreviousHandler;
  155. bool SignalHandlerInstalled;
  156. bool RecoverableSignal;
  157. gwp_asan::GuardedPoolAllocator *GPAForSignalHandler;
  158. Printf_t PrintfForSignalHandler;
  159. PrintBacktrace_t PrintBacktraceForSignalHandler;
  160. SegvBacktrace_t BacktraceForSignalHandler;
  161. static void sigSegvHandler(int sig, siginfo_t *info, void *ucontext) {
  162. const gwp_asan::AllocatorState *State =
  163. GPAForSignalHandler->getAllocatorState();
  164. void *FaultAddr = info->si_addr;
  165. uintptr_t FaultAddrUPtr = reinterpret_cast<uintptr_t>(FaultAddr);
  166. if (__gwp_asan_error_is_mine(State, FaultAddrUPtr)) {
  167. GPAForSignalHandler->preCrashReport(FaultAddr);
  168. dumpReport(FaultAddrUPtr, State, GPAForSignalHandler->getMetadataRegion(),
  169. BacktraceForSignalHandler, PrintfForSignalHandler,
  170. PrintBacktraceForSignalHandler, ucontext);
  171. if (RecoverableSignal) {
  172. GPAForSignalHandler->postCrashReportRecoverableOnly(FaultAddr);
  173. return;
  174. }
  175. }
  176. // Process any previous handlers as long as the crash wasn't a GWP-ASan crash
  177. // in recoverable mode.
  178. if (PreviousHandler.sa_flags & SA_SIGINFO) {
  179. PreviousHandler.sa_sigaction(sig, info, ucontext);
  180. } else if (PreviousHandler.sa_handler == SIG_DFL) {
  181. // If the previous handler was the default handler, cause a core dump.
  182. signal(SIGSEGV, SIG_DFL);
  183. raise(SIGSEGV);
  184. } else if (PreviousHandler.sa_handler == SIG_IGN) {
  185. // If the previous segv handler was SIGIGN, crash iff we were responsible
  186. // for the crash.
  187. if (__gwp_asan_error_is_mine(GPAForSignalHandler->getAllocatorState(),
  188. reinterpret_cast<uintptr_t>(info->si_addr))) {
  189. signal(SIGSEGV, SIG_DFL);
  190. raise(SIGSEGV);
  191. }
  192. } else {
  193. PreviousHandler.sa_handler(sig);
  194. }
  195. }
  196. } // anonymous namespace
  197. namespace gwp_asan {
  198. namespace segv_handler {
  199. void installSignalHandlers(gwp_asan::GuardedPoolAllocator *GPA, Printf_t Printf,
  200. PrintBacktrace_t PrintBacktrace,
  201. SegvBacktrace_t SegvBacktrace, bool Recoverable) {
  202. assert(GPA && "GPA wasn't provided to installSignalHandlers.");
  203. assert(Printf && "Printf wasn't provided to installSignalHandlers.");
  204. assert(PrintBacktrace &&
  205. "PrintBacktrace wasn't provided to installSignalHandlers.");
  206. assert(SegvBacktrace &&
  207. "SegvBacktrace wasn't provided to installSignalHandlers.");
  208. GPAForSignalHandler = GPA;
  209. PrintfForSignalHandler = Printf;
  210. PrintBacktraceForSignalHandler = PrintBacktrace;
  211. BacktraceForSignalHandler = SegvBacktrace;
  212. RecoverableSignal = Recoverable;
  213. struct sigaction Action = {};
  214. Action.sa_sigaction = sigSegvHandler;
  215. Action.sa_flags = SA_SIGINFO;
  216. sigaction(SIGSEGV, &Action, &PreviousHandler);
  217. SignalHandlerInstalled = true;
  218. }
  219. void uninstallSignalHandlers() {
  220. if (SignalHandlerInstalled) {
  221. sigaction(SIGSEGV, &PreviousHandler, nullptr);
  222. SignalHandlerInstalled = false;
  223. }
  224. }
  225. } // namespace segv_handler
  226. } // namespace gwp_asan