Support: add llvm::unique_lock
[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 <algorithm>
20 #include <string>
21 #include <vector>
22 #if HAVE_EXECINFO_H
23 # include <execinfo.h>         // For backtrace().
24 #endif
25 #if HAVE_SIGNAL_H
26 #include <signal.h>
27 #endif
28 #if HAVE_SYS_STAT_H
29 #include <sys/stat.h>
30 #endif
31 #if HAVE_CXXABI_H
32 #include <cxxabi.h>
33 #endif
34 #if HAVE_DLFCN_H
35 #include <dlfcn.h>
36 #endif
37 #if HAVE_MACH_MACH_H
38 #include <mach/mach.h>
39 #endif
40
41 using namespace llvm;
42
43 static RETSIGTYPE SignalHandler(int Sig);  // defined below.
44
45 static SmartMutex<true> SignalsMutex;
46
47 /// InterruptFunction - The function to call if ctrl-c is pressed.
48 static void (*InterruptFunction)() = nullptr;
49
50 static std::vector<std::string> FilesToRemove;
51 static std::vector<std::pair<void(*)(void*), void*> > CallBacksToRun;
52
53 // IntSigs - Signals that represent requested termination. There's no bug
54 // or failure, or if there is, it's not our direct responsibility. For whatever
55 // reason, our continued execution is no longer desirable.
56 static const int IntSigs[] = {
57   SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
58 };
59 static const int *const IntSigsEnd = std::end(IntSigs);
60
61 // KillSigs - Signals that represent that we have a bug, and our prompt
62 // termination has been ordered.
63 static const int KillSigs[] = {
64   SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
65 #ifdef SIGSYS
66   , SIGSYS
67 #endif
68 #ifdef SIGXCPU
69   , SIGXCPU
70 #endif
71 #ifdef SIGXFSZ
72   , SIGXFSZ
73 #endif
74 #ifdef SIGEMT
75   , SIGEMT
76 #endif
77 };
78 static const int *const KillSigsEnd = std::end(KillSigs);
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   std::for_each(IntSigs, IntSigsEnd, RegisterHandler);
110   std::for_each(KillSigs, KillSigsEnd, RegisterHandler);
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   for (unsigned i = 0, e = FilesToRemove.size(); i != e; ++i) {
130     // We rely on a std::string implementation for which repeated calls to
131     // 'c_str()' don't allocate memory. We pre-call 'c_str()' on all of these
132     // strings to try to ensure this is safe.
133     const char *path = FilesToRemove[i].c_str();
134
135     // Get the status so we can determine if it's a file or directory. If we
136     // can't stat the file, ignore it.
137     struct stat buf;
138     if (stat(path, &buf) != 0)
139       continue;
140
141     // If this is not a regular file, ignore it. We want to prevent removal of
142     // special files like /dev/null, even if the compiler is being run with the
143     // super-user permissions.
144     if (!S_ISREG(buf.st_mode))
145       continue;
146   
147     // Otherwise, remove the file. We ignore any errors here as there is nothing
148     // else we can do.
149     unlink(path);
150   }
151 }
152
153 // SignalHandler - The signal handler that runs.
154 static RETSIGTYPE SignalHandler(int Sig) {
155   // Restore the signal behavior to default, so that the program actually
156   // crashes when we return and the signal reissues.  This also ensures that if
157   // we crash in our signal handler that the program will terminate immediately
158   // instead of recursing in the signal handler.
159   UnregisterHandlers();
160
161   // Unmask all potentially blocked kill signals.
162   sigset_t SigMask;
163   sigfillset(&SigMask);
164   sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
165
166   {
167     unique_lock<SmartMutex<true>> Guard(SignalsMutex);
168     RemoveFilesToRemove();
169
170     if (std::find(IntSigs, IntSigsEnd, Sig) != IntSigsEnd) {
171       if (InterruptFunction) {
172         void (*IF)() = InterruptFunction;
173         Guard.unlock();
174         InterruptFunction = nullptr;
175         IF();        // run the interrupt function.
176         return;
177       }
178
179       Guard.unlock();
180       raise(Sig);   // Execute the default handler.
181       return;
182    }
183   }
184
185   // Otherwise if it is a fault (like SEGV) run any handler.
186   for (unsigned i = 0, e = CallBacksToRun.size(); i != e; ++i)
187     CallBacksToRun[i].first(CallBacksToRun[i].second);
188
189 #ifdef __s390__
190   // On S/390, certain signals are delivered with PSW Address pointing to
191   // *after* the faulting instruction.  Simply returning from the signal
192   // handler would continue execution after that point, instead of
193   // re-raising the signal.  Raise the signal manually in those cases.
194   if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
195     raise(Sig);
196 #endif
197 }
198
199 void llvm::sys::RunInterruptHandlers() {
200   sys::SmartScopedLock<true> Guard(SignalsMutex);
201   RemoveFilesToRemove();
202 }
203
204 void llvm::sys::SetInterruptFunction(void (*IF)()) {
205   {
206     sys::SmartScopedLock<true> Guard(SignalsMutex);
207     InterruptFunction = IF;
208   }
209   RegisterHandlers();
210 }
211
212 // RemoveFileOnSignal - The public API
213 bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
214                                    std::string* ErrMsg) {
215   {
216     sys::SmartScopedLock<true> Guard(SignalsMutex);
217     std::string *OldPtr = FilesToRemove.empty() ? nullptr : &FilesToRemove[0];
218     FilesToRemove.push_back(Filename);
219
220     // We want to call 'c_str()' on every std::string in this vector so that if
221     // the underlying implementation requires a re-allocation, it happens here
222     // rather than inside of the signal handler. If we see the vector grow, we
223     // have to call it on every entry. If it remains in place, we only need to
224     // call it on the latest one.
225     if (OldPtr == &FilesToRemove[0])
226       FilesToRemove.back().c_str();
227     else
228       for (unsigned i = 0, e = FilesToRemove.size(); i != e; ++i)
229         FilesToRemove[i].c_str();
230   }
231
232   RegisterHandlers();
233   return false;
234 }
235
236 // DontRemoveFileOnSignal - The public API
237 void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
238   sys::SmartScopedLock<true> Guard(SignalsMutex);
239   std::vector<std::string>::reverse_iterator RI =
240     std::find(FilesToRemove.rbegin(), FilesToRemove.rend(), Filename);
241   std::vector<std::string>::iterator I = FilesToRemove.end();
242   if (RI != FilesToRemove.rend())
243     I = FilesToRemove.erase(RI.base()-1);
244
245   // We need to call c_str() on every element which would have been moved by
246   // the erase. These elements, in a C++98 implementation where c_str()
247   // requires a reallocation on the first call may have had the call to c_str()
248   // made on insertion become invalid by being copied down an element.
249   for (std::vector<std::string>::iterator E = FilesToRemove.end(); I != E; ++I)
250     I->c_str();
251 }
252
253 /// AddSignalHandler - Add a function to be called when a signal is delivered
254 /// to the process.  The handler can have a cookie passed to it to identify
255 /// what instance of the handler it is.
256 void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
257   CallBacksToRun.push_back(std::make_pair(FnPtr, Cookie));
258   RegisterHandlers();
259 }
260
261
262 // PrintStackTrace - In the case of a program crash or fault, print out a stack
263 // trace so that the user has an indication of why and where we died.
264 //
265 // On glibc systems we have the 'backtrace' function, which works nicely, but
266 // doesn't demangle symbols.
267 void llvm::sys::PrintStackTrace(FILE *FD) {
268 #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
269   static void* StackTrace[256];
270   // Use backtrace() to output a backtrace on Linux systems with glibc.
271   int depth = backtrace(StackTrace,
272                         static_cast<int>(array_lengthof(StackTrace)));
273 #if HAVE_DLFCN_H && __GNUG__
274   int width = 0;
275   for (int i = 0; i < depth; ++i) {
276     Dl_info dlinfo;
277     dladdr(StackTrace[i], &dlinfo);
278     const char* name = strrchr(dlinfo.dli_fname, '/');
279
280     int nwidth;
281     if (!name) nwidth = strlen(dlinfo.dli_fname);
282     else       nwidth = strlen(name) - 1;
283
284     if (nwidth > width) width = nwidth;
285   }
286
287   for (int i = 0; i < depth; ++i) {
288     Dl_info dlinfo;
289     dladdr(StackTrace[i], &dlinfo);
290
291     fprintf(FD, "%-2d", i);
292
293     const char* name = strrchr(dlinfo.dli_fname, '/');
294     if (!name) fprintf(FD, " %-*s", width, dlinfo.dli_fname);
295     else       fprintf(FD, " %-*s", width, name+1);
296
297     fprintf(FD, " %#0*lx",
298             (int)(sizeof(void*) * 2) + 2, (unsigned long)StackTrace[i]);
299
300     if (dlinfo.dli_sname != nullptr) {
301       fputc(' ', FD);
302 #  if HAVE_CXXABI_H
303       int res;
304       char* d = abi::__cxa_demangle(dlinfo.dli_sname, nullptr, nullptr, &res);
305 #  else
306       char* d = NULL;
307 #  endif
308       if (!d) fputs(dlinfo.dli_sname, FD);
309       else    fputs(d, FD);
310       free(d);
311
312       // FIXME: When we move to C++11, use %t length modifier. It's not in
313       // C++03 and causes gcc to issue warnings. Losing the upper 32 bits of
314       // the stack offset for a stack dump isn't likely to cause any problems.
315       fprintf(FD, " + %u",(unsigned)((char*)StackTrace[i]-
316                                      (char*)dlinfo.dli_saddr));
317     }
318     fputc('\n', FD);
319   }
320 #else
321   backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
322 #endif
323 #endif
324 }
325
326 static void PrintStackTraceSignalHandler(void *) {
327   PrintStackTrace(stderr);
328 }
329
330 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIGABRT or
331 /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
332 void llvm::sys::PrintStackTraceOnErrorSignal() {
333   AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
334
335 #if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES)
336   // Environment variable to disable any kind of crash dialog.
337   if (getenv("LLVM_DISABLE_CRASH_REPORT")) {
338     mach_port_t self = mach_task_self();
339
340     exception_mask_t mask = EXC_MASK_CRASH;
341
342     kern_return_t ret = task_set_exception_ports(self,
343                              mask,
344                              MACH_PORT_NULL,
345                              EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
346                              THREAD_STATE_NONE);
347     (void)ret;
348   }
349 #endif
350 }
351
352
353 /***/
354
355 // On Darwin, raise sends a signal to the main thread instead of the current
356 // thread. This has the unfortunate effect that assert() and abort() will end up
357 // bypassing our crash recovery attempts. We work around this for anything in
358 // the same linkage unit by just defining our own versions of the assert handler
359 // and abort.
360
361 #if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES)
362
363 #include <signal.h>
364 #include <pthread.h>
365
366 int raise(int sig) {
367   return pthread_kill(pthread_self(), sig);
368 }
369
370 void __assert_rtn(const char *func,
371                   const char *file,
372                   int line,
373                   const char *expr) {
374   if (func)
375     fprintf(stderr, "Assertion failed: (%s), function %s, file %s, line %d.\n",
376             expr, func, file, line);
377   else
378     fprintf(stderr, "Assertion failed: (%s), file %s, line %d.\n",
379             expr, file, line);
380   abort();
381 }
382
383 void abort() {
384   raise(SIGABRT);
385   usleep(1000);
386   __builtin_trap();
387 }
388
389 #endif