1 //===- Signals.cpp - Generic Unix Signals Implementation -----*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines some helpful functions for dealing with the possibility of
10 // Unix signals occurring while your program is running.
12 //===----------------------------------------------------------------------===//
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:
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.
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!
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
33 //===----------------------------------------------------------------------===//
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/raw_ostream.h"
51 # include BACKTRACE_HEADER // For backtrace().
63 #include <mach/mach.h>
68 #ifdef HAVE__UNWIND_BACKTRACE
69 // FIXME: We should be able to use <unwind.h> for any target that has an
70 // _Unwind_Backtrace function, but on FreeBSD the configure test passes
71 // despite the function not existing, and on Android, <unwind.h> conflicts
76 #undef HAVE__UNWIND_BACKTRACE
82 static RETSIGTYPE SignalHandler(int Sig); // defined below.
83 static RETSIGTYPE InfoSignalHandler(int Sig); // defined below.
85 static void DefaultPipeSignalFunction() {
89 using SignalHandlerFunctionType = void (*)();
90 /// The function to call if ctrl-c is pressed.
91 static std::atomic<SignalHandlerFunctionType> InterruptFunction =
92 ATOMIC_VAR_INIT(nullptr);
93 static std::atomic<SignalHandlerFunctionType> InfoSignalFunction =
94 ATOMIC_VAR_INIT(nullptr);
95 static std::atomic<SignalHandlerFunctionType> PipeSignalFunction =
96 ATOMIC_VAR_INIT(DefaultPipeSignalFunction);
99 /// Signal-safe removal of files.
100 /// Inserting and erasing from the list isn't signal-safe, but removal of files
101 /// themselves is signal-safe. Memory is freed when the head is freed, deletion
102 /// is therefore not signal-safe either.
103 class FileToRemoveList {
104 std::atomic<char *> Filename = ATOMIC_VAR_INIT(nullptr);
105 std::atomic<FileToRemoveList *> Next = ATOMIC_VAR_INIT(nullptr);
107 FileToRemoveList() = default;
109 FileToRemoveList(const std::string &str) : Filename(strdup(str.c_str())) {}
113 ~FileToRemoveList() {
114 if (FileToRemoveList *N = Next.exchange(nullptr))
116 if (char *F = Filename.exchange(nullptr))
121 static void insert(std::atomic<FileToRemoveList *> &Head,
122 const std::string &Filename) {
123 // Insert the new file at the end of the list.
124 FileToRemoveList *NewHead = new FileToRemoveList(Filename);
125 std::atomic<FileToRemoveList *> *InsertionPoint = &Head;
126 FileToRemoveList *OldHead = nullptr;
127 while (!InsertionPoint->compare_exchange_strong(OldHead, NewHead)) {
128 InsertionPoint = &OldHead->Next;
134 static void erase(std::atomic<FileToRemoveList *> &Head,
135 const std::string &Filename) {
136 // Use a lock to avoid concurrent erase: the comparison would access
138 static ManagedStatic<sys::SmartMutex<true>> Lock;
139 sys::SmartScopedLock<true> Writer(*Lock);
141 for (FileToRemoveList *Current = Head.load(); Current;
142 Current = Current->Next.load()) {
143 if (char *OldFilename = Current->Filename.load()) {
144 if (OldFilename != Filename)
146 // Leave an empty filename.
147 OldFilename = Current->Filename.exchange(nullptr);
148 // The filename might have become null between the time we
149 // compared it and we exchanged it.
157 static void removeAllFiles(std::atomic<FileToRemoveList *> &Head) {
158 // If cleanup were to occur while we're removing files we'd have a bad time.
159 // Make sure we're OK by preventing cleanup from doing anything while we're
160 // removing files. If cleanup races with us and we win we'll have a leak,
161 // but we won't crash.
162 FileToRemoveList *OldHead = Head.exchange(nullptr);
164 for (FileToRemoveList *currentFile = OldHead; currentFile;
165 currentFile = currentFile->Next.load()) {
166 // If erasing was occuring while we're trying to remove files we'd look
167 // at free'd data. Take away the path and put it back when done.
168 if (char *path = currentFile->Filename.exchange(nullptr)) {
169 // Get the status so we can determine if it's a file or directory. If we
170 // can't stat the file, ignore it.
172 if (stat(path, &buf) != 0)
175 // If this is not a regular file, ignore it. We want to prevent removal
176 // of special files like /dev/null, even if the compiler is being run
177 // with the super-user permissions.
178 if (!S_ISREG(buf.st_mode))
181 // Otherwise, remove the file. We ignore any errors here as there is
182 // nothing else we can do.
185 // We're done removing the file, erasing can safely proceed.
186 currentFile->Filename.exchange(path);
190 // We're done removing files, cleanup can safely proceed.
191 Head.exchange(OldHead);
194 static std::atomic<FileToRemoveList *> FilesToRemove = ATOMIC_VAR_INIT(nullptr);
196 /// Clean up the list in a signal-friendly manner.
197 /// Recall that signals can fire during llvm_shutdown. If this occurs we should
198 /// either clean something up or nothing at all, but we shouldn't crash!
199 struct FilesToRemoveCleanup {
201 ~FilesToRemoveCleanup() {
202 FileToRemoveList *Head = FilesToRemove.exchange(nullptr);
209 static StringRef Argv0;
211 /// Signals that represent requested termination. There's no bug or failure, or
212 /// if there is, it's not our direct responsibility. For whatever reason, our
213 /// continued execution is no longer desirable.
214 static const int IntSigs[] = {
215 SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR2
218 /// Signals that represent that we have a bug, and our prompt termination has
220 static const int KillSigs[] = {
221 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
236 /// Signals that represent requests for status.
237 static const int InfoSigs[] = {
244 static const size_t NumSigs =
245 array_lengthof(IntSigs) + array_lengthof(KillSigs) +
246 array_lengthof(InfoSigs);
249 static std::atomic<unsigned> NumRegisteredSignals = ATOMIC_VAR_INIT(0);
253 } RegisteredSignalInfo[NumSigs];
255 #if defined(HAVE_SIGALTSTACK)
256 // Hold onto both the old and new alternate signal stack so that it's not
257 // reported as a leak. We don't make any attempt to remove our alt signal
258 // stack if we remove our signal handlers; that can't be done reliably if
259 // someone else is also trying to do the same thing.
260 static stack_t OldAltStack;
261 static void* NewAltStackPointer;
263 static void CreateSigAltStack() {
264 const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024;
266 // If we're executing on the alternate stack, or we already have an alternate
267 // signal stack that we're happy with, there's nothing for us to do. Don't
268 // reduce the size, some other part of the process might need a larger stack
270 if (sigaltstack(nullptr, &OldAltStack) != 0 ||
271 OldAltStack.ss_flags & SS_ONSTACK ||
272 (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize))
275 stack_t AltStack = {};
276 AltStack.ss_sp = static_cast<char *>(safe_malloc(AltStackSize));
277 NewAltStackPointer = AltStack.ss_sp; // Save to avoid reporting a leak.
278 AltStack.ss_size = AltStackSize;
279 if (sigaltstack(&AltStack, &OldAltStack) != 0)
280 free(AltStack.ss_sp);
283 static void CreateSigAltStack() {}
286 static void RegisterHandlers() { // Not signal-safe.
287 // The mutex prevents other threads from registering handlers while we're
288 // doing it. We also have to protect the handlers and their count because
289 // a signal handler could fire while we're registeting handlers.
290 static ManagedStatic<sys::SmartMutex<true>> SignalHandlerRegistrationMutex;
291 sys::SmartScopedLock<true> Guard(*SignalHandlerRegistrationMutex);
293 // If the handlers are already registered, we're done.
294 if (NumRegisteredSignals.load() != 0)
297 // Create an alternate stack for signal handling. This is necessary for us to
298 // be able to reliably handle signals due to stack overflow.
301 enum class SignalKind { IsKill, IsInfo };
302 auto registerHandler = [&](int Signal, SignalKind Kind) {
303 unsigned Index = NumRegisteredSignals.load();
304 assert(Index < array_lengthof(RegisteredSignalInfo) &&
305 "Out of space for signal handlers!");
307 struct sigaction NewHandler;
310 case SignalKind::IsKill:
311 NewHandler.sa_handler = SignalHandler;
312 NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK;
314 case SignalKind::IsInfo:
315 NewHandler.sa_handler = InfoSignalHandler;
316 NewHandler.sa_flags = SA_ONSTACK;
319 sigemptyset(&NewHandler.sa_mask);
321 // Install the new handler, save the old one in RegisteredSignalInfo.
322 sigaction(Signal, &NewHandler, &RegisteredSignalInfo[Index].SA);
323 RegisteredSignalInfo[Index].SigNo = Signal;
324 ++NumRegisteredSignals;
327 for (auto S : IntSigs)
328 registerHandler(S, SignalKind::IsKill);
329 for (auto S : KillSigs)
330 registerHandler(S, SignalKind::IsKill);
331 for (auto S : InfoSigs)
332 registerHandler(S, SignalKind::IsInfo);
335 static void UnregisterHandlers() {
336 // Restore all of the signal handlers to how they were before we showed up.
337 for (unsigned i = 0, e = NumRegisteredSignals.load(); i != e; ++i) {
338 sigaction(RegisteredSignalInfo[i].SigNo,
339 &RegisteredSignalInfo[i].SA, nullptr);
340 --NumRegisteredSignals;
344 /// Process the FilesToRemove list.
345 static void RemoveFilesToRemove() {
346 FileToRemoveList::removeAllFiles(FilesToRemove);
349 // The signal handler that runs.
350 static RETSIGTYPE SignalHandler(int Sig) {
351 // Restore the signal behavior to default, so that the program actually
352 // crashes when we return and the signal reissues. This also ensures that if
353 // we crash in our signal handler that the program will terminate immediately
354 // instead of recursing in the signal handler.
355 UnregisterHandlers();
357 // Unmask all potentially blocked kill signals.
359 sigfillset(&SigMask);
360 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
363 RemoveFilesToRemove();
365 if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
366 != std::end(IntSigs)) {
367 if (auto OldInterruptFunction = InterruptFunction.exchange(nullptr))
368 return OldInterruptFunction();
370 // Send a special return code that drivers can check for, from sysexits.h.
372 if (SignalHandlerFunctionType CurrentPipeFunction = PipeSignalFunction)
373 CurrentPipeFunction();
375 raise(Sig); // Execute the default handler.
380 // Otherwise if it is a fault (like SEGV) run any handler.
381 llvm::sys::RunSignalHandlers();
384 // On S/390, certain signals are delivered with PSW Address pointing to
385 // *after* the faulting instruction. Simply returning from the signal
386 // handler would continue execution after that point, instead of
387 // re-raising the signal. Raise the signal manually in those cases.
388 if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
393 static RETSIGTYPE InfoSignalHandler(int Sig) {
394 SaveAndRestore<int> SaveErrnoDuringASignalHandler(errno);
395 if (SignalHandlerFunctionType CurrentInfoFunction = InfoSignalFunction)
396 CurrentInfoFunction();
399 void llvm::sys::RunInterruptHandlers() {
400 RemoveFilesToRemove();
403 void llvm::sys::SetInterruptFunction(void (*IF)()) {
404 InterruptFunction.exchange(IF);
408 void llvm::sys::SetInfoSignalFunction(void (*Handler)()) {
409 InfoSignalFunction.exchange(Handler);
413 void llvm::sys::SetPipeSignalFunction(void (*Handler)()) {
414 PipeSignalFunction.exchange(Handler);
419 bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
420 std::string* ErrMsg) {
421 // Ensure that cleanup will occur as soon as one file is added.
422 static ManagedStatic<FilesToRemoveCleanup> FilesToRemoveCleanup;
423 *FilesToRemoveCleanup;
424 FileToRemoveList::insert(FilesToRemove, Filename.str());
430 void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
431 FileToRemoveList::erase(FilesToRemove, Filename.str());
434 /// Add a function to be called when a signal is delivered to the process. The
435 /// handler can have a cookie passed to it to identify what instance of the
437 void llvm::sys::AddSignalHandler(sys::SignalHandlerCallback FnPtr,
438 void *Cookie) { // Signal-safe.
439 insertSignalHandler(FnPtr, Cookie);
443 #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && HAVE_LINK_H && \
444 (defined(__linux__) || defined(__FreeBSD__) || \
445 defined(__FreeBSD_kernel__) || defined(__NetBSD__))
446 struct DlIteratePhdrData {
450 const char **modules;
452 const char *main_exec_name;
455 static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
456 DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
457 const char *name = data->first ? data->main_exec_name : info->dlpi_name;
459 for (int i = 0; i < info->dlpi_phnum; i++) {
460 const auto *phdr = &info->dlpi_phdr[i];
461 if (phdr->p_type != PT_LOAD)
463 intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
464 intptr_t end = beg + phdr->p_memsz;
465 for (int j = 0; j < data->depth; j++) {
466 if (data->modules[j])
468 intptr_t addr = (intptr_t)data->StackTrace[j];
469 if (beg <= addr && addr < end) {
470 data->modules[j] = name;
471 data->offsets[j] = addr - info->dlpi_addr;
478 /// If this is an ELF platform, we can find all loaded modules and their virtual
479 /// addresses with dl_iterate_phdr.
480 static bool findModulesAndOffsets(void **StackTrace, int Depth,
481 const char **Modules, intptr_t *Offsets,
482 const char *MainExecutableName,
483 StringSaver &StrPool) {
484 DlIteratePhdrData data = {StackTrace, Depth, true,
485 Modules, Offsets, MainExecutableName};
486 dl_iterate_phdr(dl_iterate_phdr_cb, &data);
490 /// This platform does not have dl_iterate_phdr, so we do not yet know how to
491 /// find all loaded DSOs.
492 static bool findModulesAndOffsets(void **StackTrace, int Depth,
493 const char **Modules, intptr_t *Offsets,
494 const char *MainExecutableName,
495 StringSaver &StrPool) {
498 #endif // defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && ...
500 #if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE)
501 static int unwindBacktrace(void **StackTrace, int MaxEntries) {
505 // Skip the first frame ('unwindBacktrace' itself).
508 auto HandleFrame = [&](_Unwind_Context *Context) -> _Unwind_Reason_Code {
509 // Apparently we need to detect reaching the end of the stack ourselves.
510 void *IP = (void *)_Unwind_GetIP(Context);
512 return _URC_END_OF_STACK;
514 assert(Entries < MaxEntries && "recursively called after END_OF_STACK?");
516 StackTrace[Entries] = IP;
518 if (++Entries == MaxEntries)
519 return _URC_END_OF_STACK;
520 return _URC_NO_REASON;
524 [](_Unwind_Context *Context, void *Handler) {
525 return (*static_cast<decltype(HandleFrame) *>(Handler))(Context);
527 static_cast<void *>(&HandleFrame));
528 return std::max(Entries, 0);
532 // In the case of a program crash or fault, print out a stack trace so that the
533 // user has an indication of why and where we died.
535 // On glibc systems we have the 'backtrace' function, which works nicely, but
536 // doesn't demangle symbols.
537 void llvm::sys::PrintStackTrace(raw_ostream &OS) {
538 #if ENABLE_BACKTRACES
539 static void *StackTrace[256];
541 #if defined(HAVE_BACKTRACE)
542 // Use backtrace() to output a backtrace on Linux systems with glibc.
544 depth = backtrace(StackTrace, static_cast<int>(array_lengthof(StackTrace)));
546 #if defined(HAVE__UNWIND_BACKTRACE)
547 // Try _Unwind_Backtrace() if backtrace() failed.
549 depth = unwindBacktrace(StackTrace,
550 static_cast<int>(array_lengthof(StackTrace)));
555 if (printSymbolizedStackTrace(Argv0, StackTrace, depth, OS))
557 #if HAVE_DLFCN_H && HAVE_DLADDR
559 for (int i = 0; i < depth; ++i) {
561 dladdr(StackTrace[i], &dlinfo);
562 const char* name = strrchr(dlinfo.dli_fname, '/');
565 if (!name) nwidth = strlen(dlinfo.dli_fname);
566 else nwidth = strlen(name) - 1;
568 if (nwidth > width) width = nwidth;
571 for (int i = 0; i < depth; ++i) {
573 dladdr(StackTrace[i], &dlinfo);
575 OS << format("%-2d", i);
577 const char* name = strrchr(dlinfo.dli_fname, '/');
578 if (!name) OS << format(" %-*s", width, dlinfo.dli_fname);
579 else OS << format(" %-*s", width, name+1);
581 OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2,
582 (unsigned long)StackTrace[i]);
584 if (dlinfo.dli_sname != nullptr) {
587 char* d = itaniumDemangle(dlinfo.dli_sname, nullptr, nullptr, &res);
588 if (!d) OS << dlinfo.dli_sname;
592 OS << format(" + %tu", (static_cast<const char*>(StackTrace[i])-
593 static_cast<const char*>(dlinfo.dli_saddr)));
597 #elif defined(HAVE_BACKTRACE)
598 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
603 static void PrintStackTraceSignalHandler(void *) {
604 sys::PrintStackTrace(llvm::errs());
607 void llvm::sys::DisableSystemDialogsOnCrash() {}
609 /// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
610 /// process, print a stack trace and then exit.
611 void llvm::sys::PrintStackTraceOnErrorSignal(StringRef Argv0,
612 bool DisableCrashReporting) {
615 AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
617 #if defined(__APPLE__) && ENABLE_CRASH_OVERRIDES
618 // Environment variable to disable any kind of crash dialog.
619 if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) {
620 mach_port_t self = mach_task_self();
622 exception_mask_t mask = EXC_MASK_CRASH;
624 kern_return_t ret = task_set_exception_ports(self,
627 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,