xref: /src/contrib/llvm-project/llvm/lib/Support/PrettyStackTrace.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1009b1c42SEd Schouten //===- PrettyStackTrace.cpp - Pretty Crash Handling -----------------------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This file defines some helpful functions for dealing with the possibility of
106b943ff3SDimitry Andric // Unix signals occurring while your program is running.
11009b1c42SEd Schouten //
12009b1c42SEd Schouten //===----------------------------------------------------------------------===//
13009b1c42SEd Schouten 
14009b1c42SEd Schouten #include "llvm/Support/PrettyStackTrace.h"
15dd58ef01SDimitry Andric #include "llvm-c/ErrorHandling.h"
16e6d15924SDimitry Andric #include "llvm/Config/config.h"
175a5ac124SDimitry Andric #include "llvm/Support/Compiler.h"
18e6d15924SDimitry Andric #include "llvm/Support/SaveAndRestore.h"
19cf099d11SDimitry Andric #include "llvm/Support/Signals.h"
204a16efa3SDimitry Andric #include "llvm/Support/Watchdog.h"
214a16efa3SDimitry Andric #include "llvm/Support/raw_ostream.h"
2266e41e3cSRoman Divacky 
236f8fc217SDimitry Andric #ifdef __APPLE__
246f8fc217SDimitry Andric #include "llvm/ADT/SmallString.h"
256f8fc217SDimitry Andric #endif
266f8fc217SDimitry Andric 
27e6d15924SDimitry Andric #include <atomic>
28cfca06d7SDimitry Andric #include <cassert>
29b915e9e0SDimitry Andric #include <cstdarg>
30a303c417SDimitry Andric #include <cstdio>
31b60736ecSDimitry Andric #include <cstring>
3201095a5dSDimitry Andric #include <tuple>
3301095a5dSDimitry Andric 
3466e41e3cSRoman Divacky #ifdef HAVE_CRASHREPORTERCLIENT_H
3566e41e3cSRoman Divacky #include <CrashReporterClient.h>
3666e41e3cSRoman Divacky #endif
3766e41e3cSRoman Divacky 
38009b1c42SEd Schouten using namespace llvm;
39009b1c42SEd Schouten 
40cfca06d7SDimitry Andric static const char *BugReportMsg =
41cfca06d7SDimitry Andric     "PLEASE submit a bug report to " BUG_REPORT_URL
42cfca06d7SDimitry Andric     " and include the crash backtrace.\n";
43cfca06d7SDimitry Andric 
445a5ac124SDimitry Andric // If backtrace support is not enabled, compile out support for pretty stack
455a5ac124SDimitry Andric // traces.  This has the secondary effect of not requiring thread local storage
465a5ac124SDimitry Andric // when backtrace support is disabled.
47e6d15924SDimitry Andric #if ENABLE_BACKTRACES
485a5ac124SDimitry Andric 
495a5ac124SDimitry Andric // We need a thread local pointer to manage the stack of our stack trace
505a5ac124SDimitry Andric // objects, but we *really* cannot tolerate destructors running and do not want
515a5ac124SDimitry Andric // to pay any overhead of synchronizing. As a consequence, we use a raw
525a5ac124SDimitry Andric // thread-local variable.
5301095a5dSDimitry Andric static LLVM_THREAD_LOCAL PrettyStackTraceEntry *PrettyStackTraceHead = nullptr;
54009b1c42SEd Schouten 
55e6d15924SDimitry Andric // The use of 'volatile' here is to ensure that any particular thread always
56e6d15924SDimitry Andric // reloads the value of the counter. The 'std::atomic' allows us to specify that
57e6d15924SDimitry Andric // this variable is accessed in an unsychronized way (it's not actually
58e6d15924SDimitry Andric // synchronizing). This does technically mean that the value may not appear to
59e6d15924SDimitry Andric // be the same across threads running simultaneously on different CPUs, but in
60e6d15924SDimitry Andric // practice the worst that will happen is that we won't print a stack trace when
61e6d15924SDimitry Andric // we could have.
62e6d15924SDimitry Andric //
63e6d15924SDimitry Andric // This is initialized to 1 because 0 is used as a sentinel for "not enabled on
64e6d15924SDimitry Andric // the current thread". If the user happens to overflow an 'unsigned' with
65e6d15924SDimitry Andric // SIGINFO requests, it's possible that some threads will stop responding to it,
66e6d15924SDimitry Andric // but the program won't crash.
677fa27ce4SDimitry Andric static volatile std::atomic<unsigned> GlobalSigInfoGenerationCounter = 1;
68e6d15924SDimitry Andric static LLVM_THREAD_LOCAL unsigned ThreadLocalSigInfoGenerationCounter = 0;
69e6d15924SDimitry Andric 
7001095a5dSDimitry Andric namespace llvm {
ReverseStackTrace(PrettyStackTraceEntry * Head)7101095a5dSDimitry Andric PrettyStackTraceEntry *ReverseStackTrace(PrettyStackTraceEntry *Head) {
7201095a5dSDimitry Andric   PrettyStackTraceEntry *Prev = nullptr;
7301095a5dSDimitry Andric   while (Head)
7401095a5dSDimitry Andric     std::tie(Prev, Head, Head->NextEntry) =
7501095a5dSDimitry Andric         std::make_tuple(Head, Head->NextEntry, Prev);
7601095a5dSDimitry Andric   return Prev;
7701095a5dSDimitry Andric }
78344a3780SDimitry Andric } // namespace llvm
7901095a5dSDimitry Andric 
PrintStack(raw_ostream & OS)8001095a5dSDimitry Andric static void PrintStack(raw_ostream &OS) {
8101095a5dSDimitry Andric   // Print out the stack in reverse order. To avoid recursion (which is likely
8201095a5dSDimitry Andric   // to fail if we crashed due to stack overflow), we do an up-front pass to
8301095a5dSDimitry Andric   // reverse the stack, then print it, then reverse it again.
8401095a5dSDimitry Andric   unsigned ID = 0;
85e6d15924SDimitry Andric   SaveAndRestore<PrettyStackTraceEntry *> SavedStack{PrettyStackTraceHead,
86e6d15924SDimitry Andric                                                      nullptr};
87e6d15924SDimitry Andric   PrettyStackTraceEntry *ReversedStack = ReverseStackTrace(SavedStack.get());
8801095a5dSDimitry Andric   for (const PrettyStackTraceEntry *Entry = ReversedStack; Entry;
8901095a5dSDimitry Andric        Entry = Entry->getNextEntry()) {
9001095a5dSDimitry Andric     OS << ID++ << ".\t";
914a16efa3SDimitry Andric     sys::Watchdog W(5);
92009b1c42SEd Schouten     Entry->print(OS);
934a16efa3SDimitry Andric   }
9401095a5dSDimitry Andric   llvm::ReverseStackTrace(ReversedStack);
95009b1c42SEd Schouten }
96009b1c42SEd Schouten 
97e6d15924SDimitry Andric /// Print the current stack trace to the specified stream.
98e6d15924SDimitry Andric ///
99e6d15924SDimitry Andric /// Marked NOINLINE so it can be called from debuggers.
100e6d15924SDimitry Andric LLVM_ATTRIBUTE_NOINLINE
PrintCurStackTrace(raw_ostream & OS)101009b1c42SEd Schouten static void PrintCurStackTrace(raw_ostream &OS) {
102009b1c42SEd Schouten   // Don't print an empty trace.
1035a5ac124SDimitry Andric   if (!PrettyStackTraceHead) return;
104009b1c42SEd Schouten 
105009b1c42SEd Schouten   // If there are pretty stack frames registered, walk and emit them.
106009b1c42SEd Schouten   OS << "Stack dump:\n";
107009b1c42SEd Schouten 
10801095a5dSDimitry Andric   PrintStack(OS);
109009b1c42SEd Schouten   OS.flush();
110009b1c42SEd Schouten }
111009b1c42SEd Schouten 
11266e41e3cSRoman Divacky // Integrate with crash reporter libraries.
113b915e9e0SDimitry Andric #if defined (__APPLE__) && defined(HAVE_CRASHREPORTERCLIENT_H)
11466e41e3cSRoman Divacky //  If any clients of llvm try to link to libCrashReporterClient.a themselves,
11566e41e3cSRoman Divacky //  only one crash info struct will be used.
11666e41e3cSRoman Divacky extern "C" {
11766e41e3cSRoman Divacky CRASH_REPORTER_CLIENT_HIDDEN
11866e41e3cSRoman Divacky struct crashreporter_annotations_t gCRAnnotations
11966e41e3cSRoman Divacky         __attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION)))
120eb11fae6SDimitry Andric #if CRASHREPORTER_ANNOTATIONS_VERSION < 5
12130815c53SDimitry Andric         = { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0 };
122eb11fae6SDimitry Andric #else
123eb11fae6SDimitry Andric         = { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0, 0 };
124eb11fae6SDimitry Andric #endif
12566e41e3cSRoman Divacky }
126cf099d11SDimitry Andric #elif defined(__APPLE__) && HAVE_CRASHREPORTER_INFO
127b915e9e0SDimitry Andric extern "C" const char *__crashreporter_info__
128b915e9e0SDimitry Andric     __attribute__((visibility("hidden"))) = 0;
129abdf259dSRoman Divacky asm(".desc ___crashreporter_info__, 0x10");
130009b1c42SEd Schouten #endif
131009b1c42SEd Schouten 
1321d5ae102SDimitry Andric static void setCrashLogMessage(const char *msg) LLVM_ATTRIBUTE_UNUSED;
setCrashLogMessage(const char * msg)1331d5ae102SDimitry Andric static void setCrashLogMessage(const char *msg) {
1341d5ae102SDimitry Andric #ifdef HAVE_CRASHREPORTERCLIENT_H
1351d5ae102SDimitry Andric   (void)CRSetCrashLogMessage(msg);
1361d5ae102SDimitry Andric #elif HAVE_CRASHREPORTER_INFO
1371d5ae102SDimitry Andric   __crashreporter_info__ = msg;
1381d5ae102SDimitry Andric #endif
1391d5ae102SDimitry Andric   // Don't reorder subsequent operations: whatever comes after might crash and
1401d5ae102SDimitry Andric   // we want the system crash handling to see the message we just set.
1411d5ae102SDimitry Andric   std::atomic_signal_fence(std::memory_order_seq_cst);
1421d5ae102SDimitry Andric }
1431d5ae102SDimitry Andric 
1441d5ae102SDimitry Andric #ifdef __APPLE__
1451d5ae102SDimitry Andric using CrashHandlerString = SmallString<2048>;
146ac9a064cSDimitry Andric using CrashHandlerStringStorage = std::byte[sizeof(CrashHandlerString)];
147ac9a064cSDimitry Andric alignas(CrashHandlerString) static CrashHandlerStringStorage
148ac9a064cSDimitry Andric     crashHandlerStringStorage;
1491d5ae102SDimitry Andric #endif
1501d5ae102SDimitry Andric 
1511d5ae102SDimitry Andric /// This callback is run if a fatal signal is delivered to the process, it
1521d5ae102SDimitry Andric /// prints the pretty stack trace.
CrashHandler(void *)153d39c594dSDimitry Andric static void CrashHandler(void *) {
154cfca06d7SDimitry Andric   errs() << BugReportMsg ;
155cfca06d7SDimitry Andric 
156009b1c42SEd Schouten #ifndef __APPLE__
157009b1c42SEd Schouten   // On non-apple systems, just emit the crash stack trace to stderr.
158009b1c42SEd Schouten   PrintCurStackTrace(errs());
159009b1c42SEd Schouten #else
1601d5ae102SDimitry Andric   // Emit the crash stack trace to a SmallString, put it where the system crash
1611d5ae102SDimitry Andric   // handling will find it, and also send it to stderr.
1621d5ae102SDimitry Andric   //
1631d5ae102SDimitry Andric   // The SmallString is fairly large in the hope that we don't allocate (we're
1641d5ae102SDimitry Andric   // handling a fatal signal, something is already pretty wrong, allocation
1651d5ae102SDimitry Andric   // might not work). Further, we don't use a magic static in case that's also
1661d5ae102SDimitry Andric   // borked. We leak any allocation that does occur because the program is about
1671d5ae102SDimitry Andric   // to die anyways. This is technically racy if we were handling two fatal
1681d5ae102SDimitry Andric   // signals, however if we're in that situation a race is the least of our
1691d5ae102SDimitry Andric   // worries.
1701d5ae102SDimitry Andric   auto &crashHandlerString =
1711d5ae102SDimitry Andric       *new (&crashHandlerStringStorage) CrashHandlerString;
1721d5ae102SDimitry Andric 
1731d5ae102SDimitry Andric   // If we crash while trying to print the stack trace, we still want the system
1741d5ae102SDimitry Andric   // crash handling to have some partial information. That'll work out as long
1751d5ae102SDimitry Andric   // as the SmallString doesn't allocate. If it does allocate then the system
1761d5ae102SDimitry Andric   // crash handling will see some garbage because the inline buffer now contains
1771d5ae102SDimitry Andric   // a pointer.
1781d5ae102SDimitry Andric   setCrashLogMessage(crashHandlerString.c_str());
1791d5ae102SDimitry Andric 
180009b1c42SEd Schouten   {
1811d5ae102SDimitry Andric     raw_svector_ostream Stream(crashHandlerString);
182009b1c42SEd Schouten     PrintCurStackTrace(Stream);
183009b1c42SEd Schouten   }
184009b1c42SEd Schouten 
1851d5ae102SDimitry Andric   if (!crashHandlerString.empty()) {
1861d5ae102SDimitry Andric     setCrashLogMessage(crashHandlerString.c_str());
1871d5ae102SDimitry Andric     errs() << crashHandlerString.str();
1881d5ae102SDimitry Andric   } else
1891d5ae102SDimitry Andric     setCrashLogMessage("No crash information.");
190009b1c42SEd Schouten #endif
191009b1c42SEd Schouten }
192009b1c42SEd Schouten 
printForSigInfoIfNeeded()193e6d15924SDimitry Andric static void printForSigInfoIfNeeded() {
194e6d15924SDimitry Andric   unsigned CurrentSigInfoGeneration =
195e6d15924SDimitry Andric       GlobalSigInfoGenerationCounter.load(std::memory_order_relaxed);
196e6d15924SDimitry Andric   if (ThreadLocalSigInfoGenerationCounter == 0 ||
197e6d15924SDimitry Andric       ThreadLocalSigInfoGenerationCounter == CurrentSigInfoGeneration) {
198e6d15924SDimitry Andric     return;
199e6d15924SDimitry Andric   }
200e6d15924SDimitry Andric 
201e6d15924SDimitry Andric   PrintCurStackTrace(errs());
202e6d15924SDimitry Andric   ThreadLocalSigInfoGenerationCounter = CurrentSigInfoGeneration;
203e6d15924SDimitry Andric }
204e6d15924SDimitry Andric 
205e6d15924SDimitry Andric #endif // ENABLE_BACKTRACES
2065a5ac124SDimitry Andric 
setBugReportMsg(const char * Msg)207cfca06d7SDimitry Andric void llvm::setBugReportMsg(const char *Msg) {
208cfca06d7SDimitry Andric   BugReportMsg = Msg;
209cfca06d7SDimitry Andric }
210cfca06d7SDimitry Andric 
getBugReportMsg()211cfca06d7SDimitry Andric const char *llvm::getBugReportMsg() {
212cfca06d7SDimitry Andric   return BugReportMsg;
213cfca06d7SDimitry Andric }
214cfca06d7SDimitry Andric 
PrettyStackTraceEntry()215009b1c42SEd Schouten PrettyStackTraceEntry::PrettyStackTraceEntry() {
216e6d15924SDimitry Andric #if ENABLE_BACKTRACES
217e6d15924SDimitry Andric   // Handle SIGINFO first, because we haven't finished constructing yet.
218e6d15924SDimitry Andric   printForSigInfoIfNeeded();
219009b1c42SEd Schouten   // Link ourselves.
2205a5ac124SDimitry Andric   NextEntry = PrettyStackTraceHead;
2215a5ac124SDimitry Andric   PrettyStackTraceHead = this;
2225a5ac124SDimitry Andric #endif
223009b1c42SEd Schouten }
224009b1c42SEd Schouten 
~PrettyStackTraceEntry()225009b1c42SEd Schouten PrettyStackTraceEntry::~PrettyStackTraceEntry() {
226e6d15924SDimitry Andric #if ENABLE_BACKTRACES
2275a5ac124SDimitry Andric   assert(PrettyStackTraceHead == this &&
228009b1c42SEd Schouten          "Pretty stack trace entry destruction is out of order");
22901095a5dSDimitry Andric   PrettyStackTraceHead = NextEntry;
230e6d15924SDimitry Andric   // Handle SIGINFO first, because we already started destructing.
231e6d15924SDimitry Andric   printForSigInfoIfNeeded();
2325a5ac124SDimitry Andric #endif
233009b1c42SEd Schouten }
234009b1c42SEd Schouten 
print(raw_ostream & OS) const235b915e9e0SDimitry Andric void PrettyStackTraceString::print(raw_ostream &OS) const { OS << Str << "\n"; }
236b915e9e0SDimitry Andric 
PrettyStackTraceFormat(const char * Format,...)237b915e9e0SDimitry Andric PrettyStackTraceFormat::PrettyStackTraceFormat(const char *Format, ...) {
238b915e9e0SDimitry Andric   va_list AP;
239b915e9e0SDimitry Andric   va_start(AP, Format);
240b915e9e0SDimitry Andric   const int SizeOrError = vsnprintf(nullptr, 0, Format, AP);
241b915e9e0SDimitry Andric   va_end(AP);
242b915e9e0SDimitry Andric   if (SizeOrError < 0) {
243b915e9e0SDimitry Andric     return;
244009b1c42SEd Schouten   }
245009b1c42SEd Schouten 
246b915e9e0SDimitry Andric   const int Size = SizeOrError + 1; // '\0'
247b915e9e0SDimitry Andric   Str.resize(Size);
248b915e9e0SDimitry Andric   va_start(AP, Format);
249b915e9e0SDimitry Andric   vsnprintf(Str.data(), Size, Format, AP);
250b915e9e0SDimitry Andric   va_end(AP);
251b915e9e0SDimitry Andric }
252b915e9e0SDimitry Andric 
print(raw_ostream & OS) const253b915e9e0SDimitry Andric void PrettyStackTraceFormat::print(raw_ostream &OS) const { OS << Str << "\n"; }
254b915e9e0SDimitry Andric 
print(raw_ostream & OS) const255009b1c42SEd Schouten void PrettyStackTraceProgram::print(raw_ostream &OS) const {
256009b1c42SEd Schouten   OS << "Program arguments: ";
257009b1c42SEd Schouten   // Print the argument list.
258b60736ecSDimitry Andric   for (int I = 0; I < ArgC; ++I) {
259b60736ecSDimitry Andric     const bool HaveSpace = ::strchr(ArgV[I], ' ');
260b60736ecSDimitry Andric     if (I)
261b60736ecSDimitry Andric       OS << ' ';
262b60736ecSDimitry Andric     if (HaveSpace)
263b60736ecSDimitry Andric       OS << '"';
264b60736ecSDimitry Andric     OS.write_escaped(ArgV[I]);
265b60736ecSDimitry Andric     if (HaveSpace)
266b60736ecSDimitry Andric       OS << '"';
267b60736ecSDimitry Andric   }
268009b1c42SEd Schouten   OS << '\n';
269009b1c42SEd Schouten }
270f8af5cf6SDimitry Andric 
271e6d15924SDimitry Andric #if ENABLE_BACKTRACES
RegisterCrashPrinter()272f8af5cf6SDimitry Andric static bool RegisterCrashPrinter() {
2735ca98fd9SDimitry Andric   sys::AddSignalHandler(CrashHandler, nullptr);
274f8af5cf6SDimitry Andric   return false;
275f8af5cf6SDimitry Andric }
2765a5ac124SDimitry Andric #endif
277f8af5cf6SDimitry Andric 
EnablePrettyStackTrace()278f8af5cf6SDimitry Andric void llvm::EnablePrettyStackTrace() {
279e6d15924SDimitry Andric #if ENABLE_BACKTRACES
280f8af5cf6SDimitry Andric   // The first time this is called, we register the crash printer.
281f8af5cf6SDimitry Andric   static bool HandlerRegistered = RegisterCrashPrinter();
282f8af5cf6SDimitry Andric   (void)HandlerRegistered;
2835a5ac124SDimitry Andric #endif
284f8af5cf6SDimitry Andric }
285f8af5cf6SDimitry Andric 
EnablePrettyStackTraceOnSigInfoForThisThread(bool ShouldEnable)286e6d15924SDimitry Andric void llvm::EnablePrettyStackTraceOnSigInfoForThisThread(bool ShouldEnable) {
287e6d15924SDimitry Andric #if ENABLE_BACKTRACES
288e6d15924SDimitry Andric   if (!ShouldEnable) {
289e6d15924SDimitry Andric     ThreadLocalSigInfoGenerationCounter = 0;
290e6d15924SDimitry Andric     return;
291e6d15924SDimitry Andric   }
292e6d15924SDimitry Andric 
293e6d15924SDimitry Andric   // The first time this is called, we register the SIGINFO handler.
294e6d15924SDimitry Andric   static bool HandlerRegistered = []{
295e6d15924SDimitry Andric     sys::SetInfoSignalFunction([]{
296e6d15924SDimitry Andric       GlobalSigInfoGenerationCounter.fetch_add(1, std::memory_order_relaxed);
297e6d15924SDimitry Andric     });
298e6d15924SDimitry Andric     return false;
299e6d15924SDimitry Andric   }();
300e6d15924SDimitry Andric   (void)HandlerRegistered;
301e6d15924SDimitry Andric 
302e6d15924SDimitry Andric   // Next, enable it for the current thread.
303e6d15924SDimitry Andric   ThreadLocalSigInfoGenerationCounter =
304e6d15924SDimitry Andric       GlobalSigInfoGenerationCounter.load(std::memory_order_relaxed);
305e6d15924SDimitry Andric #endif
306e6d15924SDimitry Andric }
307e6d15924SDimitry Andric 
SavePrettyStackState()308dd58ef01SDimitry Andric const void *llvm::SavePrettyStackState() {
309e6d15924SDimitry Andric #if ENABLE_BACKTRACES
310dd58ef01SDimitry Andric   return PrettyStackTraceHead;
311dd58ef01SDimitry Andric #else
312dd58ef01SDimitry Andric   return nullptr;
313dd58ef01SDimitry Andric #endif
314dd58ef01SDimitry Andric }
315dd58ef01SDimitry Andric 
RestorePrettyStackState(const void * Top)316dd58ef01SDimitry Andric void llvm::RestorePrettyStackState(const void *Top) {
317e6d15924SDimitry Andric #if ENABLE_BACKTRACES
31801095a5dSDimitry Andric   PrettyStackTraceHead =
31901095a5dSDimitry Andric       static_cast<PrettyStackTraceEntry *>(const_cast<void *>(Top));
320dd58ef01SDimitry Andric #endif
321dd58ef01SDimitry Andric }
322dd58ef01SDimitry Andric 
LLVMEnablePrettyStackTrace()323f8af5cf6SDimitry Andric void LLVMEnablePrettyStackTrace() {
324f8af5cf6SDimitry Andric   EnablePrettyStackTrace();
325f8af5cf6SDimitry Andric }
326