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