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