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