1 //===- Signals.cpp - Generic Unix Signals Implementation -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines some helpful functions for dealing with the possibility of
11 // Unix signals occurring while your program is running.
13 //===----------------------------------------------------------------------===//
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/Support/Mutex.h"
22 # include <execinfo.h> // For backtrace().
30 #if HAVE_DLFCN_H && __GNUG__
35 #include <mach/mach.h>
40 static RETSIGTYPE SignalHandler(int Sig); // defined below.
42 static SmartMutex<true> SignalsMutex;
44 /// InterruptFunction - The function to call if ctrl-c is pressed.
45 static void (*InterruptFunction)() = 0;
47 static std::vector<std::string> FilesToRemove;
48 static std::vector<std::pair<void(*)(void*), void*> > CallBacksToRun;
50 // IntSigs - Signals that may interrupt the program at any time.
51 static const int IntSigs[] = {
52 SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
54 static const int *const IntSigsEnd =
55 IntSigs + sizeof(IntSigs) / sizeof(IntSigs[0]);
57 // KillSigs - Signals that are synchronous with the program that will cause it
59 static const int KillSigs[] = {
60 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV
74 static const int *const KillSigsEnd =
75 KillSigs + sizeof(KillSigs) / sizeof(KillSigs[0]);
77 static unsigned NumRegisteredSignals = 0;
81 } RegisteredSignalInfo[(sizeof(IntSigs)+sizeof(KillSigs))/sizeof(KillSigs[0])];
84 static void RegisterHandler(int Signal) {
85 assert(NumRegisteredSignals <
86 sizeof(RegisteredSignalInfo)/sizeof(RegisteredSignalInfo[0]) &&
87 "Out of space for signal handlers!");
89 struct sigaction NewHandler;
91 NewHandler.sa_handler = SignalHandler;
92 NewHandler.sa_flags = SA_NODEFER|SA_RESETHAND;
93 sigemptyset(&NewHandler.sa_mask);
95 // Install the new handler, save the old one in RegisteredSignalInfo.
96 sigaction(Signal, &NewHandler,
97 &RegisteredSignalInfo[NumRegisteredSignals].SA);
98 RegisteredSignalInfo[NumRegisteredSignals].SigNo = Signal;
99 ++NumRegisteredSignals;
102 static void RegisterHandlers() {
103 // If the handlers are already registered, we're done.
104 if (NumRegisteredSignals != 0) return;
106 std::for_each(IntSigs, IntSigsEnd, RegisterHandler);
107 std::for_each(KillSigs, KillSigsEnd, RegisterHandler);
110 static void UnregisterHandlers() {
111 // Restore all of the signal handlers to how they were before we showed up.
112 for (unsigned i = 0, e = NumRegisteredSignals; i != e; ++i)
113 sigaction(RegisteredSignalInfo[i].SigNo,
114 &RegisteredSignalInfo[i].SA, 0);
115 NumRegisteredSignals = 0;
119 /// RemoveFilesToRemove - Process the FilesToRemove list. This function
120 /// should be called with the SignalsMutex lock held.
121 /// NB: This must be an async signal safe function. It cannot allocate or free
122 /// memory, even in debug builds.
123 static void RemoveFilesToRemove() {
124 // We avoid iterators in case of debug iterators that allocate or release
126 for (unsigned i = 0, e = FilesToRemove.size(); i != e; ++i) {
127 // We rely on a std::string implementation for which repeated calls to
128 // 'c_str()' don't allocate memory. We pre-call 'c_str()' on all of these
129 // strings to try to ensure this is safe.
130 const char *path = FilesToRemove[i].c_str();
132 // Get the status so we can determine if it's a file or directory. If we
133 // can't stat the file, ignore it.
135 if (stat(path, &buf) != 0)
138 // If this is not a regular file, ignore it. We want to prevent removal of
139 // special files like /dev/null, even if the compiler is being run with the
140 // super-user permissions.
141 if (!S_ISREG(buf.st_mode))
144 // Otherwise, remove the file. We ignore any errors here as there is nothing
150 // SignalHandler - The signal handler that runs.
151 static RETSIGTYPE SignalHandler(int Sig) {
152 // Restore the signal behavior to default, so that the program actually
153 // crashes when we return and the signal reissues. This also ensures that if
154 // we crash in our signal handler that the program will terminate immediately
155 // instead of recursing in the signal handler.
156 UnregisterHandlers();
158 // Unmask all potentially blocked kill signals.
160 sigfillset(&SigMask);
161 sigprocmask(SIG_UNBLOCK, &SigMask, 0);
163 SignalsMutex.acquire();
164 RemoveFilesToRemove();
166 if (std::find(IntSigs, IntSigsEnd, Sig) != IntSigsEnd) {
167 if (InterruptFunction) {
168 void (*IF)() = InterruptFunction;
169 SignalsMutex.release();
170 InterruptFunction = 0;
171 IF(); // run the interrupt function.
175 SignalsMutex.release();
176 raise(Sig); // Execute the default handler.
180 SignalsMutex.release();
182 // Otherwise if it is a fault (like SEGV) run any handler.
183 for (unsigned i = 0, e = CallBacksToRun.size(); i != e; ++i)
184 CallBacksToRun[i].first(CallBacksToRun[i].second);
187 void llvm::sys::RunInterruptHandlers() {
188 SignalsMutex.acquire();
189 RemoveFilesToRemove();
190 SignalsMutex.release();
193 void llvm::sys::SetInterruptFunction(void (*IF)()) {
194 SignalsMutex.acquire();
195 InterruptFunction = IF;
196 SignalsMutex.release();
200 // RemoveFileOnSignal - The public API
201 bool llvm::sys::RemoveFileOnSignal(const sys::Path &Filename,
202 std::string* ErrMsg) {
203 SignalsMutex.acquire();
204 std::string *OldPtr = FilesToRemove.empty() ? 0 : &FilesToRemove[0];
205 FilesToRemove.push_back(Filename.str());
207 // We want to call 'c_str()' on every std::string in this vector so that if
208 // the underlying implementation requires a re-allocation, it happens here
209 // rather than inside of the signal handler. If we see the vector grow, we
210 // have to call it on every entry. If it remains in place, we only need to
211 // call it on the latest one.
212 if (OldPtr == &FilesToRemove[0])
213 FilesToRemove.back().c_str();
215 for (unsigned i = 0, e = FilesToRemove.size(); i != e; ++i)
216 FilesToRemove[i].c_str();
218 SignalsMutex.release();
224 // DontRemoveFileOnSignal - The public API
225 void llvm::sys::DontRemoveFileOnSignal(const sys::Path &Filename) {
226 SignalsMutex.acquire();
227 std::vector<std::string>::reverse_iterator RI =
228 std::find(FilesToRemove.rbegin(), FilesToRemove.rend(), Filename.str());
229 std::vector<std::string>::iterator I = FilesToRemove.end();
230 if (RI != FilesToRemove.rend())
231 I = FilesToRemove.erase(RI.base()-1);
233 // We need to call c_str() on every element which would have been moved by
234 // the erase. These elements, in a C++98 implementation where c_str()
235 // requires a reallocation on the first call may have had the call to c_str()
236 // made on insertion become invalid by being copied down an element.
237 for (std::vector<std::string>::iterator E = FilesToRemove.end(); I != E; ++I)
240 SignalsMutex.release();
243 /// AddSignalHandler - Add a function to be called when a signal is delivered
244 /// to the process. The handler can have a cookie passed to it to identify
245 /// what instance of the handler it is.
246 void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
247 CallBacksToRun.push_back(std::make_pair(FnPtr, Cookie));
252 // PrintStackTrace - In the case of a program crash or fault, print out a stack
253 // trace so that the user has an indication of why and where we died.
255 // On glibc systems we have the 'backtrace' function, which works nicely, but
256 // doesn't demangle symbols.
257 void llvm::sys::PrintStackTrace(FILE *FD) {
258 #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
259 static void* StackTrace[256];
260 // Use backtrace() to output a backtrace on Linux systems with glibc.
261 int depth = backtrace(StackTrace,
262 static_cast<int>(array_lengthof(StackTrace)));
263 #if HAVE_DLFCN_H && __GNUG__
265 for (int i = 0; i < depth; ++i) {
267 dladdr(StackTrace[i], &dlinfo);
268 const char* name = strrchr(dlinfo.dli_fname, '/');
271 if (name == NULL) nwidth = strlen(dlinfo.dli_fname);
272 else nwidth = strlen(name) - 1;
274 if (nwidth > width) width = nwidth;
277 for (int i = 0; i < depth; ++i) {
279 dladdr(StackTrace[i], &dlinfo);
281 fprintf(FD, "%-2d", i);
283 const char* name = strrchr(dlinfo.dli_fname, '/');
284 if (name == NULL) fprintf(FD, " %-*s", width, dlinfo.dli_fname);
285 else fprintf(FD, " %-*s", width, name+1);
287 fprintf(FD, " %#0*lx",
288 (int)(sizeof(void*) * 2) + 2, (unsigned long)StackTrace[i]);
290 if (dlinfo.dli_sname != NULL) {
293 char* d = abi::__cxa_demangle(dlinfo.dli_sname, NULL, NULL, &res);
294 if (d == NULL) fputs(dlinfo.dli_sname, FD);
298 fprintf(FD, " + %tu",(char*)StackTrace[i]-(char*)dlinfo.dli_saddr);
303 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
308 static void PrintStackTraceSignalHandler(void *) {
309 PrintStackTrace(stderr);
312 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIGABRT or
313 /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
314 void llvm::sys::PrintStackTraceOnErrorSignal() {
315 AddSignalHandler(PrintStackTraceSignalHandler, 0);
317 #if defined(__APPLE__)
318 // Environment variable to disable any kind of crash dialog.
319 if (getenv("LLVM_DISABLE_CRASH_REPORT")) {
320 mach_port_t self = mach_task_self();
322 exception_mask_t mask = EXC_MASK_CRASH;
324 kern_return_t ret = task_set_exception_ports(self,
327 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
337 // On Darwin, raise sends a signal to the main thread instead of the current
338 // thread. This has the unfortunate effect that assert() and abort() will end up
339 // bypassing our crash recovery attempts. We work around this for anything in
340 // the same linkage unit by just defining our own versions of the assert handler
349 return pthread_kill(pthread_self(), sig);
352 void __assert_rtn(const char *func,
357 fprintf(stderr, "Assertion failed: (%s), function %s, file %s, line %d.\n",
358 expr, func, file, line);
360 fprintf(stderr, "Assertion failed: (%s), file %s, line %d.\n",