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