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/UniqueLock.h"
47 #include "llvm/Support/raw_ostream.h"
52 # include BACKTRACE_HEADER // For backtrace().
64 #include <mach/mach.h>
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
77 #undef HAVE__UNWIND_BACKTRACE
83 static RETSIGTYPE SignalHandler(int Sig); // defined below.
84 static RETSIGTYPE InfoSignalHandler(int Sig); // defined below.
86 using SignalHandlerFunctionType = void (*)();
87 /// The function to call if ctrl-c is pressed.
88 static std::atomic<SignalHandlerFunctionType> InterruptFunction =
89 ATOMIC_VAR_INIT(nullptr);
90 static std::atomic<SignalHandlerFunctionType> InfoSignalFunction =
91 ATOMIC_VAR_INIT(nullptr);
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.
98 class FileToRemoveList {
99 std::atomic<char *> Filename = ATOMIC_VAR_INIT(nullptr);
100 std::atomic<FileToRemoveList *> Next = ATOMIC_VAR_INIT(nullptr);
102 FileToRemoveList() = default;
104 FileToRemoveList(const std::string &str) : Filename(strdup(str.c_str())) {}
108 ~FileToRemoveList() {
109 if (FileToRemoveList *N = Next.exchange(nullptr))
111 if (char *F = Filename.exchange(nullptr))
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;
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
133 static ManagedStatic<sys::SmartMutex<true>> Lock;
134 sys::SmartScopedLock<true> Writer(*Lock);
136 for (FileToRemoveList *Current = Head.load(); Current;
137 Current = Current->Next.load()) {
138 if (char *OldFilename = Current->Filename.load()) {
139 if (OldFilename != Filename)
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.
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);
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.
167 if (stat(path, &buf) != 0)
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))
176 // Otherwise, remove the file. We ignore any errors here as there is
177 // nothing else we can do.
180 // We're done removing the file, erasing can safely proceed.
181 currentFile->Filename.exchange(path);
185 // We're done removing files, cleanup can safely proceed.
186 Head.exchange(OldHead);
189 static std::atomic<FileToRemoveList *> FilesToRemove = ATOMIC_VAR_INIT(nullptr);
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!
194 struct FilesToRemoveCleanup {
196 ~FilesToRemoveCleanup() {
197 FileToRemoveList *Head = FilesToRemove.exchange(nullptr);
204 static StringRef Argv0;
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.
209 static const int IntSigs[] = {
210 SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR2
213 /// Signals that represent that we have a bug, and our prompt termination has
215 static const int KillSigs[] = {
216 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
231 /// Signals that represent requests for status.
232 static const int InfoSigs[] = {
239 static const size_t NumSigs =
240 array_lengthof(IntSigs) + array_lengthof(KillSigs) +
241 array_lengthof(InfoSigs);
244 static std::atomic<unsigned> NumRegisteredSignals = ATOMIC_VAR_INIT(0);
248 } RegisteredSignalInfo[NumSigs];
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.
255 static stack_t OldAltStack;
256 static void* NewAltStackPointer;
258 static void CreateSigAltStack() {
259 const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024;
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
265 if (sigaltstack(nullptr, &OldAltStack) != 0 ||
266 OldAltStack.ss_flags & SS_ONSTACK ||
267 (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize))
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);
278 static void CreateSigAltStack() {}
281 static 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);
288 // If the handlers are already registered, we're done.
289 if (NumRegisteredSignals.load() != 0)
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.
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!");
302 struct sigaction NewHandler;
305 case SignalKind::IsKill:
306 NewHandler.sa_handler = SignalHandler;
307 NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK;
309 case SignalKind::IsInfo:
310 NewHandler.sa_handler = InfoSignalHandler;
311 NewHandler.sa_flags = SA_ONSTACK;
314 sigemptyset(&NewHandler.sa_mask);
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;
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);
330 static 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;
339 /// Process the FilesToRemove list.
340 static void RemoveFilesToRemove() {
341 FileToRemoveList::removeAllFiles(FilesToRemove);
344 // The signal handler that runs.
345 static 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();
352 // Unmask all potentially blocked kill signals.
354 sigfillset(&SigMask);
355 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
358 RemoveFilesToRemove();
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();
365 // Send a special return code that drivers can check for, from sysexits.h.
369 raise(Sig); // Execute the default handler.
374 // Otherwise if it is a fault (like SEGV) run any handler.
375 llvm::sys::RunSignalHandlers();
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)
387 static RETSIGTYPE InfoSignalHandler(int Sig) {
388 SaveAndRestore<int> SaveErrnoDuringASignalHandler(errno);
389 if (SignalHandlerFunctionType CurrentInfoFunction = InfoSignalFunction)
390 CurrentInfoFunction();
393 void llvm::sys::RunInterruptHandlers() {
394 RemoveFilesToRemove();
397 void llvm::sys::SetInterruptFunction(void (*IF)()) {
398 InterruptFunction.exchange(IF);
402 void llvm::sys::SetInfoSignalFunction(void (*Handler)()) {
403 InfoSignalFunction.exchange(Handler);
408 bool 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());
419 void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
420 FileToRemoveList::erase(FilesToRemove, Filename.str());
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
426 void llvm::sys::AddSignalHandler(sys::SignalHandlerCallback FnPtr,
427 void *Cookie) { // Signal-safe.
428 insertSignalHandler(FnPtr, Cookie);
432 #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && HAVE_LINK_H && \
433 (defined(__linux__) || defined(__FreeBSD__) || \
434 defined(__FreeBSD_kernel__) || defined(__NetBSD__))
435 struct DlIteratePhdrData {
439 const char **modules;
441 const char *main_exec_name;
444 static 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;
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)
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])
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;
467 /// If this is an ELF platform, we can find all loaded modules and their virtual
468 /// addresses with dl_iterate_phdr.
469 static 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);
479 /// This platform does not have dl_iterate_phdr, so we do not yet know how to
480 /// find all loaded DSOs.
481 static bool findModulesAndOffsets(void **StackTrace, int Depth,
482 const char **Modules, intptr_t *Offsets,
483 const char *MainExecutableName,
484 StringSaver &StrPool) {
487 #endif // defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && ...
489 #if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE)
490 static int unwindBacktrace(void **StackTrace, int MaxEntries) {
494 // Skip the first frame ('unwindBacktrace' itself).
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);
501 return _URC_END_OF_STACK;
503 assert(Entries < MaxEntries && "recursively called after END_OF_STACK?");
505 StackTrace[Entries] = IP;
507 if (++Entries == MaxEntries)
508 return _URC_END_OF_STACK;
509 return _URC_NO_REASON;
513 [](_Unwind_Context *Context, void *Handler) {
514 return (*static_cast<decltype(HandleFrame) *>(Handler))(Context);
516 static_cast<void *>(&HandleFrame));
517 return std::max(Entries, 0);
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.
524 // On glibc systems we have the 'backtrace' function, which works nicely, but
525 // doesn't demangle symbols.
526 void llvm::sys::PrintStackTrace(raw_ostream &OS) {
527 #if ENABLE_BACKTRACES
528 static void *StackTrace[256];
530 #if defined(HAVE_BACKTRACE)
531 // Use backtrace() to output a backtrace on Linux systems with glibc.
533 depth = backtrace(StackTrace, static_cast<int>(array_lengthof(StackTrace)));
535 #if defined(HAVE__UNWIND_BACKTRACE)
536 // Try _Unwind_Backtrace() if backtrace() failed.
538 depth = unwindBacktrace(StackTrace,
539 static_cast<int>(array_lengthof(StackTrace)));
544 if (printSymbolizedStackTrace(Argv0, StackTrace, depth, OS))
546 #if HAVE_DLFCN_H && HAVE_DLADDR
548 for (int i = 0; i < depth; ++i) {
550 dladdr(StackTrace[i], &dlinfo);
551 const char* name = strrchr(dlinfo.dli_fname, '/');
554 if (!name) nwidth = strlen(dlinfo.dli_fname);
555 else nwidth = strlen(name) - 1;
557 if (nwidth > width) width = nwidth;
560 for (int i = 0; i < depth; ++i) {
562 dladdr(StackTrace[i], &dlinfo);
564 OS << format("%-2d", i);
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);
570 OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2,
571 (unsigned long)StackTrace[i]);
573 if (dlinfo.dli_sname != nullptr) {
576 char* d = itaniumDemangle(dlinfo.dli_sname, nullptr, nullptr, &res);
577 if (!d) OS << dlinfo.dli_sname;
581 OS << format(" + %tu", (static_cast<const char*>(StackTrace[i])-
582 static_cast<const char*>(dlinfo.dli_saddr)));
586 #elif defined(HAVE_BACKTRACE)
587 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
592 static void PrintStackTraceSignalHandler(void *) {
593 sys::PrintStackTrace(llvm::errs());
596 void llvm::sys::DisableSystemDialogsOnCrash() {}
598 /// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
599 /// process, print a stack trace and then exit.
600 void llvm::sys::PrintStackTraceOnErrorSignal(StringRef Argv0,
601 bool DisableCrashReporting) {
604 AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
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();
611 exception_mask_t mask = EXC_MASK_CRASH;
613 kern_return_t ret = task_set_exception_ports(self,
616 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,