1//===- Signals.cpp - Generic Unix Signals Implementation -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines some helpful functions for dealing with the possibility of
10// Unix signals occurring while your program is running.
11//
12//===----------------------------------------------------------------------===//
13//
14// This file is extremely careful to only do signal-safe things while in a
15// signal handler. In particular, memory allocation and acquiring a mutex
16// while in a signal handler should never occur. ManagedStatic isn't usable from
17// a signal handler for 2 reasons:
18//
19//  1. Creating a new one allocates.
20//  2. The signal handler could fire while llvm_shutdown is being processed, in
21//     which case the ManagedStatic is in an unknown state because it could
22//     already have been destroyed, or be in the process of being destroyed.
23//
24// Modifying the behavior of the signal handlers (such as registering new ones)
25// can acquire a mutex, but all this guarantees is that the signal handler
26// behavior is only modified by one thread at a time. A signal handler can still
27// fire while this occurs!
28//
29// Adding work to a signal handler requires lock-freedom (and assume atomics are
30// always lock-free) because the signal handler could fire while new work is
31// being added.
32//
33//===----------------------------------------------------------------------===//
34
35#include "Unix.h"
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/Config/config.h"
38#include "llvm/Demangle/Demangle.h"
39#include "llvm/Support/FileSystem.h"
40#include "llvm/Support/FileUtilities.h"
41#include "llvm/Support/Format.h"
42#include "llvm/Support/MemoryBuffer.h"
43#include "llvm/Support/Mutex.h"
44#include "llvm/Support/Program.h"
45#include "llvm/Support/SaveAndRestore.h"
46#include "llvm/Support/UniqueLock.h"
47#include "llvm/Support/raw_ostream.h"
48#include <algorithm>
49#include <string>
50#include <sysexits.h>
51#ifdef HAVE_BACKTRACE
52# include BACKTRACE_HEADER         // For backtrace().
53#endif
54#if HAVE_SIGNAL_H
55#include <signal.h>
56#endif
57#if HAVE_SYS_STAT_H
58#include <sys/stat.h>
59#endif
60#if HAVE_DLFCN_H
61#include <dlfcn.h>
62#endif
63#if HAVE_MACH_MACH_H
64#include <mach/mach.h>
65#endif
66#if HAVE_LINK_H
67#include <link.h>
68#endif
69#ifdef HAVE__UNWIND_BACKTRACE
70// FIXME: We should be able to use <unwind.h> for any target that has an
71// _Unwind_Backtrace function, but on FreeBSD the configure test passes
72// despite the function not existing, and on Android, <unwind.h> conflicts
73// with <link.h>.
74#ifdef __GLIBC__
75#include <unwind.h>
76#else
77#undef HAVE__UNWIND_BACKTRACE
78#endif
79#endif
80
81using namespace llvm;
82
83static RETSIGTYPE SignalHandler(int Sig);  // defined below.
84static RETSIGTYPE InfoSignalHandler(int Sig);  // defined below.
85
86using SignalHandlerFunctionType = void (*)();
87/// The function to call if ctrl-c is pressed.
88static std::atomic<SignalHandlerFunctionType> InterruptFunction =
89    ATOMIC_VAR_INIT(nullptr);
90static std::atomic<SignalHandlerFunctionType> InfoSignalFunction =
91    ATOMIC_VAR_INIT(nullptr);
92
93namespace {
94/// Signal-safe removal of files.
95/// Inserting and erasing from the list isn't signal-safe, but removal of files
96/// themselves is signal-safe. Memory is freed when the head is freed, deletion
97/// is therefore not signal-safe either.
98class FileToRemoveList {
99  std::atomic<char *> Filename = ATOMIC_VAR_INIT(nullptr);
100  std::atomic<FileToRemoveList *> Next = ATOMIC_VAR_INIT(nullptr);
101
102  FileToRemoveList() = default;
103  // Not signal-safe.
104  FileToRemoveList(const std::string &str) : Filename(strdup(str.c_str())) {}
105
106public:
107  // Not signal-safe.
108  ~FileToRemoveList() {
109    if (FileToRemoveList *N = Next.exchange(nullptr))
110      delete N;
111    if (char *F = Filename.exchange(nullptr))
112      free(F);
113  }
114
115  // Not signal-safe.
116  static void insert(std::atomic<FileToRemoveList *> &Head,
117                     const std::string &Filename) {
118    // Insert the new file at the end of the list.
119    FileToRemoveList *NewHead = new FileToRemoveList(Filename);
120    std::atomic<FileToRemoveList *> *InsertionPoint = &Head;
121    FileToRemoveList *OldHead = nullptr;
122    while (!InsertionPoint->compare_exchange_strong(OldHead, NewHead)) {
123      InsertionPoint = &OldHead->Next;
124      OldHead = nullptr;
125    }
126  }
127
128  // Not signal-safe.
129  static void erase(std::atomic<FileToRemoveList *> &Head,
130                    const std::string &Filename) {
131    // Use a lock to avoid concurrent erase: the comparison would access
132    // free'd memory.
133    static ManagedStatic<sys::SmartMutex<true>> Lock;
134    sys::SmartScopedLock<true> Writer(*Lock);
135
136    for (FileToRemoveList *Current = Head.load(); Current;
137         Current = Current->Next.load()) {
138      if (char *OldFilename = Current->Filename.load()) {
139        if (OldFilename != Filename)
140          continue;
141        // Leave an empty filename.
142        OldFilename = Current->Filename.exchange(nullptr);
143        // The filename might have become null between the time we
144        // compared it and we exchanged it.
145        if (OldFilename)
146          free(OldFilename);
147      }
148    }
149  }
150
151  // Signal-safe.
152  static void removeAllFiles(std::atomic<FileToRemoveList *> &Head) {
153    // If cleanup were to occur while we're removing files we'd have a bad time.
154    // Make sure we're OK by preventing cleanup from doing anything while we're
155    // removing files. If cleanup races with us and we win we'll have a leak,
156    // but we won't crash.
157    FileToRemoveList *OldHead = Head.exchange(nullptr);
158
159    for (FileToRemoveList *currentFile = OldHead; currentFile;
160         currentFile = currentFile->Next.load()) {
161      // If erasing was occuring while we're trying to remove files we'd look
162      // at free'd data. Take away the path and put it back when done.
163      if (char *path = currentFile->Filename.exchange(nullptr)) {
164        // Get the status so we can determine if it's a file or directory. If we
165        // can't stat the file, ignore it.
166        struct stat buf;
167        if (stat(path, &buf) != 0)
168          continue;
169
170        // If this is not a regular file, ignore it. We want to prevent removal
171        // of special files like /dev/null, even if the compiler is being run
172        // with the super-user permissions.
173        if (!S_ISREG(buf.st_mode))
174          continue;
175
176        // Otherwise, remove the file. We ignore any errors here as there is
177        // nothing else we can do.
178        unlink(path);
179
180        // We're done removing the file, erasing can safely proceed.
181        currentFile->Filename.exchange(path);
182      }
183    }
184
185    // We're done removing files, cleanup can safely proceed.
186    Head.exchange(OldHead);
187  }
188};
189static std::atomic<FileToRemoveList *> FilesToRemove = ATOMIC_VAR_INIT(nullptr);
190
191/// Clean up the list in a signal-friendly manner.
192/// Recall that signals can fire during llvm_shutdown. If this occurs we should
193/// either clean something up or nothing at all, but we shouldn't crash!
194struct FilesToRemoveCleanup {
195  // Not signal-safe.
196  ~FilesToRemoveCleanup() {
197    FileToRemoveList *Head = FilesToRemove.exchange(nullptr);
198    if (Head)
199      delete Head;
200  }
201};
202} // namespace
203
204static StringRef Argv0;
205
206/// Signals that represent requested termination. There's no bug or failure, or
207/// if there is, it's not our direct responsibility. For whatever reason, our
208/// continued execution is no longer desirable.
209static const int IntSigs[] = {
210  SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR2
211};
212
213/// Signals that represent that we have a bug, and our prompt termination has
214/// been ordered.
215static const int KillSigs[] = {
216  SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
217#ifdef SIGSYS
218  , SIGSYS
219#endif
220#ifdef SIGXCPU
221  , SIGXCPU
222#endif
223#ifdef SIGXFSZ
224  , SIGXFSZ
225#endif
226#ifdef SIGEMT
227  , SIGEMT
228#endif
229};
230
231/// Signals that represent requests for status.
232static const int InfoSigs[] = {
233  SIGUSR1
234#ifdef SIGINFO
235  , SIGINFO
236#endif
237};
238
239static const size_t NumSigs =
240    array_lengthof(IntSigs) + array_lengthof(KillSigs) +
241    array_lengthof(InfoSigs);
242
243
244static std::atomic<unsigned> NumRegisteredSignals = ATOMIC_VAR_INIT(0);
245static struct {
246  struct sigaction SA;
247  int SigNo;
248} RegisteredSignalInfo[NumSigs];
249
250#if defined(HAVE_SIGALTSTACK)
251// Hold onto both the old and new alternate signal stack so that it's not
252// reported as a leak. We don't make any attempt to remove our alt signal
253// stack if we remove our signal handlers; that can't be done reliably if
254// someone else is also trying to do the same thing.
255static stack_t OldAltStack;
256static void* NewAltStackPointer;
257
258static void CreateSigAltStack() {
259  const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024;
260
261  // If we're executing on the alternate stack, or we already have an alternate
262  // signal stack that we're happy with, there's nothing for us to do. Don't
263  // reduce the size, some other part of the process might need a larger stack
264  // than we do.
265  if (sigaltstack(nullptr, &OldAltStack) != 0 ||
266      OldAltStack.ss_flags & SS_ONSTACK ||
267      (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize))
268    return;
269
270  stack_t AltStack = {};
271  AltStack.ss_sp = static_cast<char *>(safe_malloc(AltStackSize));
272  NewAltStackPointer = AltStack.ss_sp; // Save to avoid reporting a leak.
273  AltStack.ss_size = AltStackSize;
274  if (sigaltstack(&AltStack, &OldAltStack) != 0)
275    free(AltStack.ss_sp);
276}
277#else
278static void CreateSigAltStack() {}
279#endif
280
281static void RegisterHandlers() { // Not signal-safe.
282  // The mutex prevents other threads from registering handlers while we're
283  // doing it. We also have to protect the handlers and their count because
284  // a signal handler could fire while we're registeting handlers.
285  static ManagedStatic<sys::SmartMutex<true>> SignalHandlerRegistrationMutex;
286  sys::SmartScopedLock<true> Guard(*SignalHandlerRegistrationMutex);
287
288  // If the handlers are already registered, we're done.
289  if (NumRegisteredSignals.load() != 0)
290    return;
291
292  // Create an alternate stack for signal handling. This is necessary for us to
293  // be able to reliably handle signals due to stack overflow.
294  CreateSigAltStack();
295
296  enum class SignalKind { IsKill, IsInfo };
297  auto registerHandler = [&](int Signal, SignalKind Kind) {
298    unsigned Index = NumRegisteredSignals.load();
299    assert(Index < array_lengthof(RegisteredSignalInfo) &&
300           "Out of space for signal handlers!");
301
302    struct sigaction NewHandler;
303
304    switch (Kind) {
305    case SignalKind::IsKill:
306      NewHandler.sa_handler = SignalHandler;
307      NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK;
308      break;
309    case SignalKind::IsInfo:
310      NewHandler.sa_handler = InfoSignalHandler;
311      NewHandler.sa_flags = SA_ONSTACK;
312      break;
313    }
314    sigemptyset(&NewHandler.sa_mask);
315
316    // Install the new handler, save the old one in RegisteredSignalInfo.
317    sigaction(Signal, &NewHandler, &RegisteredSignalInfo[Index].SA);
318    RegisteredSignalInfo[Index].SigNo = Signal;
319    ++NumRegisteredSignals;
320  };
321
322  for (auto S : IntSigs)
323    registerHandler(S, SignalKind::IsKill);
324  for (auto S : KillSigs)
325    registerHandler(S, SignalKind::IsKill);
326  for (auto S : InfoSigs)
327    registerHandler(S, SignalKind::IsInfo);
328}
329
330static void UnregisterHandlers() {
331  // Restore all of the signal handlers to how they were before we showed up.
332  for (unsigned i = 0, e = NumRegisteredSignals.load(); i != e; ++i) {
333    sigaction(RegisteredSignalInfo[i].SigNo,
334              &RegisteredSignalInfo[i].SA, nullptr);
335    --NumRegisteredSignals;
336  }
337}
338
339/// Process the FilesToRemove list.
340static void RemoveFilesToRemove() {
341  FileToRemoveList::removeAllFiles(FilesToRemove);
342}
343
344// The signal handler that runs.
345static RETSIGTYPE SignalHandler(int Sig) {
346  // Restore the signal behavior to default, so that the program actually
347  // crashes when we return and the signal reissues.  This also ensures that if
348  // we crash in our signal handler that the program will terminate immediately
349  // instead of recursing in the signal handler.
350  UnregisterHandlers();
351
352  // Unmask all potentially blocked kill signals.
353  sigset_t SigMask;
354  sigfillset(&SigMask);
355  sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
356
357  {
358    RemoveFilesToRemove();
359
360    if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
361        != std::end(IntSigs)) {
362      if (auto OldInterruptFunction = InterruptFunction.exchange(nullptr))
363        return OldInterruptFunction();
364
365      // Send a special return code that drivers can check for, from sysexits.h.
366      if (Sig == SIGPIPE)
367        exit(EX_IOERR);
368
369      raise(Sig);   // Execute the default handler.
370      return;
371   }
372  }
373
374  // Otherwise if it is a fault (like SEGV) run any handler.
375  llvm::sys::RunSignalHandlers();
376
377#ifdef __s390__
378  // On S/390, certain signals are delivered with PSW Address pointing to
379  // *after* the faulting instruction.  Simply returning from the signal
380  // handler would continue execution after that point, instead of
381  // re-raising the signal.  Raise the signal manually in those cases.
382  if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
383    raise(Sig);
384#endif
385}
386
387static RETSIGTYPE InfoSignalHandler(int Sig) {
388  SaveAndRestore<int> SaveErrnoDuringASignalHandler(errno);
389  if (SignalHandlerFunctionType CurrentInfoFunction = InfoSignalFunction)
390    CurrentInfoFunction();
391}
392
393void llvm::sys::RunInterruptHandlers() {
394  RemoveFilesToRemove();
395}
396
397void llvm::sys::SetInterruptFunction(void (*IF)()) {
398  InterruptFunction.exchange(IF);
399  RegisterHandlers();
400}
401
402void llvm::sys::SetInfoSignalFunction(void (*Handler)()) {
403  InfoSignalFunction.exchange(Handler);
404  RegisterHandlers();
405}
406
407// The public API
408bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
409                                   std::string* ErrMsg) {
410  // Ensure that cleanup will occur as soon as one file is added.
411  static ManagedStatic<FilesToRemoveCleanup> FilesToRemoveCleanup;
412  *FilesToRemoveCleanup;
413  FileToRemoveList::insert(FilesToRemove, Filename.str());
414  RegisterHandlers();
415  return false;
416}
417
418// The public API
419void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
420  FileToRemoveList::erase(FilesToRemove, Filename.str());
421}
422
423/// Add a function to be called when a signal is delivered to the process. The
424/// handler can have a cookie passed to it to identify what instance of the
425/// handler it is.
426void llvm::sys::AddSignalHandler(sys::SignalHandlerCallback FnPtr,
427                                 void *Cookie) { // Signal-safe.
428  insertSignalHandler(FnPtr, Cookie);
429  RegisterHandlers();
430}
431
432#if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && HAVE_LINK_H &&    \
433    (defined(__linux__) || defined(__FreeBSD__) ||                             \
434     defined(__FreeBSD_kernel__) || defined(__NetBSD__))
435struct DlIteratePhdrData {
436  void **StackTrace;
437  int depth;
438  bool first;
439  const char **modules;
440  intptr_t *offsets;
441  const char *main_exec_name;
442};
443
444static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
445  DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
446  const char *name = data->first ? data->main_exec_name : info->dlpi_name;
447  data->first = false;
448  for (int i = 0; i < info->dlpi_phnum; i++) {
449    const auto *phdr = &info->dlpi_phdr[i];
450    if (phdr->p_type != PT_LOAD)
451      continue;
452    intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
453    intptr_t end = beg + phdr->p_memsz;
454    for (int j = 0; j < data->depth; j++) {
455      if (data->modules[j])
456        continue;
457      intptr_t addr = (intptr_t)data->StackTrace[j];
458      if (beg <= addr && addr < end) {
459        data->modules[j] = name;
460        data->offsets[j] = addr - info->dlpi_addr;
461      }
462    }
463  }
464  return 0;
465}
466
467/// If this is an ELF platform, we can find all loaded modules and their virtual
468/// addresses with dl_iterate_phdr.
469static bool findModulesAndOffsets(void **StackTrace, int Depth,
470                                  const char **Modules, intptr_t *Offsets,
471                                  const char *MainExecutableName,
472                                  StringSaver &StrPool) {
473  DlIteratePhdrData data = {StackTrace, Depth,   true,
474                            Modules,    Offsets, MainExecutableName};
475  dl_iterate_phdr(dl_iterate_phdr_cb, &data);
476  return true;
477}
478#else
479/// This platform does not have dl_iterate_phdr, so we do not yet know how to
480/// find all loaded DSOs.
481static bool findModulesAndOffsets(void **StackTrace, int Depth,
482                                  const char **Modules, intptr_t *Offsets,
483                                  const char *MainExecutableName,
484                                  StringSaver &StrPool) {
485  return false;
486}
487#endif // defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && ...
488
489#if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE)
490static int unwindBacktrace(void **StackTrace, int MaxEntries) {
491  if (MaxEntries < 0)
492    return 0;
493
494  // Skip the first frame ('unwindBacktrace' itself).
495  int Entries = -1;
496
497  auto HandleFrame = [&](_Unwind_Context *Context) -> _Unwind_Reason_Code {
498    // Apparently we need to detect reaching the end of the stack ourselves.
499    void *IP = (void *)_Unwind_GetIP(Context);
500    if (!IP)
501      return _URC_END_OF_STACK;
502
503    assert(Entries < MaxEntries && "recursively called after END_OF_STACK?");
504    if (Entries >= 0)
505      StackTrace[Entries] = IP;
506
507    if (++Entries == MaxEntries)
508      return _URC_END_OF_STACK;
509    return _URC_NO_REASON;
510  };
511
512  _Unwind_Backtrace(
513      [](_Unwind_Context *Context, void *Handler) {
514        return (*static_cast<decltype(HandleFrame) *>(Handler))(Context);
515      },
516      static_cast<void *>(&HandleFrame));
517  return std::max(Entries, 0);
518}
519#endif
520
521// In the case of a program crash or fault, print out a stack trace so that the
522// user has an indication of why and where we died.
523//
524// On glibc systems we have the 'backtrace' function, which works nicely, but
525// doesn't demangle symbols.
526void llvm::sys::PrintStackTrace(raw_ostream &OS) {
527#if ENABLE_BACKTRACES
528  static void *StackTrace[256];
529  int depth = 0;
530#if defined(HAVE_BACKTRACE)
531  // Use backtrace() to output a backtrace on Linux systems with glibc.
532  if (!depth)
533    depth = backtrace(StackTrace, static_cast<int>(array_lengthof(StackTrace)));
534#endif
535#if defined(HAVE__UNWIND_BACKTRACE)
536  // Try _Unwind_Backtrace() if backtrace() failed.
537  if (!depth)
538    depth = unwindBacktrace(StackTrace,
539                        static_cast<int>(array_lengthof(StackTrace)));
540#endif
541  if (!depth)
542    return;
543
544  if (printSymbolizedStackTrace(Argv0, StackTrace, depth, OS))
545    return;
546#if HAVE_DLFCN_H && HAVE_DLADDR
547  int width = 0;
548  for (int i = 0; i < depth; ++i) {
549    Dl_info dlinfo;
550    dladdr(StackTrace[i], &dlinfo);
551    const char* name = strrchr(dlinfo.dli_fname, '/');
552
553    int nwidth;
554    if (!name) nwidth = strlen(dlinfo.dli_fname);
555    else       nwidth = strlen(name) - 1;
556
557    if (nwidth > width) width = nwidth;
558  }
559
560  for (int i = 0; i < depth; ++i) {
561    Dl_info dlinfo;
562    dladdr(StackTrace[i], &dlinfo);
563
564    OS << format("%-2d", i);
565
566    const char* name = strrchr(dlinfo.dli_fname, '/');
567    if (!name) OS << format(" %-*s", width, dlinfo.dli_fname);
568    else       OS << format(" %-*s", width, name+1);
569
570    OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2,
571                 (unsigned long)StackTrace[i]);
572
573    if (dlinfo.dli_sname != nullptr) {
574      OS << ' ';
575      int res;
576      char* d = itaniumDemangle(dlinfo.dli_sname, nullptr, nullptr, &res);
577      if (!d) OS << dlinfo.dli_sname;
578      else    OS << d;
579      free(d);
580
581      OS << format(" + %tu", (static_cast<const char*>(StackTrace[i])-
582                              static_cast<const char*>(dlinfo.dli_saddr)));
583    }
584    OS << '\n';
585  }
586#elif defined(HAVE_BACKTRACE)
587  backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
588#endif
589#endif
590}
591
592static void PrintStackTraceSignalHandler(void *) {
593  sys::PrintStackTrace(llvm::errs());
594}
595
596void llvm::sys::DisableSystemDialogsOnCrash() {}
597
598/// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
599/// process, print a stack trace and then exit.
600void llvm::sys::PrintStackTraceOnErrorSignal(StringRef Argv0,
601                                             bool DisableCrashReporting) {
602  ::Argv0 = Argv0;
603
604  AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
605
606#if defined(__APPLE__) && ENABLE_CRASH_OVERRIDES
607  // Environment variable to disable any kind of crash dialog.
608  if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) {
609    mach_port_t self = mach_task_self();
610
611    exception_mask_t mask = EXC_MASK_CRASH;
612
613    kern_return_t ret = task_set_exception_ports(self,
614                             mask,
615                             MACH_PORT_NULL,
616                             EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
617                             THREAD_STATE_NONE);
618    (void)ret;
619  }
620#endif
621}
622