73decfd89be6019181d5ac72a9c2f7e05e96e568
[oota-llvm.git] / lib / Support / Signals.cpp
1 //===- Signals.cpp - Signal Handling support ------------------------------===//
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 "Support/Signals.h"
16 #include <vector>
17 #include <algorithm>
18 #include <cstdlib>
19 #include <cstdio>
20 #include <signal.h>
21 #include "Config/config.h"     // Get the signal handler return type
22
23 namespace llvm {
24
25 static std::vector<std::string> FilesToRemove;
26
27 // IntSigs - Signals that may interrupt the program at any time.
28 static const int IntSigs[] = {
29   SIGHUP, SIGINT, SIGQUIT, SIGKILL, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
30 };
31 static const int *IntSigsEnd = IntSigs + sizeof(IntSigs)/sizeof(IntSigs[0]);
32
33 // KillSigs - Signals that are synchronous with the program that will cause it
34 // to die.
35 static const int KillSigs[] = {
36   SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGSYS, SIGXCPU, SIGXFSZ
37 #ifdef SIGEMT
38   , SIGEMT
39 #endif
40 };
41 static const int *KillSigsEnd = KillSigs + sizeof(KillSigs)/sizeof(KillSigs[0]);
42
43
44 // SignalHandler - The signal handler that runs...
45 static RETSIGTYPE SignalHandler(int Sig) {
46   while (!FilesToRemove.empty()) {
47     std::remove(FilesToRemove.back().c_str());
48     FilesToRemove.pop_back();
49   }
50
51   if (std::find(IntSigs, IntSigsEnd, Sig) != IntSigsEnd)
52     exit(1);   // If this is an interrupt signal, exit the program
53
54   // Otherwise if it is a fault (like SEGV) reissue the signal to die...
55   signal(Sig, SIG_DFL);
56 }
57
58 static void RegisterHandler(int Signal) { signal(Signal, SignalHandler); }
59
60 // RemoveFileOnSignal - The public API
61 void RemoveFileOnSignal(const std::string &Filename) {
62   FilesToRemove.push_back(Filename);
63
64   std::for_each(IntSigs, IntSigsEnd, RegisterHandler);
65   std::for_each(KillSigs, KillSigsEnd, RegisterHandler);
66 }
67
68 } // End llvm namespace