blob: 0a514045855860067fd8a84b7a4115d0bb8a56cc [file] [log] [blame]
Chris Lattnere97c7332009-03-04 21:40:23 +00001//===- 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 occuring while your program is running.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Support/PrettyStackTrace.h"
16#include "llvm/Support/raw_ostream.h"
17#include "llvm/System/Signals.h"
18using namespace llvm;
19
20// FIXME: This should be thread local when llvm supports threads.
21static const PrettyStackTraceEntry *PrettyStackTraceHead = 0;
22
23/// CrashHandler - This callback is run if a fatal signal is delivered to the
24/// process, it prints the pretty stack trace.
25static void CrashHandler(void *Cookie) {
26 // If there are pretty stack frames registered, walk and emit them.
27 raw_ostream &OS = errs();
28 OS << "Stack dump:\n";
29
30 unsigned i = 0;
31 for (const PrettyStackTraceEntry *Entry = PrettyStackTraceHead; Entry;
32 Entry = Entry->getNextEntry(), ++i) {
33 OS << i << ".\t";
34 Entry->print(OS);
35 }
36 OS.flush();
37}
38
39static bool RegisterCrashPrinter() {
40 sys::AddSignalHandler(CrashHandler, 0);
41 return false;
42}
43
44PrettyStackTraceEntry::PrettyStackTraceEntry() {
45 // The first time this is called, we register the crash printer.
46 static bool HandlerRegistered = RegisterCrashPrinter();
47 HandlerRegistered = HandlerRegistered;
48
49 // Link ourselves.
50 NextEntry = PrettyStackTraceHead;
51 PrettyStackTraceHead = this;
52}
53
54PrettyStackTraceEntry::~PrettyStackTraceEntry() {
55 assert(PrettyStackTraceHead == this &&
56 "Pretty stack trace entry destruction is out of order");
57 PrettyStackTraceHead = getNextEntry();
58}
59
60void PrettyStackTraceString::print(raw_ostream &OS) const {
61 OS << Str << "\n";
62}
63
64void PrettyStackTraceProgram::print(raw_ostream &OS) const {
Chris Lattnerfcba7cd2009-03-05 06:51:42 +000065 OS << "Program arguments: ";
Chris Lattnere97c7332009-03-04 21:40:23 +000066 // Print the argument list.
67 for (unsigned i = 0, e = ArgC; i != e; ++i)
68 OS << ArgV[i] << ' ';
69 OS << '\n';
Chris Lattnerfcba7cd2009-03-05 06:51:42 +000070}
71