1 //===- Signals.cpp - Signal Handling support --------------------*- 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 "llvm/Support/Signals.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/StringRef.h" 18 #include "llvm/Config/llvm-config.h" 19 #include "llvm/Support/ErrorOr.h" 20 #include "llvm/Support/FileSystem.h" 21 #include "llvm/Support/FileUtilities.h" 22 #include "llvm/Support/Format.h" 23 #include "llvm/Support/ManagedStatic.h" 24 #include "llvm/Support/MemoryBuffer.h" 25 #include "llvm/Support/Mutex.h" 26 #include "llvm/Support/Program.h" 27 #include "llvm/Support/StringSaver.h" 28 #include "llvm/Support/raw_ostream.h" 29 #include "llvm/Support/Options.h" 30 #include <vector> 31 32 //===----------------------------------------------------------------------===// 33 //=== WARNING: Implementation here must contain only TRULY operating system 34 //=== independent code. 35 //===----------------------------------------------------------------------===// 36 37 using namespace llvm; 38 39 static cl::opt<bool> 40 DisableSymbolication("disable-symbolication", 41 cl::desc("Disable symbolizing crash backtraces."), 42 cl::init(false), cl::Hidden); 43 44 static ManagedStatic<std::vector<std::pair<void (*)(void *), void *>>> 45 CallBacksToRun; 46 void sys::RunSignalHandlers() { 47 if (!CallBacksToRun.isConstructed()) 48 return; 49 for (auto &I : *CallBacksToRun) 50 I.first(I.second); 51 CallBacksToRun->clear(); 52 } 53 54 static bool findModulesAndOffsets(void **StackTrace, int Depth, 55 const char **Modules, intptr_t *Offsets, 56 const char *MainExecutableName, 57 StringSaver &StrPool); 58 59 /// Format a pointer value as hexadecimal. Zero pad it out so its always the 60 /// same width. 61 static FormattedNumber format_ptr(void *PC) { 62 // Each byte is two hex digits plus 2 for the 0x prefix. 63 unsigned PtrWidth = 2 + 2 * sizeof(void *); 64 return format_hex((uint64_t)PC, PtrWidth); 65 } 66 67 /// Helper that launches llvm-symbolizer and symbolizes a backtrace. 68 LLVM_ATTRIBUTE_USED 69 static bool printSymbolizedStackTrace(StringRef Argv0, void **StackTrace, 70 int Depth, llvm::raw_ostream &OS) { 71 if (DisableSymbolication) 72 return false; 73 74 // Don't recursively invoke the llvm-symbolizer binary. 75 if (Argv0.find("llvm-symbolizer") != std::string::npos) 76 return false; 77 78 // FIXME: Subtract necessary number from StackTrace entries to turn return addresses 79 // into actual instruction addresses. 80 // Use llvm-symbolizer tool to symbolize the stack traces. First look for it 81 // alongside our binary, then in $PATH. 82 ErrorOr<std::string> LLVMSymbolizerPathOrErr = std::error_code(); 83 if (!Argv0.empty()) { 84 StringRef Parent = llvm::sys::path::parent_path(Argv0); 85 if (!Parent.empty()) 86 LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer", Parent); 87 } 88 if (!LLVMSymbolizerPathOrErr) 89 LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer"); 90 if (!LLVMSymbolizerPathOrErr) 91 return false; 92 const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr; 93 94 // If we don't know argv0 or the address of main() at this point, try 95 // to guess it anyway (it's possible on some platforms). 96 std::string MainExecutableName = 97 Argv0.empty() ? sys::fs::getMainExecutable(nullptr, nullptr) 98 : (std::string)Argv0; 99 BumpPtrAllocator Allocator; 100 StringSaver StrPool(Allocator); 101 std::vector<const char *> Modules(Depth, nullptr); 102 std::vector<intptr_t> Offsets(Depth, 0); 103 if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(), 104 MainExecutableName.c_str(), StrPool)) 105 return false; 106 int InputFD; 107 SmallString<32> InputFile, OutputFile; 108 sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile); 109 sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile); 110 FileRemover InputRemover(InputFile.c_str()); 111 FileRemover OutputRemover(OutputFile.c_str()); 112 113 { 114 raw_fd_ostream Input(InputFD, true); 115 for (int i = 0; i < Depth; i++) { 116 if (Modules[i]) 117 Input << Modules[i] << " " << (void*)Offsets[i] << "\n"; 118 } 119 } 120 121 Optional<StringRef> Redirects[] = {InputFile.str(), OutputFile.str(), llvm::None}; 122 const char *Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining", 123 #ifdef _WIN32 124 // Pass --relative-address on Windows so that we don't 125 // have to add ImageBase from PE file. 126 // FIXME: Make this the default for llvm-symbolizer. 127 "--relative-address", 128 #endif 129 "--demangle", nullptr}; 130 int RunResult = 131 sys::ExecuteAndWait(LLVMSymbolizerPath, Args, nullptr, Redirects); 132 if (RunResult != 0) 133 return false; 134 135 // This report format is based on the sanitizer stack trace printer. See 136 // sanitizer_stacktrace_printer.cc in compiler-rt. 137 auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str()); 138 if (!OutputBuf) 139 return false; 140 StringRef Output = OutputBuf.get()->getBuffer(); 141 SmallVector<StringRef, 32> Lines; 142 Output.split(Lines, "\n"); 143 auto CurLine = Lines.begin(); 144 int frame_no = 0; 145 for (int i = 0; i < Depth; i++) { 146 if (!Modules[i]) { 147 OS << '#' << frame_no++ << ' ' << format_ptr(StackTrace[i]) << '\n'; 148 continue; 149 } 150 // Read pairs of lines (function name and file/line info) until we 151 // encounter empty line. 152 for (;;) { 153 if (CurLine == Lines.end()) 154 return false; 155 StringRef FunctionName = *CurLine++; 156 if (FunctionName.empty()) 157 break; 158 OS << '#' << frame_no++ << ' ' << format_ptr(StackTrace[i]) << ' '; 159 if (!FunctionName.startswith("??")) 160 OS << FunctionName << ' '; 161 if (CurLine == Lines.end()) 162 return false; 163 StringRef FileLineInfo = *CurLine++; 164 if (!FileLineInfo.startswith("??")) 165 OS << FileLineInfo; 166 else 167 OS << "(" << Modules[i] << '+' << format_hex(Offsets[i], 0) << ")"; 168 OS << "\n"; 169 } 170 } 171 return true; 172 } 173 174 // Include the platform-specific parts of this class. 175 #ifdef LLVM_ON_UNIX 176 #include "Unix/Signals.inc" 177 #endif 178 #ifdef _WIN32 179 #include "Windows/Signals.inc" 180 #endif 181