Only print the stack trace if it was requested. Previously, any call into
[oota-llvm.git] / lib / System / Unix / Signals.inc
1 //===- Signals.cpp - Generic Unix Signals Implementation -----*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 "Unix.h"
16 #include <vector>
17 #include <algorithm>
18 #if HAVE_EXECINFO_H
19 # include <execinfo.h>         // For backtrace().
20 #endif
21 #if HAVE_SIGNAL_H
22 #include <signal.h>
23 #endif
24
25 namespace {
26
27 bool StackTraceRequested = false; 
28
29 /// InterruptFunction - The function to call if ctrl-c is pressed.
30 void (*InterruptFunction)() = 0;
31
32 std::vector<std::string> *FilesToRemove = 0 ;
33 std::vector<llvm::sys::Path> *DirectoriesToRemove = 0;
34
35 // IntSigs - Signals that may interrupt the program at any time.
36 const int IntSigs[] = {
37   SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
38 };
39 const int *IntSigsEnd = IntSigs + sizeof(IntSigs)/sizeof(IntSigs[0]);
40
41 // KillSigs - Signals that are synchronous with the program that will cause it
42 // to die.
43 const int KillSigs[] = {
44   SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGSYS, SIGXCPU, SIGXFSZ
45 #ifdef SIGEMT
46   , SIGEMT
47 #endif
48 };
49 const int *KillSigsEnd = KillSigs + sizeof(KillSigs)/sizeof(KillSigs[0]);
50
51 #ifdef HAVE_BACKTRACE
52 void* StackTrace[256];
53 #endif
54
55 // PrintStackTrace - In the case of a program crash or fault, print out a stack
56 // trace so that the user has an indication of why and where we died.
57 //
58 // On glibc systems we have the 'backtrace' function, which works nicely, but
59 // doesn't demangle symbols.  In order to backtrace symbols, we fork and exec a
60 // 'c++filt' process to do the demangling.  This seems like the simplest and
61 // most robust solution when we can't allocate memory (such as in a signal
62 // handler).  If we can't find 'c++filt', we fallback to printing mangled names.
63 //
64 void PrintStackTrace() {
65 #ifdef HAVE_BACKTRACE
66   // Use backtrace() to output a backtrace on Linux systems with glibc.
67   int depth = backtrace(StackTrace, sizeof(StackTrace)/sizeof(StackTrace[0]));
68   
69   // Create a one-way unix pipe.  The backtracing process writes to PipeFDs[1],
70   // the c++filt process reads from PipeFDs[0].
71   int PipeFDs[2];
72   if (pipe(PipeFDs)) {
73     backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
74     return;
75   }
76
77   switch (pid_t ChildPID = fork()) {
78   case -1:        // Error forking, print mangled stack trace
79     close(PipeFDs[0]);
80     close(PipeFDs[1]);
81     backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
82     return;
83   default:        // backtracing process
84     close(PipeFDs[0]);  // Close the reader side.
85
86     // Print the mangled backtrace into the pipe.
87     backtrace_symbols_fd(StackTrace, depth, PipeFDs[1]);
88     close(PipeFDs[1]);   // We are done writing.
89     while (waitpid(ChildPID, 0, 0) == -1)
90       if (errno != EINTR) break;
91     return;
92
93   case 0:         // c++filt process
94     close(PipeFDs[1]);    // Close the writer side.
95     dup2(PipeFDs[0], 0);  // Read from standard input
96     close(PipeFDs[0]);    // Close the old descriptor
97     dup2(2, 1);           // Revector stdout -> stderr
98
99     // Try to run c++filt or gc++filt.  If neither is found, call back on 'cat'
100     // to print the mangled stack trace.  If we can't find cat, just exit.
101     execlp("c++filt", "c++filt", (char*)NULL);
102     execlp("gc++filt", "gc++filt", (char*)NULL);
103     execlp("cat", "cat", (char*)NULL);
104     execlp("/bin/cat", "cat", (char*)NULL);
105     exit(0);
106   }
107 #endif
108 }
109
110 // SignalHandler - The signal handler that runs...
111 RETSIGTYPE SignalHandler(int Sig) {
112   if (FilesToRemove != 0)
113     while (!FilesToRemove->empty()) {
114       std::remove(FilesToRemove->back().c_str());
115       FilesToRemove->pop_back();
116     }
117
118   if (DirectoriesToRemove != 0)
119     while (!DirectoriesToRemove->empty()) {
120       DirectoriesToRemove->back().eraseFromDisk(true);
121       DirectoriesToRemove->pop_back();
122     }
123
124   if (std::find(IntSigs, IntSigsEnd, Sig) != IntSigsEnd) {
125     if (InterruptFunction) {
126       void (*IF)() = InterruptFunction;
127       InterruptFunction = 0;
128       IF();        // run the interrupt function.
129       return;
130     } else {
131       exit(1);   // If this is an interrupt signal, exit the program
132     }
133   }
134
135   // Otherwise if it is a fault (like SEGV) output the stacktrace to
136   // STDERR (if we can) and reissue the signal to die...
137   if (StackTraceRequested)
138     PrintStackTrace();
139   signal(Sig, SIG_DFL);
140 }
141
142 // Just call signal
143 void RegisterHandler(int Signal) { 
144   signal(Signal, SignalHandler); 
145 }
146
147 }
148
149 namespace llvm {
150
151 void sys::SetInterruptFunction(void (*IF)()) {
152   InterruptFunction = IF;
153   RegisterHandler(SIGINT);
154 }
155
156 // RemoveFileOnSignal - The public API
157 void sys::RemoveFileOnSignal(const sys::Path &Filename) {
158   if (FilesToRemove == 0)
159     FilesToRemove = new std::vector<std::string>;
160
161   FilesToRemove->push_back(Filename.toString());
162
163   std::for_each(IntSigs, IntSigsEnd, RegisterHandler);
164   std::for_each(KillSigs, KillSigsEnd, RegisterHandler);
165 }
166
167 // RemoveDirectoryOnSignal - The public API
168 void sys::RemoveDirectoryOnSignal(const llvm::sys::Path& path) {
169   if (!path.isDirectory())
170     return;
171
172   if (DirectoriesToRemove == 0)
173     DirectoriesToRemove = new std::vector<sys::Path>;
174
175   DirectoriesToRemove->push_back(path);
176
177   std::for_each(IntSigs, IntSigsEnd, RegisterHandler);
178   std::for_each(KillSigs, KillSigsEnd, RegisterHandler);
179 }
180
181 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
182 /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
183 void sys::PrintStackTraceOnErrorSignal() {
184   StackTraceRequested = true;
185   std::for_each(KillSigs, KillSigsEnd, RegisterHandler);
186 }
187
188 }
189