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