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/raw_ostream.h" 47#include <algorithm> 48#include <string> 49#include <sysexits.h> 50#ifdef HAVE_BACKTRACE 51# include BACKTRACE_HEADER // For backtrace(). 52#endif 53#if HAVE_SIGNAL_H 54#include <signal.h> 55#endif 56#if HAVE_SYS_STAT_H 57#include <sys/stat.h> 58#endif 59#if HAVE_DLFCN_H 60#include <dlfcn.h> 61#endif 62#if HAVE_MACH_MACH_H 63#include <mach/mach.h> 64#endif 65#if HAVE_LINK_H 66#include <link.h> 67#endif 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 72// with <link.h>. 73#ifdef __GLIBC__ 74#include <unwind.h> 75#else 76#undef HAVE__UNWIND_BACKTRACE 77#endif 78#endif 79 80using namespace llvm; 81 82static RETSIGTYPE SignalHandler(int Sig); // defined below. 83static RETSIGTYPE InfoSignalHandler(int Sig); // defined below. 84 85using SignalHandlerFunctionType = void (*)(); 86/// The function to call if ctrl-c is pressed. 87static std::atomic<SignalHandlerFunctionType> InterruptFunction = 88 ATOMIC_VAR_INIT(nullptr); 89static std::atomic<SignalHandlerFunctionType> InfoSignalFunction = 90 ATOMIC_VAR_INIT(nullptr); 91 92namespace { 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. 97class FileToRemoveList { 98 std::atomic<char *> Filename = ATOMIC_VAR_INIT(nullptr); 99 std::atomic<FileToRemoveList *> Next = ATOMIC_VAR_INIT(nullptr); 100 101 FileToRemoveList() = default; 102 // Not signal-safe. 103 FileToRemoveList(const std::string &str) : Filename(strdup(str.c_str())) {} 104 105public: 106 // Not signal-safe. 107 ~FileToRemoveList() { 108 if (FileToRemoveList *N = Next.exchange(nullptr)) 109 delete N; 110 if (char *F = Filename.exchange(nullptr)) 111 free(F); 112 } 113 114 // Not signal-safe. 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; 123 OldHead = nullptr; 124 } 125 } 126 127 // Not signal-safe. 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 131 // free'd memory. 132 static ManagedStatic<sys::SmartMutex<true>> Lock; 133 sys::SmartScopedLock<true> Writer(*Lock); 134 135 for (FileToRemoveList *Current = Head.load(); Current; 136 Current = Current->Next.load()) { 137 if (char *OldFilename = Current->Filename.load()) { 138 if (OldFilename != Filename) 139 continue; 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. 144 if (OldFilename) 145 free(OldFilename); 146 } 147 } 148 } 149 150 // Signal-safe. 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); 157 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. 165 struct stat buf; 166 if (stat(path, &buf) != 0) 167 continue; 168 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)) 173 continue; 174 175 // Otherwise, remove the file. We ignore any errors here as there is 176 // nothing else we can do. 177 unlink(path); 178 179 // We're done removing the file, erasing can safely proceed. 180 currentFile->Filename.exchange(path); 181 } 182 } 183 184 // We're done removing files, cleanup can safely proceed. 185 Head.exchange(OldHead); 186 } 187}; 188static std::atomic<FileToRemoveList *> FilesToRemove = ATOMIC_VAR_INIT(nullptr); 189 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! 193struct FilesToRemoveCleanup { 194 // Not signal-safe. 195 ~FilesToRemoveCleanup() { 196 FileToRemoveList *Head = FilesToRemove.exchange(nullptr); 197 if (Head) 198 delete Head; 199 } 200}; 201} // namespace 202 203static StringRef Argv0; 204 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. 208static const int IntSigs[] = { 209 SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR2 210}; 211 212/// Signals that represent that we have a bug, and our prompt termination has 213/// been ordered. 214static const int KillSigs[] = { 215 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT 216#ifdef SIGSYS 217 , SIGSYS 218#endif 219#ifdef SIGXCPU 220 , SIGXCPU 221#endif 222#ifdef SIGXFSZ 223 , SIGXFSZ 224#endif 225#ifdef SIGEMT 226 , SIGEMT 227#endif 228}; 229 230/// Signals that represent requests for status. 231static const int InfoSigs[] = { 232 SIGUSR1 233#ifdef SIGINFO 234 , SIGINFO 235#endif 236}; 237 238static const size_t NumSigs = 239 array_lengthof(IntSigs) + array_lengthof(KillSigs) + 240 array_lengthof(InfoSigs); 241 242 243static std::atomic<unsigned> NumRegisteredSignals = ATOMIC_VAR_INIT(0); 244static struct { 245 struct sigaction SA; 246 int SigNo; 247} RegisteredSignalInfo[NumSigs]; 248 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. 254static stack_t OldAltStack; 255static void* NewAltStackPointer; 256 257static void CreateSigAltStack() { 258 const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024; 259 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 263 // than we do. 264 if (sigaltstack(nullptr, &OldAltStack) != 0 || 265 OldAltStack.ss_flags & SS_ONSTACK || 266 (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize)) 267 return; 268 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); 275} 276#else 277static void CreateSigAltStack() {} 278#endif 279 280static 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); 286 287 // If the handlers are already registered, we're done. 288 if (NumRegisteredSignals.load() != 0) 289 return; 290 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. 293 CreateSigAltStack(); 294 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!"); 300 301 struct sigaction NewHandler; 302 303 switch (Kind) { 304 case SignalKind::IsKill: 305 NewHandler.sa_handler = SignalHandler; 306 NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK; 307 break; 308 case SignalKind::IsInfo: 309 NewHandler.sa_handler = InfoSignalHandler; 310 NewHandler.sa_flags = SA_ONSTACK; 311 break; 312 } 313 sigemptyset(&NewHandler.sa_mask); 314 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; 319 }; 320 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); 327} 328 329static 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; 335 } 336} 337 338/// Process the FilesToRemove list. 339static void RemoveFilesToRemove() { 340 FileToRemoveList::removeAllFiles(FilesToRemove); 341} 342 343// The signal handler that runs. 344static 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(); 350 351 // Unmask all potentially blocked kill signals. 352 sigset_t SigMask; 353 sigfillset(&SigMask); 354 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr); 355 356 { 357 RemoveFilesToRemove(); 358 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(); 363 364 // Send a special return code that drivers can check for, from sysexits.h. 365 if (Sig == SIGPIPE) 366 exit(EX_IOERR); 367 368 raise(Sig); // Execute the default handler. 369 return; 370 } 371 } 372 373 // Otherwise if it is a fault (like SEGV) run any handler. 374 llvm::sys::RunSignalHandlers(); 375 376#ifdef __s390__ 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) 382 raise(Sig); 383#endif 384} 385 386static RETSIGTYPE InfoSignalHandler(int Sig) { 387 SaveAndRestore<int> SaveErrnoDuringASignalHandler(errno); 388 if (SignalHandlerFunctionType CurrentInfoFunction = InfoSignalFunction) 389 CurrentInfoFunction(); 390} 391 392void llvm::sys::RunInterruptHandlers() { 393 RemoveFilesToRemove(); 394} 395 396void llvm::sys::SetInterruptFunction(void (*IF)()) { 397 InterruptFunction.exchange(IF); 398 RegisterHandlers(); 399} 400 401void llvm::sys::SetInfoSignalFunction(void (*Handler)()) { 402 InfoSignalFunction.exchange(Handler); 403 RegisterHandlers(); 404} 405 406// The public API 407bool 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()); 413 RegisterHandlers(); 414 return false; 415} 416 417// The public API 418void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) { 419 FileToRemoveList::erase(FilesToRemove, Filename.str()); 420} 421 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 424/// handler it is. 425void llvm::sys::AddSignalHandler(sys::SignalHandlerCallback FnPtr, 426 void *Cookie) { // Signal-safe. 427 insertSignalHandler(FnPtr, Cookie); 428 RegisterHandlers(); 429} 430 431#if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && HAVE_LINK_H && \ 432 (defined(__linux__) || defined(__FreeBSD__) || \ 433 defined(__FreeBSD_kernel__) || defined(__NetBSD__)) 434struct DlIteratePhdrData { 435 void **StackTrace; 436 int depth; 437 bool first; 438 const char **modules; 439 intptr_t *offsets; 440 const char *main_exec_name; 441}; 442 443static 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; 446 data->first = false; 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) 450 continue; 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]) 455 continue; 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; 460 } 461 } 462 } 463 return 0; 464} 465 466/// If this is an ELF platform, we can find all loaded modules and their virtual 467/// addresses with dl_iterate_phdr. 468static 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); 475 return true; 476} 477#else 478/// This platform does not have dl_iterate_phdr, so we do not yet know how to 479/// find all loaded DSOs. 480static bool findModulesAndOffsets(void **StackTrace, int Depth, 481 const char **Modules, intptr_t *Offsets, 482 const char *MainExecutableName, 483 StringSaver &StrPool) { 484 return false; 485} 486#endif // defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && ... 487 488#if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE) 489static int unwindBacktrace(void **StackTrace, int MaxEntries) { 490 if (MaxEntries < 0) 491 return 0; 492 493 // Skip the first frame ('unwindBacktrace' itself). 494 int Entries = -1; 495 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); 499 if (!IP) 500 return _URC_END_OF_STACK; 501 502 assert(Entries < MaxEntries && "recursively called after END_OF_STACK?"); 503 if (Entries >= 0) 504 StackTrace[Entries] = IP; 505 506 if (++Entries == MaxEntries) 507 return _URC_END_OF_STACK; 508 return _URC_NO_REASON; 509 }; 510 511 _Unwind_Backtrace( 512 [](_Unwind_Context *Context, void *Handler) { 513 return (*static_cast<decltype(HandleFrame) *>(Handler))(Context); 514 }, 515 static_cast<void *>(&HandleFrame)); 516 return std::max(Entries, 0); 517} 518#endif 519 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. 522// 523// On glibc systems we have the 'backtrace' function, which works nicely, but 524// doesn't demangle symbols. 525void llvm::sys::PrintStackTrace(raw_ostream &OS) { 526#if ENABLE_BACKTRACES 527 static void *StackTrace[256]; 528 int depth = 0; 529#if defined(HAVE_BACKTRACE) 530 // Use backtrace() to output a backtrace on Linux systems with glibc. 531 if (!depth) 532 depth = backtrace(StackTrace, static_cast<int>(array_lengthof(StackTrace))); 533#endif 534#if defined(HAVE__UNWIND_BACKTRACE) 535 // Try _Unwind_Backtrace() if backtrace() failed. 536 if (!depth) 537 depth = unwindBacktrace(StackTrace, 538 static_cast<int>(array_lengthof(StackTrace))); 539#endif 540 if (!depth) 541 return; 542 543 if (printSymbolizedStackTrace(Argv0, StackTrace, depth, OS)) 544 return; 545#if HAVE_DLFCN_H && HAVE_DLADDR 546 int width = 0; 547 for (int i = 0; i < depth; ++i) { 548 Dl_info dlinfo; 549 dladdr(StackTrace[i], &dlinfo); 550 const char* name = strrchr(dlinfo.dli_fname, '/'); 551 552 int nwidth; 553 if (!name) nwidth = strlen(dlinfo.dli_fname); 554 else nwidth = strlen(name) - 1; 555 556 if (nwidth > width) width = nwidth; 557 } 558 559 for (int i = 0; i < depth; ++i) { 560 Dl_info dlinfo; 561 dladdr(StackTrace[i], &dlinfo); 562 563 OS << format("%-2d", i); 564 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); 568 569 OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2, 570 (unsigned long)StackTrace[i]); 571 572 if (dlinfo.dli_sname != nullptr) { 573 OS << ' '; 574 int res; 575 char* d = itaniumDemangle(dlinfo.dli_sname, nullptr, nullptr, &res); 576 if (!d) OS << dlinfo.dli_sname; 577 else OS << d; 578 free(d); 579 580 OS << format(" + %tu", (static_cast<const char*>(StackTrace[i])- 581 static_cast<const char*>(dlinfo.dli_saddr))); 582 } 583 OS << '\n'; 584 } 585#elif defined(HAVE_BACKTRACE) 586 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO); 587#endif 588#endif 589} 590 591static void PrintStackTraceSignalHandler(void *) { 592 sys::PrintStackTrace(llvm::errs()); 593} 594 595void llvm::sys::DisableSystemDialogsOnCrash() {} 596 597/// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the 598/// process, print a stack trace and then exit. 599void llvm::sys::PrintStackTraceOnErrorSignal(StringRef Argv0, 600 bool DisableCrashReporting) { 601 ::Argv0 = Argv0; 602 603 AddSignalHandler(PrintStackTraceSignalHandler, nullptr); 604 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(); 609 610 exception_mask_t mask = EXC_MASK_CRASH; 611 612 kern_return_t ret = task_set_exception_ports(self, 613 mask, 614 MACH_PORT_NULL, 615 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES, 616 THREAD_STATE_NONE); 617 (void)ret; 618 } 619#endif 620} 621