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/UniqueLock.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.
84 /// The function to call if ctrl-c is pressed.
85 using InterruptFunctionType = void (*)();
86 static std::atomic<InterruptFunctionType> InterruptFunction =
87 ATOMIC_VAR_INIT(nullptr);
90 /// Signal-safe removal of files.
91 /// Inserting and erasing from the list isn't signal-safe, but removal of files
92 /// themselves is signal-safe. Memory is freed when the head is freed, deletion
93 /// is therefore not signal-safe either.
94 class FileToRemoveList {
95 std::atomic<char *> Filename = ATOMIC_VAR_INIT(nullptr);
96 std::atomic<FileToRemoveList *> Next = ATOMIC_VAR_INIT(nullptr);
98 FileToRemoveList() = default;
100 FileToRemoveList(const std::string &str) : Filename(strdup(str.c_str())) {}
104 ~FileToRemoveList() {
105 if (FileToRemoveList *N = Next.exchange(nullptr))
107 if (char *F = Filename.exchange(nullptr))
112 static void insert(std::atomic<FileToRemoveList *> &Head,
113 const std::string &Filename) {
114 // Insert the new file at the end of the list.
115 FileToRemoveList *NewHead = new FileToRemoveList(Filename);
116 std::atomic<FileToRemoveList *> *InsertionPoint = &Head;
117 FileToRemoveList *OldHead = nullptr;
118 while (!InsertionPoint->compare_exchange_strong(OldHead, NewHead)) {
119 InsertionPoint = &OldHead->Next;
125 static void erase(std::atomic<FileToRemoveList *> &Head,
126 const std::string &Filename) {
127 // Use a lock to avoid concurrent erase: the comparison would access
129 static ManagedStatic<sys::SmartMutex<true>> Lock;
130 sys::SmartScopedLock<true> Writer(*Lock);
132 for (FileToRemoveList *Current = Head.load(); Current;
133 Current = Current->Next.load()) {
134 if (char *OldFilename = Current->Filename.load()) {
135 if (OldFilename != Filename)
137 // Leave an empty filename.
138 OldFilename = Current->Filename.exchange(nullptr);
139 // The filename might have become null between the time we
140 // compared it and we exchanged it.
148 static void removeAllFiles(std::atomic<FileToRemoveList *> &Head) {
149 // If cleanup were to occur while we're removing files we'd have a bad time.
150 // Make sure we're OK by preventing cleanup from doing anything while we're
151 // removing files. If cleanup races with us and we win we'll have a leak,
152 // but we won't crash.
153 FileToRemoveList *OldHead = Head.exchange(nullptr);
155 for (FileToRemoveList *currentFile = OldHead; currentFile;
156 currentFile = currentFile->Next.load()) {
157 // If erasing was occuring while we're trying to remove files we'd look
158 // at free'd data. Take away the path and put it back when done.
159 if (char *path = currentFile->Filename.exchange(nullptr)) {
160 // Get the status so we can determine if it's a file or directory. If we
161 // can't stat the file, ignore it.
163 if (stat(path, &buf) != 0)
166 // If this is not a regular file, ignore it. We want to prevent removal
167 // of special files like /dev/null, even if the compiler is being run
168 // with the super-user permissions.
169 if (!S_ISREG(buf.st_mode))
172 // Otherwise, remove the file. We ignore any errors here as there is
173 // nothing else we can do.
176 // We're done removing the file, erasing can safely proceed.
177 currentFile->Filename.exchange(path);
181 // We're done removing files, cleanup can safely proceed.
182 Head.exchange(OldHead);
185 static std::atomic<FileToRemoveList *> FilesToRemove = ATOMIC_VAR_INIT(nullptr);
187 /// Clean up the list in a signal-friendly manner.
188 /// Recall that signals can fire during llvm_shutdown. If this occurs we should
189 /// either clean something up or nothing at all, but we shouldn't crash!
190 struct FilesToRemoveCleanup {
192 ~FilesToRemoveCleanup() {
193 FileToRemoveList *Head = FilesToRemove.exchange(nullptr);
200 static StringRef Argv0;
202 // Signals that represent requested termination. There's no bug or failure, or
203 // if there is, it's not our direct responsibility. For whatever reason, our
204 // continued execution is no longer desirable.
205 static const int IntSigs[] = {
206 SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
209 // Signals that represent that we have a bug, and our prompt termination has
211 static const int KillSigs[] = {
212 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
227 static std::atomic<unsigned> NumRegisteredSignals = ATOMIC_VAR_INIT(0);
231 } RegisteredSignalInfo[array_lengthof(IntSigs) + array_lengthof(KillSigs)];
233 #if defined(HAVE_SIGALTSTACK)
234 // Hold onto both the old and new alternate signal stack so that it's not
235 // reported as a leak. We don't make any attempt to remove our alt signal
236 // stack if we remove our signal handlers; that can't be done reliably if
237 // someone else is also trying to do the same thing.
238 static stack_t OldAltStack;
239 static void* NewAltStackPointer;
241 static void CreateSigAltStack() {
242 const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024;
244 // If we're executing on the alternate stack, or we already have an alternate
245 // signal stack that we're happy with, there's nothing for us to do. Don't
246 // reduce the size, some other part of the process might need a larger stack
248 if (sigaltstack(nullptr, &OldAltStack) != 0 ||
249 OldAltStack.ss_flags & SS_ONSTACK ||
250 (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize))
253 stack_t AltStack = {};
254 AltStack.ss_sp = static_cast<char *>(safe_malloc(AltStackSize));
255 NewAltStackPointer = AltStack.ss_sp; // Save to avoid reporting a leak.
256 AltStack.ss_size = AltStackSize;
257 if (sigaltstack(&AltStack, &OldAltStack) != 0)
258 free(AltStack.ss_sp);
261 static void CreateSigAltStack() {}
264 static void RegisterHandlers() { // Not signal-safe.
265 // The mutex prevents other threads from registering handlers while we're
266 // doing it. We also have to protect the handlers and their count because
267 // a signal handler could fire while we're registeting handlers.
268 static ManagedStatic<sys::SmartMutex<true>> SignalHandlerRegistrationMutex;
269 sys::SmartScopedLock<true> Guard(*SignalHandlerRegistrationMutex);
271 // If the handlers are already registered, we're done.
272 if (NumRegisteredSignals.load() != 0)
275 // Create an alternate stack for signal handling. This is necessary for us to
276 // be able to reliably handle signals due to stack overflow.
279 auto registerHandler = [&](int Signal) {
280 unsigned Index = NumRegisteredSignals.load();
281 assert(Index < array_lengthof(RegisteredSignalInfo) &&
282 "Out of space for signal handlers!");
284 struct sigaction NewHandler;
286 NewHandler.sa_handler = SignalHandler;
287 NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK;
288 sigemptyset(&NewHandler.sa_mask);
290 // Install the new handler, save the old one in RegisteredSignalInfo.
291 sigaction(Signal, &NewHandler, &RegisteredSignalInfo[Index].SA);
292 RegisteredSignalInfo[Index].SigNo = Signal;
293 ++NumRegisteredSignals;
296 for (auto S : IntSigs)
298 for (auto S : KillSigs)
302 static void UnregisterHandlers() {
303 // Restore all of the signal handlers to how they were before we showed up.
304 for (unsigned i = 0, e = NumRegisteredSignals.load(); i != e; ++i) {
305 sigaction(RegisteredSignalInfo[i].SigNo,
306 &RegisteredSignalInfo[i].SA, nullptr);
307 --NumRegisteredSignals;
311 /// Process the FilesToRemove list.
312 static void RemoveFilesToRemove() {
313 FileToRemoveList::removeAllFiles(FilesToRemove);
316 // The signal handler that runs.
317 static RETSIGTYPE SignalHandler(int Sig) {
318 // Restore the signal behavior to default, so that the program actually
319 // crashes when we return and the signal reissues. This also ensures that if
320 // we crash in our signal handler that the program will terminate immediately
321 // instead of recursing in the signal handler.
322 UnregisterHandlers();
324 // Unmask all potentially blocked kill signals.
326 sigfillset(&SigMask);
327 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
330 RemoveFilesToRemove();
332 if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
333 != std::end(IntSigs)) {
334 if (auto OldInterruptFunction = InterruptFunction.exchange(nullptr))
335 return OldInterruptFunction();
337 // Send a special return code that drivers can check for, from sysexits.h.
341 raise(Sig); // Execute the default handler.
346 // Otherwise if it is a fault (like SEGV) run any handler.
347 llvm::sys::RunSignalHandlers();
350 // On S/390, certain signals are delivered with PSW Address pointing to
351 // *after* the faulting instruction. Simply returning from the signal
352 // handler would continue execution after that point, instead of
353 // re-raising the signal. Raise the signal manually in those cases.
354 if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
359 void llvm::sys::RunInterruptHandlers() {
360 RemoveFilesToRemove();
363 void llvm::sys::SetInterruptFunction(void (*IF)()) {
364 InterruptFunction.exchange(IF);
369 bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
370 std::string* ErrMsg) {
371 // Ensure that cleanup will occur as soon as one file is added.
372 static ManagedStatic<FilesToRemoveCleanup> FilesToRemoveCleanup;
373 *FilesToRemoveCleanup;
374 FileToRemoveList::insert(FilesToRemove, Filename.str());
380 void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
381 FileToRemoveList::erase(FilesToRemove, Filename.str());
384 /// Add a function to be called when a signal is delivered to the process. The
385 /// handler can have a cookie passed to it to identify what instance of the
387 void llvm::sys::AddSignalHandler(sys::SignalHandlerCallback FnPtr,
388 void *Cookie) { // Signal-safe.
389 insertSignalHandler(FnPtr, Cookie);
393 #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && HAVE_LINK_H && \
394 (defined(__linux__) || defined(__FreeBSD__) || \
395 defined(__FreeBSD_kernel__) || defined(__NetBSD__))
396 struct DlIteratePhdrData {
400 const char **modules;
402 const char *main_exec_name;
405 static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
406 DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
407 const char *name = data->first ? data->main_exec_name : info->dlpi_name;
409 for (int i = 0; i < info->dlpi_phnum; i++) {
410 const auto *phdr = &info->dlpi_phdr[i];
411 if (phdr->p_type != PT_LOAD)
413 intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
414 intptr_t end = beg + phdr->p_memsz;
415 for (int j = 0; j < data->depth; j++) {
416 if (data->modules[j])
418 intptr_t addr = (intptr_t)data->StackTrace[j];
419 if (beg <= addr && addr < end) {
420 data->modules[j] = name;
421 data->offsets[j] = addr - info->dlpi_addr;
428 /// If this is an ELF platform, we can find all loaded modules and their virtual
429 /// addresses with dl_iterate_phdr.
430 static bool findModulesAndOffsets(void **StackTrace, int Depth,
431 const char **Modules, intptr_t *Offsets,
432 const char *MainExecutableName,
433 StringSaver &StrPool) {
434 DlIteratePhdrData data = {StackTrace, Depth, true,
435 Modules, Offsets, MainExecutableName};
436 dl_iterate_phdr(dl_iterate_phdr_cb, &data);
440 /// This platform does not have dl_iterate_phdr, so we do not yet know how to
441 /// find all loaded DSOs.
442 static bool findModulesAndOffsets(void **StackTrace, int Depth,
443 const char **Modules, intptr_t *Offsets,
444 const char *MainExecutableName,
445 StringSaver &StrPool) {
448 #endif // defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && ...
450 #if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE)
451 static int unwindBacktrace(void **StackTrace, int MaxEntries) {
455 // Skip the first frame ('unwindBacktrace' itself).
458 auto HandleFrame = [&](_Unwind_Context *Context) -> _Unwind_Reason_Code {
459 // Apparently we need to detect reaching the end of the stack ourselves.
460 void *IP = (void *)_Unwind_GetIP(Context);
462 return _URC_END_OF_STACK;
464 assert(Entries < MaxEntries && "recursively called after END_OF_STACK?");
466 StackTrace[Entries] = IP;
468 if (++Entries == MaxEntries)
469 return _URC_END_OF_STACK;
470 return _URC_NO_REASON;
474 [](_Unwind_Context *Context, void *Handler) {
475 return (*static_cast<decltype(HandleFrame) *>(Handler))(Context);
477 static_cast<void *>(&HandleFrame));
478 return std::max(Entries, 0);
482 // In the case of a program crash or fault, print out a stack trace so that the
483 // user has an indication of why and where we died.
485 // On glibc systems we have the 'backtrace' function, which works nicely, but
486 // doesn't demangle symbols.
487 void llvm::sys::PrintStackTrace(raw_ostream &OS) {
488 #if ENABLE_BACKTRACES
489 static void *StackTrace[256];
491 #if defined(HAVE_BACKTRACE)
492 // Use backtrace() to output a backtrace on Linux systems with glibc.
494 depth = backtrace(StackTrace, static_cast<int>(array_lengthof(StackTrace)));
496 #if defined(HAVE__UNWIND_BACKTRACE)
497 // Try _Unwind_Backtrace() if backtrace() failed.
499 depth = unwindBacktrace(StackTrace,
500 static_cast<int>(array_lengthof(StackTrace)));
505 if (printSymbolizedStackTrace(Argv0, StackTrace, depth, OS))
507 #if HAVE_DLFCN_H && HAVE_DLADDR
509 for (int i = 0; i < depth; ++i) {
511 dladdr(StackTrace[i], &dlinfo);
512 const char* name = strrchr(dlinfo.dli_fname, '/');
515 if (!name) nwidth = strlen(dlinfo.dli_fname);
516 else nwidth = strlen(name) - 1;
518 if (nwidth > width) width = nwidth;
521 for (int i = 0; i < depth; ++i) {
523 dladdr(StackTrace[i], &dlinfo);
525 OS << format("%-2d", i);
527 const char* name = strrchr(dlinfo.dli_fname, '/');
528 if (!name) OS << format(" %-*s", width, dlinfo.dli_fname);
529 else OS << format(" %-*s", width, name+1);
531 OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2,
532 (unsigned long)StackTrace[i]);
534 if (dlinfo.dli_sname != nullptr) {
537 char* d = itaniumDemangle(dlinfo.dli_sname, nullptr, nullptr, &res);
538 if (!d) OS << dlinfo.dli_sname;
542 // FIXME: When we move to C++11, use %t length modifier. It's not in
543 // C++03 and causes gcc to issue warnings. Losing the upper 32 bits of
544 // the stack offset for a stack dump isn't likely to cause any problems.
545 OS << format(" + %u",(unsigned)((char*)StackTrace[i]-
546 (char*)dlinfo.dli_saddr));
550 #elif defined(HAVE_BACKTRACE)
551 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
556 static void PrintStackTraceSignalHandler(void *) {
557 sys::PrintStackTrace(llvm::errs());
560 void llvm::sys::DisableSystemDialogsOnCrash() {}
562 /// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
563 /// process, print a stack trace and then exit.
564 void llvm::sys::PrintStackTraceOnErrorSignal(StringRef Argv0,
565 bool DisableCrashReporting) {
568 AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
570 #if defined(__APPLE__) && ENABLE_CRASH_OVERRIDES
571 // Environment variable to disable any kind of crash dialog.
572 if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) {
573 mach_port_t self = mach_task_self();
575 exception_mask_t mask = EXC_MASK_CRASH;
577 kern_return_t ret = task_set_exception_ports(self,
580 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,