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/UniqueLock.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. 83 84/// The function to call if ctrl-c is pressed. 85using InterruptFunctionType = void (*)(); 86static std::atomic<InterruptFunctionType> InterruptFunction = 87 ATOMIC_VAR_INIT(nullptr); 88 89namespace { 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. 94class FileToRemoveList { 95 std::atomic<char *> Filename = ATOMIC_VAR_INIT(nullptr); 96 std::atomic<FileToRemoveList *> Next = ATOMIC_VAR_INIT(nullptr); 97 98 FileToRemoveList() = default; 99 // Not signal-safe. 100 FileToRemoveList(const std::string &str) : Filename(strdup(str.c_str())) {} 101 102public: 103 // Not signal-safe. 104 ~FileToRemoveList() { 105 if (FileToRemoveList *N = Next.exchange(nullptr)) 106 delete N; 107 if (char *F = Filename.exchange(nullptr)) 108 free(F); 109 } 110 111 // Not signal-safe. 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; 120 OldHead = nullptr; 121 } 122 } 123 124 // Not signal-safe. 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 128 // free'd memory. 129 static ManagedStatic<sys::SmartMutex<true>> Lock; 130 sys::SmartScopedLock<true> Writer(*Lock); 131 132 for (FileToRemoveList *Current = Head.load(); Current; 133 Current = Current->Next.load()) { 134 if (char *OldFilename = Current->Filename.load()) { 135 if (OldFilename != Filename) 136 continue; 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. 141 if (OldFilename) 142 free(OldFilename); 143 } 144 } 145 } 146 147 // Signal-safe. 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); 154 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. 162 struct stat buf; 163 if (stat(path, &buf) != 0) 164 continue; 165 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)) 170 continue; 171 172 // Otherwise, remove the file. We ignore any errors here as there is 173 // nothing else we can do. 174 unlink(path); 175 176 // We're done removing the file, erasing can safely proceed. 177 currentFile->Filename.exchange(path); 178 } 179 } 180 181 // We're done removing files, cleanup can safely proceed. 182 Head.exchange(OldHead); 183 } 184}; 185static std::atomic<FileToRemoveList *> FilesToRemove = ATOMIC_VAR_INIT(nullptr); 186 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! 190struct FilesToRemoveCleanup { 191 // Not signal-safe. 192 ~FilesToRemoveCleanup() { 193 FileToRemoveList *Head = FilesToRemove.exchange(nullptr); 194 if (Head) 195 delete Head; 196 } 197}; 198} // namespace 199 200static StringRef Argv0; 201 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. 205static const int IntSigs[] = { 206 SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2 207}; 208 209// Signals that represent that we have a bug, and our prompt termination has 210// been ordered. 211static const int KillSigs[] = { 212 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT 213#ifdef SIGSYS 214 , SIGSYS 215#endif 216#ifdef SIGXCPU 217 , SIGXCPU 218#endif 219#ifdef SIGXFSZ 220 , SIGXFSZ 221#endif 222#ifdef SIGEMT 223 , SIGEMT 224#endif 225}; 226 227static std::atomic<unsigned> NumRegisteredSignals = ATOMIC_VAR_INIT(0); 228static struct { 229 struct sigaction SA; 230 int SigNo; 231} RegisteredSignalInfo[array_lengthof(IntSigs) + array_lengthof(KillSigs)]; 232 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. 238static stack_t OldAltStack; 239static void* NewAltStackPointer; 240 241static void CreateSigAltStack() { 242 const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024; 243 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 247 // than we do. 248 if (sigaltstack(nullptr, &OldAltStack) != 0 || 249 OldAltStack.ss_flags & SS_ONSTACK || 250 (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize)) 251 return; 252 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); 259} 260#else 261static void CreateSigAltStack() {} 262#endif 263 264static 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); 270 271 // If the handlers are already registered, we're done. 272 if (NumRegisteredSignals.load() != 0) 273 return; 274 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. 277 CreateSigAltStack(); 278 279 auto registerHandler = [&](int Signal) { 280 unsigned Index = NumRegisteredSignals.load(); 281 assert(Index < array_lengthof(RegisteredSignalInfo) && 282 "Out of space for signal handlers!"); 283 284 struct sigaction NewHandler; 285 286 NewHandler.sa_handler = SignalHandler; 287 NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK; 288 sigemptyset(&NewHandler.sa_mask); 289 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; 294 }; 295 296 for (auto S : IntSigs) 297 registerHandler(S); 298 for (auto S : KillSigs) 299 registerHandler(S); 300} 301 302static 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; 308 } 309} 310 311/// Process the FilesToRemove list. 312static void RemoveFilesToRemove() { 313 FileToRemoveList::removeAllFiles(FilesToRemove); 314} 315 316// The signal handler that runs. 317static 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(); 323 324 // Unmask all potentially blocked kill signals. 325 sigset_t SigMask; 326 sigfillset(&SigMask); 327 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr); 328 329 { 330 RemoveFilesToRemove(); 331 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(); 336 337 // Send a special return code that drivers can check for, from sysexits.h. 338 if (Sig == SIGPIPE) 339 exit(EX_IOERR); 340 341 raise(Sig); // Execute the default handler. 342 return; 343 } 344 } 345 346 // Otherwise if it is a fault (like SEGV) run any handler. 347 llvm::sys::RunSignalHandlers(); 348 349#ifdef __s390__ 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) 355 raise(Sig); 356#endif 357} 358 359void llvm::sys::RunInterruptHandlers() { 360 RemoveFilesToRemove(); 361} 362 363void llvm::sys::SetInterruptFunction(void (*IF)()) { 364 InterruptFunction.exchange(IF); 365 RegisterHandlers(); 366} 367 368// The public API 369bool 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()); 375 RegisterHandlers(); 376 return false; 377} 378 379// The public API 380void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) { 381 FileToRemoveList::erase(FilesToRemove, Filename.str()); 382} 383 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 386/// handler it is. 387void llvm::sys::AddSignalHandler(sys::SignalHandlerCallback FnPtr, 388 void *Cookie) { // Signal-safe. 389 insertSignalHandler(FnPtr, Cookie); 390 RegisterHandlers(); 391} 392 393#if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && HAVE_LINK_H && \ 394 (defined(__linux__) || defined(__FreeBSD__) || \ 395 defined(__FreeBSD_kernel__) || defined(__NetBSD__)) 396struct DlIteratePhdrData { 397 void **StackTrace; 398 int depth; 399 bool first; 400 const char **modules; 401 intptr_t *offsets; 402 const char *main_exec_name; 403}; 404 405static 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; 408 data->first = false; 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) 412 continue; 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]) 417 continue; 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; 422 } 423 } 424 } 425 return 0; 426} 427 428/// If this is an ELF platform, we can find all loaded modules and their virtual 429/// addresses with dl_iterate_phdr. 430static 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); 437 return true; 438} 439#else 440/// This platform does not have dl_iterate_phdr, so we do not yet know how to 441/// find all loaded DSOs. 442static bool findModulesAndOffsets(void **StackTrace, int Depth, 443 const char **Modules, intptr_t *Offsets, 444 const char *MainExecutableName, 445 StringSaver &StrPool) { 446 return false; 447} 448#endif // defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && ... 449 450#if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE) 451static int unwindBacktrace(void **StackTrace, int MaxEntries) { 452 if (MaxEntries < 0) 453 return 0; 454 455 // Skip the first frame ('unwindBacktrace' itself). 456 int Entries = -1; 457 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); 461 if (!IP) 462 return _URC_END_OF_STACK; 463 464 assert(Entries < MaxEntries && "recursively called after END_OF_STACK?"); 465 if (Entries >= 0) 466 StackTrace[Entries] = IP; 467 468 if (++Entries == MaxEntries) 469 return _URC_END_OF_STACK; 470 return _URC_NO_REASON; 471 }; 472 473 _Unwind_Backtrace( 474 [](_Unwind_Context *Context, void *Handler) { 475 return (*static_cast<decltype(HandleFrame) *>(Handler))(Context); 476 }, 477 static_cast<void *>(&HandleFrame)); 478 return std::max(Entries, 0); 479} 480#endif 481 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. 484// 485// On glibc systems we have the 'backtrace' function, which works nicely, but 486// doesn't demangle symbols. 487void llvm::sys::PrintStackTrace(raw_ostream &OS) { 488#if ENABLE_BACKTRACES 489 static void *StackTrace[256]; 490 int depth = 0; 491#if defined(HAVE_BACKTRACE) 492 // Use backtrace() to output a backtrace on Linux systems with glibc. 493 if (!depth) 494 depth = backtrace(StackTrace, static_cast<int>(array_lengthof(StackTrace))); 495#endif 496#if defined(HAVE__UNWIND_BACKTRACE) 497 // Try _Unwind_Backtrace() if backtrace() failed. 498 if (!depth) 499 depth = unwindBacktrace(StackTrace, 500 static_cast<int>(array_lengthof(StackTrace))); 501#endif 502 if (!depth) 503 return; 504 505 if (printSymbolizedStackTrace(Argv0, StackTrace, depth, OS)) 506 return; 507#if HAVE_DLFCN_H && HAVE_DLADDR 508 int width = 0; 509 for (int i = 0; i < depth; ++i) { 510 Dl_info dlinfo; 511 dladdr(StackTrace[i], &dlinfo); 512 const char* name = strrchr(dlinfo.dli_fname, '/'); 513 514 int nwidth; 515 if (!name) nwidth = strlen(dlinfo.dli_fname); 516 else nwidth = strlen(name) - 1; 517 518 if (nwidth > width) width = nwidth; 519 } 520 521 for (int i = 0; i < depth; ++i) { 522 Dl_info dlinfo; 523 dladdr(StackTrace[i], &dlinfo); 524 525 OS << format("%-2d", i); 526 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); 530 531 OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2, 532 (unsigned long)StackTrace[i]); 533 534 if (dlinfo.dli_sname != nullptr) { 535 OS << ' '; 536 int res; 537 char* d = itaniumDemangle(dlinfo.dli_sname, nullptr, nullptr, &res); 538 if (!d) OS << dlinfo.dli_sname; 539 else OS << d; 540 free(d); 541 542 OS << format(" + %tu", (static_cast<const char*>(StackTrace[i])- 543 static_cast<const char*>(dlinfo.dli_saddr))); 544 } 545 OS << '\n'; 546 } 547#elif defined(HAVE_BACKTRACE) 548 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO); 549#endif 550#endif 551} 552 553static void PrintStackTraceSignalHandler(void *) { 554 sys::PrintStackTrace(llvm::errs()); 555} 556 557void llvm::sys::DisableSystemDialogsOnCrash() {} 558 559/// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the 560/// process, print a stack trace and then exit. 561void llvm::sys::PrintStackTraceOnErrorSignal(StringRef Argv0, 562 bool DisableCrashReporting) { 563 ::Argv0 = Argv0; 564 565 AddSignalHandler(PrintStackTraceSignalHandler, nullptr); 566 567#if defined(__APPLE__) && ENABLE_CRASH_OVERRIDES 568 // Environment variable to disable any kind of crash dialog. 569 if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) { 570 mach_port_t self = mach_task_self(); 571 572 exception_mask_t mask = EXC_MASK_CRASH; 573 574 kern_return_t ret = task_set_exception_ports(self, 575 mask, 576 MACH_PORT_NULL, 577 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES, 578 THREAD_STATE_NONE); 579 (void)ret; 580 } 581#endif 582} 583