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