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