LCOV - code coverage report
Current view: top level - lib/Support/Unix - Signals.inc (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 83 138 60.1 %
Date: 2017-09-14 15:23:50 Functions: 14 21 66.7 %
Legend: Lines: hit not hit

          Line data    Source code
       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/Demangle/Demangle.h"
      18             : #include "llvm/Support/FileSystem.h"
      19             : #include "llvm/Support/FileUtilities.h"
      20             : #include "llvm/Support/Format.h"
      21             : #include "llvm/Support/MemoryBuffer.h"
      22             : #include "llvm/Support/Mutex.h"
      23             : #include "llvm/Support/Program.h"
      24             : #include "llvm/Support/UniqueLock.h"
      25             : #include "llvm/Support/raw_ostream.h"
      26             : #include <algorithm>
      27             : #include <string>
      28             : #ifdef HAVE_BACKTRACE
      29             : # include BACKTRACE_HEADER         // For backtrace().
      30             : #endif
      31             : #if HAVE_SIGNAL_H
      32             : #include <signal.h>
      33             : #endif
      34             : #if HAVE_SYS_STAT_H
      35             : #include <sys/stat.h>
      36             : #endif
      37             : #if HAVE_DLFCN_H
      38             : #include <dlfcn.h>
      39             : #endif
      40             : #if HAVE_MACH_MACH_H
      41             : #include <mach/mach.h>
      42             : #endif
      43             : #if HAVE_LINK_H
      44             : #include <link.h>
      45             : #endif
      46             : #ifdef HAVE__UNWIND_BACKTRACE
      47             : // FIXME: We should be able to use <unwind.h> for any target that has an
      48             : // _Unwind_Backtrace function, but on FreeBSD the configure test passes
      49             : // despite the function not existing, and on Android, <unwind.h> conflicts
      50             : // with <link.h>.
      51             : #ifdef __GLIBC__
      52             : #include <unwind.h>
      53             : #else
      54             : #undef HAVE__UNWIND_BACKTRACE
      55             : #endif
      56             : #endif
      57             : 
      58             : using namespace llvm;
      59             : 
      60             : static RETSIGTYPE SignalHandler(int Sig);  // defined below.
      61             : 
      62             : static ManagedStatic<sys::SmartMutex<true> > SignalsMutex;
      63             : 
      64             : /// InterruptFunction - The function to call if ctrl-c is pressed.
      65             : static void (*InterruptFunction)() = nullptr;
      66             : 
      67             : static ManagedStatic<std::vector<std::string>> FilesToRemove;
      68             : 
      69             : static StringRef Argv0;
      70             : 
      71             : // IntSigs - Signals that represent requested termination. There's no bug
      72             : // or failure, or if there is, it's not our direct responsibility. For whatever
      73             : // reason, our continued execution is no longer desirable.
      74             : static const int IntSigs[] = {
      75             :   SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
      76             : };
      77             : 
      78             : // KillSigs - Signals that represent that we have a bug, and our prompt
      79             : // termination has been ordered.
      80             : static const int KillSigs[] = {
      81             :   SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
      82             : #ifdef SIGSYS
      83             :   , SIGSYS
      84             : #endif
      85             : #ifdef SIGXCPU
      86             :   , SIGXCPU
      87             : #endif
      88             : #ifdef SIGXFSZ
      89             :   , SIGXFSZ
      90             : #endif
      91             : #ifdef SIGEMT
      92             :   , SIGEMT
      93             : #endif
      94             : };
      95             : 
      96             : static unsigned NumRegisteredSignals = 0;
      97             : static struct {
      98             :   struct sigaction SA;
      99             :   int SigNo;
     100             : } RegisteredSignalInfo[array_lengthof(IntSigs) + array_lengthof(KillSigs)];
     101             : 
     102             : 
     103     1860992 : static void RegisterHandler(int Signal) {
     104             :   assert(NumRegisteredSignals < array_lengthof(RegisteredSignalInfo) &&
     105             :          "Out of space for signal handlers!");
     106             : 
     107             :   struct sigaction NewHandler;
     108             : 
     109     1860992 :   NewHandler.sa_handler = SignalHandler;
     110     1860992 :   NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK;
     111     1860992 :   sigemptyset(&NewHandler.sa_mask);
     112             : 
     113             :   // Install the new handler, save the old one in RegisteredSignalInfo.
     114     1860992 :   sigaction(Signal, &NewHandler,
     115     1860992 :             &RegisteredSignalInfo[NumRegisteredSignals].SA);
     116     1860992 :   RegisteredSignalInfo[NumRegisteredSignals].SigNo = Signal;
     117     1860992 :   ++NumRegisteredSignals;
     118     1860992 : }
     119             : 
     120             : #if defined(HAVE_SIGALTSTACK)
     121             : // Hold onto both the old and new alternate signal stack so that it's not
     122             : // reported as a leak. We don't make any attempt to remove our alt signal
     123             : // stack if we remove our signal handlers; that can't be done reliably if
     124             : // someone else is also trying to do the same thing.
     125             : static stack_t OldAltStack;
     126             : static void* NewAltStackPointer;
     127             : 
     128      116312 : static void CreateSigAltStack() {
     129      116312 :   const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024;
     130             : 
     131             :   // If we're executing on the alternate stack, or we already have an alternate
     132             :   // signal stack that we're happy with, there's nothing for us to do. Don't
     133             :   // reduce the size, some other part of the process might need a larger stack
     134             :   // than we do.
     135      232624 :   if (sigaltstack(nullptr, &OldAltStack) != 0 ||
     136      232624 :       OldAltStack.ss_flags & SS_ONSTACK ||
     137      116312 :       (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize))
     138           0 :     return;
     139             : 
     140      116312 :   stack_t AltStack = {};
     141      116312 :   AltStack.ss_sp = reinterpret_cast<char *>(malloc(AltStackSize));
     142      116312 :   NewAltStackPointer = AltStack.ss_sp; // Save to avoid reporting a leak.
     143      116312 :   AltStack.ss_size = AltStackSize;
     144      116312 :   if (sigaltstack(&AltStack, &OldAltStack) != 0)
     145           0 :     free(AltStack.ss_sp);
     146             : }
     147             : #else
     148             : static void CreateSigAltStack() {}
     149             : #endif
     150             : 
     151      240053 : static void RegisterHandlers() {
     152      596418 :   sys::SmartScopedLock<true> Guard(*SignalsMutex);
     153             : 
     154             :   // If the handlers are already registered, we're done.
     155      363794 :   if (NumRegisteredSignals != 0) return;
     156             : 
     157             :   // Create an alternate stack for signal handling. This is necessary for us to
     158             :   // be able to reliably handle signals due to stack overflow.
     159      116312 :   CreateSigAltStack();
     160             : 
     161      116312 :   for (auto S : IntSigs) RegisterHandler(S);
     162     1279432 :   for (auto S : KillSigs) RegisterHandler(S);
     163             : }
     164             : 
     165          13 : static void UnregisterHandlers() {
     166             :   // Restore all of the signal handlers to how they were before we showed up.
     167         221 :   for (unsigned i = 0, e = NumRegisteredSignals; i != e; ++i)
     168         208 :     sigaction(RegisteredSignalInfo[i].SigNo,
     169         208 :               &RegisteredSignalInfo[i].SA, nullptr);
     170          13 :   NumRegisteredSignals = 0;
     171          13 : }
     172             : 
     173             : 
     174             : /// RemoveFilesToRemove - Process the FilesToRemove list. This function
     175             : /// should be called with the SignalsMutex lock held.
     176             : /// NB: This must be an async signal safe function. It cannot allocate or free
     177             : /// memory, even in debug builds.
     178         354 : static void RemoveFilesToRemove() {
     179             :   // Avoid constructing ManagedStatic in the signal handler.
     180             :   // If FilesToRemove is not constructed, there are no files to remove.
     181         354 :   if (!FilesToRemove.isConstructed())
     182             :     return;
     183             : 
     184             :   // We avoid iterators in case of debug iterators that allocate or release
     185             :   // memory.
     186          34 :   std::vector<std::string>& FilesToRemoveRef = *FilesToRemove;
     187         106 :   for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i) {
     188          76 :     const char *path = FilesToRemoveRef[i].c_str();
     189             : 
     190             :     // Get the status so we can determine if it's a file or directory. If we
     191             :     // can't stat the file, ignore it.
     192             :     struct stat buf;
     193          38 :     if (stat(path, &buf) != 0)
     194          43 :       continue;
     195             : 
     196             :     // If this is not a regular file, ignore it. We want to prevent removal of
     197             :     // special files like /dev/null, even if the compiler is being run with the
     198             :     // super-user permissions.
     199          26 :     if (!S_ISREG(buf.st_mode))
     200          19 :       continue;
     201             : 
     202             :     // Otherwise, remove the file. We ignore any errors here as there is nothing
     203             :     // else we can do.
     204           7 :     unlink(path);
     205             :   }
     206             : }
     207             : 
     208             : // SignalHandler - The signal handler that runs.
     209          13 : static RETSIGTYPE SignalHandler(int Sig) {
     210             :   // Restore the signal behavior to default, so that the program actually
     211             :   // crashes when we return and the signal reissues.  This also ensures that if
     212             :   // we crash in our signal handler that the program will terminate immediately
     213             :   // instead of recursing in the signal handler.
     214          13 :   UnregisterHandlers();
     215             : 
     216             :   // Unmask all potentially blocked kill signals.
     217             :   sigset_t SigMask;
     218          13 :   sigfillset(&SigMask);
     219          13 :   sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
     220             : 
     221             :   {
     222          26 :     unique_lock<sys::SmartMutex<true>> Guard(*SignalsMutex);
     223          13 :     RemoveFilesToRemove();
     224             : 
     225          39 :     if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
     226          13 :         != std::end(IntSigs)) {
     227          13 :       if (InterruptFunction) {
     228           0 :         void (*IF)() = InterruptFunction;
     229           0 :         Guard.unlock();
     230           0 :         InterruptFunction = nullptr;
     231           0 :         IF();        // run the interrupt function.
     232          13 :         return;
     233             :       }
     234             : 
     235          13 :       Guard.unlock();
     236          13 :       raise(Sig);   // Execute the default handler.
     237          13 :       return;
     238             :    }
     239             :   }
     240             : 
     241             :   // Otherwise if it is a fault (like SEGV) run any handler.
     242           0 :   llvm::sys::RunSignalHandlers();
     243             : 
     244             : #ifdef __s390__
     245             :   // On S/390, certain signals are delivered with PSW Address pointing to
     246             :   // *after* the faulting instruction.  Simply returning from the signal
     247             :   // handler would continue execution after that point, instead of
     248             :   // re-raising the signal.  Raise the signal manually in those cases.
     249             :   if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
     250             :     raise(Sig);
     251             : #endif
     252             : }
     253             : 
     254         341 : void llvm::sys::RunInterruptHandlers() {
     255        1023 :   sys::SmartScopedLock<true> Guard(*SignalsMutex);
     256         341 :   RemoveFilesToRemove();
     257         341 : }
     258             : 
     259          10 : void llvm::sys::SetInterruptFunction(void (*IF)()) {
     260             :   {
     261          30 :     sys::SmartScopedLock<true> Guard(*SignalsMutex);
     262          10 :     InterruptFunction = IF;
     263             :   }
     264          10 :   RegisterHandlers();
     265          10 : }
     266             : 
     267             : // RemoveFileOnSignal - The public API
     268       15773 : bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
     269             :                                    std::string* ErrMsg) {
     270             :   {
     271       47319 :     sys::SmartScopedLock<true> Guard(*SignalsMutex);
     272       63092 :     FilesToRemove->push_back(Filename);
     273             :   }
     274             : 
     275       15773 :   RegisterHandlers();
     276       15773 :   return false;
     277             : }
     278             : 
     279             : // DontRemoveFileOnSignal - The public API
     280        7211 : void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
     281       21633 :   sys::SmartScopedLock<true> Guard(*SignalsMutex);
     282             :   std::vector<std::string>::reverse_iterator RI =
     283       21633 :       find(reverse(*FilesToRemove), Filename);
     284       14422 :   std::vector<std::string>::iterator I = FilesToRemove->end();
     285       21633 :   if (RI != FilesToRemove->rend())
     286       36055 :     I = FilesToRemove->erase(RI.base()-1);
     287        7211 : }
     288             : 
     289             : /// AddSignalHandler - Add a function to be called when a signal is delivered
     290             : /// to the process.  The handler can have a cookie passed to it to identify
     291             : /// what instance of the handler it is.
     292      224270 : void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
     293      672810 :   CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
     294      224270 :   RegisterHandlers();
     295      224270 : }
     296             : 
     297             : #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && HAVE_LINK_H &&    \
     298             :     (defined(__linux__) || defined(__FreeBSD__) ||                             \
     299             :      defined(__FreeBSD_kernel__) || defined(__NetBSD__))
     300             : struct DlIteratePhdrData {
     301             :   void **StackTrace;
     302             :   int depth;
     303             :   bool first;
     304             :   const char **modules;
     305             :   intptr_t *offsets;
     306             :   const char *main_exec_name;
     307             : };
     308             : 
     309           0 : static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
     310           0 :   DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
     311           0 :   const char *name = data->first ? data->main_exec_name : info->dlpi_name;
     312           0 :   data->first = false;
     313           0 :   for (int i = 0; i < info->dlpi_phnum; i++) {
     314           0 :     const auto *phdr = &info->dlpi_phdr[i];
     315           0 :     if (phdr->p_type != PT_LOAD)
     316           0 :       continue;
     317           0 :     intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
     318           0 :     intptr_t end = beg + phdr->p_memsz;
     319           0 :     for (int j = 0; j < data->depth; j++) {
     320           0 :       if (data->modules[j])
     321           0 :         continue;
     322           0 :       intptr_t addr = (intptr_t)data->StackTrace[j];
     323           0 :       if (beg <= addr && addr < end) {
     324           0 :         data->modules[j] = name;
     325           0 :         data->offsets[j] = addr - info->dlpi_addr;
     326             :       }
     327             :     }
     328             :   }
     329           0 :   return 0;
     330             : }
     331             : 
     332             : /// If this is an ELF platform, we can find all loaded modules and their virtual
     333             : /// addresses with dl_iterate_phdr.
     334             : static bool findModulesAndOffsets(void **StackTrace, int Depth,
     335             :                                   const char **Modules, intptr_t *Offsets,
     336             :                                   const char *MainExecutableName,
     337             :                                   StringSaver &StrPool) {
     338           0 :   DlIteratePhdrData data = {StackTrace, Depth,   true,
     339           0 :                             Modules,    Offsets, MainExecutableName};
     340           0 :   dl_iterate_phdr(dl_iterate_phdr_cb, &data);
     341             :   return true;
     342             : }
     343             : #else
     344             : /// This platform does not have dl_iterate_phdr, so we do not yet know how to
     345             : /// find all loaded DSOs.
     346             : static bool findModulesAndOffsets(void **StackTrace, int Depth,
     347             :                                   const char **Modules, intptr_t *Offsets,
     348             :                                   const char *MainExecutableName,
     349             :                                   StringSaver &StrPool) {
     350             :   return false;
     351             : }
     352             : #endif // defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && ...
     353             : 
     354             : #if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE)
     355           0 : static int unwindBacktrace(void **StackTrace, int MaxEntries) {
     356           0 :   if (MaxEntries < 0)
     357             :     return 0;
     358             : 
     359             :   // Skip the first frame ('unwindBacktrace' itself).
     360           0 :   int Entries = -1;
     361             : 
     362           0 :   auto HandleFrame = [&](_Unwind_Context *Context) -> _Unwind_Reason_Code {
     363             :     // Apparently we need to detect reaching the end of the stack ourselves.
     364           0 :     void *IP = (void *)_Unwind_GetIP(Context);
     365           0 :     if (!IP)
     366             :       return _URC_END_OF_STACK;
     367             : 
     368             :     assert(Entries < MaxEntries && "recursively called after END_OF_STACK?");
     369           0 :     if (Entries >= 0)
     370           0 :       StackTrace[Entries] = IP;
     371             : 
     372           0 :     if (++Entries == MaxEntries)
     373             :       return _URC_END_OF_STACK;
     374           0 :     return _URC_NO_REASON;
     375           0 :   };
     376             : 
     377           0 :   _Unwind_Backtrace(
     378           0 :       [](_Unwind_Context *Context, void *Handler) {
     379             :         return (*static_cast<decltype(HandleFrame) *>(Handler))(Context);
     380           0 :       },
     381             :       static_cast<void *>(&HandleFrame));
     382           0 :   return std::max(Entries, 0);
     383             : }
     384             : #endif
     385             : 
     386             : // PrintStackTrace - In the case of a program crash or fault, print out a stack
     387             : // trace so that the user has an indication of why and where we died.
     388             : //
     389             : // On glibc systems we have the 'backtrace' function, which works nicely, but
     390             : // doesn't demangle symbols.
     391           0 : void llvm::sys::PrintStackTrace(raw_ostream &OS) {
     392             : #if ENABLE_BACKTRACES
     393             :   static void *StackTrace[256];
     394           0 :   int depth = 0;
     395             : #if defined(HAVE_BACKTRACE)
     396             :   // Use backtrace() to output a backtrace on Linux systems with glibc.
     397             :   if (!depth)
     398           0 :     depth = backtrace(StackTrace, static_cast<int>(array_lengthof(StackTrace)));
     399             : #endif
     400             : #if defined(HAVE__UNWIND_BACKTRACE)
     401             :   // Try _Unwind_Backtrace() if backtrace() failed.
     402           0 :   if (!depth)
     403           0 :     depth = unwindBacktrace(StackTrace,
     404             :                         static_cast<int>(array_lengthof(StackTrace)));
     405             : #endif
     406           0 :   if (!depth)
     407             :     return;
     408             : 
     409           0 :   if (printSymbolizedStackTrace(Argv0, StackTrace, depth, OS))
     410             :     return;
     411             : #if HAVE_DLFCN_H && HAVE_DLADDR
     412             :   int width = 0;
     413             :   for (int i = 0; i < depth; ++i) {
     414             :     Dl_info dlinfo;
     415             :     dladdr(StackTrace[i], &dlinfo);
     416             :     const char* name = strrchr(dlinfo.dli_fname, '/');
     417             : 
     418             :     int nwidth;
     419             :     if (!name) nwidth = strlen(dlinfo.dli_fname);
     420             :     else       nwidth = strlen(name) - 1;
     421             : 
     422             :     if (nwidth > width) width = nwidth;
     423             :   }
     424             : 
     425             :   for (int i = 0; i < depth; ++i) {
     426             :     Dl_info dlinfo;
     427             :     dladdr(StackTrace[i], &dlinfo);
     428             : 
     429             :     OS << format("%-2d", i);
     430             : 
     431             :     const char* name = strrchr(dlinfo.dli_fname, '/');
     432             :     if (!name) OS << format(" %-*s", width, dlinfo.dli_fname);
     433             :     else       OS << format(" %-*s", width, name+1);
     434             : 
     435             :     OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2,
     436             :                  (unsigned long)StackTrace[i]);
     437             : 
     438             :     if (dlinfo.dli_sname != nullptr) {
     439             :       OS << ' ';
     440             :       int res;
     441             :       char* d = itaniumDemangle(dlinfo.dli_sname, nullptr, nullptr, &res);
     442             :       if (!d) OS << dlinfo.dli_sname;
     443             :       else    OS << d;
     444             :       free(d);
     445             : 
     446             :       // FIXME: When we move to C++11, use %t length modifier. It's not in
     447             :       // C++03 and causes gcc to issue warnings. Losing the upper 32 bits of
     448             :       // the stack offset for a stack dump isn't likely to cause any problems.
     449             :       OS << format(" + %u",(unsigned)((char*)StackTrace[i]-
     450             :                                       (char*)dlinfo.dli_saddr));
     451             :     }
     452             :     OS << '\n';
     453             :   }
     454             : #elif defined(HAVE_BACKTRACE)
     455           0 :   backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
     456             : #endif
     457             : #endif
     458             : }
     459             : 
     460           0 : static void PrintStackTraceSignalHandler(void *) {
     461           0 :   sys::PrintStackTrace(llvm::errs());
     462           0 : }
     463             : 
     464           0 : void llvm::sys::DisableSystemDialogsOnCrash() {}
     465             : 
     466             : /// PrintStackTraceOnErrorSignal - When an error signal (such as SIGABRT or
     467             : /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
     468      114281 : void llvm::sys::PrintStackTraceOnErrorSignal(StringRef Argv0,
     469             :                                              bool DisableCrashReporting) {
     470      114281 :   ::Argv0 = Argv0;
     471             : 
     472      114281 :   AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
     473             : 
     474             : #if defined(__APPLE__) && ENABLE_CRASH_OVERRIDES
     475             :   // Environment variable to disable any kind of crash dialog.
     476             :   if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) {
     477             :     mach_port_t self = mach_task_self();
     478             : 
     479             :     exception_mask_t mask = EXC_MASK_CRASH;
     480             : 
     481             :     kern_return_t ret = task_set_exception_ports(self,
     482             :                              mask,
     483             :                              MACH_PORT_NULL,
     484             :                              EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
     485             :                              THREAD_STATE_NONE);
     486             :     (void)ret;
     487             :   }
     488             : #endif
     489      478316 : }

Generated by: LCOV version 1.13