xref: /llvm-project/llvm/lib/Support/PrettyStackTrace.cpp (revision be28cddeeaa6e4377de9365e506645ee1eb97e35)
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 <cstdarg>
25 #include <cstdio>
26 #include <tuple>
27 
28 #ifdef HAVE_CRASHREPORTERCLIENT_H
29 #include <CrashReporterClient.h>
30 #endif
31 
32 using namespace llvm;
33 
34 // If backtrace support is not enabled, compile out support for pretty stack
35 // traces.  This has the secondary effect of not requiring thread local storage
36 // when backtrace support is disabled.
37 #if ENABLE_BACKTRACES
38 
39 // We need a thread local pointer to manage the stack of our stack trace
40 // objects, but we *really* cannot tolerate destructors running and do not want
41 // to pay any overhead of synchronizing. As a consequence, we use a raw
42 // thread-local variable.
43 static LLVM_THREAD_LOCAL PrettyStackTraceEntry *PrettyStackTraceHead = nullptr;
44 
45 // The use of 'volatile' here is to ensure that any particular thread always
46 // reloads the value of the counter. The 'std::atomic' allows us to specify that
47 // this variable is accessed in an unsychronized way (it's not actually
48 // synchronizing). This does technically mean that the value may not appear to
49 // be the same across threads running simultaneously on different CPUs, but in
50 // practice the worst that will happen is that we won't print a stack trace when
51 // we could have.
52 //
53 // This is initialized to 1 because 0 is used as a sentinel for "not enabled on
54 // the current thread". If the user happens to overflow an 'unsigned' with
55 // SIGINFO requests, it's possible that some threads will stop responding to it,
56 // but the program won't crash.
57 static volatile std::atomic<unsigned> GlobalSigInfoGenerationCounter =
58     ATOMIC_VAR_INIT(1);
59 static LLVM_THREAD_LOCAL unsigned ThreadLocalSigInfoGenerationCounter = 0;
60 
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 }
70 
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
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 /// CrashHandler - This callback is run if a fatal signal is delivered to the
124 /// process, it prints the pretty stack trace.
125 static void CrashHandler(void *) {
126 #ifndef __APPLE__
127   // On non-apple systems, just emit the crash stack trace to stderr.
128   PrintCurStackTrace(errs());
129 #else
130   // Otherwise, emit to a smallvector of chars, send *that* to stderr, but also
131   // put it into __crashreporter_info__.
132   SmallString<2048> TmpStr;
133   {
134     raw_svector_ostream Stream(TmpStr);
135     PrintCurStackTrace(Stream);
136   }
137 
138   if (!TmpStr.empty()) {
139 #ifdef HAVE_CRASHREPORTERCLIENT_H
140     // Cast to void to avoid warning.
141     (void)CRSetCrashLogMessage(TmpStr.c_str());
142 #elif HAVE_CRASHREPORTER_INFO
143     __crashreporter_info__ = strdup(TmpStr.c_str());
144 #endif
145     errs() << TmpStr.str();
146   }
147 
148 #endif
149 }
150 
151 static void printForSigInfoIfNeeded() {
152   unsigned CurrentSigInfoGeneration =
153       GlobalSigInfoGenerationCounter.load(std::memory_order_relaxed);
154   if (ThreadLocalSigInfoGenerationCounter == 0 ||
155       ThreadLocalSigInfoGenerationCounter == CurrentSigInfoGeneration) {
156     return;
157   }
158 
159   PrintCurStackTrace(errs());
160   ThreadLocalSigInfoGenerationCounter = CurrentSigInfoGeneration;
161 }
162 
163 #endif // ENABLE_BACKTRACES
164 
165 PrettyStackTraceEntry::PrettyStackTraceEntry() {
166 #if ENABLE_BACKTRACES
167   // Handle SIGINFO first, because we haven't finished constructing yet.
168   printForSigInfoIfNeeded();
169   // Link ourselves.
170   NextEntry = PrettyStackTraceHead;
171   PrettyStackTraceHead = this;
172 #endif
173 }
174 
175 PrettyStackTraceEntry::~PrettyStackTraceEntry() {
176 #if ENABLE_BACKTRACES
177   assert(PrettyStackTraceHead == this &&
178          "Pretty stack trace entry destruction is out of order");
179   PrettyStackTraceHead = NextEntry;
180   // Handle SIGINFO first, because we already started destructing.
181   printForSigInfoIfNeeded();
182 #endif
183 }
184 
185 void PrettyStackTraceString::print(raw_ostream &OS) const { OS << Str << "\n"; }
186 
187 PrettyStackTraceFormat::PrettyStackTraceFormat(const char *Format, ...) {
188   va_list AP;
189   va_start(AP, Format);
190   const int SizeOrError = vsnprintf(nullptr, 0, Format, AP);
191   va_end(AP);
192   if (SizeOrError < 0) {
193     return;
194   }
195 
196   const int Size = SizeOrError + 1; // '\0'
197   Str.resize(Size);
198   va_start(AP, Format);
199   vsnprintf(Str.data(), Size, Format, AP);
200   va_end(AP);
201 }
202 
203 void PrettyStackTraceFormat::print(raw_ostream &OS) const { OS << Str << "\n"; }
204 
205 void PrettyStackTraceProgram::print(raw_ostream &OS) const {
206   OS << "Program arguments: ";
207   // Print the argument list.
208   for (unsigned i = 0, e = ArgC; i != e; ++i)
209     OS << ArgV[i] << ' ';
210   OS << '\n';
211 }
212 
213 #if ENABLE_BACKTRACES
214 static bool RegisterCrashPrinter() {
215   sys::AddSignalHandler(CrashHandler, nullptr);
216   return false;
217 }
218 #endif
219 
220 void llvm::EnablePrettyStackTrace() {
221 #if ENABLE_BACKTRACES
222   // The first time this is called, we register the crash printer.
223   static bool HandlerRegistered = RegisterCrashPrinter();
224   (void)HandlerRegistered;
225 #endif
226 }
227 
228 void llvm::EnablePrettyStackTraceOnSigInfoForThisThread(bool ShouldEnable) {
229 #if ENABLE_BACKTRACES
230   if (!ShouldEnable) {
231     ThreadLocalSigInfoGenerationCounter = 0;
232     return;
233   }
234 
235   // The first time this is called, we register the SIGINFO handler.
236   static bool HandlerRegistered = []{
237     sys::SetInfoSignalFunction([]{
238       GlobalSigInfoGenerationCounter.fetch_add(1, std::memory_order_relaxed);
239     });
240     return false;
241   }();
242   (void)HandlerRegistered;
243 
244   // Next, enable it for the current thread.
245   ThreadLocalSigInfoGenerationCounter =
246       GlobalSigInfoGenerationCounter.load(std::memory_order_relaxed);
247 #endif
248 }
249 
250 const void *llvm::SavePrettyStackState() {
251 #if ENABLE_BACKTRACES
252   return PrettyStackTraceHead;
253 #else
254   return nullptr;
255 #endif
256 }
257 
258 void llvm::RestorePrettyStackState(const void *Top) {
259 #if ENABLE_BACKTRACES
260   PrettyStackTraceHead =
261       static_cast<PrettyStackTraceEntry *>(const_cast<void *>(Top));
262 #endif
263 }
264 
265 void LLVMEnablePrettyStackTrace() {
266   EnablePrettyStackTrace();
267 }
268