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/Support/Format.h" 18#include "llvm/Support/FileSystem.h" 19#include "llvm/Support/FileUtilities.h" 20#include "llvm/Support/ManagedStatic.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#include <vector> 29#if HAVE_EXECINFO_H 30# include <execinfo.h> // For backtrace(). 31#endif 32#if HAVE_SIGNAL_H 33#include <signal.h> 34#endif 35#if HAVE_SYS_STAT_H 36#include <sys/stat.h> 37#endif 38#if HAVE_CXXABI_H 39#include <cxxabi.h> 40#endif 41#if HAVE_DLFCN_H 42#include <dlfcn.h> 43#endif 44#if HAVE_MACH_MACH_H 45#include <mach/mach.h> 46#endif 47#if HAVE_LINK_H 48#include <link.h> 49#endif 50 51using namespace llvm; 52 53static RETSIGTYPE SignalHandler(int Sig); // defined below. 54 55static ManagedStatic<SmartMutex<true> > SignalsMutex; 56 57/// InterruptFunction - The function to call if ctrl-c is pressed. 58static void (*InterruptFunction)() = nullptr; 59 60static ManagedStatic<std::vector<std::string>> FilesToRemove; 61static ManagedStatic<std::vector<std::pair<void (*)(void *), void *>>> 62 CallBacksToRun; 63 64// IntSigs - Signals that represent requested termination. There's no bug 65// or failure, or if there is, it's not our direct responsibility. For whatever 66// reason, our continued execution is no longer desirable. 67static const int IntSigs[] = { 68 SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2 69}; 70 71// KillSigs - Signals that represent that we have a bug, and our prompt 72// termination has been ordered. 73static const int KillSigs[] = { 74 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT 75#ifdef SIGSYS 76 , SIGSYS 77#endif 78#ifdef SIGXCPU 79 , SIGXCPU 80#endif 81#ifdef SIGXFSZ 82 , SIGXFSZ 83#endif 84#ifdef SIGEMT 85 , SIGEMT 86#endif 87}; 88 89static unsigned NumRegisteredSignals = 0; 90static struct { 91 struct sigaction SA; 92 int SigNo; 93} RegisteredSignalInfo[(sizeof(IntSigs)+sizeof(KillSigs))/sizeof(KillSigs[0])]; 94 95 96static void RegisterHandler(int Signal) { 97 assert(NumRegisteredSignals < 98 sizeof(RegisteredSignalInfo)/sizeof(RegisteredSignalInfo[0]) && 99 "Out of space for signal handlers!"); 100 101 struct sigaction NewHandler; 102 103 NewHandler.sa_handler = SignalHandler; 104 NewHandler.sa_flags = SA_NODEFER|SA_RESETHAND; 105 sigemptyset(&NewHandler.sa_mask); 106 107 // Install the new handler, save the old one in RegisteredSignalInfo. 108 sigaction(Signal, &NewHandler, 109 &RegisteredSignalInfo[NumRegisteredSignals].SA); 110 RegisteredSignalInfo[NumRegisteredSignals].SigNo = Signal; 111 ++NumRegisteredSignals; 112} 113 114static void RegisterHandlers() { 115 // We need to dereference the signals mutex during handler registration so 116 // that we force its construction. This is to prevent the first use being 117 // during handling an actual signal because you can't safely call new in a 118 // signal handler. 119 *SignalsMutex; 120 121 // If the handlers are already registered, we're done. 122 if (NumRegisteredSignals != 0) return; 123 124 for (auto S : IntSigs) RegisterHandler(S); 125 for (auto S : KillSigs) RegisterHandler(S); 126} 127 128static void UnregisterHandlers() { 129 // Restore all of the signal handlers to how they were before we showed up. 130 for (unsigned i = 0, e = NumRegisteredSignals; i != e; ++i) 131 sigaction(RegisteredSignalInfo[i].SigNo, 132 &RegisteredSignalInfo[i].SA, nullptr); 133 NumRegisteredSignals = 0; 134} 135 136 137/// RemoveFilesToRemove - Process the FilesToRemove list. This function 138/// should be called with the SignalsMutex lock held. 139/// NB: This must be an async signal safe function. It cannot allocate or free 140/// memory, even in debug builds. 141static void RemoveFilesToRemove() { 142 // We avoid iterators in case of debug iterators that allocate or release 143 // memory. 144 std::vector<std::string>& FilesToRemoveRef = *FilesToRemove; 145 for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i) { 146 // We rely on a std::string implementation for which repeated calls to 147 // 'c_str()' don't allocate memory. We pre-call 'c_str()' on all of these 148 // strings to try to ensure this is safe. 149 const char *path = FilesToRemoveRef[i].c_str(); 150 151 // Get the status so we can determine if it's a file or directory. If we 152 // can't stat the file, ignore it. 153 struct stat buf; 154 if (stat(path, &buf) != 0) 155 continue; 156 157 // If this is not a regular file, ignore it. We want to prevent removal of 158 // special files like /dev/null, even if the compiler is being run with the 159 // super-user permissions. 160 if (!S_ISREG(buf.st_mode)) 161 continue; 162 163 // Otherwise, remove the file. We ignore any errors here as there is nothing 164 // else we can do. 165 unlink(path); 166 } 167} 168 169// SignalHandler - The signal handler that runs. 170static RETSIGTYPE SignalHandler(int Sig) { 171 // Restore the signal behavior to default, so that the program actually 172 // crashes when we return and the signal reissues. This also ensures that if 173 // we crash in our signal handler that the program will terminate immediately 174 // instead of recursing in the signal handler. 175 UnregisterHandlers(); 176 177 // Unmask all potentially blocked kill signals. 178 sigset_t SigMask; 179 sigfillset(&SigMask); 180 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr); 181 182 { 183 unique_lock<SmartMutex<true>> Guard(*SignalsMutex); 184 RemoveFilesToRemove(); 185 186 if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig) 187 != std::end(IntSigs)) { 188 if (InterruptFunction) { 189 void (*IF)() = InterruptFunction; 190 Guard.unlock(); 191 InterruptFunction = nullptr; 192 IF(); // run the interrupt function. 193 return; 194 } 195 196 Guard.unlock(); 197 raise(Sig); // Execute the default handler. 198 return; 199 } 200 } 201 202 // Otherwise if it is a fault (like SEGV) run any handler. 203 std::vector<std::pair<void (*)(void *), void *>>& CallBacksToRunRef = 204 *CallBacksToRun; 205 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i) 206 CallBacksToRunRef[i].first(CallBacksToRunRef[i].second); 207 208#ifdef __s390__ 209 // On S/390, certain signals are delivered with PSW Address pointing to 210 // *after* the faulting instruction. Simply returning from the signal 211 // handler would continue execution after that point, instead of 212 // re-raising the signal. Raise the signal manually in those cases. 213 if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP) 214 raise(Sig); 215#endif 216} 217 218void llvm::sys::RunInterruptHandlers() { 219 sys::SmartScopedLock<true> Guard(*SignalsMutex); 220 RemoveFilesToRemove(); 221} 222 223void llvm::sys::SetInterruptFunction(void (*IF)()) { 224 { 225 sys::SmartScopedLock<true> Guard(*SignalsMutex); 226 InterruptFunction = IF; 227 } 228 RegisterHandlers(); 229} 230 231// RemoveFileOnSignal - The public API 232bool llvm::sys::RemoveFileOnSignal(StringRef Filename, 233 std::string* ErrMsg) { 234 { 235 sys::SmartScopedLock<true> Guard(*SignalsMutex); 236 std::vector<std::string>& FilesToRemoveRef = *FilesToRemove; 237 std::string *OldPtr = 238 FilesToRemoveRef.empty() ? nullptr : &FilesToRemoveRef[0]; 239 FilesToRemoveRef.push_back(Filename); 240 241 // We want to call 'c_str()' on every std::string in this vector so that if 242 // the underlying implementation requires a re-allocation, it happens here 243 // rather than inside of the signal handler. If we see the vector grow, we 244 // have to call it on every entry. If it remains in place, we only need to 245 // call it on the latest one. 246 if (OldPtr == &FilesToRemoveRef[0]) 247 FilesToRemoveRef.back().c_str(); 248 else 249 for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i) 250 FilesToRemoveRef[i].c_str(); 251 } 252 253 RegisterHandlers(); 254 return false; 255} 256 257// DontRemoveFileOnSignal - The public API 258void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) { 259 sys::SmartScopedLock<true> Guard(*SignalsMutex); 260 std::vector<std::string>::reverse_iterator RI = 261 std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename); 262 std::vector<std::string>::iterator I = FilesToRemove->end(); 263 if (RI != FilesToRemove->rend()) 264 I = FilesToRemove->erase(RI.base()-1); 265 266 // We need to call c_str() on every element which would have been moved by 267 // the erase. These elements, in a C++98 implementation where c_str() 268 // requires a reallocation on the first call may have had the call to c_str() 269 // made on insertion become invalid by being copied down an element. 270 for (std::vector<std::string>::iterator E = FilesToRemove->end(); I != E; ++I) 271 I->c_str(); 272} 273 274/// AddSignalHandler - Add a function to be called when a signal is delivered 275/// to the process. The handler can have a cookie passed to it to identify 276/// what instance of the handler it is. 277void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) { 278 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie)); 279 RegisterHandlers(); 280} 281 282#if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES) 283 284#if HAVE_LINK_H && (defined(__linux__) || defined(__FreeBSD__) || \ 285 defined(__FreeBSD_kernel__) || defined(__NetBSD__)) 286struct DlIteratePhdrData { 287 void **StackTrace; 288 int depth; 289 bool first; 290 const char **modules; 291 intptr_t *offsets; 292 const char *main_exec_name; 293}; 294 295static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) { 296 DlIteratePhdrData *data = (DlIteratePhdrData*)arg; 297 const char *name = data->first ? data->main_exec_name : info->dlpi_name; 298 data->first = false; 299 for (int i = 0; i < info->dlpi_phnum; i++) { 300 const auto *phdr = &info->dlpi_phdr[i]; 301 if (phdr->p_type != PT_LOAD) 302 continue; 303 intptr_t beg = info->dlpi_addr + phdr->p_vaddr; 304 intptr_t end = beg + phdr->p_memsz; 305 for (int j = 0; j < data->depth; j++) { 306 if (data->modules[j]) 307 continue; 308 intptr_t addr = (intptr_t)data->StackTrace[j]; 309 if (beg <= addr && addr < end) { 310 data->modules[j] = name; 311 data->offsets[j] = addr - info->dlpi_addr; 312 } 313 } 314 } 315 return 0; 316} 317 318static bool findModulesAndOffsets(void **StackTrace, int Depth, 319 const char **Modules, intptr_t *Offsets, 320 const char *MainExecutableName) { 321 DlIteratePhdrData data = {StackTrace, Depth, true, 322 Modules, Offsets, MainExecutableName}; 323 dl_iterate_phdr(dl_iterate_phdr_cb, &data); 324 return true; 325} 326#else 327static bool findModulesAndOffsets(void **StackTrace, int Depth, 328 const char **Modules, intptr_t *Offsets, 329 const char *MainExecutableName) { 330 return false; 331} 332#endif 333 334static bool printSymbolizedStackTrace(void **StackTrace, int Depth, 335 llvm::raw_ostream &OS) { 336 // FIXME: Subtract necessary number from StackTrace entries to turn return addresses 337 // into actual instruction addresses. 338 // Use llvm-symbolizer tool to symbolize the stack traces. 339 ErrorOr<std::string> LLVMSymbolizerPathOrErr = 340 sys::findProgramByName("llvm-symbolizer"); 341 if (!LLVMSymbolizerPathOrErr) 342 return false; 343 const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr; 344 // We don't know argv0 or the address of main() at this point, but try 345 // to guess it anyway (it's possible on some platforms). 346 std::string MainExecutableName = sys::fs::getMainExecutable(nullptr, nullptr); 347 if (MainExecutableName.empty() || 348 MainExecutableName.find("llvm-symbolizer") != std::string::npos) 349 return false; 350 351 std::vector<const char *> Modules(Depth, nullptr); 352 std::vector<intptr_t> Offsets(Depth, 0); 353 if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(), 354 MainExecutableName.c_str())) 355 return false; 356 int InputFD; 357 SmallString<32> InputFile, OutputFile; 358 sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile); 359 sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile); 360 FileRemover InputRemover(InputFile.c_str()); 361 FileRemover OutputRemover(OutputFile.c_str()); 362 363 { 364 raw_fd_ostream Input(InputFD, true); 365 for (int i = 0; i < Depth; i++) { 366 if (Modules[i]) 367 Input << Modules[i] << " " << (void*)Offsets[i] << "\n"; 368 } 369 } 370 371 StringRef InputFileStr(InputFile); 372 StringRef OutputFileStr(OutputFile); 373 StringRef StderrFileStr; 374 const StringRef *Redirects[] = {&InputFileStr, &OutputFileStr, 375 &StderrFileStr}; 376 const char *Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining", 377 "--demangle", nullptr}; 378 int RunResult = 379 sys::ExecuteAndWait(LLVMSymbolizerPath, Args, nullptr, Redirects); 380 if (RunResult != 0) 381 return false; 382 383 auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str()); 384 if (!OutputBuf) 385 return false; 386 StringRef Output = OutputBuf.get()->getBuffer(); 387 SmallVector<StringRef, 32> Lines; 388 Output.split(Lines, "\n"); 389 auto CurLine = Lines.begin(); 390 int frame_no = 0; 391 for (int i = 0; i < Depth; i++) { 392 if (!Modules[i]) { 393 OS << format("#%d %p\n", frame_no++, StackTrace[i]); 394 continue; 395 } 396 // Read pairs of lines (function name and file/line info) until we 397 // encounter empty line. 398 for (;;) { 399 if (CurLine == Lines.end()) 400 return false; 401 StringRef FunctionName = *CurLine++; 402 if (FunctionName.empty()) 403 break; 404 OS << format("#%d %p ", frame_no++, StackTrace[i]); 405 if (!FunctionName.startswith("??")) 406 OS << format("%s ", FunctionName.str().c_str()); 407 if (CurLine == Lines.end()) 408 return false; 409 StringRef FileLineInfo = *CurLine++; 410 if (!FileLineInfo.startswith("??")) 411 OS << format("%s", FileLineInfo.str().c_str()); 412 else 413 OS << format("(%s+%p)", Modules[i], (void *)Offsets[i]); 414 OS << "\n"; 415 } 416 } 417 return true; 418} 419#endif // defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES) 420 421// PrintStackTrace - In the case of a program crash or fault, print out a stack 422// trace so that the user has an indication of why and where we died. 423// 424// On glibc systems we have the 'backtrace' function, which works nicely, but 425// doesn't demangle symbols. 426void llvm::sys::PrintStackTrace(raw_ostream &OS) { 427#if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES) 428 static void* StackTrace[256]; 429 // Use backtrace() to output a backtrace on Linux systems with glibc. 430 int depth = backtrace(StackTrace, 431 static_cast<int>(array_lengthof(StackTrace))); 432 if (printSymbolizedStackTrace(StackTrace, depth, OS)) 433 return; 434#if HAVE_DLFCN_H && __GNUG__ 435 int width = 0; 436 for (int i = 0; i < depth; ++i) { 437 Dl_info dlinfo; 438 dladdr(StackTrace[i], &dlinfo); 439 const char* name = strrchr(dlinfo.dli_fname, '/'); 440 441 int nwidth; 442 if (!name) nwidth = strlen(dlinfo.dli_fname); 443 else nwidth = strlen(name) - 1; 444 445 if (nwidth > width) width = nwidth; 446 } 447 448 for (int i = 0; i < depth; ++i) { 449 Dl_info dlinfo; 450 dladdr(StackTrace[i], &dlinfo); 451 452 OS << format("%-2d", i); 453 454 const char* name = strrchr(dlinfo.dli_fname, '/'); 455 if (!name) OS << format(" %-*s", width, dlinfo.dli_fname); 456 else OS << format(" %-*s", width, name+1); 457 458 OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2, 459 (unsigned long)StackTrace[i]); 460 461 if (dlinfo.dli_sname != nullptr) { 462 OS << ' '; 463# if HAVE_CXXABI_H 464 int res; 465 char* d = abi::__cxa_demangle(dlinfo.dli_sname, nullptr, nullptr, &res); 466# else 467 char* d = NULL; 468# endif 469 if (!d) OS << dlinfo.dli_sname; 470 else OS << d; 471 free(d); 472 473 // FIXME: When we move to C++11, use %t length modifier. It's not in 474 // C++03 and causes gcc to issue warnings. Losing the upper 32 bits of 475 // the stack offset for a stack dump isn't likely to cause any problems. 476 OS << format(" + %u",(unsigned)((char*)StackTrace[i]- 477 (char*)dlinfo.dli_saddr)); 478 } 479 OS << '\n'; 480 } 481#else 482 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO); 483#endif 484#endif 485} 486 487static void PrintStackTraceSignalHandler(void *) { 488 PrintStackTrace(llvm::errs()); 489} 490 491void llvm::sys::DisableSystemDialogsOnCrash() {} 492 493/// PrintStackTraceOnErrorSignal - When an error signal (such as SIGABRT or 494/// SIGSEGV) is delivered to the process, print a stack trace and then exit. 495void llvm::sys::PrintStackTraceOnErrorSignal(bool DisableCrashReporting) { 496 AddSignalHandler(PrintStackTraceSignalHandler, nullptr); 497 498#if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES) 499 // Environment variable to disable any kind of crash dialog. 500 if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) { 501 mach_port_t self = mach_task_self(); 502 503 exception_mask_t mask = EXC_MASK_CRASH; 504 505 kern_return_t ret = task_set_exception_ports(self, 506 mask, 507 MACH_PORT_NULL, 508 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES, 509 THREAD_STATE_NONE); 510 (void)ret; 511 } 512#endif 513} 514 515 516/***/ 517 518// On Darwin, raise sends a signal to the main thread instead of the current 519// thread. This has the unfortunate effect that assert() and abort() will end up 520// bypassing our crash recovery attempts. We work around this for anything in 521// the same linkage unit by just defining our own versions of the assert handler 522// and abort. 523 524#if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES) 525 526#include <signal.h> 527#include <pthread.h> 528 529int raise(int sig) { 530 return pthread_kill(pthread_self(), sig); 531} 532 533void __assert_rtn(const char *func, 534 const char *file, 535 int line, 536 const char *expr) { 537 if (func) 538 fprintf(stderr, "Assertion failed: (%s), function %s, file %s, line %d.\n", 539 expr, func, file, line); 540 else 541 fprintf(stderr, "Assertion failed: (%s), file %s, line %d.\n", 542 expr, file, line); 543 abort(); 544} 545 546void abort() { 547 raise(SIGABRT); 548 usleep(1000); 549 __builtin_trap(); 550} 551 552#endif 553