segv_handler_posix.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. if (E != Error::UNKNOWN && Metadata != nullptr) {
  44. uintptr_t Address = __gwp_asan_get_allocation_address(Metadata);
  45. size_t Size = __gwp_asan_get_allocation_size(Metadata);
  46. if (E == Error::USE_AFTER_FREE) {
  47. snprintf(DescriptionBuffer, kDescriptionBufferLen,
  48. "(%zu byte%s into a %zu-byte allocation at 0x%zx) ",
  49. AccessPtr - Address, (AccessPtr - Address == 1) ? "" : "s", Size,
  50. Address);
  51. } else if (AccessPtr < Address) {
  52. snprintf(DescriptionBuffer, kDescriptionBufferLen,
  53. "(%zu byte%s to the left of a %zu-byte allocation at 0x%zx) ",
  54. Address - AccessPtr, (Address - AccessPtr == 1) ? "" : "s", Size,
  55. Address);
  56. } else if (AccessPtr > Address) {
  57. snprintf(DescriptionBuffer, kDescriptionBufferLen,
  58. "(%zu byte%s to the right of a %zu-byte allocation at 0x%zx) ",
  59. AccessPtr - Address, (AccessPtr - Address == 1) ? "" : "s", Size,
  60. Address);
  61. } else {
  62. snprintf(DescriptionBuffer, kDescriptionBufferLen,
  63. "(a %zu-byte allocation) ", Size);
  64. }
  65. }
  66. // Possible number of digits of a 64-bit number: ceil(log10(2^64)) == 20. Add
  67. // a null terminator, and round to the nearest 8-byte boundary.
  68. uint64_t ThreadID = gwp_asan::getThreadID();
  69. constexpr size_t kThreadBufferLen = 24;
  70. char ThreadBuffer[kThreadBufferLen];
  71. if (ThreadID == gwp_asan::kInvalidThreadID)
  72. snprintf(ThreadBuffer, kThreadBufferLen, "<unknown>");
  73. else
  74. snprintf(ThreadBuffer, kThreadBufferLen, "%" PRIu64, ThreadID);
  75. Printf("%s at 0x%zx %sby thread %s here:\n", gwp_asan::ErrorToString(E),
  76. AccessPtr, DescriptionBuffer, ThreadBuffer);
  77. }
  78. void dumpReport(uintptr_t ErrorPtr, const gwp_asan::AllocatorState *State,
  79. const gwp_asan::AllocationMetadata *Metadata,
  80. SegvBacktrace_t SegvBacktrace, Printf_t Printf,
  81. PrintBacktrace_t PrintBacktrace, void *Context) {
  82. assert(State && "dumpReport missing Allocator State.");
  83. assert(Metadata && "dumpReport missing Metadata.");
  84. assert(Printf && "dumpReport missing Printf.");
  85. if (!__gwp_asan_error_is_mine(State, ErrorPtr))
  86. return;
  87. Printf("*** GWP-ASan detected a memory error ***\n");
  88. ScopedEndOfReportDecorator Decorator(Printf);
  89. uintptr_t InternalErrorPtr = __gwp_asan_get_internal_crash_address(State);
  90. if (InternalErrorPtr != 0u)
  91. ErrorPtr = InternalErrorPtr;
  92. Error E = __gwp_asan_diagnose_error(State, Metadata, ErrorPtr);
  93. if (E == Error::UNKNOWN) {
  94. Printf("GWP-ASan cannot provide any more information about this error. "
  95. "This may occur due to a wild memory access into the GWP-ASan pool, "
  96. "or an overflow/underflow that is > 512B in length.\n");
  97. return;
  98. }
  99. const gwp_asan::AllocationMetadata *AllocMeta =
  100. __gwp_asan_get_metadata(State, Metadata, ErrorPtr);
  101. // Print the error header.
  102. printHeader(E, ErrorPtr, AllocMeta, Printf);
  103. // Print the fault backtrace.
  104. static constexpr unsigned kMaximumStackFramesForCrashTrace = 512;
  105. uintptr_t Trace[kMaximumStackFramesForCrashTrace];
  106. size_t TraceLength =
  107. SegvBacktrace(Trace, kMaximumStackFramesForCrashTrace, Context);
  108. PrintBacktrace(Trace, TraceLength, Printf);
  109. if (AllocMeta == nullptr)
  110. return;
  111. // Maybe print the deallocation trace.
  112. if (__gwp_asan_is_deallocated(AllocMeta)) {
  113. uint64_t ThreadID = __gwp_asan_get_deallocation_thread_id(AllocMeta);
  114. if (ThreadID == gwp_asan::kInvalidThreadID)
  115. Printf("0x%zx was deallocated by thread <unknown> here:\n", ErrorPtr);
  116. else
  117. Printf("0x%zx was deallocated by thread %zu here:\n", ErrorPtr, ThreadID);
  118. TraceLength = __gwp_asan_get_deallocation_trace(
  119. AllocMeta, Trace, kMaximumStackFramesForCrashTrace);
  120. PrintBacktrace(Trace, TraceLength, Printf);
  121. }
  122. // Print the allocation trace.
  123. uint64_t ThreadID = __gwp_asan_get_allocation_thread_id(AllocMeta);
  124. if (ThreadID == gwp_asan::kInvalidThreadID)
  125. Printf("0x%zx was allocated by thread <unknown> here:\n", ErrorPtr);
  126. else
  127. Printf("0x%zx was allocated by thread %zu here:\n", ErrorPtr, ThreadID);
  128. TraceLength = __gwp_asan_get_allocation_trace(
  129. AllocMeta, Trace, kMaximumStackFramesForCrashTrace);
  130. PrintBacktrace(Trace, TraceLength, Printf);
  131. }
  132. struct sigaction PreviousHandler;
  133. bool SignalHandlerInstalled;
  134. gwp_asan::GuardedPoolAllocator *GPAForSignalHandler;
  135. Printf_t PrintfForSignalHandler;
  136. PrintBacktrace_t PrintBacktraceForSignalHandler;
  137. SegvBacktrace_t BacktraceForSignalHandler;
  138. static void sigSegvHandler(int sig, siginfo_t *info, void *ucontext) {
  139. if (GPAForSignalHandler) {
  140. GPAForSignalHandler->stop();
  141. dumpReport(reinterpret_cast<uintptr_t>(info->si_addr),
  142. GPAForSignalHandler->getAllocatorState(),
  143. GPAForSignalHandler->getMetadataRegion(),
  144. BacktraceForSignalHandler, PrintfForSignalHandler,
  145. PrintBacktraceForSignalHandler, ucontext);
  146. }
  147. // Process any previous handlers.
  148. if (PreviousHandler.sa_flags & SA_SIGINFO) {
  149. PreviousHandler.sa_sigaction(sig, info, ucontext);
  150. } else if (PreviousHandler.sa_handler == SIG_DFL) {
  151. // If the previous handler was the default handler, cause a core dump.
  152. signal(SIGSEGV, SIG_DFL);
  153. raise(SIGSEGV);
  154. } else if (PreviousHandler.sa_handler == SIG_IGN) {
  155. // If the previous segv handler was SIGIGN, crash iff we were responsible
  156. // for the crash.
  157. if (__gwp_asan_error_is_mine(GPAForSignalHandler->getAllocatorState(),
  158. reinterpret_cast<uintptr_t>(info->si_addr))) {
  159. signal(SIGSEGV, SIG_DFL);
  160. raise(SIGSEGV);
  161. }
  162. } else {
  163. PreviousHandler.sa_handler(sig);
  164. }
  165. }
  166. } // anonymous namespace
  167. namespace gwp_asan {
  168. namespace segv_handler {
  169. void installSignalHandlers(gwp_asan::GuardedPoolAllocator *GPA, Printf_t Printf,
  170. PrintBacktrace_t PrintBacktrace,
  171. SegvBacktrace_t SegvBacktrace) {
  172. assert(GPA && "GPA wasn't provided to installSignalHandlers.");
  173. assert(Printf && "Printf wasn't provided to installSignalHandlers.");
  174. assert(PrintBacktrace &&
  175. "PrintBacktrace wasn't provided to installSignalHandlers.");
  176. assert(SegvBacktrace &&
  177. "SegvBacktrace wasn't provided to installSignalHandlers.");
  178. GPAForSignalHandler = GPA;
  179. PrintfForSignalHandler = Printf;
  180. PrintBacktraceForSignalHandler = PrintBacktrace;
  181. BacktraceForSignalHandler = SegvBacktrace;
  182. struct sigaction Action = {};
  183. Action.sa_sigaction = sigSegvHandler;
  184. Action.sa_flags = SA_SIGINFO;
  185. sigaction(SIGSEGV, &Action, &PreviousHandler);
  186. SignalHandlerInstalled = true;
  187. }
  188. void uninstallSignalHandlers() {
  189. if (SignalHandlerInstalled) {
  190. sigaction(SIGSEGV, &PreviousHandler, nullptr);
  191. SignalHandlerInstalled = false;
  192. }
  193. }
  194. } // namespace segv_handler
  195. } // namespace gwp_asan