Add locking around signal handler registration.
[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 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 "Unix.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/System/Mutex.h"
18 #include <vector>
19 #include <algorithm>
20 #if HAVE_EXECINFO_H
21 # include <execinfo.h>         // For backtrace().
22 #endif
23 #if HAVE_SIGNAL_H
24 #include <signal.h>
25 #endif
26 #if HAVE_SYS_STAT_H
27 #include <sys/stat.h>
28 #endif
29 #if HAVE_DLFCN_H && __GNUG__
30 #include <dlfcn.h>
31 #include <cxxabi.h> 
32 #endif
33 using namespace llvm;
34
35 static RETSIGTYPE SignalHandler(int Sig);  // defined below.
36
37 static SmartMutex<true> SignalsMutex;
38
39 /// InterruptFunction - The function to call if ctrl-c is pressed.
40 static void (*InterruptFunction)() = 0;
41
42 static std::vector<sys::Path> *FilesToRemove = 0;
43 static std::vector<std::pair<void(*)(void*), void*> > *CallBacksToRun = 0;
44
45 // IntSigs - Signals that may interrupt the program at any time.
46 static const int IntSigs[] = {
47   SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
48 };
49 static const int *const IntSigsEnd =
50   IntSigs + sizeof(IntSigs) / sizeof(IntSigs[0]);
51
52 // KillSigs - Signals that are synchronous with the program that will cause it
53 // to die.
54 static const int KillSigs[] = {
55   SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGSYS, SIGXCPU, SIGXFSZ
56 #ifdef SIGEMT
57   , SIGEMT
58 #endif
59 };
60 static const int *const KillSigsEnd =
61   KillSigs + sizeof(KillSigs) / sizeof(KillSigs[0]);
62
63 static unsigned NumRegisteredSignals = 0;
64 static struct {
65   struct sigaction SA;
66   int SigNo;
67 } RegisteredSignalInfo[(sizeof(IntSigs)+sizeof(KillSigs))/sizeof(KillSigs[0])];
68
69
70 static void RegisterHandler(int Signal) {
71   assert(NumRegisteredSignals <
72          sizeof(RegisteredSignalInfo)/sizeof(RegisteredSignalInfo[0]) &&
73          "Out of space for signal handlers!");
74
75   struct sigaction NewHandler;
76   
77   NewHandler.sa_handler = SignalHandler;
78   NewHandler.sa_flags = SA_NODEFER|SA_RESETHAND;
79   sigemptyset(&NewHandler.sa_mask); 
80   
81   // Install the new handler, save the old one in RegisteredSignalInfo.
82   sigaction(Signal, &NewHandler,
83             &RegisteredSignalInfo[NumRegisteredSignals].SA);
84   RegisteredSignalInfo[NumRegisteredSignals].SigNo = Signal;
85   ++NumRegisteredSignals;
86 }
87
88 static void RegisterHandlers() {
89   // If the handlers are already registered, we're done.
90   if (NumRegisteredSignals != 0) return;
91
92   std::for_each(IntSigs, IntSigsEnd, RegisterHandler);
93   std::for_each(KillSigs, KillSigsEnd, RegisterHandler);
94 }
95
96 static void UnregisterHandlers() {
97   // Restore all of the signal handlers to how they were before we showed up.
98   for (unsigned i = 0, e = NumRegisteredSignals; i != e; ++i)
99     sigaction(RegisteredSignalInfo[i].SigNo,
100               &RegisteredSignalInfo[i].SA, 0);
101   NumRegisteredSignals = 0;
102 }
103
104
105
106 // SignalHandler - The signal handler that runs.
107 static RETSIGTYPE SignalHandler(int Sig) {
108   // Restore the signal behavior to default, so that the program actually
109   // crashes when we return and the signal reissues.  This also ensures that if
110   // we crash in our signal handler that the program will terminate immediately
111   // instead of recursing in the signal handler.
112   UnregisterHandlers();
113
114   // Unmask all potentially blocked kill signals.
115   sigset_t SigMask;
116   sigfillset(&SigMask);
117   sigprocmask(SIG_UNBLOCK, &SigMask, 0);
118
119   SignalsMutex.acquire();
120   if (FilesToRemove != 0)
121     while (!FilesToRemove->empty()) {
122       FilesToRemove->back().eraseFromDisk(true);
123       FilesToRemove->pop_back();
124     }
125
126   if (std::find(IntSigs, IntSigsEnd, Sig) != IntSigsEnd) {
127     if (InterruptFunction) {
128       void (*IF)() = InterruptFunction;
129       SignalsMutex.release();
130       InterruptFunction = 0;
131       IF();        // run the interrupt function.
132       return;
133     }
134     
135     SignalsMutex.release();
136     raise(Sig);   // Execute the default handler.
137     return;
138   }
139
140   SignalsMutex.release();
141
142   // Otherwise if it is a fault (like SEGV) run any handler.
143   if (CallBacksToRun)
144     for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
145       (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
146 }
147
148
149
150 void llvm::sys::SetInterruptFunction(void (*IF)()) {
151   SignalsMutex.acquire();
152   InterruptFunction = IF;
153   SignalsMutex.release();
154   RegisterHandlers();
155 }
156
157 // RemoveFileOnSignal - The public API
158 bool llvm::sys::RemoveFileOnSignal(const sys::Path &Filename,
159                                    std::string* ErrMsg) {
160   SignalsMutex.acquire();
161   if (FilesToRemove == 0)
162     FilesToRemove = new std::vector<sys::Path>();
163
164   FilesToRemove->push_back(Filename);
165
166   SignalsMutex.release();
167
168   RegisterHandlers();
169   return false;
170 }
171
172 /// AddSignalHandler - Add a function to be called when a signal is delivered
173 /// to the process.  The handler can have a cookie passed to it to identify
174 /// what instance of the handler it is.
175 void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
176   if (CallBacksToRun == 0)
177     CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >();
178   CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
179   RegisterHandlers();
180 }
181
182
183 // PrintStackTrace - In the case of a program crash or fault, print out a stack
184 // trace so that the user has an indication of why and where we died.
185 //
186 // On glibc systems we have the 'backtrace' function, which works nicely, but
187 // doesn't demangle symbols.  
188 static void PrintStackTrace(void *) {
189 #ifdef HAVE_BACKTRACE
190   static void* StackTrace[256];
191   // Use backtrace() to output a backtrace on Linux systems with glibc.
192   int depth = backtrace(StackTrace,
193                         static_cast<int>(array_lengthof(StackTrace)));
194 #if HAVE_DLFCN_H && __GNUG__
195   int width = 0;
196   for (int i = 0; i < depth; ++i) {
197     Dl_info dlinfo;
198     dladdr(StackTrace[i], &dlinfo);
199     const char* name = strrchr(dlinfo.dli_fname, '/');
200
201     int nwidth;
202     if (name == NULL) nwidth = strlen(dlinfo.dli_fname);
203     else              nwidth = strlen(name) - 1;
204
205     if (nwidth > width) width = nwidth;
206   }
207
208   for (int i = 0; i < depth; ++i) {
209     Dl_info dlinfo;
210     dladdr(StackTrace[i], &dlinfo);
211
212     fprintf(stderr, "%-3d", i);
213
214     const char* name = strrchr(dlinfo.dli_fname, '/');
215     if (name == NULL) fprintf(stderr, " %-*s", width, dlinfo.dli_fname);
216     else              fprintf(stderr, " %-*s", width, name+1);
217
218     fprintf(stderr, " %#0*lx",
219             (int)(sizeof(void*) * 2) + 2, (unsigned long)StackTrace[i]);
220
221     if (dlinfo.dli_sname != NULL) {
222       int res;
223       fputc(' ', stderr);
224       char* d = abi::__cxa_demangle(dlinfo.dli_sname, NULL, NULL, &res);
225       if (d == NULL) fputs(dlinfo.dli_sname, stderr);
226       else           fputs(d, stderr);
227       free(d);
228
229       fprintf(stderr, " + %tu",(char*)StackTrace[i]-(char*)dlinfo.dli_saddr);
230     }
231     fputc('\n', stderr);
232   }
233 #else
234   backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
235 #endif
236 #endif
237 }
238
239 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
240 /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
241 void llvm::sys::PrintStackTraceOnErrorSignal() {
242   AddSignalHandler(PrintStackTrace, 0);
243 }
244