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 85static void DefaultPipeSignalFunction() { 86 exit(EX_IOERR); 87} 88 89using SignalHandlerFunctionType = void (*)(); 90/// The function to call if ctrl-c is pressed. 91static std::atomic<SignalHandlerFunctionType> InterruptFunction = 92 ATOMIC_VAR_INIT(nullptr); 93static std::atomic<SignalHandlerFunctionType> InfoSignalFunction = 94 ATOMIC_VAR_INIT(nullptr); 95static std::atomic<SignalHandlerFunctionType> PipeSignalFunction = 96 ATOMIC_VAR_INIT(DefaultPipeSignalFunction); 97 98namespace { 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. 103class FileToRemoveList { 104 std::atomic<char *> Filename = ATOMIC_VAR_INIT(nullptr); 105 std::atomic<FileToRemoveList *> Next = ATOMIC_VAR_INIT(nullptr); 106 107 FileToRemoveList() = default; 108 // Not signal-safe. 109 FileToRemoveList(const std::string &str) : Filename(strdup(str.c_str())) {} 110 111public: 112 // Not signal-safe. 113 ~FileToRemoveList() { 114 if (FileToRemoveList *N = Next.exchange(nullptr)) 115 delete N; 116 if (char *F = Filename.exchange(nullptr)) 117 free(F); 118 } 119 120 // Not signal-safe. 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; 129 OldHead = nullptr; 130 } 131 } 132 133 // Not signal-safe. 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 137 // free'd memory. 138 static ManagedStatic<sys::SmartMutex<true>> Lock; 139 sys::SmartScopedLock<true> Writer(*Lock); 140 141 for (FileToRemoveList *Current = Head.load(); Current; 142 Current = Current->Next.load()) { 143 if (char *OldFilename = Current->Filename.load()) { 144 if (OldFilename != Filename) 145 continue; 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. 150 if (OldFilename) 151 free(OldFilename); 152 } 153 } 154 } 155 156 // Signal-safe. 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); 163 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. 171 struct stat buf; 172 if (stat(path, &buf) != 0) 173 continue; 174 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)) 179 continue; 180 181 // Otherwise, remove the file. We ignore any errors here as there is 182 // nothing else we can do. 183 unlink(path); 184 185 // We're done removing the file, erasing can safely proceed. 186 currentFile->Filename.exchange(path); 187 } 188 } 189 190 // We're done removing files, cleanup can safely proceed. 191 Head.exchange(OldHead); 192 } 193}; 194static std::atomic<FileToRemoveList *> FilesToRemove = ATOMIC_VAR_INIT(nullptr); 195 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! 199struct FilesToRemoveCleanup { 200 // Not signal-safe. 201 ~FilesToRemoveCleanup() { 202 FileToRemoveList *Head = FilesToRemove.exchange(nullptr); 203 if (Head) 204 delete Head; 205 } 206}; 207} // namespace 208 209static StringRef Argv0; 210 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. 214static const int IntSigs[] = { 215 SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR2 216}; 217 218/// Signals that represent that we have a bug, and our prompt termination has 219/// been ordered. 220static const int KillSigs[] = { 221 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT 222#ifdef SIGSYS 223 , SIGSYS 224#endif 225#ifdef SIGXCPU 226 , SIGXCPU 227#endif 228#ifdef SIGXFSZ 229 , SIGXFSZ 230#endif 231#ifdef SIGEMT 232 , SIGEMT 233#endif 234}; 235 236/// Signals that represent requests for status. 237static const int InfoSigs[] = { 238 SIGUSR1 239#ifdef SIGINFO 240 , SIGINFO 241#endif 242}; 243 244static const size_t NumSigs = 245 array_lengthof(IntSigs) + array_lengthof(KillSigs) + 246 array_lengthof(InfoSigs); 247 248 249static std::atomic<unsigned> NumRegisteredSignals = ATOMIC_VAR_INIT(0); 250static struct { 251 struct sigaction SA; 252 int SigNo; 253} RegisteredSignalInfo[NumSigs]; 254 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. 260static stack_t OldAltStack; 261static void* NewAltStackPointer; 262 263static void CreateSigAltStack() { 264 const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024; 265 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 269 // than we do. 270 if (sigaltstack(nullptr, &OldAltStack) != 0 || 271 OldAltStack.ss_flags & SS_ONSTACK || 272 (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize)) 273 return; 274 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); 281} 282#else 283static void CreateSigAltStack() {} 284#endif 285 286static 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); 292 293 // If the handlers are already registered, we're done. 294 if (NumRegisteredSignals.load() != 0) 295 return; 296 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. 299 CreateSigAltStack(); 300 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!"); 306 307 struct sigaction NewHandler; 308 309 switch (Kind) { 310 case SignalKind::IsKill: 311 NewHandler.sa_handler = SignalHandler; 312 NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK; 313 break; 314 case SignalKind::IsInfo: 315 NewHandler.sa_handler = InfoSignalHandler; 316 NewHandler.sa_flags = SA_ONSTACK; 317 break; 318 } 319 sigemptyset(&NewHandler.sa_mask); 320 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; 325 }; 326 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); 333} 334 335static 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; 341 } 342} 343 344/// Process the FilesToRemove list. 345static void RemoveFilesToRemove() { 346 FileToRemoveList::removeAllFiles(FilesToRemove); 347} 348 349// The signal handler that runs. 350static 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(); 356 357 // Unmask all potentially blocked kill signals. 358 sigset_t SigMask; 359 sigfillset(&SigMask); 360 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr); 361 362 { 363 RemoveFilesToRemove(); 364 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(); 369 370 // Send a special return code that drivers can check for, from sysexits.h. 371 if (Sig == SIGPIPE) 372 if (SignalHandlerFunctionType CurrentPipeFunction = PipeSignalFunction) 373 CurrentPipeFunction(); 374 375 raise(Sig); // Execute the default handler. 376 return; 377 } 378 } 379 380 // Otherwise if it is a fault (like SEGV) run any handler. 381 llvm::sys::RunSignalHandlers(); 382 383#ifdef __s390__ 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) 389 raise(Sig); 390#endif 391} 392 393static RETSIGTYPE InfoSignalHandler(int Sig) { 394 SaveAndRestore<int> SaveErrnoDuringASignalHandler(errno); 395 if (SignalHandlerFunctionType CurrentInfoFunction = InfoSignalFunction) 396 CurrentInfoFunction(); 397} 398 399void llvm::sys::RunInterruptHandlers() { 400 RemoveFilesToRemove(); 401} 402 403void llvm::sys::SetInterruptFunction(void (*IF)()) { 404 InterruptFunction.exchange(IF); 405 RegisterHandlers(); 406} 407 408void llvm::sys::SetInfoSignalFunction(void (*Handler)()) { 409 InfoSignalFunction.exchange(Handler); 410 RegisterHandlers(); 411} 412 413void llvm::sys::SetPipeSignalFunction(void (*Handler)()) { 414 PipeSignalFunction.exchange(Handler); 415 RegisterHandlers(); 416} 417 418// The public API 419bool 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()); 425 RegisterHandlers(); 426 return false; 427} 428 429// The public API 430void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) { 431 FileToRemoveList::erase(FilesToRemove, Filename.str()); 432} 433 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 436/// handler it is. 437void llvm::sys::AddSignalHandler(sys::SignalHandlerCallback FnPtr, 438 void *Cookie) { // Signal-safe. 439 insertSignalHandler(FnPtr, Cookie); 440 RegisterHandlers(); 441} 442 443#if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && HAVE_LINK_H && \ 444 (defined(__linux__) || defined(__FreeBSD__) || \ 445 defined(__FreeBSD_kernel__) || defined(__NetBSD__)) 446struct DlIteratePhdrData { 447 void **StackTrace; 448 int depth; 449 bool first; 450 const char **modules; 451 intptr_t *offsets; 452 const char *main_exec_name; 453}; 454 455static 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; 458 data->first = false; 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) 462 continue; 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]) 467 continue; 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; 472 } 473 } 474 } 475 return 0; 476} 477 478/// If this is an ELF platform, we can find all loaded modules and their virtual 479/// addresses with dl_iterate_phdr. 480static 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); 487 return true; 488} 489#else 490/// This platform does not have dl_iterate_phdr, so we do not yet know how to 491/// find all loaded DSOs. 492static bool findModulesAndOffsets(void **StackTrace, int Depth, 493 const char **Modules, intptr_t *Offsets, 494 const char *MainExecutableName, 495 StringSaver &StrPool) { 496 return false; 497} 498#endif // defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && ... 499 500#if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE) 501static int unwindBacktrace(void **StackTrace, int MaxEntries) { 502 if (MaxEntries < 0) 503 return 0; 504 505 // Skip the first frame ('unwindBacktrace' itself). 506 int Entries = -1; 507 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); 511 if (!IP) 512 return _URC_END_OF_STACK; 513 514 assert(Entries < MaxEntries && "recursively called after END_OF_STACK?"); 515 if (Entries >= 0) 516 StackTrace[Entries] = IP; 517 518 if (++Entries == MaxEntries) 519 return _URC_END_OF_STACK; 520 return _URC_NO_REASON; 521 }; 522 523 _Unwind_Backtrace( 524 [](_Unwind_Context *Context, void *Handler) { 525 return (*static_cast<decltype(HandleFrame) *>(Handler))(Context); 526 }, 527 static_cast<void *>(&HandleFrame)); 528 return std::max(Entries, 0); 529} 530#endif 531 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. 534// 535// On glibc systems we have the 'backtrace' function, which works nicely, but 536// doesn't demangle symbols. 537void llvm::sys::PrintStackTrace(raw_ostream &OS) { 538#if ENABLE_BACKTRACES 539 static void *StackTrace[256]; 540 int depth = 0; 541#if defined(HAVE_BACKTRACE) 542 // Use backtrace() to output a backtrace on Linux systems with glibc. 543 if (!depth) 544 depth = backtrace(StackTrace, static_cast<int>(array_lengthof(StackTrace))); 545#endif 546#if defined(HAVE__UNWIND_BACKTRACE) 547 // Try _Unwind_Backtrace() if backtrace() failed. 548 if (!depth) 549 depth = unwindBacktrace(StackTrace, 550 static_cast<int>(array_lengthof(StackTrace))); 551#endif 552 if (!depth) 553 return; 554 555 if (printSymbolizedStackTrace(Argv0, StackTrace, depth, OS)) 556 return; 557#if HAVE_DLFCN_H && HAVE_DLADDR 558 int width = 0; 559 for (int i = 0; i < depth; ++i) { 560 Dl_info dlinfo; 561 dladdr(StackTrace[i], &dlinfo); 562 const char* name = strrchr(dlinfo.dli_fname, '/'); 563 564 int nwidth; 565 if (!name) nwidth = strlen(dlinfo.dli_fname); 566 else nwidth = strlen(name) - 1; 567 568 if (nwidth > width) width = nwidth; 569 } 570 571 for (int i = 0; i < depth; ++i) { 572 Dl_info dlinfo; 573 dladdr(StackTrace[i], &dlinfo); 574 575 OS << format("%-2d", i); 576 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); 580 581 OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2, 582 (unsigned long)StackTrace[i]); 583 584 if (dlinfo.dli_sname != nullptr) { 585 OS << ' '; 586 int res; 587 char* d = itaniumDemangle(dlinfo.dli_sname, nullptr, nullptr, &res); 588 if (!d) OS << dlinfo.dli_sname; 589 else OS << d; 590 free(d); 591 592 OS << format(" + %tu", (static_cast<const char*>(StackTrace[i])- 593 static_cast<const char*>(dlinfo.dli_saddr))); 594 } 595 OS << '\n'; 596 } 597#elif defined(HAVE_BACKTRACE) 598 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO); 599#endif 600#endif 601} 602 603static void PrintStackTraceSignalHandler(void *) { 604 sys::PrintStackTrace(llvm::errs()); 605} 606 607void llvm::sys::DisableSystemDialogsOnCrash() {} 608 609/// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the 610/// process, print a stack trace and then exit. 611void llvm::sys::PrintStackTraceOnErrorSignal(StringRef Argv0, 612 bool DisableCrashReporting) { 613 ::Argv0 = Argv0; 614 615 AddSignalHandler(PrintStackTraceSignalHandler, nullptr); 616 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(); 621 622 exception_mask_t mask = EXC_MASK_CRASH; 623 624 kern_return_t ret = task_set_exception_ports(self, 625 mask, 626 MACH_PORT_NULL, 627 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES, 628 THREAD_STATE_NONE); 629 (void)ret; 630 } 631#endif 632} 633