LLVM  6.0.0svn
Signals.inc
Go to the documentation of this file.
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"
20 #include "llvm/Support/Format.h"
22 #include "llvm/Support/Mutex.h"
23 #include "llvm/Support/Program.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 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  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 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 static void CreateSigAltStack() {
129  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  if (sigaltstack(nullptr, &OldAltStack) != 0 ||
136  OldAltStack.ss_flags & SS_ONSTACK ||
137  (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize))
138  return;
139 
140  stack_t AltStack = {};
141  AltStack.ss_sp = reinterpret_cast<char *>(malloc(AltStackSize));
142  NewAltStackPointer = AltStack.ss_sp; // Save to avoid reporting a leak.
143  AltStack.ss_size = AltStackSize;
144  if (sigaltstack(&AltStack, &OldAltStack) != 0)
145  free(AltStack.ss_sp);
146 }
147 #else
148 static void CreateSigAltStack() {}
149 #endif
150 
151 static void RegisterHandlers() {
152  sys::SmartScopedLock<true> Guard(*SignalsMutex);
153 
154  // If the handlers are already registered, we're done.
155  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  CreateSigAltStack();
160 
161  for (auto S : IntSigs) RegisterHandler(S);
162  for (auto S : KillSigs) RegisterHandler(S);
163 }
164 
165 static void UnregisterHandlers() {
166  // Restore all of the signal handlers to how they were before we showed up.
167  for (unsigned i = 0, e = NumRegisteredSignals; i != e; ++i)
168  sigaction(RegisteredSignalInfo[i].SigNo,
169  &RegisteredSignalInfo[i].SA, nullptr);
170  NumRegisteredSignals = 0;
171 }
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 static void RemoveFilesToRemove() {
179  // Avoid constructing ManagedStatic in the signal handler.
180  // If FilesToRemove is not constructed, there are no files to remove.
181  if (!FilesToRemove.isConstructed())
182  return;
183 
184  // We avoid iterators in case of debug iterators that allocate or release
185  // memory.
186  std::vector<std::string>& FilesToRemoveRef = *FilesToRemove;
187  for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i) {
188  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  if (stat(path, &buf) != 0)
194  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  if (!S_ISREG(buf.st_mode))
200  continue;
201 
202  // Otherwise, remove the file. We ignore any errors here as there is nothing
203  // else we can do.
204  unlink(path);
205  }
206 }
207 
208 // SignalHandler - The signal handler that runs.
209 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  UnregisterHandlers();
215 
216  // Unmask all potentially blocked kill signals.
217  sigset_t SigMask;
218  sigfillset(&SigMask);
219  sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
220 
221  {
222  unique_lock<sys::SmartMutex<true>> Guard(*SignalsMutex);
223  RemoveFilesToRemove();
224 
225  if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
226  != std::end(IntSigs)) {
227  if (InterruptFunction) {
228  void (*IF)() = InterruptFunction;
229  Guard.unlock();
230  InterruptFunction = nullptr;
231  IF(); // run the interrupt function.
232  return;
233  }
234 
235  Guard.unlock();
236  raise(Sig); // Execute the default handler.
237  return;
238  }
239  }
240 
241  // Otherwise if it is a fault (like SEGV) run any handler.
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 
255  sys::SmartScopedLock<true> Guard(*SignalsMutex);
256  RemoveFilesToRemove();
257 }
258 
259 void llvm::sys::SetInterruptFunction(void (*IF)()) {
260  {
261  sys::SmartScopedLock<true> Guard(*SignalsMutex);
262  InterruptFunction = IF;
263  }
264  RegisterHandlers();
265 }
266 
267 // RemoveFileOnSignal - The public API
269  std::string* ErrMsg) {
270  {
271  sys::SmartScopedLock<true> Guard(*SignalsMutex);
272  FilesToRemove->push_back(Filename);
273  }
274 
275  RegisterHandlers();
276  return false;
277 }
278 
279 // DontRemoveFileOnSignal - The public API
281  sys::SmartScopedLock<true> Guard(*SignalsMutex);
282  std::vector<std::string>::reverse_iterator RI =
283  find(reverse(*FilesToRemove), Filename);
284  std::vector<std::string>::iterator I = FilesToRemove->end();
285  if (RI != FilesToRemove->rend())
286  I = FilesToRemove->erase(RI.base()-1);
287 }
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 void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
293  CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
294  RegisterHandlers();
295 }
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 static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
310  DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
311  const char *name = data->first ? data->main_exec_name : info->dlpi_name;
312  data->first = false;
313  for (int i = 0; i < info->dlpi_phnum; i++) {
314  const auto *phdr = &info->dlpi_phdr[i];
315  if (phdr->p_type != PT_LOAD)
316  continue;
317  intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
318  intptr_t end = beg + phdr->p_memsz;
319  for (int j = 0; j < data->depth; j++) {
320  if (data->modules[j])
321  continue;
322  intptr_t addr = (intptr_t)data->StackTrace[j];
323  if (beg <= addr && addr < end) {
324  data->modules[j] = name;
325  data->offsets[j] = addr - info->dlpi_addr;
326  }
327  }
328  }
329  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  DlIteratePhdrData data = {StackTrace, Depth, true,
339  Modules, Offsets, MainExecutableName};
340  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 static int unwindBacktrace(void **StackTrace, int MaxEntries) {
356  if (MaxEntries < 0)
357  return 0;
358 
359  // Skip the first frame ('unwindBacktrace' itself).
360  int Entries = -1;
361 
362  auto HandleFrame = [&](_Unwind_Context *Context) -> _Unwind_Reason_Code {
363  // Apparently we need to detect reaching the end of the stack ourselves.
364  void *IP = (void *)_Unwind_GetIP(Context);
365  if (!IP)
366  return _URC_END_OF_STACK;
367 
368  assert(Entries < MaxEntries && "recursively called after END_OF_STACK?");
369  if (Entries >= 0)
370  StackTrace[Entries] = IP;
371 
372  if (++Entries == MaxEntries)
373  return _URC_END_OF_STACK;
374  return _URC_NO_REASON;
375  };
376 
377  _Unwind_Backtrace(
378  [](_Unwind_Context *Context, void *Handler) {
379  return (*static_cast<decltype(HandleFrame) *>(Handler))(Context);
380  },
381  static_cast<void *>(&HandleFrame));
382  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.
392 #if ENABLE_BACKTRACES
393  static void *StackTrace[256];
394  int depth = 0;
395 #if defined(HAVE_BACKTRACE)
396  // Use backtrace() to output a backtrace on Linux systems with glibc.
397  if (!depth)
398  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  if (!depth)
403  depth = unwindBacktrace(StackTrace,
404  static_cast<int>(array_lengthof(StackTrace)));
405 #endif
406  if (!depth)
407  return;
408 
409  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  backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
456 #endif
457 #endif
458 }
459 
460 static void PrintStackTraceSignalHandler(void *) {
462 }
463 
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.
469  bool DisableCrashReporting) {
470  ::Argv0 = Argv0;
471 
472  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 }
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:243
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
char * itaniumDemangle(const char *mangled_name, char *buf, size_t *n, int *status)
This is a llvm local version of __cxa_demangle.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
LLVMContext & Context
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:234
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:124
Offsets
Offsets in bytes from the start of the input buffer.
Definition: SIInstrInfo.h:911
void DisableSystemDialogsOnCrash()
Disable all system dialog boxes that appear when the process crashes.
static bool findModulesAndOffsets(void **StackTrace, int Depth, const char **Modules, intptr_t *Offsets, const char *MainExecutableName, StringSaver &StrPool)
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:248
void RunSignalHandlers()
Definition: Signals.cpp:46
void PrintStackTraceOnErrorSignal(StringRef Argv0, bool DisableCrashReporting=false)
When an error signal (such as SIBABRT or SIGSEGV) is delivered to the process, print a stack trace an...
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
void PrintStackTrace(raw_ostream &OS)
Print the stack trace using the given raw_ostream object.
void RunInterruptHandlers()
This function runs all the registered interrupt handlers, including the removal of files registered b...
A pared-down imitation of std::unique_lock from C++11.
Definition: UniqueLock.h:29
void DontRemoveFileOnSignal(StringRef Filename)
This function removes a file from the list of files to be removed on signal delivery.
lazy value info
unsigned first
static bool printSymbolizedStackTrace(StringRef Argv0, void **StackTrace, int Depth, llvm::raw_ostream &OS) LLVM_ATTRIBUTE_USED
Helper that launches llvm-symbolizer and symbolizes a backtrace.
Definition: Signals.cpp:73
auto find(R &&Range, const T &Val) -> decltype(std::begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:837
constexpr size_t array_lengthof(T(&)[N])
Find the length of an array.
Definition: STLExtras.h:729
bool RemoveFileOnSignal(StringRef Filename, std::string *ErrMsg=nullptr)
This function registers signal handlers to ensure that if a signal gets delivered that the named file...
Saves strings in the inheritor&#39;s stable storage and returns a StringRef with a stable character point...
Definition: StringSaver.h:21
bool isConstructed() const
isConstructed - Return true if this object has not been created yet.
Definition: ManagedStatic.h:49
#define I(x, y, z)
Definition: MD5.cpp:58
static ManagedStatic< std::vector< std::pair< void(*)(void *), void * > > > CallBacksToRun
Definition: Signals.cpp:45
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static const char * name
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
Definition: ManagedStatic.h:61
void SetInterruptFunction(void(*IF)())
This function registers a function to be called when the user "interrupts" the program (typically by ...
void AddSignalHandler(void(*FnPtr)(void *), void *Cookie)
AddSignalHandler - Add a function to be called when an abort/kill signal is delivered to the process...