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 using SignalHandlerFunctionType = void (*)();
86 /// The function to call if ctrl-c is pressed.
87 static std::atomic<SignalHandlerFunctionType> InterruptFunction =
88 ATOMIC_VAR_INIT(nullptr);
89 static std::atomic<SignalHandlerFunctionType> InfoSignalFunction =
90 ATOMIC_VAR_INIT(nullptr);
93 /// Signal-safe removal of files.
94 /// Inserting and erasing from the list isn't signal-safe, but removal of files
95 /// themselves is signal-safe. Memory is freed when the head is freed, deletion
96 /// is therefore not signal-safe either.
97 class FileToRemoveList {
98 std::atomic<char *> Filename = ATOMIC_VAR_INIT(nullptr);
99 std::atomic<FileToRemoveList *> Next = ATOMIC_VAR_INIT(nullptr);
101 FileToRemoveList() = default;
103 FileToRemoveList(const std::string &str) : Filename(strdup(str.c_str())) {}
107 ~FileToRemoveList() {
108 if (FileToRemoveList *N = Next.exchange(nullptr))
110 if (char *F = Filename.exchange(nullptr))
115 static void insert(std::atomic<FileToRemoveList *> &Head,
116 const std::string &Filename) {
117 // Insert the new file at the end of the list.
118 FileToRemoveList *NewHead = new FileToRemoveList(Filename);
119 std::atomic<FileToRemoveList *> *InsertionPoint = &Head;
120 FileToRemoveList *OldHead = nullptr;
121 while (!InsertionPoint->compare_exchange_strong(OldHead, NewHead)) {
122 InsertionPoint = &OldHead->Next;
128 static void erase(std::atomic<FileToRemoveList *> &Head,
129 const std::string &Filename) {
130 // Use a lock to avoid concurrent erase: the comparison would access
132 static ManagedStatic<sys::SmartMutex<true>> Lock;
133 sys::SmartScopedLock<true> Writer(*Lock);
135 for (FileToRemoveList *Current = Head.load(); Current;
136 Current = Current->Next.load()) {
137 if (char *OldFilename = Current->Filename.load()) {
138 if (OldFilename != Filename)
140 // Leave an empty filename.
141 OldFilename = Current->Filename.exchange(nullptr);
142 // The filename might have become null between the time we
143 // compared it and we exchanged it.
151 static void removeAllFiles(std::atomic<FileToRemoveList *> &Head) {
152 // If cleanup were to occur while we're removing files we'd have a bad time.
153 // Make sure we're OK by preventing cleanup from doing anything while we're
154 // removing files. If cleanup races with us and we win we'll have a leak,
155 // but we won't crash.
156 FileToRemoveList *OldHead = Head.exchange(nullptr);
158 for (FileToRemoveList *currentFile = OldHead; currentFile;
159 currentFile = currentFile->Next.load()) {
160 // If erasing was occuring while we're trying to remove files we'd look
161 // at free'd data. Take away the path and put it back when done.
162 if (char *path = currentFile->Filename.exchange(nullptr)) {
163 // Get the status so we can determine if it's a file or directory. If we
164 // can't stat the file, ignore it.
166 if (stat(path, &buf) != 0)
169 // If this is not a regular file, ignore it. We want to prevent removal
170 // of special files like /dev/null, even if the compiler is being run
171 // with the super-user permissions.
172 if (!S_ISREG(buf.st_mode))
175 // Otherwise, remove the file. We ignore any errors here as there is
176 // nothing else we can do.
179 // We're done removing the file, erasing can safely proceed.
180 currentFile->Filename.exchange(path);
184 // We're done removing files, cleanup can safely proceed.
185 Head.exchange(OldHead);
188 static std::atomic<FileToRemoveList *> FilesToRemove = ATOMIC_VAR_INIT(nullptr);
190 /// Clean up the list in a signal-friendly manner.
191 /// Recall that signals can fire during llvm_shutdown. If this occurs we should
192 /// either clean something up or nothing at all, but we shouldn't crash!
193 struct FilesToRemoveCleanup {
195 ~FilesToRemoveCleanup() {
196 FileToRemoveList *Head = FilesToRemove.exchange(nullptr);
203 static StringRef Argv0;
205 /// Signals that represent requested termination. There's no bug or failure, or
206 /// if there is, it's not our direct responsibility. For whatever reason, our
207 /// continued execution is no longer desirable.
208 static const int IntSigs[] = {
209 SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR2
212 /// Signals that represent that we have a bug, and our prompt termination has
214 static const int KillSigs[] = {
215 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
230 /// Signals that represent requests for status.
231 static const int InfoSigs[] = {
238 static const size_t NumSigs =
239 array_lengthof(IntSigs) + array_lengthof(KillSigs) +
240 array_lengthof(InfoSigs);
243 static std::atomic<unsigned> NumRegisteredSignals = ATOMIC_VAR_INIT(0);
247 } RegisteredSignalInfo[NumSigs];
249 #if defined(HAVE_SIGALTSTACK)
250 // Hold onto both the old and new alternate signal stack so that it's not
251 // reported as a leak. We don't make any attempt to remove our alt signal
252 // stack if we remove our signal handlers; that can't be done reliably if
253 // someone else is also trying to do the same thing.
254 static stack_t OldAltStack;
255 static void* NewAltStackPointer;
257 static void CreateSigAltStack() {
258 const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024;
260 // If we're executing on the alternate stack, or we already have an alternate
261 // signal stack that we're happy with, there's nothing for us to do. Don't
262 // reduce the size, some other part of the process might need a larger stack
264 if (sigaltstack(nullptr, &OldAltStack) != 0 ||
265 OldAltStack.ss_flags & SS_ONSTACK ||
266 (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize))
269 stack_t AltStack = {};
270 AltStack.ss_sp = static_cast<char *>(safe_malloc(AltStackSize));
271 NewAltStackPointer = AltStack.ss_sp; // Save to avoid reporting a leak.
272 AltStack.ss_size = AltStackSize;
273 if (sigaltstack(&AltStack, &OldAltStack) != 0)
274 free(AltStack.ss_sp);
277 static void CreateSigAltStack() {}
280 static void RegisterHandlers() { // Not signal-safe.
281 // The mutex prevents other threads from registering handlers while we're
282 // doing it. We also have to protect the handlers and their count because
283 // a signal handler could fire while we're registeting handlers.
284 static ManagedStatic<sys::SmartMutex<true>> SignalHandlerRegistrationMutex;
285 sys::SmartScopedLock<true> Guard(*SignalHandlerRegistrationMutex);
287 // If the handlers are already registered, we're done.
288 if (NumRegisteredSignals.load() != 0)
291 // Create an alternate stack for signal handling. This is necessary for us to
292 // be able to reliably handle signals due to stack overflow.
295 enum class SignalKind { IsKill, IsInfo };
296 auto registerHandler = [&](int Signal, SignalKind Kind) {
297 unsigned Index = NumRegisteredSignals.load();
298 assert(Index < array_lengthof(RegisteredSignalInfo) &&
299 "Out of space for signal handlers!");
301 struct sigaction NewHandler;
304 case SignalKind::IsKill:
305 NewHandler.sa_handler = SignalHandler;
306 NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK;
308 case SignalKind::IsInfo:
309 NewHandler.sa_handler = InfoSignalHandler;
310 NewHandler.sa_flags = SA_ONSTACK;
313 sigemptyset(&NewHandler.sa_mask);
315 // Install the new handler, save the old one in RegisteredSignalInfo.
316 sigaction(Signal, &NewHandler, &RegisteredSignalInfo[Index].SA);
317 RegisteredSignalInfo[Index].SigNo = Signal;
318 ++NumRegisteredSignals;
321 for (auto S : IntSigs)
322 registerHandler(S, SignalKind::IsKill);
323 for (auto S : KillSigs)
324 registerHandler(S, SignalKind::IsKill);
325 for (auto S : InfoSigs)
326 registerHandler(S, SignalKind::IsInfo);
329 static void UnregisterHandlers() {
330 // Restore all of the signal handlers to how they were before we showed up.
331 for (unsigned i = 0, e = NumRegisteredSignals.load(); i != e; ++i) {
332 sigaction(RegisteredSignalInfo[i].SigNo,
333 &RegisteredSignalInfo[i].SA, nullptr);
334 --NumRegisteredSignals;
338 /// Process the FilesToRemove list.
339 static void RemoveFilesToRemove() {
340 FileToRemoveList::removeAllFiles(FilesToRemove);
343 // The signal handler that runs.
344 static RETSIGTYPE SignalHandler(int Sig) {
345 // Restore the signal behavior to default, so that the program actually
346 // crashes when we return and the signal reissues. This also ensures that if
347 // we crash in our signal handler that the program will terminate immediately
348 // instead of recursing in the signal handler.
349 UnregisterHandlers();
351 // Unmask all potentially blocked kill signals.
353 sigfillset(&SigMask);
354 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
357 RemoveFilesToRemove();
359 if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
360 != std::end(IntSigs)) {
361 if (auto OldInterruptFunction = InterruptFunction.exchange(nullptr))
362 return OldInterruptFunction();
364 // Send a special return code that drivers can check for, from sysexits.h.
368 raise(Sig); // Execute the default handler.
373 // Otherwise if it is a fault (like SEGV) run any handler.
374 llvm::sys::RunSignalHandlers();
377 // On S/390, certain signals are delivered with PSW Address pointing to
378 // *after* the faulting instruction. Simply returning from the signal
379 // handler would continue execution after that point, instead of
380 // re-raising the signal. Raise the signal manually in those cases.
381 if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
386 static RETSIGTYPE InfoSignalHandler(int Sig) {
387 SaveAndRestore<int> SaveErrnoDuringASignalHandler(errno);
388 if (SignalHandlerFunctionType CurrentInfoFunction = InfoSignalFunction)
389 CurrentInfoFunction();
392 void llvm::sys::RunInterruptHandlers() {
393 RemoveFilesToRemove();
396 void llvm::sys::SetInterruptFunction(void (*IF)()) {
397 InterruptFunction.exchange(IF);
401 void llvm::sys::SetInfoSignalFunction(void (*Handler)()) {
402 InfoSignalFunction.exchange(Handler);
407 bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
408 std::string* ErrMsg) {
409 // Ensure that cleanup will occur as soon as one file is added.
410 static ManagedStatic<FilesToRemoveCleanup> FilesToRemoveCleanup;
411 *FilesToRemoveCleanup;
412 FileToRemoveList::insert(FilesToRemove, Filename.str());
418 void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
419 FileToRemoveList::erase(FilesToRemove, Filename.str());
422 /// Add a function to be called when a signal is delivered to the process. The
423 /// handler can have a cookie passed to it to identify what instance of the
425 void llvm::sys::AddSignalHandler(sys::SignalHandlerCallback FnPtr,
426 void *Cookie) { // Signal-safe.
427 insertSignalHandler(FnPtr, Cookie);
431 #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && HAVE_LINK_H && \
432 (defined(__linux__) || defined(__FreeBSD__) || \
433 defined(__FreeBSD_kernel__) || defined(__NetBSD__))
434 struct DlIteratePhdrData {
438 const char **modules;
440 const char *main_exec_name;
443 static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
444 DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
445 const char *name = data->first ? data->main_exec_name : info->dlpi_name;
447 for (int i = 0; i < info->dlpi_phnum; i++) {
448 const auto *phdr = &info->dlpi_phdr[i];
449 if (phdr->p_type != PT_LOAD)
451 intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
452 intptr_t end = beg + phdr->p_memsz;
453 for (int j = 0; j < data->depth; j++) {
454 if (data->modules[j])
456 intptr_t addr = (intptr_t)data->StackTrace[j];
457 if (beg <= addr && addr < end) {
458 data->modules[j] = name;
459 data->offsets[j] = addr - info->dlpi_addr;
466 /// If this is an ELF platform, we can find all loaded modules and their virtual
467 /// addresses with dl_iterate_phdr.
468 static bool findModulesAndOffsets(void **StackTrace, int Depth,
469 const char **Modules, intptr_t *Offsets,
470 const char *MainExecutableName,
471 StringSaver &StrPool) {
472 DlIteratePhdrData data = {StackTrace, Depth, true,
473 Modules, Offsets, MainExecutableName};
474 dl_iterate_phdr(dl_iterate_phdr_cb, &data);
478 /// This platform does not have dl_iterate_phdr, so we do not yet know how to
479 /// find all loaded DSOs.
480 static bool findModulesAndOffsets(void **StackTrace, int Depth,
481 const char **Modules, intptr_t *Offsets,
482 const char *MainExecutableName,
483 StringSaver &StrPool) {
486 #endif // defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && ...
488 #if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE)
489 static int unwindBacktrace(void **StackTrace, int MaxEntries) {
493 // Skip the first frame ('unwindBacktrace' itself).
496 auto HandleFrame = [&](_Unwind_Context *Context) -> _Unwind_Reason_Code {
497 // Apparently we need to detect reaching the end of the stack ourselves.
498 void *IP = (void *)_Unwind_GetIP(Context);
500 return _URC_END_OF_STACK;
502 assert(Entries < MaxEntries && "recursively called after END_OF_STACK?");
504 StackTrace[Entries] = IP;
506 if (++Entries == MaxEntries)
507 return _URC_END_OF_STACK;
508 return _URC_NO_REASON;
512 [](_Unwind_Context *Context, void *Handler) {
513 return (*static_cast<decltype(HandleFrame) *>(Handler))(Context);
515 static_cast<void *>(&HandleFrame));
516 return std::max(Entries, 0);
520 // In the case of a program crash or fault, print out a stack trace so that the
521 // user has an indication of why and where we died.
523 // On glibc systems we have the 'backtrace' function, which works nicely, but
524 // doesn't demangle symbols.
525 void llvm::sys::PrintStackTrace(raw_ostream &OS) {
526 #if ENABLE_BACKTRACES
527 static void *StackTrace[256];
529 #if defined(HAVE_BACKTRACE)
530 // Use backtrace() to output a backtrace on Linux systems with glibc.
532 depth = backtrace(StackTrace, static_cast<int>(array_lengthof(StackTrace)));
534 #if defined(HAVE__UNWIND_BACKTRACE)
535 // Try _Unwind_Backtrace() if backtrace() failed.
537 depth = unwindBacktrace(StackTrace,
538 static_cast<int>(array_lengthof(StackTrace)));
543 if (printSymbolizedStackTrace(Argv0, StackTrace, depth, OS))
545 #if HAVE_DLFCN_H && HAVE_DLADDR
547 for (int i = 0; i < depth; ++i) {
549 dladdr(StackTrace[i], &dlinfo);
550 const char* name = strrchr(dlinfo.dli_fname, '/');
553 if (!name) nwidth = strlen(dlinfo.dli_fname);
554 else nwidth = strlen(name) - 1;
556 if (nwidth > width) width = nwidth;
559 for (int i = 0; i < depth; ++i) {
561 dladdr(StackTrace[i], &dlinfo);
563 OS << format("%-2d", i);
565 const char* name = strrchr(dlinfo.dli_fname, '/');
566 if (!name) OS << format(" %-*s", width, dlinfo.dli_fname);
567 else OS << format(" %-*s", width, name+1);
569 OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2,
570 (unsigned long)StackTrace[i]);
572 if (dlinfo.dli_sname != nullptr) {
575 char* d = itaniumDemangle(dlinfo.dli_sname, nullptr, nullptr, &res);
576 if (!d) OS << dlinfo.dli_sname;
580 OS << format(" + %tu", (static_cast<const char*>(StackTrace[i])-
581 static_cast<const char*>(dlinfo.dli_saddr)));
585 #elif defined(HAVE_BACKTRACE)
586 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
591 static void PrintStackTraceSignalHandler(void *) {
592 sys::PrintStackTrace(llvm::errs());
595 void llvm::sys::DisableSystemDialogsOnCrash() {}
597 /// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
598 /// process, print a stack trace and then exit.
599 void llvm::sys::PrintStackTraceOnErrorSignal(StringRef Argv0,
600 bool DisableCrashReporting) {
603 AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
605 #if defined(__APPLE__) && ENABLE_CRASH_OVERRIDES
606 // Environment variable to disable any kind of crash dialog.
607 if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) {
608 mach_port_t self = mach_task_self();
610 exception_mask_t mask = EXC_MASK_CRASH;
612 kern_return_t ret = task_set_exception_ports(self,
615 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,