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