1 //===- PrettyStackTrace.cpp - Pretty Crash Handling -----------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines some helpful functions for dealing with the possibility of
10 // Unix signals occurring while your program is running.
12 //===----------------------------------------------------------------------===//
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"
29 #ifdef HAVE_CRASHREPORTERCLIENT_H
30 #include <CrashReporterClient.h>
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.
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;
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
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
=
60 static LLVM_THREAD_LOCAL
unsigned ThreadLocalSigInfoGenerationCounter
= 0;
63 PrettyStackTraceEntry
*ReverseStackTrace(PrettyStackTraceEntry
*Head
) {
64 PrettyStackTraceEntry
*Prev
= nullptr;
66 std::tie(Prev
, Head
, Head
->NextEntry
) =
67 std::make_tuple(Head
, Head
->NextEntry
, Prev
);
72 static void PrintStack(raw_ostream
&OS
) {
73 // Print out the stack in reverse order. To avoid recursion (which is likely
74 // to fail if we crashed due to stack overflow), we do an up-front pass to
75 // reverse the stack, then print it, then reverse it again.
77 SaveAndRestore
<PrettyStackTraceEntry
*> SavedStack
{PrettyStackTraceHead
,
79 PrettyStackTraceEntry
*ReversedStack
= ReverseStackTrace(SavedStack
.get());
80 for (const PrettyStackTraceEntry
*Entry
= ReversedStack
; Entry
;
81 Entry
= Entry
->getNextEntry()) {
86 llvm::ReverseStackTrace(ReversedStack
);
89 /// Print the current stack trace to the specified stream.
91 /// Marked NOINLINE so it can be called from debuggers.
92 LLVM_ATTRIBUTE_NOINLINE
93 static void PrintCurStackTrace(raw_ostream
&OS
) {
94 // Don't print an empty trace.
95 if (!PrettyStackTraceHead
) return;
97 // If there are pretty stack frames registered, walk and emit them.
98 OS
<< "Stack dump:\n";
104 // Integrate with crash reporter libraries.
105 #if defined (__APPLE__) && defined(HAVE_CRASHREPORTERCLIENT_H)
106 // If any clients of llvm try to link to libCrashReporterClient.a themselves,
107 // only one crash info struct will be used.
109 CRASH_REPORTER_CLIENT_HIDDEN
110 struct crashreporter_annotations_t gCRAnnotations
111 __attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION
)))
112 #if CRASHREPORTER_ANNOTATIONS_VERSION < 5
113 = { CRASHREPORTER_ANNOTATIONS_VERSION
, 0, 0, 0, 0, 0, 0 };
115 = { CRASHREPORTER_ANNOTATIONS_VERSION
, 0, 0, 0, 0, 0, 0, 0 };
118 #elif defined(__APPLE__) && HAVE_CRASHREPORTER_INFO
119 extern "C" const char *__crashreporter_info__
120 __attribute__((visibility("hidden"))) = 0;
121 asm(".desc ___crashreporter_info__, 0x10");
124 /// CrashHandler - This callback is run if a fatal signal is delivered to the
125 /// process, it prints the pretty stack trace.
126 static void CrashHandler(void *) {
128 // On non-apple systems, just emit the crash stack trace to stderr.
129 PrintCurStackTrace(errs());
131 // Otherwise, emit to a smallvector of chars, send *that* to stderr, but also
132 // put it into __crashreporter_info__.
133 SmallString
<2048> TmpStr
;
135 raw_svector_ostream
Stream(TmpStr
);
136 PrintCurStackTrace(Stream
);
139 if (!TmpStr
.empty()) {
140 #ifdef HAVE_CRASHREPORTERCLIENT_H
141 // Cast to void to avoid warning.
142 (void)CRSetCrashLogMessage(TmpStr
.c_str());
143 #elif HAVE_CRASHREPORTER_INFO
144 __crashreporter_info__
= strdup(TmpStr
.c_str());
146 errs() << TmpStr
.str();
152 static void printForSigInfoIfNeeded() {
153 unsigned CurrentSigInfoGeneration
=
154 GlobalSigInfoGenerationCounter
.load(std::memory_order_relaxed
);
155 if (ThreadLocalSigInfoGenerationCounter
== 0 ||
156 ThreadLocalSigInfoGenerationCounter
== CurrentSigInfoGeneration
) {
160 PrintCurStackTrace(errs());
161 ThreadLocalSigInfoGenerationCounter
= CurrentSigInfoGeneration
;
164 #endif // ENABLE_BACKTRACES
166 PrettyStackTraceEntry::PrettyStackTraceEntry() {
167 #if ENABLE_BACKTRACES
168 // Handle SIGINFO first, because we haven't finished constructing yet.
169 printForSigInfoIfNeeded();
171 NextEntry
= PrettyStackTraceHead
;
172 PrettyStackTraceHead
= this;
176 PrettyStackTraceEntry::~PrettyStackTraceEntry() {
177 #if ENABLE_BACKTRACES
178 assert(PrettyStackTraceHead
== this &&
179 "Pretty stack trace entry destruction is out of order");
180 PrettyStackTraceHead
= NextEntry
;
181 // Handle SIGINFO first, because we already started destructing.
182 printForSigInfoIfNeeded();
186 void PrettyStackTraceString::print(raw_ostream
&OS
) const { OS
<< Str
<< "\n"; }
188 PrettyStackTraceFormat::PrettyStackTraceFormat(const char *Format
, ...) {
190 va_start(AP
, Format
);
191 const int SizeOrError
= vsnprintf(nullptr, 0, Format
, AP
);
193 if (SizeOrError
< 0) {
197 const int Size
= SizeOrError
+ 1; // '\0'
199 va_start(AP
, Format
);
200 vsnprintf(Str
.data(), Size
, Format
, AP
);
204 void PrettyStackTraceFormat::print(raw_ostream
&OS
) const { OS
<< Str
<< "\n"; }
206 void PrettyStackTraceProgram::print(raw_ostream
&OS
) const {
207 OS
<< "Program arguments: ";
208 // Print the argument list.
209 for (unsigned i
= 0, e
= ArgC
; i
!= e
; ++i
)
210 OS
<< ArgV
[i
] << ' ';
214 #if ENABLE_BACKTRACES
215 static bool RegisterCrashPrinter() {
216 sys::AddSignalHandler(CrashHandler
, nullptr);
221 void llvm::EnablePrettyStackTrace() {
222 #if ENABLE_BACKTRACES
223 // The first time this is called, we register the crash printer.
224 static bool HandlerRegistered
= RegisterCrashPrinter();
225 (void)HandlerRegistered
;
229 void llvm::EnablePrettyStackTraceOnSigInfoForThisThread(bool ShouldEnable
) {
230 #if ENABLE_BACKTRACES
232 ThreadLocalSigInfoGenerationCounter
= 0;
236 // The first time this is called, we register the SIGINFO handler.
237 static bool HandlerRegistered
= []{
238 sys::SetInfoSignalFunction([]{
239 GlobalSigInfoGenerationCounter
.fetch_add(1, std::memory_order_relaxed
);
243 (void)HandlerRegistered
;
245 // Next, enable it for the current thread.
246 ThreadLocalSigInfoGenerationCounter
=
247 GlobalSigInfoGenerationCounter
.load(std::memory_order_relaxed
);
251 const void *llvm::SavePrettyStackState() {
252 #if ENABLE_BACKTRACES
253 return PrettyStackTraceHead
;
259 void llvm::RestorePrettyStackState(const void *Top
) {
260 #if ENABLE_BACKTRACES
261 PrettyStackTraceHead
=
262 static_cast<PrettyStackTraceEntry
*>(const_cast<void *>(Top
));
266 void LLVMEnablePrettyStackTrace() {
267 EnablePrettyStackTrace();