PrettyStackTrace.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. //===- PrettyStackTrace.cpp - Pretty Crash Handling -----------------------===//
  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. //
  9. // This file defines some helpful functions for dealing with the possibility of
  10. // Unix signals occurring while your program is running.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Support/PrettyStackTrace.h"
  14. #include "llvm-c/ErrorHandling.h"
  15. #include "llvm/Config/config.h"
  16. #include "llvm/Support/Compiler.h"
  17. #include "llvm/Support/SaveAndRestore.h"
  18. #include "llvm/Support/Signals.h"
  19. #include "llvm/Support/Watchdog.h"
  20. #include "llvm/Support/raw_ostream.h"
  21. #ifdef __APPLE__
  22. #include "llvm/ADT/SmallString.h"
  23. #endif
  24. #include <atomic>
  25. #include <cassert>
  26. #include <cstdarg>
  27. #include <cstdio>
  28. #include <cstring>
  29. #include <tuple>
  30. #ifdef HAVE_CRASHREPORTERCLIENT_H
  31. #include <CrashReporterClient.h>
  32. #endif
  33. using namespace llvm;
  34. static const char *BugReportMsg =
  35. "PLEASE submit a bug report to " BUG_REPORT_URL
  36. " and include the crash backtrace.\n";
  37. // If backtrace support is not enabled, compile out support for pretty stack
  38. // traces. This has the secondary effect of not requiring thread local storage
  39. // when backtrace support is disabled.
  40. #if ENABLE_BACKTRACES
  41. // We need a thread local pointer to manage the stack of our stack trace
  42. // objects, but we *really* cannot tolerate destructors running and do not want
  43. // to pay any overhead of synchronizing. As a consequence, we use a raw
  44. // thread-local variable.
  45. static LLVM_THREAD_LOCAL PrettyStackTraceEntry *PrettyStackTraceHead = nullptr;
  46. // The use of 'volatile' here is to ensure that any particular thread always
  47. // reloads the value of the counter. The 'std::atomic' allows us to specify that
  48. // this variable is accessed in an unsychronized way (it's not actually
  49. // synchronizing). This does technically mean that the value may not appear to
  50. // be the same across threads running simultaneously on different CPUs, but in
  51. // practice the worst that will happen is that we won't print a stack trace when
  52. // we could have.
  53. //
  54. // This is initialized to 1 because 0 is used as a sentinel for "not enabled on
  55. // the current thread". If the user happens to overflow an 'unsigned' with
  56. // SIGINFO requests, it's possible that some threads will stop responding to it,
  57. // but the program won't crash.
  58. static volatile std::atomic<unsigned> GlobalSigInfoGenerationCounter =
  59. ATOMIC_VAR_INIT(1);
  60. static LLVM_THREAD_LOCAL unsigned ThreadLocalSigInfoGenerationCounter = 0;
  61. namespace llvm {
  62. PrettyStackTraceEntry *ReverseStackTrace(PrettyStackTraceEntry *Head) {
  63. PrettyStackTraceEntry *Prev = nullptr;
  64. while (Head)
  65. std::tie(Prev, Head, Head->NextEntry) =
  66. std::make_tuple(Head, Head->NextEntry, Prev);
  67. return Prev;
  68. }
  69. } // namespace llvm
  70. static void PrintStack(raw_ostream &OS) {
  71. // Print out the stack in reverse order. To avoid recursion (which is likely
  72. // to fail if we crashed due to stack overflow), we do an up-front pass to
  73. // reverse the stack, then print it, then reverse it again.
  74. unsigned ID = 0;
  75. SaveAndRestore<PrettyStackTraceEntry *> SavedStack{PrettyStackTraceHead,
  76. nullptr};
  77. PrettyStackTraceEntry *ReversedStack = ReverseStackTrace(SavedStack.get());
  78. for (const PrettyStackTraceEntry *Entry = ReversedStack; Entry;
  79. Entry = Entry->getNextEntry()) {
  80. OS << ID++ << ".\t";
  81. sys::Watchdog W(5);
  82. Entry->print(OS);
  83. }
  84. llvm::ReverseStackTrace(ReversedStack);
  85. }
  86. /// Print the current stack trace to the specified stream.
  87. ///
  88. /// Marked NOINLINE so it can be called from debuggers.
  89. LLVM_ATTRIBUTE_NOINLINE
  90. static void PrintCurStackTrace(raw_ostream &OS) {
  91. // Don't print an empty trace.
  92. if (!PrettyStackTraceHead) return;
  93. // If there are pretty stack frames registered, walk and emit them.
  94. OS << "Stack dump:\n";
  95. PrintStack(OS);
  96. OS.flush();
  97. }
  98. // Integrate with crash reporter libraries.
  99. #if defined (__APPLE__) && defined(HAVE_CRASHREPORTERCLIENT_H)
  100. // If any clients of llvm try to link to libCrashReporterClient.a themselves,
  101. // only one crash info struct will be used.
  102. extern "C" {
  103. CRASH_REPORTER_CLIENT_HIDDEN
  104. struct crashreporter_annotations_t gCRAnnotations
  105. __attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION)))
  106. #if CRASHREPORTER_ANNOTATIONS_VERSION < 5
  107. = { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0 };
  108. #else
  109. = { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0, 0 };
  110. #endif
  111. }
  112. #elif defined(__APPLE__) && HAVE_CRASHREPORTER_INFO
  113. extern "C" const char *__crashreporter_info__
  114. __attribute__((visibility("hidden"))) = 0;
  115. asm(".desc ___crashreporter_info__, 0x10");
  116. #endif
  117. static void setCrashLogMessage(const char *msg) LLVM_ATTRIBUTE_UNUSED;
  118. static void setCrashLogMessage(const char *msg) {
  119. #ifdef HAVE_CRASHREPORTERCLIENT_H
  120. (void)CRSetCrashLogMessage(msg);
  121. #elif HAVE_CRASHREPORTER_INFO
  122. __crashreporter_info__ = msg;
  123. #endif
  124. // Don't reorder subsequent operations: whatever comes after might crash and
  125. // we want the system crash handling to see the message we just set.
  126. std::atomic_signal_fence(std::memory_order_seq_cst);
  127. }
  128. #ifdef __APPLE__
  129. using CrashHandlerString = SmallString<2048>;
  130. using CrashHandlerStringStorage =
  131. std::aligned_storage<sizeof(CrashHandlerString),
  132. alignof(CrashHandlerString)>::type;
  133. static CrashHandlerStringStorage crashHandlerStringStorage;
  134. #endif
  135. /// This callback is run if a fatal signal is delivered to the process, it
  136. /// prints the pretty stack trace.
  137. static void CrashHandler(void *) {
  138. errs() << BugReportMsg ;
  139. #ifndef __APPLE__
  140. // On non-apple systems, just emit the crash stack trace to stderr.
  141. PrintCurStackTrace(errs());
  142. #else
  143. // Emit the crash stack trace to a SmallString, put it where the system crash
  144. // handling will find it, and also send it to stderr.
  145. //
  146. // The SmallString is fairly large in the hope that we don't allocate (we're
  147. // handling a fatal signal, something is already pretty wrong, allocation
  148. // might not work). Further, we don't use a magic static in case that's also
  149. // borked. We leak any allocation that does occur because the program is about
  150. // to die anyways. This is technically racy if we were handling two fatal
  151. // signals, however if we're in that situation a race is the least of our
  152. // worries.
  153. auto &crashHandlerString =
  154. *new (&crashHandlerStringStorage) CrashHandlerString;
  155. // If we crash while trying to print the stack trace, we still want the system
  156. // crash handling to have some partial information. That'll work out as long
  157. // as the SmallString doesn't allocate. If it does allocate then the system
  158. // crash handling will see some garbage because the inline buffer now contains
  159. // a pointer.
  160. setCrashLogMessage(crashHandlerString.c_str());
  161. {
  162. raw_svector_ostream Stream(crashHandlerString);
  163. PrintCurStackTrace(Stream);
  164. }
  165. if (!crashHandlerString.empty()) {
  166. setCrashLogMessage(crashHandlerString.c_str());
  167. errs() << crashHandlerString.str();
  168. } else
  169. setCrashLogMessage("No crash information.");
  170. #endif
  171. }
  172. static void printForSigInfoIfNeeded() {
  173. unsigned CurrentSigInfoGeneration =
  174. GlobalSigInfoGenerationCounter.load(std::memory_order_relaxed);
  175. if (ThreadLocalSigInfoGenerationCounter == 0 ||
  176. ThreadLocalSigInfoGenerationCounter == CurrentSigInfoGeneration) {
  177. return;
  178. }
  179. PrintCurStackTrace(errs());
  180. ThreadLocalSigInfoGenerationCounter = CurrentSigInfoGeneration;
  181. }
  182. #endif // ENABLE_BACKTRACES
  183. void llvm::setBugReportMsg(const char *Msg) {
  184. BugReportMsg = Msg;
  185. }
  186. const char *llvm::getBugReportMsg() {
  187. return BugReportMsg;
  188. }
  189. PrettyStackTraceEntry::PrettyStackTraceEntry() {
  190. #if ENABLE_BACKTRACES
  191. // Handle SIGINFO first, because we haven't finished constructing yet.
  192. printForSigInfoIfNeeded();
  193. // Link ourselves.
  194. NextEntry = PrettyStackTraceHead;
  195. PrettyStackTraceHead = this;
  196. #endif
  197. }
  198. PrettyStackTraceEntry::~PrettyStackTraceEntry() {
  199. #if ENABLE_BACKTRACES
  200. assert(PrettyStackTraceHead == this &&
  201. "Pretty stack trace entry destruction is out of order");
  202. PrettyStackTraceHead = NextEntry;
  203. // Handle SIGINFO first, because we already started destructing.
  204. printForSigInfoIfNeeded();
  205. #endif
  206. }
  207. void PrettyStackTraceString::print(raw_ostream &OS) const { OS << Str << "\n"; }
  208. PrettyStackTraceFormat::PrettyStackTraceFormat(const char *Format, ...) {
  209. va_list AP;
  210. va_start(AP, Format);
  211. const int SizeOrError = vsnprintf(nullptr, 0, Format, AP);
  212. va_end(AP);
  213. if (SizeOrError < 0) {
  214. return;
  215. }
  216. const int Size = SizeOrError + 1; // '\0'
  217. Str.resize(Size);
  218. va_start(AP, Format);
  219. vsnprintf(Str.data(), Size, Format, AP);
  220. va_end(AP);
  221. }
  222. void PrettyStackTraceFormat::print(raw_ostream &OS) const { OS << Str << "\n"; }
  223. void PrettyStackTraceProgram::print(raw_ostream &OS) const {
  224. OS << "Program arguments: ";
  225. // Print the argument list.
  226. for (int I = 0; I < ArgC; ++I) {
  227. const bool HaveSpace = ::strchr(ArgV[I], ' ');
  228. if (I)
  229. OS << ' ';
  230. if (HaveSpace)
  231. OS << '"';
  232. OS.write_escaped(ArgV[I]);
  233. if (HaveSpace)
  234. OS << '"';
  235. }
  236. OS << '\n';
  237. }
  238. #if ENABLE_BACKTRACES
  239. static bool RegisterCrashPrinter() {
  240. sys::AddSignalHandler(CrashHandler, nullptr);
  241. return false;
  242. }
  243. #endif
  244. void llvm::EnablePrettyStackTrace() {
  245. #if ENABLE_BACKTRACES
  246. // The first time this is called, we register the crash printer.
  247. static bool HandlerRegistered = RegisterCrashPrinter();
  248. (void)HandlerRegistered;
  249. #endif
  250. }
  251. void llvm::EnablePrettyStackTraceOnSigInfoForThisThread(bool ShouldEnable) {
  252. #if ENABLE_BACKTRACES
  253. if (!ShouldEnable) {
  254. ThreadLocalSigInfoGenerationCounter = 0;
  255. return;
  256. }
  257. // The first time this is called, we register the SIGINFO handler.
  258. static bool HandlerRegistered = []{
  259. sys::SetInfoSignalFunction([]{
  260. GlobalSigInfoGenerationCounter.fetch_add(1, std::memory_order_relaxed);
  261. });
  262. return false;
  263. }();
  264. (void)HandlerRegistered;
  265. // Next, enable it for the current thread.
  266. ThreadLocalSigInfoGenerationCounter =
  267. GlobalSigInfoGenerationCounter.load(std::memory_order_relaxed);
  268. #endif
  269. }
  270. const void *llvm::SavePrettyStackState() {
  271. #if ENABLE_BACKTRACES
  272. return PrettyStackTraceHead;
  273. #else
  274. return nullptr;
  275. #endif
  276. }
  277. void llvm::RestorePrettyStackState(const void *Top) {
  278. #if ENABLE_BACKTRACES
  279. PrettyStackTraceHead =
  280. static_cast<PrettyStackTraceEntry *>(const_cast<void *>(Top));
  281. #endif
  282. }
  283. void LLVMEnablePrettyStackTrace() {
  284. EnablePrettyStackTrace();
  285. }