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