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