Remove unnecessary in C++11 c_str() calls
[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     const char *path = FilesToRemoveRef[i].c_str();
148
149     // Get the status so we can determine if it's a file or directory. If we
150     // can't stat the file, ignore it.
151     struct stat buf;
152     if (stat(path, &buf) != 0)
153       continue;
154
155     // If this is not a regular file, ignore it. We want to prevent removal of
156     // special files like /dev/null, even if the compiler is being run with the
157     // super-user permissions.
158     if (!S_ISREG(buf.st_mode))
159       continue;
160   
161     // Otherwise, remove the file. We ignore any errors here as there is nothing
162     // else we can do.
163     unlink(path);
164   }
165 }
166
167 // SignalHandler - The signal handler that runs.
168 static RETSIGTYPE SignalHandler(int Sig) {
169   // Restore the signal behavior to default, so that the program actually
170   // crashes when we return and the signal reissues.  This also ensures that if
171   // we crash in our signal handler that the program will terminate immediately
172   // instead of recursing in the signal handler.
173   UnregisterHandlers();
174
175   // Unmask all potentially blocked kill signals.
176   sigset_t SigMask;
177   sigfillset(&SigMask);
178   sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
179
180   {
181     unique_lock<SmartMutex<true>> Guard(*SignalsMutex);
182     RemoveFilesToRemove();
183
184     if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
185         != std::end(IntSigs)) {
186       if (InterruptFunction) {
187         void (*IF)() = InterruptFunction;
188         Guard.unlock();
189         InterruptFunction = nullptr;
190         IF();        // run the interrupt function.
191         return;
192       }
193
194       Guard.unlock();
195       raise(Sig);   // Execute the default handler.
196       return;
197    }
198   }
199
200   // Otherwise if it is a fault (like SEGV) run any handler.
201   llvm::sys::RunSignalHandlers();
202
203 #ifdef __s390__
204   // On S/390, certain signals are delivered with PSW Address pointing to
205   // *after* the faulting instruction.  Simply returning from the signal
206   // handler would continue execution after that point, instead of
207   // re-raising the signal.  Raise the signal manually in those cases.
208   if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
209     raise(Sig);
210 #endif
211 }
212
213 void llvm::sys::RunInterruptHandlers() {
214   sys::SmartScopedLock<true> Guard(*SignalsMutex);
215   RemoveFilesToRemove();
216 }
217
218 void llvm::sys::SetInterruptFunction(void (*IF)()) {
219   {
220     sys::SmartScopedLock<true> Guard(*SignalsMutex);
221     InterruptFunction = IF;
222   }
223   RegisterHandlers();
224 }
225
226 // RemoveFileOnSignal - The public API
227 bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
228                                    std::string* ErrMsg) {
229   {
230     sys::SmartScopedLock<true> Guard(*SignalsMutex);
231     FilesToRemove->push_back(Filename);
232   }
233
234   RegisterHandlers();
235   return false;
236 }
237
238 // DontRemoveFileOnSignal - The public API
239 void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
240   sys::SmartScopedLock<true> Guard(*SignalsMutex);
241   std::vector<std::string>::reverse_iterator RI =
242     std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
243   std::vector<std::string>::iterator I = FilesToRemove->end();
244   if (RI != FilesToRemove->rend())
245     I = FilesToRemove->erase(RI.base()-1);
246 }
247
248 /// AddSignalHandler - Add a function to be called when a signal is delivered
249 /// to the process.  The handler can have a cookie passed to it to identify
250 /// what instance of the handler it is.
251 void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
252   CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
253   RegisterHandlers();
254 }
255
256 #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
257
258 #if HAVE_LINK_H && (defined(__linux__) || defined(__FreeBSD__) ||              \
259                     defined(__FreeBSD_kernel__) || defined(__NetBSD__))
260 struct DlIteratePhdrData {
261   void **StackTrace;
262   int depth;
263   bool first;
264   const char **modules;
265   intptr_t *offsets;
266   const char *main_exec_name;
267 };
268
269 static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
270   DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
271   const char *name = data->first ? data->main_exec_name : info->dlpi_name;
272   data->first = false;
273   for (int i = 0; i < info->dlpi_phnum; i++) {
274     const auto *phdr = &info->dlpi_phdr[i];
275     if (phdr->p_type != PT_LOAD)
276       continue;
277     intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
278     intptr_t end = beg + phdr->p_memsz;
279     for (int j = 0; j < data->depth; j++) {
280       if (data->modules[j])
281         continue;
282       intptr_t addr = (intptr_t)data->StackTrace[j];
283       if (beg <= addr && addr < end) {
284         data->modules[j] = name;
285         data->offsets[j] = addr - info->dlpi_addr;
286       }
287     }
288   }
289   return 0;
290 }
291
292 static bool findModulesAndOffsets(void **StackTrace, int Depth,
293                                   const char **Modules, intptr_t *Offsets,
294                                   const char *MainExecutableName) {
295   DlIteratePhdrData data = {StackTrace, Depth,   true,
296                             Modules,    Offsets, MainExecutableName};
297   dl_iterate_phdr(dl_iterate_phdr_cb, &data);
298   return true;
299 }
300 #else
301 static bool findModulesAndOffsets(void **StackTrace, int Depth,
302                                   const char **Modules, intptr_t *Offsets,
303                                   const char *MainExecutableName) {
304   return false;
305 }
306 #endif
307
308 static bool printSymbolizedStackTrace(void **StackTrace, int Depth,
309                                       llvm::raw_ostream &OS) {
310   // FIXME: Subtract necessary number from StackTrace entries to turn return addresses
311   // into actual instruction addresses.
312   // Use llvm-symbolizer tool to symbolize the stack traces.
313   ErrorOr<std::string> LLVMSymbolizerPathOrErr =
314       sys::findProgramByName("llvm-symbolizer");
315   if (!LLVMSymbolizerPathOrErr)
316     return false;
317   const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
318   // We don't know argv0 or the address of main() at this point, but try
319   // to guess it anyway (it's possible on some platforms).
320   std::string MainExecutableName = sys::fs::getMainExecutable(nullptr, nullptr);
321   if (MainExecutableName.empty() ||
322       MainExecutableName.find("llvm-symbolizer") != std::string::npos)
323     return false;
324
325   std::vector<const char *> Modules(Depth, nullptr);
326   std::vector<intptr_t> Offsets(Depth, 0);
327   if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(),
328                              MainExecutableName.c_str()))
329     return false;
330   int InputFD;
331   SmallString<32> InputFile, OutputFile;
332   sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile);
333   sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile);
334   FileRemover InputRemover(InputFile.c_str());
335   FileRemover OutputRemover(OutputFile.c_str());
336
337   {
338     raw_fd_ostream Input(InputFD, true);
339     for (int i = 0; i < Depth; i++) {
340       if (Modules[i])
341         Input << Modules[i] << " " << (void*)Offsets[i] << "\n";
342     }
343   }
344
345   StringRef InputFileStr(InputFile);
346   StringRef OutputFileStr(OutputFile);
347   StringRef StderrFileStr;
348   const StringRef *Redirects[] = {&InputFileStr, &OutputFileStr,
349                                   &StderrFileStr};
350   const char *Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
351                         "--demangle", nullptr};
352   int RunResult =
353       sys::ExecuteAndWait(LLVMSymbolizerPath, Args, nullptr, Redirects);
354   if (RunResult != 0)
355     return false;
356
357   auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str());
358   if (!OutputBuf)
359     return false;
360   StringRef Output = OutputBuf.get()->getBuffer();
361   SmallVector<StringRef, 32> Lines;
362   Output.split(Lines, "\n");
363   auto CurLine = Lines.begin();
364   int frame_no = 0;
365   for (int i = 0; i < Depth; i++) {
366     if (!Modules[i]) {
367       OS << format("#%d %p\n", frame_no++, StackTrace[i]);
368       continue;
369     }
370     // Read pairs of lines (function name and file/line info) until we
371     // encounter empty line.
372     for (;;) {
373       if (CurLine == Lines.end())
374         return false;
375       StringRef FunctionName = *CurLine++;
376       if (FunctionName.empty())
377         break;
378       OS << format("#%d %p ", frame_no++, StackTrace[i]);
379       if (!FunctionName.startswith("??"))
380         OS << format("%s ", FunctionName.str().c_str());
381       if (CurLine == Lines.end())
382         return false;
383       StringRef FileLineInfo = *CurLine++;
384       if (!FileLineInfo.startswith("??"))
385         OS << format("%s", FileLineInfo.str().c_str());
386       else
387         OS << format("(%s+%p)", Modules[i], (void *)Offsets[i]);
388       OS << "\n";
389     }
390   }
391   return true;
392 }
393 #endif // defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
394
395 // PrintStackTrace - In the case of a program crash or fault, print out a stack
396 // trace so that the user has an indication of why and where we died.
397 //
398 // On glibc systems we have the 'backtrace' function, which works nicely, but
399 // doesn't demangle symbols.
400 void llvm::sys::PrintStackTrace(raw_ostream &OS) {
401 #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
402   static void* StackTrace[256];
403   // Use backtrace() to output a backtrace on Linux systems with glibc.
404   int depth = backtrace(StackTrace,
405                         static_cast<int>(array_lengthof(StackTrace)));
406   if (printSymbolizedStackTrace(StackTrace, depth, OS))
407     return;
408 #if HAVE_DLFCN_H && __GNUG__
409   int width = 0;
410   for (int i = 0; i < depth; ++i) {
411     Dl_info dlinfo;
412     dladdr(StackTrace[i], &dlinfo);
413     const char* name = strrchr(dlinfo.dli_fname, '/');
414
415     int nwidth;
416     if (!name) nwidth = strlen(dlinfo.dli_fname);
417     else       nwidth = strlen(name) - 1;
418
419     if (nwidth > width) width = nwidth;
420   }
421
422   for (int i = 0; i < depth; ++i) {
423     Dl_info dlinfo;
424     dladdr(StackTrace[i], &dlinfo);
425
426     OS << format("%-2d", i);
427
428     const char* name = strrchr(dlinfo.dli_fname, '/');
429     if (!name) OS << format(" %-*s", width, dlinfo.dli_fname);
430     else       OS << format(" %-*s", width, name+1);
431
432     OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2,
433                  (unsigned long)StackTrace[i]);
434
435     if (dlinfo.dli_sname != nullptr) {
436       OS << ' ';
437 #  if HAVE_CXXABI_H
438       int res;
439       char* d = abi::__cxa_demangle(dlinfo.dli_sname, nullptr, nullptr, &res);
440 #  else
441       char* d = NULL;
442 #  endif
443       if (!d) OS << dlinfo.dli_sname;
444       else    OS << d;
445       free(d);
446
447       // FIXME: When we move to C++11, use %t length modifier. It's not in
448       // C++03 and causes gcc to issue warnings. Losing the upper 32 bits of
449       // the stack offset for a stack dump isn't likely to cause any problems.
450       OS << format(" + %u",(unsigned)((char*)StackTrace[i]-
451                                       (char*)dlinfo.dli_saddr));
452     }
453     OS << '\n';
454   }
455 #else
456   backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
457 #endif
458 #endif
459 }
460
461 static void PrintStackTraceSignalHandler(void *) {
462   PrintStackTrace(llvm::errs());
463 }
464
465 void llvm::sys::DisableSystemDialogsOnCrash() {}
466
467 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIGABRT or
468 /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
469 void llvm::sys::PrintStackTraceOnErrorSignal(bool DisableCrashReporting) {
470   AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
471
472 #if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES)
473   // Environment variable to disable any kind of crash dialog.
474   if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) {
475     mach_port_t self = mach_task_self();
476
477     exception_mask_t mask = EXC_MASK_CRASH;
478
479     kern_return_t ret = task_set_exception_ports(self,
480                              mask,
481                              MACH_PORT_NULL,
482                              EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
483                              THREAD_STATE_NONE);
484     (void)ret;
485   }
486 #endif
487 }
488
489
490 /***/
491
492 // On Darwin, raise sends a signal to the main thread instead of the current
493 // thread. This has the unfortunate effect that assert() and abort() will end up
494 // bypassing our crash recovery attempts. We work around this for anything in
495 // the same linkage unit by just defining our own versions of the assert handler
496 // and abort.
497
498 #if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES)
499
500 #include <signal.h>
501 #include <pthread.h>
502
503 int raise(int sig) {
504   return pthread_kill(pthread_self(), sig);
505 }
506
507 void __assert_rtn(const char *func,
508                   const char *file,
509                   int line,
510                   const char *expr) {
511   if (func)
512     fprintf(stderr, "Assertion failed: (%s), function %s, file %s, line %d.\n",
513             expr, func, file, line);
514   else
515     fprintf(stderr, "Assertion failed: (%s), file %s, line %d.\n",
516             expr, file, line);
517   abort();
518 }
519
520 void abort() {
521   raise(SIGABRT);
522   usleep(1000);
523   __builtin_trap();
524 }
525
526 #endif