1//===- Signals.cpp - Generic Unix Signals Implementation -----*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines some helpful functions for dealing with the possibility of 11// Unix signals occurring while your program is running. 12// 13//===----------------------------------------------------------------------===// 14 15#include "Unix.h" 16#include "llvm/ADT/STLExtras.h" 17#include "llvm/Demangle/Demangle.h" 18#include "llvm/Support/FileSystem.h" 19#include "llvm/Support/FileUtilities.h" 20#include "llvm/Support/Format.h" 21#include "llvm/Support/MemoryBuffer.h" 22#include "llvm/Support/Mutex.h" 23#include "llvm/Support/Program.h" 24#include "llvm/Support/UniqueLock.h" 25#include "llvm/Support/raw_ostream.h" 26#include <algorithm> 27#include <string> 28#ifdef HAVE_BACKTRACE 29# include BACKTRACE_HEADER // For backtrace(). 30#endif 31#if HAVE_SIGNAL_H 32#include <signal.h> 33#endif 34#if HAVE_SYS_STAT_H 35#include <sys/stat.h> 36#endif 37#if HAVE_DLFCN_H 38#include <dlfcn.h> 39#endif 40#if HAVE_MACH_MACH_H 41#include <mach/mach.h> 42#endif 43#if HAVE_LINK_H 44#include <link.h> 45#endif 46#ifdef HAVE__UNWIND_BACKTRACE 47// FIXME: We should be able to use <unwind.h> for any target that has an 48// _Unwind_Backtrace function, but on FreeBSD the configure test passes 49// despite the function not existing, and on Android, <unwind.h> conflicts 50// with <link.h>. 51#ifdef __GLIBC__ 52#include <unwind.h> 53#else 54#undef HAVE__UNWIND_BACKTRACE 55#endif 56#endif 57 58using namespace llvm; 59 60static RETSIGTYPE SignalHandler(int Sig); // defined below. 61 62static ManagedStatic<sys::SmartMutex<true> > SignalsMutex; 63 64/// InterruptFunction - The function to call if ctrl-c is pressed. 65static void (*InterruptFunction)() = nullptr; 66 67static ManagedStatic<std::vector<std::string>> FilesToRemove; 68 69static StringRef Argv0; 70 71// IntSigs - Signals that represent requested termination. There's no bug 72// or failure, or if there is, it's not our direct responsibility. For whatever 73// reason, our continued execution is no longer desirable. 74static const int IntSigs[] = { 75 SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2 76}; 77 78// KillSigs - Signals that represent that we have a bug, and our prompt 79// termination has been ordered. 80static const int KillSigs[] = { 81 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT 82#ifdef SIGSYS 83 , SIGSYS 84#endif 85#ifdef SIGXCPU 86 , SIGXCPU 87#endif 88#ifdef SIGXFSZ 89 , SIGXFSZ 90#endif 91#ifdef SIGEMT 92 , SIGEMT 93#endif 94}; 95 96static unsigned NumRegisteredSignals = 0; 97static struct { 98 struct sigaction SA; 99 int SigNo; 100} RegisteredSignalInfo[array_lengthof(IntSigs) + array_lengthof(KillSigs)]; 101 102 103static void RegisterHandler(int Signal) { 104 assert(NumRegisteredSignals < array_lengthof(RegisteredSignalInfo) && 105 "Out of space for signal handlers!"); 106 107 struct sigaction NewHandler; 108 109 NewHandler.sa_handler = SignalHandler; 110 NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK; 111 sigemptyset(&NewHandler.sa_mask); 112 113 // Install the new handler, save the old one in RegisteredSignalInfo. 114 sigaction(Signal, &NewHandler, 115 &RegisteredSignalInfo[NumRegisteredSignals].SA); 116 RegisteredSignalInfo[NumRegisteredSignals].SigNo = Signal; 117 ++NumRegisteredSignals; 118} 119 120#if defined(HAVE_SIGALTSTACK) 121// Hold onto both the old and new alternate signal stack so that it's not 122// reported as a leak. We don't make any attempt to remove our alt signal 123// stack if we remove our signal handlers; that can't be done reliably if 124// someone else is also trying to do the same thing. 125static stack_t OldAltStack; 126static void* NewAltStackPointer; 127 128static void CreateSigAltStack() { 129 const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024; 130 131 // If we're executing on the alternate stack, or we already have an alternate 132 // signal stack that we're happy with, there's nothing for us to do. Don't 133 // reduce the size, some other part of the process might need a larger stack 134 // than we do. 135 if (sigaltstack(nullptr, &OldAltStack) != 0 || 136 OldAltStack.ss_flags & SS_ONSTACK || 137 (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize)) 138 return; 139 140 stack_t AltStack = {}; 141 AltStack.ss_sp = reinterpret_cast<char *>(malloc(AltStackSize)); 142 NewAltStackPointer = AltStack.ss_sp; // Save to avoid reporting a leak. 143 AltStack.ss_size = AltStackSize; 144 if (sigaltstack(&AltStack, &OldAltStack) != 0) 145 free(AltStack.ss_sp); 146} 147#else 148static void CreateSigAltStack() {} 149#endif 150 151static void RegisterHandlers() { 152 sys::SmartScopedLock<true> Guard(*SignalsMutex); 153 154 // If the handlers are already registered, we're done. 155 if (NumRegisteredSignals != 0) return; 156 157 // Create an alternate stack for signal handling. This is necessary for us to 158 // be able to reliably handle signals due to stack overflow. 159 CreateSigAltStack(); 160 161 for (auto S : IntSigs) RegisterHandler(S); 162 for (auto S : KillSigs) RegisterHandler(S); 163} 164 165static void UnregisterHandlers() { 166 // Restore all of the signal handlers to how they were before we showed up. 167 for (unsigned i = 0, e = NumRegisteredSignals; i != e; ++i) 168 sigaction(RegisteredSignalInfo[i].SigNo, 169 &RegisteredSignalInfo[i].SA, nullptr); 170 NumRegisteredSignals = 0; 171} 172 173 174/// RemoveFilesToRemove - Process the FilesToRemove list. This function 175/// should be called with the SignalsMutex lock held. 176/// NB: This must be an async signal safe function. It cannot allocate or free 177/// memory, even in debug builds. 178static void RemoveFilesToRemove() { 179 // Avoid constructing ManagedStatic in the signal handler. 180 // If FilesToRemove is not constructed, there are no files to remove. 181 if (!FilesToRemove.isConstructed()) 182 return; 183 184 // We avoid iterators in case of debug iterators that allocate or release 185 // memory. 186 std::vector<std::string>& FilesToRemoveRef = *FilesToRemove; 187 for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i) { 188 const char *path = FilesToRemoveRef[i].c_str(); 189 190 // Get the status so we can determine if it's a file or directory. If we 191 // can't stat the file, ignore it. 192 struct stat buf; 193 if (stat(path, &buf) != 0) 194 continue; 195 196 // If this is not a regular file, ignore it. We want to prevent removal of 197 // special files like /dev/null, even if the compiler is being run with the 198 // super-user permissions. 199 if (!S_ISREG(buf.st_mode)) 200 continue; 201 202 // Otherwise, remove the file. We ignore any errors here as there is nothing 203 // else we can do. 204 unlink(path); 205 } 206} 207 208// SignalHandler - The signal handler that runs. 209static RETSIGTYPE SignalHandler(int Sig) { 210 // Restore the signal behavior to default, so that the program actually 211 // crashes when we return and the signal reissues. This also ensures that if 212 // we crash in our signal handler that the program will terminate immediately 213 // instead of recursing in the signal handler. 214 UnregisterHandlers(); 215 216 // Unmask all potentially blocked kill signals. 217 sigset_t SigMask; 218 sigfillset(&SigMask); 219 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr); 220 221 { 222 unique_lock<sys::SmartMutex<true>> Guard(*SignalsMutex); 223 RemoveFilesToRemove(); 224 225 if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig) 226 != std::end(IntSigs)) { 227 if (InterruptFunction) { 228 void (*IF)() = InterruptFunction; 229 Guard.unlock(); 230 InterruptFunction = nullptr; 231 IF(); // run the interrupt function. 232 return; 233 } 234 235 Guard.unlock(); 236 raise(Sig); // Execute the default handler. 237 return; 238 } 239 } 240 241 // Otherwise if it is a fault (like SEGV) run any handler. 242 llvm::sys::RunSignalHandlers(); 243 244#ifdef __s390__ 245 // On S/390, certain signals are delivered with PSW Address pointing to 246 // *after* the faulting instruction. Simply returning from the signal 247 // handler would continue execution after that point, instead of 248 // re-raising the signal. Raise the signal manually in those cases. 249 if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP) 250 raise(Sig); 251#endif 252} 253 254void llvm::sys::RunInterruptHandlers() { 255 sys::SmartScopedLock<true> Guard(*SignalsMutex); 256 RemoveFilesToRemove(); 257} 258 259void llvm::sys::SetInterruptFunction(void (*IF)()) { 260 { 261 sys::SmartScopedLock<true> Guard(*SignalsMutex); 262 InterruptFunction = IF; 263 } 264 RegisterHandlers(); 265} 266 267// RemoveFileOnSignal - The public API 268bool llvm::sys::RemoveFileOnSignal(StringRef Filename, 269 std::string* ErrMsg) { 270 { 271 sys::SmartScopedLock<true> Guard(*SignalsMutex); 272 FilesToRemove->push_back(Filename); 273 } 274 275 RegisterHandlers(); 276 return false; 277} 278 279// DontRemoveFileOnSignal - The public API 280void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) { 281 sys::SmartScopedLock<true> Guard(*SignalsMutex); 282 std::vector<std::string>::reverse_iterator RI = 283 find(reverse(*FilesToRemove), Filename); 284 std::vector<std::string>::iterator I = FilesToRemove->end(); 285 if (RI != FilesToRemove->rend()) 286 I = FilesToRemove->erase(RI.base()-1); 287} 288 289/// AddSignalHandler - Add a function to be called when a signal is delivered 290/// to the process. The handler can have a cookie passed to it to identify 291/// what instance of the handler it is. 292void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) { 293 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie)); 294 RegisterHandlers(); 295} 296 297#if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && HAVE_LINK_H && \ 298 (defined(__linux__) || defined(__FreeBSD__) || \ 299 defined(__FreeBSD_kernel__) || defined(__NetBSD__)) 300struct DlIteratePhdrData { 301 void **StackTrace; 302 int depth; 303 bool first; 304 const char **modules; 305 intptr_t *offsets; 306 const char *main_exec_name; 307}; 308 309static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) { 310 DlIteratePhdrData *data = (DlIteratePhdrData*)arg; 311 const char *name = data->first ? data->main_exec_name : info->dlpi_name; 312 data->first = false; 313 for (int i = 0; i < info->dlpi_phnum; i++) { 314 const auto *phdr = &info->dlpi_phdr[i]; 315 if (phdr->p_type != PT_LOAD) 316 continue; 317 intptr_t beg = info->dlpi_addr + phdr->p_vaddr; 318 intptr_t end = beg + phdr->p_memsz; 319 for (int j = 0; j < data->depth; j++) { 320 if (data->modules[j]) 321 continue; 322 intptr_t addr = (intptr_t)data->StackTrace[j]; 323 if (beg <= addr && addr < end) { 324 data->modules[j] = name; 325 data->offsets[j] = addr - info->dlpi_addr; 326 } 327 } 328 } 329 return 0; 330} 331 332/// If this is an ELF platform, we can find all loaded modules and their virtual 333/// addresses with dl_iterate_phdr. 334static bool findModulesAndOffsets(void **StackTrace, int Depth, 335 const char **Modules, intptr_t *Offsets, 336 const char *MainExecutableName, 337 StringSaver &StrPool) { 338 DlIteratePhdrData data = {StackTrace, Depth, true, 339 Modules, Offsets, MainExecutableName}; 340 dl_iterate_phdr(dl_iterate_phdr_cb, &data); 341 return true; 342} 343#else 344/// This platform does not have dl_iterate_phdr, so we do not yet know how to 345/// find all loaded DSOs. 346static bool findModulesAndOffsets(void **StackTrace, int Depth, 347 const char **Modules, intptr_t *Offsets, 348 const char *MainExecutableName, 349 StringSaver &StrPool) { 350 return false; 351} 352#endif // defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && ... 353 354#if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE) 355static int unwindBacktrace(void **StackTrace, int MaxEntries) { 356 if (MaxEntries < 0) 357 return 0; 358 359 // Skip the first frame ('unwindBacktrace' itself). 360 int Entries = -1; 361 362 auto HandleFrame = [&](_Unwind_Context *Context) -> _Unwind_Reason_Code { 363 // Apparently we need to detect reaching the end of the stack ourselves. 364 void *IP = (void *)_Unwind_GetIP(Context); 365 if (!IP) 366 return _URC_END_OF_STACK; 367 368 assert(Entries < MaxEntries && "recursively called after END_OF_STACK?"); 369 if (Entries >= 0) 370 StackTrace[Entries] = IP; 371 372 if (++Entries == MaxEntries) 373 return _URC_END_OF_STACK; 374 return _URC_NO_REASON; 375 }; 376 377 _Unwind_Backtrace( 378 [](_Unwind_Context *Context, void *Handler) { 379 return (*static_cast<decltype(HandleFrame) *>(Handler))(Context); 380 }, 381 static_cast<void *>(&HandleFrame)); 382 return std::max(Entries, 0); 383} 384#endif 385 386// PrintStackTrace - In the case of a program crash or fault, print out a stack 387// trace so that the user has an indication of why and where we died. 388// 389// On glibc systems we have the 'backtrace' function, which works nicely, but 390// doesn't demangle symbols. 391void llvm::sys::PrintStackTrace(raw_ostream &OS) { 392#if ENABLE_BACKTRACES 393 static void *StackTrace[256]; 394 int depth = 0; 395#if defined(HAVE_BACKTRACE) 396 // Use backtrace() to output a backtrace on Linux systems with glibc. 397 if (!depth) 398 depth = backtrace(StackTrace, static_cast<int>(array_lengthof(StackTrace))); 399#endif 400#if defined(HAVE__UNWIND_BACKTRACE) 401 // Try _Unwind_Backtrace() if backtrace() failed. 402 if (!depth) 403 depth = unwindBacktrace(StackTrace, 404 static_cast<int>(array_lengthof(StackTrace))); 405#endif 406 if (!depth) 407 return; 408 409 if (printSymbolizedStackTrace(Argv0, StackTrace, depth, OS)) 410 return; 411#if HAVE_DLFCN_H && HAVE_DLADDR 412 int width = 0; 413 for (int i = 0; i < depth; ++i) { 414 Dl_info dlinfo; 415 dladdr(StackTrace[i], &dlinfo); 416 const char* name = strrchr(dlinfo.dli_fname, '/'); 417 418 int nwidth; 419 if (!name) nwidth = strlen(dlinfo.dli_fname); 420 else nwidth = strlen(name) - 1; 421 422 if (nwidth > width) width = nwidth; 423 } 424 425 for (int i = 0; i < depth; ++i) { 426 Dl_info dlinfo; 427 dladdr(StackTrace[i], &dlinfo); 428 429 OS << format("%-2d", i); 430 431 const char* name = strrchr(dlinfo.dli_fname, '/'); 432 if (!name) OS << format(" %-*s", width, dlinfo.dli_fname); 433 else OS << format(" %-*s", width, name+1); 434 435 OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2, 436 (unsigned long)StackTrace[i]); 437 438 if (dlinfo.dli_sname != nullptr) { 439 OS << ' '; 440 int res; 441 char* d = itaniumDemangle(dlinfo.dli_sname, nullptr, nullptr, &res); 442 if (!d) OS << dlinfo.dli_sname; 443 else OS << d; 444 free(d); 445 446 // FIXME: When we move to C++11, use %t length modifier. It's not in 447 // C++03 and causes gcc to issue warnings. Losing the upper 32 bits of 448 // the stack offset for a stack dump isn't likely to cause any problems. 449 OS << format(" + %u",(unsigned)((char*)StackTrace[i]- 450 (char*)dlinfo.dli_saddr)); 451 } 452 OS << '\n'; 453 } 454#elif defined(HAVE_BACKTRACE) 455 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO); 456#endif 457#endif 458} 459 460static void PrintStackTraceSignalHandler(void *) { 461 sys::PrintStackTrace(llvm::errs()); 462} 463 464void llvm::sys::DisableSystemDialogsOnCrash() {} 465 466/// PrintStackTraceOnErrorSignal - When an error signal (such as SIGABRT or 467/// SIGSEGV) is delivered to the process, print a stack trace and then exit. 468void llvm::sys::PrintStackTraceOnErrorSignal(StringRef Argv0, 469 bool DisableCrashReporting) { 470 ::Argv0 = Argv0; 471 472 AddSignalHandler(PrintStackTraceSignalHandler, nullptr); 473 474#if defined(__APPLE__) && ENABLE_CRASH_OVERRIDES 475 // Environment variable to disable any kind of crash dialog. 476 if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) { 477 mach_port_t self = mach_task_self(); 478 479 exception_mask_t mask = EXC_MASK_CRASH; 480 481 kern_return_t ret = task_set_exception_ports(self, 482 mask, 483 MACH_PORT_NULL, 484 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES, 485 THREAD_STATE_NONE); 486 (void)ret; 487 } 488#endif 489} 490