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 using CrashHandlerStringStorage =
138 std::aligned_storage<sizeof(CrashHandlerString),
139 alignof(CrashHandlerString)>::type;
140 static CrashHandlerStringStorage crashHandlerStringStorage;
141 #endif
142
143 /// This callback is run if a fatal signal is delivered to the process, it
144 /// prints the pretty stack trace.
CrashHandler(void *)145 static void CrashHandler(void *) {
146 #ifndef __APPLE__
147 // On non-apple systems, just emit the crash stack trace to stderr.
148 PrintCurStackTrace(errs());
149 #else
150 // Emit the crash stack trace to a SmallString, put it where the system crash
151 // handling will find it, and also send it to stderr.
152 //
153 // The SmallString is fairly large in the hope that we don't allocate (we're
154 // handling a fatal signal, something is already pretty wrong, allocation
155 // might not work). Further, we don't use a magic static in case that's also
156 // borked. We leak any allocation that does occur because the program is about
157 // to die anyways. This is technically racy if we were handling two fatal
158 // signals, however if we're in that situation a race is the least of our
159 // worries.
160 auto &crashHandlerString =
161 *new (&crashHandlerStringStorage) CrashHandlerString;
162
163 // If we crash while trying to print the stack trace, we still want the system
164 // crash handling to have some partial information. That'll work out as long
165 // as the SmallString doesn't allocate. If it does allocate then the system
166 // crash handling will see some garbage because the inline buffer now contains
167 // a pointer.
168 setCrashLogMessage(crashHandlerString.c_str());
169
170 {
171 raw_svector_ostream Stream(crashHandlerString);
172 PrintCurStackTrace(Stream);
173 }
174
175 if (!crashHandlerString.empty()) {
176 setCrashLogMessage(crashHandlerString.c_str());
177 errs() << crashHandlerString.str();
178 } else
179 setCrashLogMessage("No crash information.");
180 #endif
181 }
182
printForSigInfoIfNeeded()183 static void printForSigInfoIfNeeded() {
184 unsigned CurrentSigInfoGeneration =
185 GlobalSigInfoGenerationCounter.load(std::memory_order_relaxed);
186 if (ThreadLocalSigInfoGenerationCounter == 0 ||
187 ThreadLocalSigInfoGenerationCounter == CurrentSigInfoGeneration) {
188 return;
189 }
190
191 PrintCurStackTrace(errs());
192 ThreadLocalSigInfoGenerationCounter = CurrentSigInfoGeneration;
193 }
194
195 #endif // ENABLE_BACKTRACES
196
PrettyStackTraceEntry()197 PrettyStackTraceEntry::PrettyStackTraceEntry() {
198 #if ENABLE_BACKTRACES
199 // Handle SIGINFO first, because we haven't finished constructing yet.
200 printForSigInfoIfNeeded();
201 // Link ourselves.
202 NextEntry = PrettyStackTraceHead;
203 PrettyStackTraceHead = this;
204 #endif
205 }
206
~PrettyStackTraceEntry()207 PrettyStackTraceEntry::~PrettyStackTraceEntry() {
208 #if ENABLE_BACKTRACES
209 assert(PrettyStackTraceHead == this &&
210 "Pretty stack trace entry destruction is out of order");
211 PrettyStackTraceHead = NextEntry;
212 // Handle SIGINFO first, because we already started destructing.
213 printForSigInfoIfNeeded();
214 #endif
215 }
216
print(raw_ostream & OS) const217 void PrettyStackTraceString::print(raw_ostream &OS) const { OS << Str << "\n"; }
218
PrettyStackTraceFormat(const char * Format,...)219 PrettyStackTraceFormat::PrettyStackTraceFormat(const char *Format, ...) {
220 va_list AP;
221 va_start(AP, Format);
222 const int SizeOrError = vsnprintf(nullptr, 0, Format, AP);
223 va_end(AP);
224 if (SizeOrError < 0) {
225 return;
226 }
227
228 const int Size = SizeOrError + 1; // '\0'
229 Str.resize(Size);
230 va_start(AP, Format);
231 vsnprintf(Str.data(), Size, Format, AP);
232 va_end(AP);
233 }
234
print(raw_ostream & OS) const235 void PrettyStackTraceFormat::print(raw_ostream &OS) const { OS << Str << "\n"; }
236
print(raw_ostream & OS) const237 void PrettyStackTraceProgram::print(raw_ostream &OS) const {
238 OS << "Program arguments: ";
239 // Print the argument list.
240 for (unsigned i = 0, e = ArgC; i != e; ++i)
241 OS << ArgV[i] << ' ';
242 OS << '\n';
243 }
244
245 #if ENABLE_BACKTRACES
RegisterCrashPrinter()246 static bool RegisterCrashPrinter() {
247 sys::AddSignalHandler(CrashHandler, nullptr);
248 return false;
249 }
250 #endif
251
EnablePrettyStackTrace()252 void llvm::EnablePrettyStackTrace() {
253 #if ENABLE_BACKTRACES
254 // The first time this is called, we register the crash printer.
255 static bool HandlerRegistered = RegisterCrashPrinter();
256 (void)HandlerRegistered;
257 #endif
258 }
259
EnablePrettyStackTraceOnSigInfoForThisThread(bool ShouldEnable)260 void llvm::EnablePrettyStackTraceOnSigInfoForThisThread(bool ShouldEnable) {
261 #if ENABLE_BACKTRACES
262 if (!ShouldEnable) {
263 ThreadLocalSigInfoGenerationCounter = 0;
264 return;
265 }
266
267 // The first time this is called, we register the SIGINFO handler.
268 static bool HandlerRegistered = []{
269 sys::SetInfoSignalFunction([]{
270 GlobalSigInfoGenerationCounter.fetch_add(1, std::memory_order_relaxed);
271 });
272 return false;
273 }();
274 (void)HandlerRegistered;
275
276 // Next, enable it for the current thread.
277 ThreadLocalSigInfoGenerationCounter =
278 GlobalSigInfoGenerationCounter.load(std::memory_order_relaxed);
279 #endif
280 }
281
SavePrettyStackState()282 const void *llvm::SavePrettyStackState() {
283 #if ENABLE_BACKTRACES
284 return PrettyStackTraceHead;
285 #else
286 return nullptr;
287 #endif
288 }
289
RestorePrettyStackState(const void * Top)290 void llvm::RestorePrettyStackState(const void *Top) {
291 #if ENABLE_BACKTRACES
292 PrettyStackTraceHead =
293 static_cast<PrettyStackTraceEntry *>(const_cast<void *>(Top));
294 #endif
295 }
296
LLVMEnablePrettyStackTrace()297 void LLVMEnablePrettyStackTrace() {
298 EnablePrettyStackTrace();
299 }
300