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"
18 #include "llvm/Support/UniqueLock.h"
19 #include "llvm/Support/ManagedStatic.h"
24 # include <execinfo.h> // For backtrace().
39 #include <mach/mach.h>
44 static RETSIGTYPE SignalHandler(int Sig); // defined below.
46 static ManagedStatic<SmartMutex<true> > SignalsMutex;
48 /// InterruptFunction - The function to call if ctrl-c is pressed.
49 static void (*InterruptFunction)() = nullptr;
51 static ManagedStatic<std::vector<std::string>> FilesToRemove;
52 static ManagedStatic<std::vector<std::pair<void (*)(void *), void *>>>
55 // IntSigs - Signals that represent requested termination. There's no bug
56 // or failure, or if there is, it's not our direct responsibility. For whatever
57 // reason, our continued execution is no longer desirable.
58 static const int IntSigs[] = {
59 SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
62 // KillSigs - Signals that represent that we have a bug, and our prompt
63 // termination has been ordered.
64 static const int KillSigs[] = {
65 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
80 static unsigned NumRegisteredSignals = 0;
84 } RegisteredSignalInfo[(sizeof(IntSigs)+sizeof(KillSigs))/sizeof(KillSigs[0])];
87 static void RegisterHandler(int Signal) {
88 assert(NumRegisteredSignals <
89 sizeof(RegisteredSignalInfo)/sizeof(RegisteredSignalInfo[0]) &&
90 "Out of space for signal handlers!");
92 struct sigaction NewHandler;
94 NewHandler.sa_handler = SignalHandler;
95 NewHandler.sa_flags = SA_NODEFER|SA_RESETHAND;
96 sigemptyset(&NewHandler.sa_mask);
98 // Install the new handler, save the old one in RegisteredSignalInfo.
99 sigaction(Signal, &NewHandler,
100 &RegisteredSignalInfo[NumRegisteredSignals].SA);
101 RegisteredSignalInfo[NumRegisteredSignals].SigNo = Signal;
102 ++NumRegisteredSignals;
105 static void RegisterHandlers() {
106 // If the handlers are already registered, we're done.
107 if (NumRegisteredSignals != 0) return;
109 for (auto S : IntSigs) RegisterHandler(S);
110 for (auto S : KillSigs) RegisterHandler(S);
113 static void UnregisterHandlers() {
114 // Restore all of the signal handlers to how they were before we showed up.
115 for (unsigned i = 0, e = NumRegisteredSignals; i != e; ++i)
116 sigaction(RegisteredSignalInfo[i].SigNo,
117 &RegisteredSignalInfo[i].SA, nullptr);
118 NumRegisteredSignals = 0;
122 /// RemoveFilesToRemove - Process the FilesToRemove list. This function
123 /// should be called with the SignalsMutex lock held.
124 /// NB: This must be an async signal safe function. It cannot allocate or free
125 /// memory, even in debug builds.
126 static void RemoveFilesToRemove() {
127 // We avoid iterators in case of debug iterators that allocate or release
129 std::vector<std::string>& FilesToRemoveRef = *FilesToRemove;
130 for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i) {
131 // We rely on a std::string implementation for which repeated calls to
132 // 'c_str()' don't allocate memory. We pre-call 'c_str()' on all of these
133 // strings to try to ensure this is safe.
134 const char *path = FilesToRemoveRef[i].c_str();
136 // Get the status so we can determine if it's a file or directory. If we
137 // can't stat the file, ignore it.
139 if (stat(path, &buf) != 0)
142 // If this is not a regular file, ignore it. We want to prevent removal of
143 // special files like /dev/null, even if the compiler is being run with the
144 // super-user permissions.
145 if (!S_ISREG(buf.st_mode))
148 // Otherwise, remove the file. We ignore any errors here as there is nothing
154 // SignalHandler - The signal handler that runs.
155 static RETSIGTYPE SignalHandler(int Sig) {
156 // Restore the signal behavior to default, so that the program actually
157 // crashes when we return and the signal reissues. This also ensures that if
158 // we crash in our signal handler that the program will terminate immediately
159 // instead of recursing in the signal handler.
160 UnregisterHandlers();
162 // Unmask all potentially blocked kill signals.
164 sigfillset(&SigMask);
165 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
168 unique_lock<SmartMutex<true>> Guard(*SignalsMutex);
169 RemoveFilesToRemove();
171 if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
172 != std::end(IntSigs)) {
173 if (InterruptFunction) {
174 void (*IF)() = InterruptFunction;
176 InterruptFunction = nullptr;
177 IF(); // run the interrupt function.
182 raise(Sig); // Execute the default handler.
187 // Otherwise if it is a fault (like SEGV) run any handler.
188 std::vector<std::pair<void (*)(void *), void *>>& CallBacksToRunRef =
190 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
191 CallBacksToRunRef[i].first(CallBacksToRunRef[i].second);
194 // On S/390, certain signals are delivered with PSW Address pointing to
195 // *after* the faulting instruction. Simply returning from the signal
196 // handler would continue execution after that point, instead of
197 // re-raising the signal. Raise the signal manually in those cases.
198 if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
203 void llvm::sys::RunInterruptHandlers() {
204 sys::SmartScopedLock<true> Guard(*SignalsMutex);
205 RemoveFilesToRemove();
208 void llvm::sys::SetInterruptFunction(void (*IF)()) {
210 sys::SmartScopedLock<true> Guard(*SignalsMutex);
211 InterruptFunction = IF;
216 // RemoveFileOnSignal - The public API
217 bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
218 std::string* ErrMsg) {
220 sys::SmartScopedLock<true> Guard(*SignalsMutex);
221 std::vector<std::string>& FilesToRemoveRef = *FilesToRemove;
222 std::string *OldPtr =
223 FilesToRemoveRef.empty() ? nullptr : &FilesToRemoveRef[0];
224 FilesToRemoveRef.push_back(Filename);
226 // We want to call 'c_str()' on every std::string in this vector so that if
227 // the underlying implementation requires a re-allocation, it happens here
228 // rather than inside of the signal handler. If we see the vector grow, we
229 // have to call it on every entry. If it remains in place, we only need to
230 // call it on the latest one.
231 if (OldPtr == &FilesToRemoveRef[0])
232 FilesToRemoveRef.back().c_str();
234 for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i)
235 FilesToRemoveRef[i].c_str();
242 // DontRemoveFileOnSignal - The public API
243 void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
244 sys::SmartScopedLock<true> Guard(*SignalsMutex);
245 std::vector<std::string>::reverse_iterator RI =
246 std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
247 std::vector<std::string>::iterator I = FilesToRemove->end();
248 if (RI != FilesToRemove->rend())
249 I = FilesToRemove->erase(RI.base()-1);
251 // We need to call c_str() on every element which would have been moved by
252 // the erase. These elements, in a C++98 implementation where c_str()
253 // requires a reallocation on the first call may have had the call to c_str()
254 // made on insertion become invalid by being copied down an element.
255 for (std::vector<std::string>::iterator E = FilesToRemove->end(); I != E; ++I)
259 /// AddSignalHandler - Add a function to be called when a signal is delivered
260 /// to the process. The handler can have a cookie passed to it to identify
261 /// what instance of the handler it is.
262 void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
263 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
268 // PrintStackTrace - In the case of a program crash or fault, print out a stack
269 // trace so that the user has an indication of why and where we died.
271 // On glibc systems we have the 'backtrace' function, which works nicely, but
272 // doesn't demangle symbols.
273 void llvm::sys::PrintStackTrace(FILE *FD) {
274 #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
275 static void* StackTrace[256];
276 // Use backtrace() to output a backtrace on Linux systems with glibc.
277 int depth = backtrace(StackTrace,
278 static_cast<int>(array_lengthof(StackTrace)));
279 #if HAVE_DLFCN_H && __GNUG__
281 for (int i = 0; i < depth; ++i) {
283 dladdr(StackTrace[i], &dlinfo);
284 const char* name = strrchr(dlinfo.dli_fname, '/');
287 if (!name) nwidth = strlen(dlinfo.dli_fname);
288 else nwidth = strlen(name) - 1;
290 if (nwidth > width) width = nwidth;
293 for (int i = 0; i < depth; ++i) {
295 dladdr(StackTrace[i], &dlinfo);
297 fprintf(FD, "%-2d", i);
299 const char* name = strrchr(dlinfo.dli_fname, '/');
300 if (!name) fprintf(FD, " %-*s", width, dlinfo.dli_fname);
301 else fprintf(FD, " %-*s", width, name+1);
303 fprintf(FD, " %#0*lx",
304 (int)(sizeof(void*) * 2) + 2, (unsigned long)StackTrace[i]);
306 if (dlinfo.dli_sname != nullptr) {
310 char* d = abi::__cxa_demangle(dlinfo.dli_sname, nullptr, nullptr, &res);
314 if (!d) fputs(dlinfo.dli_sname, FD);
318 // FIXME: When we move to C++11, use %t length modifier. It's not in
319 // C++03 and causes gcc to issue warnings. Losing the upper 32 bits of
320 // the stack offset for a stack dump isn't likely to cause any problems.
321 fprintf(FD, " + %u",(unsigned)((char*)StackTrace[i]-
322 (char*)dlinfo.dli_saddr));
327 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
332 static void PrintStackTraceSignalHandler(void *) {
333 PrintStackTrace(stderr);
336 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIGABRT or
337 /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
338 void llvm::sys::PrintStackTraceOnErrorSignal() {
339 AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
341 #if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES)
342 // Environment variable to disable any kind of crash dialog.
343 if (getenv("LLVM_DISABLE_CRASH_REPORT")) {
344 mach_port_t self = mach_task_self();
346 exception_mask_t mask = EXC_MASK_CRASH;
348 kern_return_t ret = task_set_exception_ports(self,
351 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
361 // On Darwin, raise sends a signal to the main thread instead of the current
362 // thread. This has the unfortunate effect that assert() and abort() will end up
363 // bypassing our crash recovery attempts. We work around this for anything in
364 // the same linkage unit by just defining our own versions of the assert handler
367 #if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES)
373 return pthread_kill(pthread_self(), sig);
376 void __assert_rtn(const char *func,
381 fprintf(stderr, "Assertion failed: (%s), function %s, file %s, line %d.\n",
382 expr, func, file, line);
384 fprintf(stderr, "Assertion failed: (%s), file %s, line %d.\n",