Signals.cpp 9.3 KB

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