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