Home | History | Annotate | Download | only in Support
      1 //===- PrettyStackTrace.cpp - Pretty Crash Handling -----------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file defines some helpful functions for dealing with the possibility of
     11 // Unix signals occurring while your program is running.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #include "llvm/Support/PrettyStackTrace.h"
     16 #include "llvm-c/ErrorHandling.h"
     17 #include "llvm/ADT/SmallString.h"
     18 #include "llvm/Config/config.h"     // Get autoconf configuration settings
     19 #include "llvm/Support/Compiler.h"
     20 #include "llvm/Support/Signals.h"
     21 #include "llvm/Support/Watchdog.h"
     22 #include "llvm/Support/raw_ostream.h"
     23 
     24 #include <tuple>
     25 
     26 #ifdef HAVE_CRASHREPORTERCLIENT_H
     27 #include <CrashReporterClient.h>
     28 #endif
     29 
     30 using namespace llvm;
     31 
     32 // If backtrace support is not enabled, compile out support for pretty stack
     33 // traces.  This has the secondary effect of not requiring thread local storage
     34 // when backtrace support is disabled.
     35 #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
     36 
     37 // We need a thread local pointer to manage the stack of our stack trace
     38 // objects, but we *really* cannot tolerate destructors running and do not want
     39 // to pay any overhead of synchronizing. As a consequence, we use a raw
     40 // thread-local variable.
     41 static LLVM_THREAD_LOCAL PrettyStackTraceEntry *PrettyStackTraceHead = nullptr;
     42 
     43 namespace llvm {
     44 PrettyStackTraceEntry *ReverseStackTrace(PrettyStackTraceEntry *Head) {
     45   PrettyStackTraceEntry *Prev = nullptr;
     46   while (Head)
     47     std::tie(Prev, Head, Head->NextEntry) =
     48         std::make_tuple(Head, Head->NextEntry, Prev);
     49   return Prev;
     50 }
     51 }
     52 
     53 static void PrintStack(raw_ostream &OS) {
     54   // Print out the stack in reverse order. To avoid recursion (which is likely
     55   // to fail if we crashed due to stack overflow), we do an up-front pass to
     56   // reverse the stack, then print it, then reverse it again.
     57   unsigned ID = 0;
     58   PrettyStackTraceEntry *ReversedStack =
     59       llvm::ReverseStackTrace(PrettyStackTraceHead);
     60   for (const PrettyStackTraceEntry *Entry = ReversedStack; Entry;
     61        Entry = Entry->getNextEntry()) {
     62     OS << ID++ << ".\t";
     63     sys::Watchdog W(5);
     64     Entry->print(OS);
     65   }
     66   llvm::ReverseStackTrace(ReversedStack);
     67 }
     68 
     69 /// PrintCurStackTrace - Print the current stack trace to the specified stream.
     70 static void PrintCurStackTrace(raw_ostream &OS) {
     71   // Don't print an empty trace.
     72   if (!PrettyStackTraceHead) return;
     73 
     74   // If there are pretty stack frames registered, walk and emit them.
     75   OS << "Stack dump:\n";
     76 
     77   PrintStack(OS);
     78   OS.flush();
     79 }
     80 
     81 // Integrate with crash reporter libraries.
     82 #if defined (__APPLE__) && HAVE_CRASHREPORTERCLIENT_H
     83 //  If any clients of llvm try to link to libCrashReporterClient.a themselves,
     84 //  only one crash info struct will be used.
     85 extern "C" {
     86 CRASH_REPORTER_CLIENT_HIDDEN
     87 struct crashreporter_annotations_t gCRAnnotations
     88         __attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION)))
     89         = { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0 };
     90 }
     91 #elif defined (__APPLE__) && HAVE_CRASHREPORTER_INFO
     92 static const char *__crashreporter_info__ = 0;
     93 asm(".desc ___crashreporter_info__, 0x10");
     94 #endif
     95 
     96 
     97 /// CrashHandler - This callback is run if a fatal signal is delivered to the
     98 /// process, it prints the pretty stack trace.
     99 static void CrashHandler(void *) {
    100 #ifndef __APPLE__
    101   // On non-apple systems, just emit the crash stack trace to stderr.
    102   PrintCurStackTrace(errs());
    103 #else
    104   // Otherwise, emit to a smallvector of chars, send *that* to stderr, but also
    105   // put it into __crashreporter_info__.
    106   SmallString<2048> TmpStr;
    107   {
    108     raw_svector_ostream Stream(TmpStr);
    109     PrintCurStackTrace(Stream);
    110   }
    111 
    112   if (!TmpStr.empty()) {
    113 #ifdef HAVE_CRASHREPORTERCLIENT_H
    114     // Cast to void to avoid warning.
    115     (void)CRSetCrashLogMessage(std::string(TmpStr.str()).c_str());
    116 #elif HAVE_CRASHREPORTER_INFO
    117     __crashreporter_info__ = strdup(std::string(TmpStr.str()).c_str());
    118 #endif
    119     errs() << TmpStr.str();
    120   }
    121 
    122 #endif
    123 }
    124 
    125 // defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
    126 #endif
    127 
    128 PrettyStackTraceEntry::PrettyStackTraceEntry() {
    129 #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
    130   // Link ourselves.
    131   NextEntry = PrettyStackTraceHead;
    132   PrettyStackTraceHead = this;
    133 #endif
    134 }
    135 
    136 PrettyStackTraceEntry::~PrettyStackTraceEntry() {
    137 #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
    138   assert(PrettyStackTraceHead == this &&
    139          "Pretty stack trace entry destruction is out of order");
    140   PrettyStackTraceHead = NextEntry;
    141 #endif
    142 }
    143 
    144 void PrettyStackTraceString::print(raw_ostream &OS) const {
    145   OS << Str << "\n";
    146 }
    147 
    148 void PrettyStackTraceProgram::print(raw_ostream &OS) const {
    149   OS << "Program arguments: ";
    150   // Print the argument list.
    151   for (unsigned i = 0, e = ArgC; i != e; ++i)
    152     OS << ArgV[i] << ' ';
    153   OS << '\n';
    154 }
    155 
    156 #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
    157 static bool RegisterCrashPrinter() {
    158   sys::AddSignalHandler(CrashHandler, nullptr);
    159   return false;
    160 }
    161 #endif
    162 
    163 void llvm::EnablePrettyStackTrace() {
    164 #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
    165   // The first time this is called, we register the crash printer.
    166   static bool HandlerRegistered = RegisterCrashPrinter();
    167   (void)HandlerRegistered;
    168 #endif
    169 }
    170 
    171 const void *llvm::SavePrettyStackState() {
    172 #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
    173   return PrettyStackTraceHead;
    174 #else
    175   return nullptr;
    176 #endif
    177 }
    178 
    179 void llvm::RestorePrettyStackState(const void *Top) {
    180 #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
    181   PrettyStackTraceHead =
    182       static_cast<PrettyStackTraceEntry *>(const_cast<void *>(Top));
    183 #endif
    184 }
    185 
    186 void LLVMEnablePrettyStackTrace() {
    187   EnablePrettyStackTrace();
    188 }
    189