Signals.cpp 9.5 KB

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