LLVM  10.0.0svn
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 
15 #include "llvm-c/ErrorHandling.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/Config/config.h"
18 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/Signals.h"
21 #include "llvm/Support/Watchdog.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.
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 =
59  ATOMIC_VAR_INIT(1);
61 
62 namespace llvm {
64  PrettyStackTraceEntry *Prev = nullptr;
65  while (Head)
66  std::tie(Prev, Head, Head->NextEntry) =
67  std::make_tuple(Head, Head->NextEntry, Prev);
68  return Prev;
69 }
70 }
71 
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.
76  unsigned ID = 0;
78  nullptr};
79  PrettyStackTraceEntry *ReversedStack = ReverseStackTrace(SavedStack.get());
80  for (const PrettyStackTraceEntry *Entry = ReversedStack; Entry;
81  Entry = Entry->getNextEntry()) {
82  OS << ID++ << ".\t";
83  sys::Watchdog W(5);
84  Entry->print(OS);
85  }
86  llvm::ReverseStackTrace(ReversedStack);
87 }
88 
89 /// Print the current stack trace to the specified stream.
90 ///
91 /// Marked NOINLINE so it can be called from debuggers.
93 static void PrintCurStackTrace(raw_ostream &OS) {
94  // Don't print an empty trace.
95  if (!PrettyStackTraceHead) return;
96 
97  // If there are pretty stack frames registered, walk and emit them.
98  OS << "Stack dump:\n";
99 
100  PrintStack(OS);
101  OS.flush();
102 }
103 
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.
108 extern "C" {
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 };
114 #else
115  = { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0, 0 };
116 #endif
117 }
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");
122 #endif
123 
124 static void setCrashLogMessage(const char *msg) LLVM_ATTRIBUTE_UNUSED;
125 static void setCrashLogMessage(const char *msg) {
126 #ifdef HAVE_CRASHREPORTERCLIENT_H
127  (void)CRSetCrashLogMessage(msg);
128 #elif HAVE_CRASHREPORTER_INFO
129  __crashreporter_info__ = msg;
130 #endif
131  // Don't reorder subsequent operations: whatever comes after might crash and
132  // we want the system crash handling to see the message we just set.
133  std::atomic_signal_fence(std::memory_order_seq_cst);
134 }
135 
136 #ifdef __APPLE__
137 using CrashHandlerString = SmallString<2048>;
138 using CrashHandlerStringStorage =
139  std::aligned_storage<sizeof(CrashHandlerString),
140  alignof(CrashHandlerString)>::type;
141 static CrashHandlerStringStorage crashHandlerStringStorage;
142 #endif
143 
144 /// This callback is run if a fatal signal is delivered to the process, it
145 /// prints the pretty stack trace.
146 static void CrashHandler(void *) {
147 #ifndef __APPLE__
148  // On non-apple systems, just emit the crash stack trace to stderr.
150 #else
151  // Emit the crash stack trace to a SmallString, put it where the system crash
152  // handling will find it, and also send it to stderr.
153  //
154  // The SmallString is fairly large in the hope that we don't allocate (we're
155  // handling a fatal signal, something is already pretty wrong, allocation
156  // might not work). Further, we don't use a magic static in case that's also
157  // borked. We leak any allocation that does occur because the program is about
158  // to die anyways. This is technically racy if we were handling two fatal
159  // signals, however if we're in that situation a race is the least of our
160  // worries.
161  auto &crashHandlerString =
162  *new (&crashHandlerStringStorage) CrashHandlerString;
163 
164  // If we crash while trying to print the stack trace, we still want the system
165  // crash handling to have some partial information. That'll work out as long
166  // as the SmallString doesn't allocate. If it does allocate then the system
167  // crash handling will see some garbage because the inline buffer now contains
168  // a pointer.
169  setCrashLogMessage(crashHandlerString.c_str());
170 
171  {
172  raw_svector_ostream Stream(crashHandlerString);
173  PrintCurStackTrace(Stream);
174  }
175 
176  if (!crashHandlerString.empty()) {
177  setCrashLogMessage(crashHandlerString.c_str());
178  errs() << crashHandlerString.str();
179  } else
180  setCrashLogMessage("No crash information.");
181 #endif
182 }
183 
184 static void printForSigInfoIfNeeded() {
185  unsigned CurrentSigInfoGeneration =
186  GlobalSigInfoGenerationCounter.load(std::memory_order_relaxed);
188  ThreadLocalSigInfoGenerationCounter == CurrentSigInfoGeneration) {
189  return;
190  }
191 
193  ThreadLocalSigInfoGenerationCounter = CurrentSigInfoGeneration;
194 }
195 
196 #endif // ENABLE_BACKTRACES
197 
199 #if ENABLE_BACKTRACES
200  // Handle SIGINFO first, because we haven't finished constructing yet.
202  // Link ourselves.
203  NextEntry = PrettyStackTraceHead;
204  PrettyStackTraceHead = this;
205 #endif
206 }
207 
209 #if ENABLE_BACKTRACES
210  assert(PrettyStackTraceHead == this &&
211  "Pretty stack trace entry destruction is out of order");
212  PrettyStackTraceHead = NextEntry;
213  // Handle SIGINFO first, because we already started destructing.
215 #endif
216 }
217 
218 void PrettyStackTraceString::print(raw_ostream &OS) const { OS << Str << "\n"; }
219 
221  va_list AP;
222  va_start(AP, Format);
223  const int SizeOrError = vsnprintf(nullptr, 0, Format, AP);
224  va_end(AP);
225  if (SizeOrError < 0) {
226  return;
227  }
228 
229  const int Size = SizeOrError + 1; // '\0'
230  Str.resize(Size);
231  va_start(AP, Format);
232  vsnprintf(Str.data(), Size, Format, AP);
233  va_end(AP);
234 }
235 
236 void PrettyStackTraceFormat::print(raw_ostream &OS) const { OS << Str << "\n"; }
237 
239  OS << "Program arguments: ";
240  // Print the argument list.
241  for (unsigned i = 0, e = ArgC; i != e; ++i)
242  OS << ArgV[i] << ' ';
243  OS << '\n';
244 }
245 
246 #if ENABLE_BACKTRACES
247 static bool RegisterCrashPrinter() {
249  return false;
250 }
251 #endif
252 
254 #if ENABLE_BACKTRACES
255  // The first time this is called, we register the crash printer.
256  static bool HandlerRegistered = RegisterCrashPrinter();
257  (void)HandlerRegistered;
258 #endif
259 }
260 
262 #if ENABLE_BACKTRACES
263  if (!ShouldEnable) {
265  return;
266  }
267 
268  // The first time this is called, we register the SIGINFO handler.
269  static bool HandlerRegistered = []{
271  GlobalSigInfoGenerationCounter.fetch_add(1, std::memory_order_relaxed);
272  });
273  return false;
274  }();
275  (void)HandlerRegistered;
276 
277  // Next, enable it for the current thread.
279  GlobalSigInfoGenerationCounter.load(std::memory_order_relaxed);
280 #endif
281 }
282 
284 #if ENABLE_BACKTRACES
285  return PrettyStackTraceHead;
286 #else
287  return nullptr;
288 #endif
289 }
290 
291 void llvm::RestorePrettyStackState(const void *Top) {
292 #if ENABLE_BACKTRACES
294  static_cast<PrettyStackTraceEntry *>(const_cast<void *>(Top));
295 #endif
296 }
297 
300 }
void RestorePrettyStackState(const void *State)
Restores the topmost element of the "pretty" stack state to State, which should come from a previous ...
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
static void printForSigInfoIfNeeded()
static LLVM_THREAD_LOCAL unsigned ThreadLocalSigInfoGenerationCounter
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:530
static volatile std::atomic< unsigned > GlobalSigInfoGenerationCounter
This class provides an abstraction for a timeout around an operation that must complete in a given am...
Definition: Watchdog.h:25
void EnablePrettyStackTrace()
Enables dumping a "pretty" stack trace when the program crashes.
void SetInfoSignalFunction(void(*Handler)())
Registers a function to be called when an "info" signal is delivered to the process.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:25
#define LLVM_THREAD_LOCAL
LLVM_THREAD_LOCAL A thread-local storage specifier which can be used with globals, extern globals, and static globals.
Definition: Compiler.h:512
void print(raw_ostream &OS) const override
print - Emit information about this stack frame to OS.
static LLVM_ATTRIBUTE_NOINLINE void PrintCurStackTrace(raw_ostream &OS)
Print the current stack trace to the specified stream.
#define LLVM_ATTRIBUTE_UNUSED
Definition: Compiler.h:167
void LLVMEnablePrettyStackTrace()
Enable LLVM&#39;s built-in stack trace code.
static void setCrashLogMessage(const char *msg) LLVM_ATTRIBUTE_UNUSED
PrettyStackTraceEntry - This class is used to represent a frame of the "pretty" stack trace that is d...
const void * SavePrettyStackState()
Returns the topmost element of the "pretty" stack state.
static void PrintStack(raw_ostream &OS)
#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:209
PrettyStackTraceFormat(const char *Format,...)
static LLVM_THREAD_LOCAL PrettyStackTraceEntry * PrettyStackTraceHead
static bool RegisterCrashPrinter()
void print(raw_ostream &OS) const override
print - Emit information about this stack frame to OS.
A utility class that uses RAII to save and restore the value of a variable.
static void CrashHandler(void *)
This callback is run if a fatal signal is delivered to the process, it prints the pretty stack trace...
void print(raw_ostream &OS) const override
print - Emit information about this stack frame to OS.
void EnablePrettyStackTraceOnSigInfoForThisThread(bool ShouldEnable=true)
Enables (or disables) dumping a "pretty" stack trace when the user sends SIGINFO or SIGUSR1 to the cu...
PrettyStackTraceEntry * ReverseStackTrace(PrettyStackTraceEntry *Head)
uint32_t Size
Definition: Profile.cpp:46
void AddSignalHandler(SignalHandlerCallback FnPtr, void *Cookie)
Add a function to be called when an abort/kill signal is delivered to the process.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file provides utility classes that use RAII to save and restore values.
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45