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