LLVM API Documentation

Unix/Signals.inc

Go to the documentation of this file.
00001 //===- Signals.cpp - Generic Unix Signals Implementation -----*- C++ -*-===//
00002 // 
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 // 
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines some helpful functions for dealing with the possibility of
00011 // Unix signals occuring while your program is running.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "Unix.h"
00016 #include "llvm/ADT/STLExtras.h"
00017 #include "llvm/System/Mutex.h"
00018 #include <vector>
00019 #include <algorithm>
00020 #if HAVE_EXECINFO_H
00021 # include <execinfo.h>         // For backtrace().
00022 #endif
00023 #if HAVE_SIGNAL_H
00024 #include <signal.h>
00025 #endif
00026 #if HAVE_SYS_STAT_H
00027 #include <sys/stat.h>
00028 #endif
00029 #if HAVE_DLFCN_H && __GNUG__
00030 #include <dlfcn.h>
00031 #include <cxxabi.h> 
00032 #endif
00033 using namespace llvm;
00034 
00035 static RETSIGTYPE SignalHandler(int Sig);  // defined below.
00036 
00037 static SmartMutex<true> SignalsMutex;
00038 
00039 /// InterruptFunction - The function to call if ctrl-c is pressed.
00040 static void (*InterruptFunction)() = 0;
00041 
00042 static std::vector<sys::Path> *FilesToRemove = 0;
00043 static std::vector<std::pair<void(*)(void*), void*> > *CallBacksToRun = 0;
00044 
00045 // IntSigs - Signals that may interrupt the program at any time.
00046 static const int IntSigs[] = {
00047   SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
00048 };
00049 static const int *const IntSigsEnd =
00050   IntSigs + sizeof(IntSigs) / sizeof(IntSigs[0]);
00051 
00052 // KillSigs - Signals that are synchronous with the program that will cause it
00053 // to die.
00054 static const int KillSigs[] = {
00055   SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGSYS, SIGXCPU, SIGXFSZ
00056 #ifdef SIGEMT
00057   , SIGEMT
00058 #endif
00059 };
00060 static const int *const KillSigsEnd =
00061   KillSigs + sizeof(KillSigs) / sizeof(KillSigs[0]);
00062 
00063 static unsigned NumRegisteredSignals = 0;
00064 static struct {
00065   struct sigaction SA;
00066   int SigNo;
00067 } RegisteredSignalInfo[(sizeof(IntSigs)+sizeof(KillSigs))/sizeof(KillSigs[0])];
00068 
00069 
00070 static void RegisterHandler(int Signal) {
00071   assert(NumRegisteredSignals <
00072          sizeof(RegisteredSignalInfo)/sizeof(RegisteredSignalInfo[0]) &&
00073          "Out of space for signal handlers!");
00074 
00075   struct sigaction NewHandler;
00076   
00077   NewHandler.sa_handler = SignalHandler;
00078   NewHandler.sa_flags = SA_NODEFER|SA_RESETHAND;
00079   sigemptyset(&NewHandler.sa_mask); 
00080   
00081   // Install the new handler, save the old one in RegisteredSignalInfo.
00082   sigaction(Signal, &NewHandler,
00083             &RegisteredSignalInfo[NumRegisteredSignals].SA);
00084   RegisteredSignalInfo[NumRegisteredSignals].SigNo = Signal;
00085   ++NumRegisteredSignals;
00086 }
00087 
00088 static void RegisterHandlers() {
00089   // If the handlers are already registered, we're done.
00090   if (NumRegisteredSignals != 0) return;
00091 
00092   std::for_each(IntSigs, IntSigsEnd, RegisterHandler);
00093   std::for_each(KillSigs, KillSigsEnd, RegisterHandler);
00094 }
00095 
00096 static void UnregisterHandlers() {
00097   // Restore all of the signal handlers to how they were before we showed up.
00098   for (unsigned i = 0, e = NumRegisteredSignals; i != e; ++i)
00099     sigaction(RegisteredSignalInfo[i].SigNo,
00100               &RegisteredSignalInfo[i].SA, 0);
00101   NumRegisteredSignals = 0;
00102 }
00103 
00104 
00105 
00106 // SignalHandler - The signal handler that runs.
00107 static RETSIGTYPE SignalHandler(int Sig) {
00108   // Restore the signal behavior to default, so that the program actually
00109   // crashes when we return and the signal reissues.  This also ensures that if
00110   // we crash in our signal handler that the program will terminate immediately
00111   // instead of recursing in the signal handler.
00112   UnregisterHandlers();
00113 
00114   // Unmask all potentially blocked kill signals.
00115   sigset_t SigMask;
00116   sigfillset(&SigMask);
00117   sigprocmask(SIG_UNBLOCK, &SigMask, 0);
00118 
00119   SignalsMutex.acquire();
00120   if (FilesToRemove != 0)
00121     while (!FilesToRemove->empty()) {
00122       FilesToRemove->back().eraseFromDisk(true);
00123       FilesToRemove->pop_back();
00124     }
00125 
00126   if (std::find(IntSigs, IntSigsEnd, Sig) != IntSigsEnd) {
00127     if (InterruptFunction) {
00128       void (*IF)() = InterruptFunction;
00129       SignalsMutex.release();
00130       InterruptFunction = 0;
00131       IF();        // run the interrupt function.
00132       return;
00133     }
00134     
00135     SignalsMutex.release();
00136     raise(Sig);   // Execute the default handler.
00137     return;
00138   }
00139 
00140   SignalsMutex.release();
00141 
00142   // Otherwise if it is a fault (like SEGV) run any handler.
00143   if (CallBacksToRun)
00144     for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
00145       (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
00146 }
00147 
00148 
00149 
00150 void llvm::sys::SetInterruptFunction(void (*IF)()) {
00151   SignalsMutex.acquire();
00152   InterruptFunction = IF;
00153   SignalsMutex.release();
00154   RegisterHandlers();
00155 }
00156 
00157 // RemoveFileOnSignal - The public API
00158 bool llvm::sys::RemoveFileOnSignal(const sys::Path &Filename,
00159                                    std::string* ErrMsg) {
00160   SignalsMutex.acquire();
00161   if (FilesToRemove == 0)
00162     FilesToRemove = new std::vector<sys::Path>();
00163 
00164   FilesToRemove->push_back(Filename);
00165 
00166   SignalsMutex.release();
00167 
00168   RegisterHandlers();
00169   return false;
00170 }
00171 
00172 /// AddSignalHandler - Add a function to be called when a signal is delivered
00173 /// to the process.  The handler can have a cookie passed to it to identify
00174 /// what instance of the handler it is.
00175 void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
00176   if (CallBacksToRun == 0)
00177     CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >();
00178   CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
00179   RegisterHandlers();
00180 }
00181 
00182 
00183 // PrintStackTrace - In the case of a program crash or fault, print out a stack
00184 // trace so that the user has an indication of why and where we died.
00185 //
00186 // On glibc systems we have the 'backtrace' function, which works nicely, but
00187 // doesn't demangle symbols.  
00188 static void PrintStackTrace(void *) {
00189 #ifdef HAVE_BACKTRACE
00190   static void* StackTrace[256];
00191   // Use backtrace() to output a backtrace on Linux systems with glibc.
00192   int depth = backtrace(StackTrace,
00193                         static_cast<int>(array_lengthof(StackTrace)));
00194 #if HAVE_DLFCN_H && __GNUG__
00195   int width = 0;
00196   for (int i = 0; i < depth; ++i) {
00197     Dl_info dlinfo;
00198     dladdr(StackTrace[i], &dlinfo);
00199     const char* name = strrchr(dlinfo.dli_fname, '/');
00200 
00201     int nwidth;
00202     if (name == NULL) nwidth = strlen(dlinfo.dli_fname);
00203     else              nwidth = strlen(name) - 1;
00204 
00205     if (nwidth > width) width = nwidth;
00206   }
00207 
00208   for (int i = 0; i < depth; ++i) {
00209     Dl_info dlinfo;
00210     dladdr(StackTrace[i], &dlinfo);
00211 
00212     fprintf(stderr, "%-3d", i);
00213 
00214     const char* name = strrchr(dlinfo.dli_fname, '/');
00215     if (name == NULL) fprintf(stderr, " %-*s", width, dlinfo.dli_fname);
00216     else              fprintf(stderr, " %-*s", width, name+1);
00217 
00218     fprintf(stderr, " %#0*lx",
00219             (int)(sizeof(void*) * 2) + 2, (unsigned long)StackTrace[i]);
00220 
00221     if (dlinfo.dli_sname != NULL) {
00222       int res;
00223       fputc(' ', stderr);
00224       char* d = abi::__cxa_demangle(dlinfo.dli_sname, NULL, NULL, &res);
00225       if (d == NULL) fputs(dlinfo.dli_sname, stderr);
00226       else           fputs(d, stderr);
00227       free(d);
00228 
00229       fprintf(stderr, " + %tu",(char*)StackTrace[i]-(char*)dlinfo.dli_saddr);
00230     }
00231     fputc('\n', stderr);
00232   }
00233 #else
00234   backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
00235 #endif
00236 #endif
00237 }
00238 
00239 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
00240 /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
00241 void llvm::sys::PrintStackTraceOnErrorSignal() {
00242   AddSignalHandler(PrintStackTrace, 0);
00243 }
00244