xref: /llvm-project/llvm/lib/Support/PrettyStackTrace.cpp (revision 032dbf9ee3646743de95a98195149d377065573f)
1 //===- PrettyStackTrace.cpp - Pretty Crash Handling -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines some helpful functions for dealing with the possibility of
11 // Unix signals occurring while your program is running.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Support/PrettyStackTrace.h"
16 #include "llvm-c/ErrorHandling.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/Config/config.h"     // Get autoconf configuration settings
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/Signals.h"
21 #include "llvm/Support/Watchdog.h"
22 #include "llvm/Support/raw_ostream.h"
23 
24 #include <tuple>
25 
26 #ifdef HAVE_CRASHREPORTERCLIENT_H
27 #include <CrashReporterClient.h>
28 #endif
29 
30 using namespace llvm;
31 
32 // If backtrace support is not enabled, compile out support for pretty stack
33 // traces.  This has the secondary effect of not requiring thread local storage
34 // when backtrace support is disabled.
35 #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES
36 
37 // We need a thread local pointer to manage the stack of our stack trace
38 // objects, but we *really* cannot tolerate destructors running and do not want
39 // to pay any overhead of synchronizing. As a consequence, we use a raw
40 // thread-local variable.
41 static LLVM_THREAD_LOCAL PrettyStackTraceEntry *PrettyStackTraceHead = nullptr;
42 
43 namespace llvm {
44 PrettyStackTraceEntry *ReverseStackTrace(PrettyStackTraceEntry *Head) {
45   PrettyStackTraceEntry *Prev = nullptr;
46   while (Head)
47     std::tie(Prev, Head, Head->NextEntry) =
48         std::make_tuple(Head, Head->NextEntry, Prev);
49   return Prev;
50 }
51 }
52 
53 static void PrintStack(raw_ostream &OS) {
54   // Print out the stack in reverse order. To avoid recursion (which is likely
55   // to fail if we crashed due to stack overflow), we do an up-front pass to
56   // reverse the stack, then print it, then reverse it again.
57   unsigned ID = 0;
58   PrettyStackTraceEntry *ReversedStack =
59       llvm::ReverseStackTrace(PrettyStackTraceHead);
60   for (const PrettyStackTraceEntry *Entry = ReversedStack; Entry;
61        Entry = Entry->getNextEntry()) {
62     OS << ID++ << ".\t";
63     sys::Watchdog W(5);
64     Entry->print(OS);
65   }
66   llvm::ReverseStackTrace(ReversedStack);
67 }
68 
69 /// PrintCurStackTrace - Print the current stack trace to the specified stream.
70 static void PrintCurStackTrace(raw_ostream &OS) {
71   // Don't print an empty trace.
72   if (!PrettyStackTraceHead) return;
73 
74   // If there are pretty stack frames registered, walk and emit them.
75   OS << "Stack dump:\n";
76 
77   PrintStack(OS);
78   OS.flush();
79 }
80 
81 // Integrate with crash reporter libraries.
82 #if defined (__APPLE__) && defined(HAVE_CRASHREPORTERCLIENT_H)
83 //  If any clients of llvm try to link to libCrashReporterClient.a themselves,
84 //  only one crash info struct will be used.
85 extern "C" {
86 CRASH_REPORTER_CLIENT_HIDDEN
87 struct crashreporter_annotations_t gCRAnnotations
88         __attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION)))
89         = { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0 };
90 }
91 #elif defined(__APPLE__) && HAVE_CRASHREPORTER_INFO
92 extern "C" const char *__crashreporter_info__
93     __attribute__((visibility("hidden"))) = 0;
94 asm(".desc ___crashreporter_info__, 0x10");
95 #endif
96 
97 /// CrashHandler - This callback is run if a fatal signal is delivered to the
98 /// process, it prints the pretty stack trace.
99 static void CrashHandler(void *) {
100 #ifndef __APPLE__
101   // On non-apple systems, just emit the crash stack trace to stderr.
102   PrintCurStackTrace(errs());
103 #else
104   // Otherwise, emit to a smallvector of chars, send *that* to stderr, but also
105   // put it into __crashreporter_info__.
106   SmallString<2048> TmpStr;
107   {
108     raw_svector_ostream Stream(TmpStr);
109     PrintCurStackTrace(Stream);
110   }
111 
112   if (!TmpStr.empty()) {
113 #ifdef HAVE_CRASHREPORTERCLIENT_H
114     // Cast to void to avoid warning.
115     (void)CRSetCrashLogMessage(std::string(TmpStr.str()).c_str());
116 #elif HAVE_CRASHREPORTER_INFO
117     __crashreporter_info__ = strdup(std::string(TmpStr.str()).c_str());
118 #endif
119     errs() << TmpStr.str();
120   }
121 
122 #endif
123 }
124 
125 // defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES
126 #endif
127 
128 PrettyStackTraceEntry::PrettyStackTraceEntry() {
129 #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES
130   // Link ourselves.
131   NextEntry = PrettyStackTraceHead;
132   PrettyStackTraceHead = this;
133 #endif
134 }
135 
136 PrettyStackTraceEntry::~PrettyStackTraceEntry() {
137 #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES
138   assert(PrettyStackTraceHead == this &&
139          "Pretty stack trace entry destruction is out of order");
140   PrettyStackTraceHead = NextEntry;
141 #endif
142 }
143 
144 void PrettyStackTraceString::print(raw_ostream &OS) const { OS << Str << "\n"; }
145 
146 PrettyStackTraceFormat::PrettyStackTraceFormat(const char *Format, ...) {
147   va_list AP;
148   va_start(AP, Format);
149   const int SizeOrError = vsnprintf(nullptr, 0, Format, AP);
150   va_end(AP);
151   if (SizeOrError < 0) {
152     return;
153   }
154 
155   const int Size = SizeOrError + 1; // '\0'
156   Str.resize(Size);
157   va_start(AP, Format);
158   vsnprintf(Str.data(), Size, Format, AP);
159   va_end(AP);
160 }
161 
162 void PrettyStackTraceFormat::print(raw_ostream &OS) const { OS << Str << "\n"; }
163 
164 void PrettyStackTraceProgram::print(raw_ostream &OS) const {
165   OS << "Program arguments: ";
166   // Print the argument list.
167   for (unsigned i = 0, e = ArgC; i != e; ++i)
168     OS << ArgV[i] << ' ';
169   OS << '\n';
170 }
171 
172 #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES
173 static bool RegisterCrashPrinter() {
174   sys::AddSignalHandler(CrashHandler, nullptr);
175   return false;
176 }
177 #endif
178 
179 void llvm::EnablePrettyStackTrace() {
180 #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES
181   // The first time this is called, we register the crash printer.
182   static bool HandlerRegistered = RegisterCrashPrinter();
183   (void)HandlerRegistered;
184 #endif
185 }
186 
187 const void *llvm::SavePrettyStackState() {
188 #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES
189   return PrettyStackTraceHead;
190 #else
191   return nullptr;
192 #endif
193 }
194 
195 void llvm::RestorePrettyStackState(const void *Top) {
196 #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES
197   PrettyStackTraceHead =
198       static_cast<PrettyStackTraceEntry *>(const_cast<void *>(Top));
199 #endif
200 }
201 
202 void LLVMEnablePrettyStackTrace() {
203   EnablePrettyStackTrace();
204 }
205