2332db58bfc96a41d2e4e86c836a9100e345ceed
[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/Format.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/FileUtilities.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/Mutex.h"
22 #include "llvm/Support/Program.h"
23 #include "llvm/Support/UniqueLock.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <algorithm>
26 #include <string>
27 #if HAVE_EXECINFO_H
28 # include <execinfo.h>         // For backtrace().
29 #endif
30 #if HAVE_SIGNAL_H
31 #include <signal.h>
32 #endif
33 #if HAVE_SYS_STAT_H
34 #include <sys/stat.h>
35 #endif
36 #if HAVE_CXXABI_H
37 #include <cxxabi.h>
38 #endif
39 #if HAVE_DLFCN_H
40 #include <dlfcn.h>
41 #endif
42 #if HAVE_MACH_MACH_H
43 #include <mach/mach.h>
44 #endif
45 #if HAVE_LINK_H
46 #include <link.h>
47 #endif
48
49 using namespace llvm;
50
51 static RETSIGTYPE SignalHandler(int Sig);  // defined below.
52
53 static ManagedStatic<SmartMutex<true> > SignalsMutex;
54
55 /// InterruptFunction - The function to call if ctrl-c is pressed.
56 static void (*InterruptFunction)() = nullptr;
57
58 static ManagedStatic<std::vector<std::string>> FilesToRemove;
59
60 // IntSigs - Signals that represent requested termination. There's no bug
61 // or failure, or if there is, it's not our direct responsibility. For whatever
62 // reason, our continued execution is no longer desirable.
63 static const int IntSigs[] = {
64   SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
65 };
66
67 // KillSigs - Signals that represent that we have a bug, and our prompt
68 // termination has been ordered.
69 static const int KillSigs[] = {
70   SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
71 #ifdef SIGSYS
72   , SIGSYS
73 #endif
74 #ifdef SIGXCPU
75   , SIGXCPU
76 #endif
77 #ifdef SIGXFSZ
78   , SIGXFSZ
79 #endif
80 #ifdef SIGEMT
81   , SIGEMT
82 #endif
83 };
84
85 static unsigned NumRegisteredSignals = 0;
86 static struct {
87   struct sigaction SA;
88   int SigNo;
89 } RegisteredSignalInfo[(sizeof(IntSigs)+sizeof(KillSigs))/sizeof(KillSigs[0])];
90
91
92 static void RegisterHandler(int Signal) {
93   assert(NumRegisteredSignals <
94          sizeof(RegisteredSignalInfo)/sizeof(RegisteredSignalInfo[0]) &&
95          "Out of space for signal handlers!");
96
97   struct sigaction NewHandler;
98
99   NewHandler.sa_handler = SignalHandler;
100   NewHandler.sa_flags = SA_NODEFER|SA_RESETHAND;
101   sigemptyset(&NewHandler.sa_mask);
102
103   // Install the new handler, save the old one in RegisteredSignalInfo.
104   sigaction(Signal, &NewHandler,
105             &RegisteredSignalInfo[NumRegisteredSignals].SA);
106   RegisteredSignalInfo[NumRegisteredSignals].SigNo = Signal;
107   ++NumRegisteredSignals;
108 }
109
110 static void RegisterHandlers() {
111   // We need to dereference the signals mutex during handler registration so
112   // that we force its construction. This is to prevent the first use being
113   // during handling an actual signal because you can't safely call new in a
114   // signal handler.
115   *SignalsMutex;
116   
117   // If the handlers are already registered, we're done.
118   if (NumRegisteredSignals != 0) return;
119
120   for (auto S : IntSigs) RegisterHandler(S);
121   for (auto S : KillSigs) RegisterHandler(S);
122 }
123
124 static void UnregisterHandlers() {
125   // Restore all of the signal handlers to how they were before we showed up.
126   for (unsigned i = 0, e = NumRegisteredSignals; i != e; ++i)
127     sigaction(RegisteredSignalInfo[i].SigNo,
128               &RegisteredSignalInfo[i].SA, nullptr);
129   NumRegisteredSignals = 0;
130 }
131
132
133 /// RemoveFilesToRemove - Process the FilesToRemove list. This function
134 /// should be called with the SignalsMutex lock held.
135 /// NB: This must be an async signal safe function. It cannot allocate or free
136 /// memory, even in debug builds.
137 static void RemoveFilesToRemove() {
138   // Avoid constructing ManagedStatic in the signal handler.
139   // If FilesToRemove is not constructed, there are no files to remove.
140   if (!FilesToRemove.isConstructed())
141     return;
142
143   // We avoid iterators in case of debug iterators that allocate or release
144   // memory.
145   std::vector<std::string>& FilesToRemoveRef = *FilesToRemove;
146   for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i) {
147     // We rely on a std::string implementation for which repeated calls to
148     // 'c_str()' don't allocate memory. We pre-call 'c_str()' on all of these
149     // strings to try to ensure this is safe.
150     const char *path = FilesToRemoveRef[i].c_str();
151
152     // Get the status so we can determine if it's a file or directory. If we
153     // can't stat the file, ignore it.
154     struct stat buf;
155     if (stat(path, &buf) != 0)
156       continue;
157
158     // If this is not a regular file, ignore it. We want to prevent removal of
159     // special files like /dev/null, even if the compiler is being run with the
160     // super-user permissions.
161     if (!S_ISREG(buf.st_mode))
162       continue;
163   
164     // Otherwise, remove the file. We ignore any errors here as there is nothing
165     // else we can do.
166     unlink(path);
167   }
168 }
169
170 // SignalHandler - The signal handler that runs.
171 static RETSIGTYPE SignalHandler(int Sig) {
172   // Restore the signal behavior to default, so that the program actually
173   // crashes when we return and the signal reissues.  This also ensures that if
174   // we crash in our signal handler that the program will terminate immediately
175   // instead of recursing in the signal handler.
176   UnregisterHandlers();
177
178   // Unmask all potentially blocked kill signals.
179   sigset_t SigMask;
180   sigfillset(&SigMask);
181   sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
182
183   {
184     unique_lock<SmartMutex<true>> Guard(*SignalsMutex);
185     RemoveFilesToRemove();
186
187     if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
188         != std::end(IntSigs)) {
189       if (InterruptFunction) {
190         void (*IF)() = InterruptFunction;
191         Guard.unlock();
192         InterruptFunction = nullptr;
193         IF();        // run the interrupt function.
194         return;
195       }
196
197       Guard.unlock();
198       raise(Sig);   // Execute the default handler.
199       return;
200    }
201   }
202
203   // Otherwise if it is a fault (like SEGV) run any handler.
204   llvm::sys::RunSignalHandlers();
205
206 #ifdef __s390__
207   // On S/390, certain signals are delivered with PSW Address pointing to
208   // *after* the faulting instruction.  Simply returning from the signal
209   // handler would continue execution after that point, instead of
210   // re-raising the signal.  Raise the signal manually in those cases.
211   if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
212     raise(Sig);
213 #endif
214 }
215
216 void llvm::sys::RunInterruptHandlers() {
217   sys::SmartScopedLock<true> Guard(*SignalsMutex);
218   RemoveFilesToRemove();
219 }
220
221 void llvm::sys::SetInterruptFunction(void (*IF)()) {
222   {
223     sys::SmartScopedLock<true> Guard(*SignalsMutex);
224     InterruptFunction = IF;
225   }
226   RegisterHandlers();
227 }
228
229 // RemoveFileOnSignal - The public API
230 bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
231                                    std::string* ErrMsg) {
232   {
233     sys::SmartScopedLock<true> Guard(*SignalsMutex);
234     std::vector<std::string>& FilesToRemoveRef = *FilesToRemove;
235     std::string *OldPtr =
236         FilesToRemoveRef.empty() ? nullptr : &FilesToRemoveRef[0];
237     FilesToRemoveRef.push_back(Filename);
238
239     // We want to call 'c_str()' on every std::string in this vector so that if
240     // the underlying implementation requires a re-allocation, it happens here
241     // rather than inside of the signal handler. If we see the vector grow, we
242     // have to call it on every entry. If it remains in place, we only need to
243     // call it on the latest one.
244     if (OldPtr == &FilesToRemoveRef[0])
245       FilesToRemoveRef.back().c_str();
246     else
247       for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i)
248         FilesToRemoveRef[i].c_str();
249   }
250
251   RegisterHandlers();
252   return false;
253 }
254
255 // DontRemoveFileOnSignal - The public API
256 void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
257   sys::SmartScopedLock<true> Guard(*SignalsMutex);
258   std::vector<std::string>::reverse_iterator RI =
259     std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
260   std::vector<std::string>::iterator I = FilesToRemove->end();
261   if (RI != FilesToRemove->rend())
262     I = FilesToRemove->erase(RI.base()-1);
263 }
264
265 /// AddSignalHandler - Add a function to be called when a signal is delivered
266 /// to the process.  The handler can have a cookie passed to it to identify
267 /// what instance of the handler it is.
268 void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
269   CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
270   RegisterHandlers();
271 }
272
273 #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
274
275 #if HAVE_LINK_H && (defined(__linux__) || defined(__FreeBSD__) ||              \
276                     defined(__FreeBSD_kernel__) || defined(__NetBSD__))
277 struct DlIteratePhdrData {
278   void **StackTrace;
279   int depth;
280   bool first;
281   const char **modules;
282   intptr_t *offsets;
283   const char *main_exec_name;
284 };
285
286 static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
287   DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
288   const char *name = data->first ? data->main_exec_name : info->dlpi_name;
289   data->first = false;
290   for (int i = 0; i < info->dlpi_phnum; i++) {
291     const auto *phdr = &info->dlpi_phdr[i];
292     if (phdr->p_type != PT_LOAD)
293       continue;
294     intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
295     intptr_t end = beg + phdr->p_memsz;
296     for (int j = 0; j < data->depth; j++) {
297       if (data->modules[j])
298         continue;
299       intptr_t addr = (intptr_t)data->StackTrace[j];
300       if (beg <= addr && addr < end) {
301         data->modules[j] = name;
302         data->offsets[j] = addr - info->dlpi_addr;
303       }
304     }
305   }
306   return 0;
307 }
308
309 static bool findModulesAndOffsets(void **StackTrace, int Depth,
310                                   const char **Modules, intptr_t *Offsets,
311                                   const char *MainExecutableName) {
312   DlIteratePhdrData data = {StackTrace, Depth,   true,
313                             Modules,    Offsets, MainExecutableName};
314   dl_iterate_phdr(dl_iterate_phdr_cb, &data);
315   return true;
316 }
317 #else
318 static bool findModulesAndOffsets(void **StackTrace, int Depth,
319                                   const char **Modules, intptr_t *Offsets,
320                                   const char *MainExecutableName) {
321   return false;
322 }
323 #endif
324
325 static bool printSymbolizedStackTrace(void **StackTrace, int Depth,
326                                       llvm::raw_ostream &OS) {
327   // FIXME: Subtract necessary number from StackTrace entries to turn return addresses
328   // into actual instruction addresses.
329   // Use llvm-symbolizer tool to symbolize the stack traces.
330   ErrorOr<std::string> LLVMSymbolizerPathOrErr =
331       sys::findProgramByName("llvm-symbolizer");
332   if (!LLVMSymbolizerPathOrErr)
333     return false;
334   const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
335   // We don't know argv0 or the address of main() at this point, but try
336   // to guess it anyway (it's possible on some platforms).
337   std::string MainExecutableName = sys::fs::getMainExecutable(nullptr, nullptr);
338   if (MainExecutableName.empty() ||
339       MainExecutableName.find("llvm-symbolizer") != std::string::npos)
340     return false;
341
342   std::vector<const char *> Modules(Depth, nullptr);
343   std::vector<intptr_t> Offsets(Depth, 0);
344   if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(),
345                              MainExecutableName.c_str()))
346     return false;
347   int InputFD;
348   SmallString<32> InputFile, OutputFile;
349   sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile);
350   sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile);
351   FileRemover InputRemover(InputFile.c_str());
352   FileRemover OutputRemover(OutputFile.c_str());
353
354   {
355     raw_fd_ostream Input(InputFD, true);
356     for (int i = 0; i < Depth; i++) {
357       if (Modules[i])
358         Input << Modules[i] << " " << (void*)Offsets[i] << "\n";
359     }
360   }
361
362   StringRef InputFileStr(InputFile);
363   StringRef OutputFileStr(OutputFile);
364   StringRef StderrFileStr;
365   const StringRef *Redirects[] = {&InputFileStr, &OutputFileStr,
366                                   &StderrFileStr};
367   const char *Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
368                         "--demangle", nullptr};
369   int RunResult =
370       sys::ExecuteAndWait(LLVMSymbolizerPath, Args, nullptr, Redirects);
371   if (RunResult != 0)
372     return false;
373
374   auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str());
375   if (!OutputBuf)
376     return false;
377   StringRef Output = OutputBuf.get()->getBuffer();
378   SmallVector<StringRef, 32> Lines;
379   Output.split(Lines, "\n");
380   auto CurLine = Lines.begin();
381   int frame_no = 0;
382   for (int i = 0; i < Depth; i++) {
383     if (!Modules[i]) {
384       OS << format("#%d %p\n", frame_no++, StackTrace[i]);
385       continue;
386     }
387     // Read pairs of lines (function name and file/line info) until we
388     // encounter empty line.
389     for (;;) {
390       if (CurLine == Lines.end())
391         return false;
392       StringRef FunctionName = *CurLine++;
393       if (FunctionName.empty())
394         break;
395       OS << format("#%d %p ", frame_no++, StackTrace[i]);
396       if (!FunctionName.startswith("??"))
397         OS << format("%s ", FunctionName.str().c_str());
398       if (CurLine == Lines.end())
399         return false;
400       StringRef FileLineInfo = *CurLine++;
401       if (!FileLineInfo.startswith("??"))
402         OS << format("%s", FileLineInfo.str().c_str());
403       else
404         OS << format("(%s+%p)", Modules[i], (void *)Offsets[i]);
405       OS << "\n";
406     }
407   }
408   return true;
409 }
410 #endif // defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
411
412 // PrintStackTrace - In the case of a program crash or fault, print out a stack
413 // trace so that the user has an indication of why and where we died.
414 //
415 // On glibc systems we have the 'backtrace' function, which works nicely, but
416 // doesn't demangle symbols.
417 void llvm::sys::PrintStackTrace(raw_ostream &OS) {
418 #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
419   static void* StackTrace[256];
420   // Use backtrace() to output a backtrace on Linux systems with glibc.
421   int depth = backtrace(StackTrace,
422                         static_cast<int>(array_lengthof(StackTrace)));
423   if (printSymbolizedStackTrace(StackTrace, depth, OS))
424     return;
425 #if HAVE_DLFCN_H && __GNUG__
426   int width = 0;
427   for (int i = 0; i < depth; ++i) {
428     Dl_info dlinfo;
429     dladdr(StackTrace[i], &dlinfo);
430     const char* name = strrchr(dlinfo.dli_fname, '/');
431
432     int nwidth;
433     if (!name) nwidth = strlen(dlinfo.dli_fname);
434     else       nwidth = strlen(name) - 1;
435
436     if (nwidth > width) width = nwidth;
437   }
438
439   for (int i = 0; i < depth; ++i) {
440     Dl_info dlinfo;
441     dladdr(StackTrace[i], &dlinfo);
442
443     OS << format("%-2d", i);
444
445     const char* name = strrchr(dlinfo.dli_fname, '/');
446     if (!name) OS << format(" %-*s", width, dlinfo.dli_fname);
447     else       OS << format(" %-*s", width, name+1);
448
449     OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2,
450                  (unsigned long)StackTrace[i]);
451
452     if (dlinfo.dli_sname != nullptr) {
453       OS << ' ';
454 #  if HAVE_CXXABI_H
455       int res;
456       char* d = abi::__cxa_demangle(dlinfo.dli_sname, nullptr, nullptr, &res);
457 #  else
458       char* d = NULL;
459 #  endif
460       if (!d) OS << dlinfo.dli_sname;
461       else    OS << d;
462       free(d);
463
464       // FIXME: When we move to C++11, use %t length modifier. It's not in
465       // C++03 and causes gcc to issue warnings. Losing the upper 32 bits of
466       // the stack offset for a stack dump isn't likely to cause any problems.
467       OS << format(" + %u",(unsigned)((char*)StackTrace[i]-
468                                       (char*)dlinfo.dli_saddr));
469     }
470     OS << '\n';
471   }
472 #else
473   backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
474 #endif
475 #endif
476 }
477
478 static void PrintStackTraceSignalHandler(void *) {
479   PrintStackTrace(llvm::errs());
480 }
481
482 void llvm::sys::DisableSystemDialogsOnCrash() {}
483
484 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIGABRT or
485 /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
486 void llvm::sys::PrintStackTraceOnErrorSignal(bool DisableCrashReporting) {
487   AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
488
489 #if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES)
490   // Environment variable to disable any kind of crash dialog.
491   if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) {
492     mach_port_t self = mach_task_self();
493
494     exception_mask_t mask = EXC_MASK_CRASH;
495
496     kern_return_t ret = task_set_exception_ports(self,
497                              mask,
498                              MACH_PORT_NULL,
499                              EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
500                              THREAD_STATE_NONE);
501     (void)ret;
502   }
503 #endif
504 }
505
506
507 /***/
508
509 // On Darwin, raise sends a signal to the main thread instead of the current
510 // thread. This has the unfortunate effect that assert() and abort() will end up
511 // bypassing our crash recovery attempts. We work around this for anything in
512 // the same linkage unit by just defining our own versions of the assert handler
513 // and abort.
514
515 #if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES)
516
517 #include <signal.h>
518 #include <pthread.h>
519
520 int raise(int sig) {
521   return pthread_kill(pthread_self(), sig);
522 }
523
524 void __assert_rtn(const char *func,
525                   const char *file,
526                   int line,
527                   const char *expr) {
528   if (func)
529     fprintf(stderr, "Assertion failed: (%s), function %s, file %s, line %d.\n",
530             expr, func, file, line);
531   else
532     fprintf(stderr, "Assertion failed: (%s), file %s, line %d.\n",
533             expr, file, line);
534   abort();
535 }
536
537 void abort() {
538   raise(SIGABRT);
539   usleep(1000);
540   __builtin_trap();
541 }
542
543 #endif