blob: 563147eabf8ddf0286ebb5a2eda9a707503668fb [file] [log] [blame]
Chris Lattnerbac27a42002-04-18 19:53:53 +00001//===- Signals.cpp - Signal Handling support ------------------------------===//
2//
3// This file defines some helpful functions for dealing with the possibility of
Misha Brukman950971d2003-09-16 15:31:46 +00004// Unix signals occuring while your program is running.
Chris Lattnerbac27a42002-04-18 19:53:53 +00005//
6//===----------------------------------------------------------------------===//
7
8#include "Support/Signals.h"
9#include <vector>
10#include <algorithm>
11#include <cstdlib>
12#include <cstdio>
13#include <signal.h>
Chris Lattnerfafac122003-08-01 19:16:29 +000014#include "Config/config.h" // Get the signal handler return type
Chris Lattnerbac27a42002-04-18 19:53:53 +000015
Chris Lattner01e770a2003-05-22 21:59:35 +000016static std::vector<std::string> FilesToRemove;
Chris Lattnerbac27a42002-04-18 19:53:53 +000017
18// IntSigs - Signals that may interrupt the program at any time.
19static const int IntSigs[] = {
20 SIGHUP, SIGINT, SIGQUIT, SIGKILL, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
21};
22static const int *IntSigsEnd = IntSigs + sizeof(IntSigs)/sizeof(IntSigs[0]);
23
24// KillSigs - Signals that are synchronous with the program that will cause it
25// to die.
26static const int KillSigs[] = {
Chris Lattner7c97cee2002-09-13 14:57:24 +000027 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGSYS, SIGXCPU, SIGXFSZ
28#ifdef SIGEMT
29 , SIGEMT
30#endif
Chris Lattnerbac27a42002-04-18 19:53:53 +000031};
32static const int *KillSigsEnd = KillSigs + sizeof(KillSigs)/sizeof(KillSigs[0]);
33
34
35// SignalHandler - The signal handler that runs...
John Criswell7a73b802003-06-30 21:59:07 +000036static RETSIGTYPE SignalHandler(int Sig) {
Chris Lattnerbac27a42002-04-18 19:53:53 +000037 while (!FilesToRemove.empty()) {
38 std::remove(FilesToRemove.back().c_str());
39 FilesToRemove.pop_back();
40 }
41
Anand Shuklacfb22d32002-06-25 20:55:50 +000042 if (std::find(IntSigs, IntSigsEnd, Sig) != IntSigsEnd)
Chris Lattnerbac27a42002-04-18 19:53:53 +000043 exit(1); // If this is an interrupt signal, exit the program
44
45 // Otherwise if it is a fault (like SEGV) reissue the signal to die...
Chris Lattner39602b22003-05-27 16:25:04 +000046 signal(Sig, SIG_DFL);
Chris Lattnerbac27a42002-04-18 19:53:53 +000047}
48
49static void RegisterHandler(int Signal) { signal(Signal, SignalHandler); }
50
51// RemoveFileOnSignal - The public API
Chris Lattner01e770a2003-05-22 21:59:35 +000052void RemoveFileOnSignal(const std::string &Filename) {
Chris Lattnerbac27a42002-04-18 19:53:53 +000053 FilesToRemove.push_back(Filename);
54
Anand Shuklacfb22d32002-06-25 20:55:50 +000055 std::for_each(IntSigs, IntSigsEnd, RegisterHandler);
56 std::for_each(KillSigs, KillSigsEnd, RegisterHandler);
Chris Lattnerbac27a42002-04-18 19:53:53 +000057}