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