1 //===- Signals.cpp - Signal Handling support --------------------*- 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 #include "llvm/Support/Signals.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/StringRef.h" 17 #include "llvm/Config/llvm-config.h" 18 #include "llvm/Support/CommandLine.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/FormatAdapters.h" 24 #include "llvm/Support/FormatVariadic.h" 25 #include "llvm/Support/ManagedStatic.h" 26 #include "llvm/Support/MemoryBuffer.h" 27 #include "llvm/Support/Mutex.h" 28 #include "llvm/Support/Program.h" 29 #include "llvm/Support/StringSaver.h" 30 #include "llvm/Support/raw_ostream.h" 31 #include <vector> 32 33 //===----------------------------------------------------------------------===// 34 //=== WARNING: Implementation here must contain only TRULY operating system 35 //=== independent code. 36 //===----------------------------------------------------------------------===// 37 38 using namespace llvm; 39 40 // Use explicit storage to avoid accessing cl::opt in a signal handler. 41 static bool DisableSymbolicationFlag = false; 42 static cl::opt<bool, true> 43 DisableSymbolication("disable-symbolication", 44 cl::desc("Disable symbolizing crash backtraces."), 45 cl::location(DisableSymbolicationFlag), cl::Hidden); 46 static std::string CrashDiagnosticsDirectory; 47 static cl::opt<std::string, true> 48 CrashDiagnosticsDir("crash-diagnostics-dir", cl::value_desc("directory"), 49 cl::desc("Directory for crash diagnostic files."), 50 cl::location(CrashDiagnosticsDirectory), cl::Hidden); 51 52 constexpr char DisableSymbolizationEnv[] = "LLVM_DISABLE_SYMBOLIZATION"; 53 constexpr char LLVMSymbolizerPathEnv[] = "LLVM_SYMBOLIZER_PATH"; 54 55 // Callbacks to run in signal handler must be lock-free because a signal handler 56 // could be running as we add new callbacks. We don't add unbounded numbers of 57 // callbacks, an array is therefore sufficient. 58 struct CallbackAndCookie { 59 sys::SignalHandlerCallback Callback; 60 void *Cookie; 61 enum class Status { Empty, Initializing, Initialized, Executing }; 62 std::atomic<Status> Flag; 63 }; 64 static constexpr size_t MaxSignalHandlerCallbacks = 8; 65 static CallbackAndCookie CallBacksToRun[MaxSignalHandlerCallbacks]; 66 67 // Signal-safe. 68 void sys::RunSignalHandlers() { 69 for (size_t I = 0; I < MaxSignalHandlerCallbacks; ++I) { 70 auto &RunMe = CallBacksToRun[I]; 71 auto Expected = CallbackAndCookie::Status::Initialized; 72 auto Desired = CallbackAndCookie::Status::Executing; 73 if (!RunMe.Flag.compare_exchange_strong(Expected, Desired)) 74 continue; 75 (*RunMe.Callback)(RunMe.Cookie); 76 RunMe.Callback = nullptr; 77 RunMe.Cookie = nullptr; 78 RunMe.Flag.store(CallbackAndCookie::Status::Empty); 79 } 80 } 81 82 // Signal-safe. 83 static void insertSignalHandler(sys::SignalHandlerCallback FnPtr, 84 void *Cookie) { 85 for (size_t I = 0; I < MaxSignalHandlerCallbacks; ++I) { 86 auto &SetMe = CallBacksToRun[I]; 87 auto Expected = CallbackAndCookie::Status::Empty; 88 auto Desired = CallbackAndCookie::Status::Initializing; 89 if (!SetMe.Flag.compare_exchange_strong(Expected, Desired)) 90 continue; 91 SetMe.Callback = FnPtr; 92 SetMe.Cookie = Cookie; 93 SetMe.Flag.store(CallbackAndCookie::Status::Initialized); 94 return; 95 } 96 report_fatal_error("too many signal callbacks already registered"); 97 } 98 99 static bool findModulesAndOffsets(void **StackTrace, int Depth, 100 const char **Modules, intptr_t *Offsets, 101 const char *MainExecutableName, 102 StringSaver &StrPool); 103 104 /// Format a pointer value as hexadecimal. Zero pad it out so its always the 105 /// same width. 106 static FormattedNumber format_ptr(void *PC) { 107 // Each byte is two hex digits plus 2 for the 0x prefix. 108 unsigned PtrWidth = 2 + 2 * sizeof(void *); 109 return format_hex((uint64_t)PC, PtrWidth); 110 } 111 112 /// Helper that launches llvm-symbolizer and symbolizes a backtrace. 113 LLVM_ATTRIBUTE_USED 114 static bool printSymbolizedStackTrace(StringRef Argv0, void **StackTrace, 115 int Depth, llvm::raw_ostream &OS) { 116 if (DisableSymbolicationFlag || getenv(DisableSymbolizationEnv)) 117 return false; 118 119 // Don't recursively invoke the llvm-symbolizer binary. 120 if (Argv0.find("llvm-symbolizer") != std::string::npos) 121 return false; 122 123 // FIXME: Subtract necessary number from StackTrace entries to turn return addresses 124 // into actual instruction addresses. 125 // Use llvm-symbolizer tool to symbolize the stack traces. First look for it 126 // alongside our binary, then in $PATH. 127 ErrorOr<std::string> LLVMSymbolizerPathOrErr = std::error_code(); 128 if (const char *Path = getenv(LLVMSymbolizerPathEnv)) { 129 LLVMSymbolizerPathOrErr = sys::findProgramByName(Path); 130 } else if (!Argv0.empty()) { 131 StringRef Parent = llvm::sys::path::parent_path(Argv0); 132 if (!Parent.empty()) 133 LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer", Parent); 134 } 135 if (!LLVMSymbolizerPathOrErr) 136 LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer"); 137 if (!LLVMSymbolizerPathOrErr) 138 return false; 139 const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr; 140 141 // If we don't know argv0 or the address of main() at this point, try 142 // to guess it anyway (it's possible on some platforms). 143 std::string MainExecutableName = 144 sys::fs::exists(Argv0) ? (std::string)std::string(Argv0) 145 : sys::fs::getMainExecutable(nullptr, nullptr); 146 BumpPtrAllocator Allocator; 147 StringSaver StrPool(Allocator); 148 std::vector<const char *> Modules(Depth, nullptr); 149 std::vector<intptr_t> Offsets(Depth, 0); 150 if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(), 151 MainExecutableName.c_str(), StrPool)) 152 return false; 153 int InputFD; 154 SmallString<32> InputFile, OutputFile; 155 sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile); 156 sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile); 157 FileRemover InputRemover(InputFile.c_str()); 158 FileRemover OutputRemover(OutputFile.c_str()); 159 160 { 161 raw_fd_ostream Input(InputFD, true); 162 for (int i = 0; i < Depth; i++) { 163 if (Modules[i]) 164 Input << Modules[i] << " " << (void*)Offsets[i] << "\n"; 165 } 166 } 167 168 Optional<StringRef> Redirects[] = {InputFile.str(), OutputFile.str(), 169 StringRef("")}; 170 StringRef Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining", 171 #ifdef _WIN32 172 // Pass --relative-address on Windows so that we don't 173 // have to add ImageBase from PE file. 174 // FIXME: Make this the default for llvm-symbolizer. 175 "--relative-address", 176 #endif 177 "--demangle"}; 178 int RunResult = 179 sys::ExecuteAndWait(LLVMSymbolizerPath, Args, None, Redirects); 180 if (RunResult != 0) 181 return false; 182 183 // This report format is based on the sanitizer stack trace printer. See 184 // sanitizer_stacktrace_printer.cc in compiler-rt. 185 auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str()); 186 if (!OutputBuf) 187 return false; 188 StringRef Output = OutputBuf.get()->getBuffer(); 189 SmallVector<StringRef, 32> Lines; 190 Output.split(Lines, "\n"); 191 auto CurLine = Lines.begin(); 192 int frame_no = 0; 193 for (int i = 0; i < Depth; i++) { 194 auto PrintLineHeader = [&]() { 195 OS << right_justify(formatv("#{0}", frame_no++).str(), 196 std::log10(Depth) + 2) 197 << ' ' << format_ptr(StackTrace[i]) << ' '; 198 }; 199 if (!Modules[i]) { 200 PrintLineHeader(); 201 OS << '\n'; 202 continue; 203 } 204 // Read pairs of lines (function name and file/line info) until we 205 // encounter empty line. 206 for (;;) { 207 if (CurLine == Lines.end()) 208 return false; 209 StringRef FunctionName = *CurLine++; 210 if (FunctionName.empty()) 211 break; 212 PrintLineHeader(); 213 if (!FunctionName.startswith("??")) 214 OS << FunctionName << ' '; 215 if (CurLine == Lines.end()) 216 return false; 217 StringRef FileLineInfo = *CurLine++; 218 if (!FileLineInfo.startswith("??")) 219 OS << FileLineInfo; 220 else 221 OS << "(" << Modules[i] << '+' << format_hex(Offsets[i], 0) << ")"; 222 OS << "\n"; 223 } 224 } 225 return true; 226 } 227 228 // Include the platform-specific parts of this class. 229 #ifdef LLVM_ON_UNIX 230 #include "Unix/Signals.inc" 231 #endif 232 #ifdef _WIN32 233 #include "Windows/Signals.inc" 234 #endif 235