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