1 //===- Signals.cpp - Signal Handling support ------------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file defines some helpful functions for dealing with the possibility of
11 // Unix signals occuring while your program is running.
13 //===----------------------------------------------------------------------===//
15 #include "Support/Signals.h"
20 #include "Config/config.h" // Get the signal handler return type
21 #ifdef HAVE_EXECINFO_H
22 # include <execinfo.h> // For backtrace().
28 static std::vector<std::string> FilesToRemove;
30 // IntSigs - Signals that may interrupt the program at any time.
31 static const int IntSigs[] = {
32 SIGHUP, SIGINT, SIGQUIT, SIGKILL, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
34 static const int *IntSigsEnd = IntSigs + sizeof(IntSigs)/sizeof(IntSigs[0]);
36 // KillSigs - Signals that are synchronous with the program that will cause it
38 static const int KillSigs[] = {
39 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGSYS, SIGXCPU, SIGXFSZ
44 static const int *KillSigsEnd = KillSigs + sizeof(KillSigs)/sizeof(KillSigs[0]);
46 static void* StackTrace[256];
48 // SignalHandler - The signal handler that runs...
49 static RETSIGTYPE SignalHandler(int Sig) {
50 while (!FilesToRemove.empty()) {
51 std::remove(FilesToRemove.back().c_str());
52 FilesToRemove.pop_back();
55 if (std::find(IntSigs, IntSigsEnd, Sig) != IntSigsEnd)
56 exit(1); // If this is an interrupt signal, exit the program
58 // Otherwise if it is a fault (like SEGV) output the stacktrace to
59 // STDERR (if we can) and reissue the signal to die...
61 // Use backtrace() to output a backtrace on Linux systems with glibc.
62 int depth = backtrace(StackTrace, sizeof(StackTrace)/sizeof(StackTrace[0]));
63 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
68 static void RegisterHandler(int Signal) { signal(Signal, SignalHandler); }
70 // RemoveFileOnSignal - The public API
71 void llvm::RemoveFileOnSignal(const std::string &Filename) {
72 FilesToRemove.push_back(Filename);
74 std::for_each(IntSigs, IntSigsEnd, RegisterHandler);
75 std::for_each(KillSigs, KillSigsEnd, RegisterHandler);
78 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
79 /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
80 void llvm::PrintStackTraceOnErrorSignal() {
81 std::for_each(KillSigs, KillSigsEnd, RegisterHandler);