LLVM 24.0.0git
PrettyStackTrace.cpp
Go to the documentation of this file.
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
16#include "llvm/Config/config.h"
22
23#ifdef __APPLE__
25#endif
26
27#include <atomic>
28#include <cassert>
29#include <cstdarg>
30#include <cstdio>
31#include <cstring>
32#include <tuple>
33
34#if __has_include(<CrashReporterClient.h>)
35#include <CrashReporterClient.h>
36#define LLVM_HAVE_CRASHREPORTERCLIENT_H
37#endif
38
39using namespace llvm;
40
41static const char *BugReportMsg =
42 "PLEASE submit a bug report to " BUG_REPORT_URL
43 " and include the crash backtrace and instructions to reproduce the bug.\n";
44
45// If backtrace support is not enabled, compile out support for pretty stack
46// traces. This has the secondary effect of not requiring thread local storage
47// when backtrace support is disabled.
48#if ENABLE_BACKTRACES
49
50// We need a thread local pointer to manage the stack of our stack trace
51// objects, but we *really* cannot tolerate destructors running and do not want
52// to pay any overhead of synchronizing. As a consequence, we use a raw
53// thread-local variable.
54static LLVM_THREAD_LOCAL PrettyStackTraceEntry *PrettyStackTraceHead = nullptr;
55
56// The use of 'volatile' here is to ensure that any particular thread always
57// reloads the value of the counter. The 'std::atomic' allows us to specify that
58// this variable is accessed in an unsychronized way (it's not actually
59// synchronizing). This does technically mean that the value may not appear to
60// be the same across threads running simultaneously on different CPUs, but in
61// practice the worst that will happen is that we won't print a stack trace when
62// we could have.
63//
64// This is initialized to 1 because 0 is used as a sentinel for "not enabled on
65// the current thread". If the user happens to overflow an 'unsigned' with
66// SIGINFO requests, it's possible that some threads will stop responding to it,
67// but the program won't crash.
68static volatile std::atomic<unsigned> GlobalSigInfoGenerationCounter = 1;
69static LLVM_THREAD_LOCAL unsigned ThreadLocalSigInfoGenerationCounter = 0;
70
71namespace llvm {
72PrettyStackTraceEntry *ReverseStackTrace(PrettyStackTraceEntry *Head) {
73 PrettyStackTraceEntry *Prev = nullptr;
74 while (Head)
75 std::tie(Prev, Head, Head->NextEntry) =
76 std::make_tuple(Head, Head->NextEntry, Prev);
77 return Prev;
78}
79} // namespace llvm
80
81static void PrintStack(raw_ostream &OS) {
82 // Print out the stack in reverse order. To avoid recursion (which is likely
83 // to fail if we crashed due to stack overflow), we do an up-front pass to
84 // reverse the stack, then print it, then reverse it again.
85 unsigned ID = 0;
86 SaveAndRestore<PrettyStackTraceEntry *> SavedStack{PrettyStackTraceHead,
87 nullptr};
88 PrettyStackTraceEntry *ReversedStack = ReverseStackTrace(SavedStack.get());
89 for (const PrettyStackTraceEntry *Entry = ReversedStack; Entry;
90 Entry = Entry->getNextEntry()) {
91 OS << ID++ << ".\t";
93 Entry->print(OS);
94 }
95 llvm::ReverseStackTrace(ReversedStack);
96}
97
98/// Print the current stack trace to the specified stream.
99///
100/// Marked NOINLINE so it can be called from debuggers.
102static void PrintCurStackTrace(raw_ostream &OS) {
103 // Don't print an empty trace.
104 if (!PrettyStackTraceHead) return;
105
106 // If there are pretty stack frames registered, walk and emit them.
107 OS << "Stack dump:\n";
108
109 PrintStack(OS);
110 OS.flush();
111}
112
113// Integrate with crash reporter libraries.
114#if defined(__APPLE__) && defined(LLVM_HAVE_CRASHREPORTERCLIENT_H)
115// If any clients of llvm try to link to libCrashReporterClient.a themselves,
116// only one crash info struct will be used.
117extern "C" {
118#ifdef CRASHREPORTER_ANNOTATIONS_INITIALIZER
119// Should be available in CRASHREPORTER_ANNOTATIONS_VERSION > 5
120CRASHREPORTER_ANNOTATIONS_INITIALIZER()
121#else
122// Older CrashReporter annotations layouts
123CRASH_REPORTER_CLIENT_HIDDEN
124struct crashreporter_annotations_t gCRAnnotations
125 __attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION))) = {
126 CRASHREPORTER_ANNOTATIONS_VERSION,
127 0,
128 0,
129 0,
130 0,
131 0,
132 0,
133#if CRASHREPORTER_ANNOTATIONS_VERSION > 4
134 0
135#endif // CRASHREPORTER_ANNOTATIONS_VERSION > 4
136};
137#endif // CRASHREPORTER_ANNOTATIONS_INITIALIZER
138} // extern "C"
139#elif defined(__APPLE__) && HAVE_CRASHREPORTER_INFO
140extern "C" const char *__crashreporter_info__
141 __attribute__((visibility("hidden"))) = 0;
142asm(".desc ___crashreporter_info__, 0x10");
143#endif
144
145[[maybe_unused]] static void setCrashLogMessage(const char *msg);
146static void setCrashLogMessage(const char *msg) {
147#ifdef LLVM_HAVE_CRASHREPORTERCLIENT_H
148 (void)CRSetCrashLogMessage(msg);
149#elif HAVE_CRASHREPORTER_INFO
150 __crashreporter_info__ = msg;
151#endif
152 // Don't reorder subsequent operations: whatever comes after might crash and
153 // we want the system crash handling to see the message we just set.
154 std::atomic_signal_fence(std::memory_order_seq_cst);
155}
156
157#ifdef __APPLE__
158using CrashHandlerString = SmallString<2048>;
159using CrashHandlerStringStorage = std::byte[sizeof(CrashHandlerString)];
160alignas(CrashHandlerString) static CrashHandlerStringStorage
161 crashHandlerStringStorage;
162#endif
163
164/// This callback is run if a fatal signal is delivered to the process, it
165/// prints the pretty stack trace.
166static void CrashHandler(void *) {
167 errs() << BugReportMsg ;
168
169#ifndef __APPLE__
170 // On non-apple systems, just emit the crash stack trace to stderr.
171 PrintCurStackTrace(errs());
172#else
173 // Emit the crash stack trace to a SmallString, put it where the system crash
174 // handling will find it, and also send it to stderr.
175 //
176 // The SmallString is fairly large in the hope that we don't allocate (we're
177 // handling a fatal signal, something is already pretty wrong, allocation
178 // might not work). Further, we don't use a magic static in case that's also
179 // borked. We leak any allocation that does occur because the program is about
180 // to die anyways. This is technically racy if we were handling two fatal
181 // signals, however if we're in that situation a race is the least of our
182 // worries.
183 auto &crashHandlerString =
184 *new (&crashHandlerStringStorage) CrashHandlerString;
185
186 // If we crash while trying to print the stack trace, we still want the system
187 // crash handling to have some partial information. That'll work out as long
188 // as the SmallString doesn't allocate. If it does allocate then the system
189 // crash handling will see some garbage because the inline buffer now contains
190 // a pointer.
191 setCrashLogMessage(crashHandlerString.c_str());
192
193 {
194 raw_svector_ostream Stream(crashHandlerString);
195 PrintCurStackTrace(Stream);
196 }
197
198 if (!crashHandlerString.empty()) {
199 setCrashLogMessage(crashHandlerString.c_str());
200 errs() << crashHandlerString.str();
201 } else {
202 setCrashLogMessage("No crash information.");
203 }
204#endif
205}
206
207static void printForSigInfoIfNeeded() {
208 unsigned CurrentSigInfoGeneration =
209 GlobalSigInfoGenerationCounter.load(std::memory_order_relaxed);
210 if (ThreadLocalSigInfoGenerationCounter == 0 ||
211 ThreadLocalSigInfoGenerationCounter == CurrentSigInfoGeneration) {
212 return;
213 }
214
215 PrintCurStackTrace(errs());
216 ThreadLocalSigInfoGenerationCounter = CurrentSigInfoGeneration;
217}
218
219#endif // ENABLE_BACKTRACES
220
221void llvm::setBugReportMsg(const char *Msg) {
223}
224
226 return BugReportMsg;
227}
228
230#if ENABLE_BACKTRACES
231 // Handle SIGINFO first, because we haven't finished constructing yet.
232 printForSigInfoIfNeeded();
233 // Link ourselves.
234 NextEntry = PrettyStackTraceHead;
235 PrettyStackTraceHead = this;
236#endif
237}
238
240#if ENABLE_BACKTRACES
241 assert(PrettyStackTraceHead == this &&
242 "Pretty stack trace entry destruction is out of order");
243 PrettyStackTraceHead = NextEntry;
244 // Handle SIGINFO first, because we already started destructing.
245 printForSigInfoIfNeeded();
246#endif
247}
248
249void PrettyStackTraceString::print(raw_ostream &OS) const { OS << Str << "\n"; }
250
252 va_list AP;
253 va_start(AP, Format);
254 const int SizeOrError = vsnprintf(nullptr, 0, Format, AP);
255 va_end(AP);
256 if (SizeOrError < 0) {
257 return;
258 }
259
260 const int Size = SizeOrError + 1; // '\0'
261 Str.resize(Size);
262 va_start(AP, Format);
263 vsnprintf(Str.data(), Size, Format, AP);
264 va_end(AP);
265}
266
267void PrettyStackTraceFormat::print(raw_ostream &OS) const { OS << Str << "\n"; }
268
270 OS << "Program arguments: ";
271 // Print the argument list.
272 for (int I = 0; I < ArgC; ++I) {
273 const bool HaveSpace = ::strchr(ArgV[I], ' ');
274 if (I)
275 OS << ' ';
276 if (HaveSpace)
277 OS << '"';
278 OS.write_escaped(ArgV[I]);
279 if (HaveSpace)
280 OS << '"';
281 }
282 OS << '\n';
283}
284
285#if ENABLE_BACKTRACES
286static bool RegisterCrashPrinter() {
287 sys::AddSignalHandler(CrashHandler, nullptr);
288 return false;
289}
290#endif
291
293#if ENABLE_BACKTRACES
294 // The first time this is called, we register the crash printer.
295 static bool HandlerRegistered = RegisterCrashPrinter();
296 (void)HandlerRegistered;
297#endif
298}
299
301#if ENABLE_BACKTRACES
302 if (!ShouldEnable) {
303 ThreadLocalSigInfoGenerationCounter = 0;
304 return;
305 }
306
307 // The first time this is called, we register the SIGINFO handler.
308 static bool HandlerRegistered = []{
310 GlobalSigInfoGenerationCounter.fetch_add(1, std::memory_order_relaxed);
311 });
312 return false;
313 }();
314 (void)HandlerRegistered;
315
316 // Next, enable it for the current thread.
317 ThreadLocalSigInfoGenerationCounter =
318 GlobalSigInfoGenerationCounter.load(std::memory_order_relaxed);
319#endif
320}
321
323#if ENABLE_BACKTRACES
324 return PrettyStackTraceHead;
325#else
326 return nullptr;
327#endif
328}
329
330void llvm::RestorePrettyStackState(const void *Top) {
331#if ENABLE_BACKTRACES
332 PrettyStackTraceHead =
333 static_cast<PrettyStackTraceEntry *>(const_cast<void *>(Top));
334#endif
335}
336
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_THREAD_LOCAL
\macro LLVM_THREAD_LOCAL A thread-local storage specifier which can be used with globals,...
Definition Compiler.h:719
#define LLVM_ATTRIBUTE_NOINLINE
LLVM_ATTRIBUTE_NOINLINE - On compilers where we have a directive to do so, mark a method "not for inl...
Definition Compiler.h:354
#define I(x, y, z)
Definition MD5.cpp:57
static const char * BugReportMsg
const char * Msg
This file provides utility classes that use RAII to save and restore values.
This file defines the SmallString class.
PrettyStackTraceEntry - This class is used to represent a frame of the "pretty" stack trace that is d...
const PrettyStackTraceEntry * getNextEntry() const
getNextEntry - Return the next entry in the list of frames.
void print(raw_ostream &OS) const override
print - Emit information about this stack frame to OS.
PrettyStackTraceFormat(const char *Format,...)
void print(raw_ostream &OS) const override
print - Emit information about this stack frame to OS.
void print(raw_ostream &OS) const override
print - Emit information about this stack frame to OS.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & write_escaped(StringRef Str, bool UseHexEscapes=false)
Output Str, turning '\', '\t', ' ', '"', and anything that doesn't satisfy llvm::isPrint into an esca...
A raw_ostream that writes to an SmallVector or SmallString.
This class provides an abstraction for a timeout around an operation that must complete in a given am...
Definition Watchdog.h:25
LLVM_C_ABI void LLVMEnablePrettyStackTrace(void)
Enable LLVM's built-in stack trace code.
LLVM_ABI void AddSignalHandler(SignalHandlerCallback FnPtr, void *Cookie, bool NeedsPOSIXUtilitySignalHandling=false)
Add a function to be called when an abort/kill signal is delivered to the process.
LLVM_ABI void SetInfoSignalFunction(void(*Handler)())
Registers a function to be called when an "info" signal is delivered to the process.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void setBugReportMsg(const char *Msg)
Replaces the generic bug report message that is output upon a crash.
LLVM_ABI const void * SavePrettyStackState()
Returns the topmost element of the "pretty" stack state.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI void RestorePrettyStackState(const void *State)
Restores the topmost element of the "pretty" stack state to State, which should come from a previous ...
LLVM_ABI void EnablePrettyStackTraceOnSigInfoForThisThread(bool ShouldEnable=true)
Enables (or disables) dumping a "pretty" stack trace when the user sends SIGINFO or SIGUSR1 to the cu...
LLVM_ABI void EnablePrettyStackTrace()
Enables dumping a "pretty" stack trace when the program crashes.
LLVM_ABI const char * getBugReportMsg()
Get the bug report message that will be output upon a crash.
A utility class that uses RAII to save and restore the value of a variable.