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 <cassert> 26 #include <cstdarg> 27 #include <cstdio> 28 #include <tuple> 29 30 #ifdef HAVE_CRASHREPORTERCLIENT_H 31 #include <CrashReporterClient.h> 32 #endif 33 34 using namespace llvm; 35 36 // If backtrace support is not enabled, compile out support for pretty stack 37 // traces. This has the secondary effect of not requiring thread local storage 38 // when backtrace support is disabled. 39 #if ENABLE_BACKTRACES 40 41 // We need a thread local pointer to manage the stack of our stack trace 42 // objects, but we *really* cannot tolerate destructors running and do not want 43 // to pay any overhead of synchronizing. As a consequence, we use a raw 44 // thread-local variable. 45 static LLVM_THREAD_LOCAL PrettyStackTraceEntry *PrettyStackTraceHead = nullptr; 46 47 // The use of 'volatile' here is to ensure that any particular thread always 48 // reloads the value of the counter. The 'std::atomic' allows us to specify that 49 // this variable is accessed in an unsychronized way (it's not actually 50 // synchronizing). This does technically mean that the value may not appear to 51 // be the same across threads running simultaneously on different CPUs, but in 52 // practice the worst that will happen is that we won't print a stack trace when 53 // we could have. 54 // 55 // This is initialized to 1 because 0 is used as a sentinel for "not enabled on 56 // the current thread". If the user happens to overflow an 'unsigned' with 57 // SIGINFO requests, it's possible that some threads will stop responding to it, 58 // but the program won't crash. 59 static volatile std::atomic<unsigned> GlobalSigInfoGenerationCounter = 60 ATOMIC_VAR_INIT(1); 61 static LLVM_THREAD_LOCAL unsigned ThreadLocalSigInfoGenerationCounter = 0; 62 63 namespace llvm { 64 PrettyStackTraceEntry *ReverseStackTrace(PrettyStackTraceEntry *Head) { 65 PrettyStackTraceEntry *Prev = nullptr; 66 while (Head) 67 std::tie(Prev, Head, Head->NextEntry) = 68 std::make_tuple(Head, Head->NextEntry, Prev); 69 return Prev; 70 } 71 } 72 73 static void PrintStack(raw_ostream &OS) { 74 // Print out the stack in reverse order. To avoid recursion (which is likely 75 // to fail if we crashed due to stack overflow), we do an up-front pass to 76 // reverse the stack, then print it, then reverse it again. 77 unsigned ID = 0; 78 SaveAndRestore<PrettyStackTraceEntry *> SavedStack{PrettyStackTraceHead, 79 nullptr}; 80 PrettyStackTraceEntry *ReversedStack = ReverseStackTrace(SavedStack.get()); 81 for (const PrettyStackTraceEntry *Entry = ReversedStack; Entry; 82 Entry = Entry->getNextEntry()) { 83 OS << ID++ << ".\t"; 84 sys::Watchdog W(5); 85 Entry->print(OS); 86 } 87 llvm::ReverseStackTrace(ReversedStack); 88 } 89 90 /// Print the current stack trace to the specified stream. 91 /// 92 /// Marked NOINLINE so it can be called from debuggers. 93 LLVM_ATTRIBUTE_NOINLINE 94 static void PrintCurStackTrace(raw_ostream &OS) { 95 // Don't print an empty trace. 96 if (!PrettyStackTraceHead) return; 97 98 // If there are pretty stack frames registered, walk and emit them. 99 OS << "Stack dump:\n"; 100 101 PrintStack(OS); 102 OS.flush(); 103 } 104 105 // Integrate with crash reporter libraries. 106 #if defined (__APPLE__) && defined(HAVE_CRASHREPORTERCLIENT_H) 107 // If any clients of llvm try to link to libCrashReporterClient.a themselves, 108 // only one crash info struct will be used. 109 extern "C" { 110 CRASH_REPORTER_CLIENT_HIDDEN 111 struct crashreporter_annotations_t gCRAnnotations 112 __attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION))) 113 #if CRASHREPORTER_ANNOTATIONS_VERSION < 5 114 = { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0 }; 115 #else 116 = { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0, 0 }; 117 #endif 118 } 119 #elif defined(__APPLE__) && HAVE_CRASHREPORTER_INFO 120 extern "C" const char *__crashreporter_info__ 121 __attribute__((visibility("hidden"))) = 0; 122 asm(".desc ___crashreporter_info__, 0x10"); 123 #endif 124 125 static void setCrashLogMessage(const char *msg) LLVM_ATTRIBUTE_UNUSED; 126 static void setCrashLogMessage(const char *msg) { 127 #ifdef HAVE_CRASHREPORTERCLIENT_H 128 (void)CRSetCrashLogMessage(msg); 129 #elif HAVE_CRASHREPORTER_INFO 130 __crashreporter_info__ = msg; 131 #endif 132 // Don't reorder subsequent operations: whatever comes after might crash and 133 // we want the system crash handling to see the message we just set. 134 std::atomic_signal_fence(std::memory_order_seq_cst); 135 } 136 137 #ifdef __APPLE__ 138 using CrashHandlerString = SmallString<2048>; 139 using CrashHandlerStringStorage = 140 std::aligned_storage<sizeof(CrashHandlerString), 141 alignof(CrashHandlerString)>::type; 142 static CrashHandlerStringStorage crashHandlerStringStorage; 143 #endif 144 145 static const char *BugReportMsg = 146 "PLEASE submit a bug report to " BUG_REPORT_URL 147 " and include the crash backtrace.\n"; 148 149 void llvm::setBugReportMsg(const char *Msg) { BugReportMsg = Msg; } 150 151 /// This callback is run if a fatal signal is delivered to the process, it 152 /// prints the pretty stack trace. 153 static void CrashHandler(void *) { 154 errs() << BugReportMsg ; 155 156 #ifndef __APPLE__ 157 // On non-apple systems, just emit the crash stack trace to stderr. 158 PrintCurStackTrace(errs()); 159 #else 160 // Emit the crash stack trace to a SmallString, put it where the system crash 161 // handling will find it, and also send it to stderr. 162 // 163 // The SmallString is fairly large in the hope that we don't allocate (we're 164 // handling a fatal signal, something is already pretty wrong, allocation 165 // might not work). Further, we don't use a magic static in case that's also 166 // borked. We leak any allocation that does occur because the program is about 167 // to die anyways. This is technically racy if we were handling two fatal 168 // signals, however if we're in that situation a race is the least of our 169 // worries. 170 auto &crashHandlerString = 171 *new (&crashHandlerStringStorage) CrashHandlerString; 172 173 // If we crash while trying to print the stack trace, we still want the system 174 // crash handling to have some partial information. That'll work out as long 175 // as the SmallString doesn't allocate. If it does allocate then the system 176 // crash handling will see some garbage because the inline buffer now contains 177 // a pointer. 178 setCrashLogMessage(crashHandlerString.c_str()); 179 180 { 181 raw_svector_ostream Stream(crashHandlerString); 182 PrintCurStackTrace(Stream); 183 } 184 185 if (!crashHandlerString.empty()) { 186 setCrashLogMessage(crashHandlerString.c_str()); 187 errs() << crashHandlerString.str(); 188 } else 189 setCrashLogMessage("No crash information."); 190 #endif 191 } 192 193 static void printForSigInfoIfNeeded() { 194 unsigned CurrentSigInfoGeneration = 195 GlobalSigInfoGenerationCounter.load(std::memory_order_relaxed); 196 if (ThreadLocalSigInfoGenerationCounter == 0 || 197 ThreadLocalSigInfoGenerationCounter == CurrentSigInfoGeneration) { 198 return; 199 } 200 201 PrintCurStackTrace(errs()); 202 ThreadLocalSigInfoGenerationCounter = CurrentSigInfoGeneration; 203 } 204 205 #endif // ENABLE_BACKTRACES 206 207 PrettyStackTraceEntry::PrettyStackTraceEntry() { 208 #if ENABLE_BACKTRACES 209 // Handle SIGINFO first, because we haven't finished constructing yet. 210 printForSigInfoIfNeeded(); 211 // Link ourselves. 212 NextEntry = PrettyStackTraceHead; 213 PrettyStackTraceHead = this; 214 #endif 215 } 216 217 PrettyStackTraceEntry::~PrettyStackTraceEntry() { 218 #if ENABLE_BACKTRACES 219 assert(PrettyStackTraceHead == this && 220 "Pretty stack trace entry destruction is out of order"); 221 PrettyStackTraceHead = NextEntry; 222 // Handle SIGINFO first, because we already started destructing. 223 printForSigInfoIfNeeded(); 224 #endif 225 } 226 227 void PrettyStackTraceString::print(raw_ostream &OS) const { OS << Str << "\n"; } 228 229 PrettyStackTraceFormat::PrettyStackTraceFormat(const char *Format, ...) { 230 va_list AP; 231 va_start(AP, Format); 232 const int SizeOrError = vsnprintf(nullptr, 0, Format, AP); 233 va_end(AP); 234 if (SizeOrError < 0) { 235 return; 236 } 237 238 const int Size = SizeOrError + 1; // '\0' 239 Str.resize(Size); 240 va_start(AP, Format); 241 vsnprintf(Str.data(), Size, Format, AP); 242 va_end(AP); 243 } 244 245 void PrettyStackTraceFormat::print(raw_ostream &OS) const { OS << Str << "\n"; } 246 247 void PrettyStackTraceProgram::print(raw_ostream &OS) const { 248 OS << "Program arguments: "; 249 // Print the argument list. 250 for (unsigned i = 0, e = ArgC; i != e; ++i) 251 OS << ArgV[i] << ' '; 252 OS << '\n'; 253 } 254 255 #if ENABLE_BACKTRACES 256 static bool RegisterCrashPrinter() { 257 sys::AddSignalHandler(CrashHandler, nullptr); 258 return false; 259 } 260 #endif 261 262 void llvm::EnablePrettyStackTrace() { 263 #if ENABLE_BACKTRACES 264 // The first time this is called, we register the crash printer. 265 static bool HandlerRegistered = RegisterCrashPrinter(); 266 (void)HandlerRegistered; 267 #endif 268 } 269 270 void llvm::EnablePrettyStackTraceOnSigInfoForThisThread(bool ShouldEnable) { 271 #if ENABLE_BACKTRACES 272 if (!ShouldEnable) { 273 ThreadLocalSigInfoGenerationCounter = 0; 274 return; 275 } 276 277 // The first time this is called, we register the SIGINFO handler. 278 static bool HandlerRegistered = []{ 279 sys::SetInfoSignalFunction([]{ 280 GlobalSigInfoGenerationCounter.fetch_add(1, std::memory_order_relaxed); 281 }); 282 return false; 283 }(); 284 (void)HandlerRegistered; 285 286 // Next, enable it for the current thread. 287 ThreadLocalSigInfoGenerationCounter = 288 GlobalSigInfoGenerationCounter.load(std::memory_order_relaxed); 289 #endif 290 } 291 292 const void *llvm::SavePrettyStackState() { 293 #if ENABLE_BACKTRACES 294 return PrettyStackTraceHead; 295 #else 296 return nullptr; 297 #endif 298 } 299 300 void llvm::RestorePrettyStackState(const void *Top) { 301 #if ENABLE_BACKTRACES 302 PrettyStackTraceHead = 303 static_cast<PrettyStackTraceEntry *>(const_cast<void *>(Top)); 304 #endif 305 } 306 307 void LLVMEnablePrettyStackTrace() { 308 EnablePrettyStackTrace(); 309 } 310