Cleaning up remaining static initializers in Signals.inc
[oota-llvm.git] / lib / Support / Unix / Signals.inc
1 //===- Signals.cpp - Generic Unix Signals Implementation -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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 occurring while your program is running.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "Unix.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/Support/Mutex.h"
18 #include "llvm/Support/UniqueLock.h"
19 #include "llvm/Support/ManagedStatic.h"
20 #include <algorithm>
21 #include <string>
22 #include <vector>
23 #if HAVE_EXECINFO_H
24 # include <execinfo.h>         // For backtrace().
25 #endif
26 #if HAVE_SIGNAL_H
27 #include <signal.h>
28 #endif
29 #if HAVE_SYS_STAT_H
30 #include <sys/stat.h>
31 #endif
32 #if HAVE_CXXABI_H
33 #include <cxxabi.h>
34 #endif
35 #if HAVE_DLFCN_H
36 #include <dlfcn.h>
37 #endif
38 #if HAVE_MACH_MACH_H
39 #include <mach/mach.h>
40 #endif
41
42 using namespace llvm;
43
44 static RETSIGTYPE SignalHandler(int Sig);  // defined below.
45
46 static ManagedStatic<SmartMutex<true> > SignalsMutex;
47
48 /// InterruptFunction - The function to call if ctrl-c is pressed.
49 static void (*InterruptFunction)() = nullptr;
50
51 static ManagedStatic<std::vector<std::string>> FilesToRemove;
52 static ManagedStatic<std::vector<std::pair<void (*)(void *), void *>>>
53     CallBacksToRun;
54
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
60 };
61
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
66 #ifdef SIGSYS
67   , SIGSYS
68 #endif
69 #ifdef SIGXCPU
70   , SIGXCPU
71 #endif
72 #ifdef SIGXFSZ
73   , SIGXFSZ
74 #endif
75 #ifdef SIGEMT
76   , SIGEMT
77 #endif
78 };
79
80 static unsigned NumRegisteredSignals = 0;
81 static struct {
82   struct sigaction SA;
83   int SigNo;
84 } RegisteredSignalInfo[(sizeof(IntSigs)+sizeof(KillSigs))/sizeof(KillSigs[0])];
85
86
87 static void RegisterHandler(int Signal) {
88   assert(NumRegisteredSignals <
89          sizeof(RegisteredSignalInfo)/sizeof(RegisteredSignalInfo[0]) &&
90          "Out of space for signal handlers!");
91
92   struct sigaction NewHandler;
93
94   NewHandler.sa_handler = SignalHandler;
95   NewHandler.sa_flags = SA_NODEFER|SA_RESETHAND;
96   sigemptyset(&NewHandler.sa_mask);
97
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;
103 }
104
105 static void RegisterHandlers() {
106   // If the handlers are already registered, we're done.
107   if (NumRegisteredSignals != 0) return;
108
109   for (auto S : IntSigs) RegisterHandler(S);
110   for (auto S : KillSigs) RegisterHandler(S);
111 }
112
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;
119 }
120
121
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
128   // memory.
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();
135
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.
138     struct stat buf;
139     if (stat(path, &buf) != 0)
140       continue;
141
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))
146       continue;
147   
148     // Otherwise, remove the file. We ignore any errors here as there is nothing
149     // else we can do.
150     unlink(path);
151   }
152 }
153
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();
161
162   // Unmask all potentially blocked kill signals.
163   sigset_t SigMask;
164   sigfillset(&SigMask);
165   sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
166
167   {
168     unique_lock<SmartMutex<true>> Guard(*SignalsMutex);
169     RemoveFilesToRemove();
170
171     if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
172         != std::end(IntSigs)) {
173       if (InterruptFunction) {
174         void (*IF)() = InterruptFunction;
175         Guard.unlock();
176         InterruptFunction = nullptr;
177         IF();        // run the interrupt function.
178         return;
179       }
180
181       Guard.unlock();
182       raise(Sig);   // Execute the default handler.
183       return;
184    }
185   }
186
187   // Otherwise if it is a fault (like SEGV) run any handler.
188   std::vector<std::pair<void (*)(void *), void *>>& CallBacksToRunRef =
189       *CallBacksToRun;
190   for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
191     CallBacksToRunRef[i].first(CallBacksToRunRef[i].second);
192
193 #ifdef __s390__
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)
199     raise(Sig);
200 #endif
201 }
202
203 void llvm::sys::RunInterruptHandlers() {
204   sys::SmartScopedLock<true> Guard(*SignalsMutex);
205   RemoveFilesToRemove();
206 }
207
208 void llvm::sys::SetInterruptFunction(void (*IF)()) {
209   {
210     sys::SmartScopedLock<true> Guard(*SignalsMutex);
211     InterruptFunction = IF;
212   }
213   RegisterHandlers();
214 }
215
216 // RemoveFileOnSignal - The public API
217 bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
218                                    std::string* ErrMsg) {
219   {
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);
225
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();
233     else
234       for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i)
235         FilesToRemoveRef[i].c_str();
236   }
237
238   RegisterHandlers();
239   return false;
240 }
241
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);
250
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)
256     I->c_str();
257 }
258
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));
264   RegisterHandlers();
265 }
266
267
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.
270 //
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__
280   int width = 0;
281   for (int i = 0; i < depth; ++i) {
282     Dl_info dlinfo;
283     dladdr(StackTrace[i], &dlinfo);
284     const char* name = strrchr(dlinfo.dli_fname, '/');
285
286     int nwidth;
287     if (!name) nwidth = strlen(dlinfo.dli_fname);
288     else       nwidth = strlen(name) - 1;
289
290     if (nwidth > width) width = nwidth;
291   }
292
293   for (int i = 0; i < depth; ++i) {
294     Dl_info dlinfo;
295     dladdr(StackTrace[i], &dlinfo);
296
297     fprintf(FD, "%-2d", i);
298
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);
302
303     fprintf(FD, " %#0*lx",
304             (int)(sizeof(void*) * 2) + 2, (unsigned long)StackTrace[i]);
305
306     if (dlinfo.dli_sname != nullptr) {
307       fputc(' ', FD);
308 #  if HAVE_CXXABI_H
309       int res;
310       char* d = abi::__cxa_demangle(dlinfo.dli_sname, nullptr, nullptr, &res);
311 #  else
312       char* d = NULL;
313 #  endif
314       if (!d) fputs(dlinfo.dli_sname, FD);
315       else    fputs(d, FD);
316       free(d);
317
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));
323     }
324     fputc('\n', FD);
325   }
326 #else
327   backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
328 #endif
329 #endif
330 }
331
332 static void PrintStackTraceSignalHandler(void *) {
333   PrintStackTrace(stderr);
334 }
335
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);
340
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();
345
346     exception_mask_t mask = EXC_MASK_CRASH;
347
348     kern_return_t ret = task_set_exception_ports(self,
349                              mask,
350                              MACH_PORT_NULL,
351                              EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
352                              THREAD_STATE_NONE);
353     (void)ret;
354   }
355 #endif
356 }
357
358
359 /***/
360
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
365 // and abort.
366
367 #if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES)
368
369 #include <signal.h>
370 #include <pthread.h>
371
372 int raise(int sig) {
373   return pthread_kill(pthread_self(), sig);
374 }
375
376 void __assert_rtn(const char *func,
377                   const char *file,
378                   int line,
379                   const char *expr) {
380   if (func)
381     fprintf(stderr, "Assertion failed: (%s), function %s, file %s, line %d.\n",
382             expr, func, file, line);
383   else
384     fprintf(stderr, "Assertion failed: (%s), file %s, line %d.\n",
385             expr, file, line);
386   abort();
387 }
388
389 void abort() {
390   raise(SIGABRT);
391   usleep(1000);
392   __builtin_trap();
393 }
394
395 #endif