LLVM 20.0.0git
Signals.cpp
Go to the documentation of this file.
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
15
16#include "DebugOptions.h"
17
18#include "llvm/ADT/StringRef.h"
19#include "llvm/Config/llvm-config.h"
24#include "llvm/Support/Format.h"
28#include "llvm/Support/Path.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
41using namespace llvm;
42
43// Use explicit storage to avoid accessing cl::opt in a signal handler.
44static bool DisableSymbolicationFlag = false;
46namespace {
47struct CreateDisableSymbolication {
48 static void *call() {
49 return new cl::opt<bool, true>(
50 "disable-symbolication",
51 cl::desc("Disable symbolizing crash backtraces."),
53 }
54};
55struct CreateCrashDiagnosticsDir {
56 static void *call() {
58 "crash-diagnostics-dir", cl::value_desc("directory"),
59 cl::desc("Directory for crash diagnostic files."),
61 }
62};
63} // namespace
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
73constexpr char DisableSymbolizationEnv[] = "LLVM_DISABLE_SYMBOLIZATION";
74constexpr char LLVMSymbolizerPathEnv[] = "LLVM_SYMBOLIZER_PATH";
75constexpr char EnableSymbolizerMarkupEnv[] = "LLVM_ENABLE_SYMBOLIZER_MARKUP";
76
77// Callbacks to run in signal handler must be lock-free because a signal handler
78// could be running as we add new callbacks. We don't add unbounded numbers of
79// callbacks, an array is therefore sufficient.
82 void *Cookie;
84 std::atomic<Status> Flag;
85};
86
87static constexpr size_t MaxSignalHandlerCallbacks = 8;
88
89// A global array of CallbackAndCookie may not compile with
90// -Werror=global-constructors in c++20 and above
91static std::array<CallbackAndCookie, MaxSignalHandlerCallbacks> &
93 static std::array<CallbackAndCookie, MaxSignalHandlerCallbacks> callbacks;
94 return callbacks;
95}
96
97// Signal-safe.
99 for (CallbackAndCookie &RunMe : CallBacksToRun()) {
102 if (!RunMe.Flag.compare_exchange_strong(Expected, Desired))
103 continue;
104 (*RunMe.Callback)(RunMe.Cookie);
105 RunMe.Callback = nullptr;
106 RunMe.Cookie = nullptr;
107 RunMe.Flag.store(CallbackAndCookie::Status::Empty);
108 }
109}
110
111// Signal-safe.
113 void *Cookie) {
114 for (CallbackAndCookie &SetMe : CallBacksToRun()) {
117 if (!SetMe.Flag.compare_exchange_strong(Expected, Desired))
118 continue;
119 SetMe.Callback = FnPtr;
120 SetMe.Cookie = Cookie;
122 return;
123 }
124 report_fatal_error("too many signal callbacks already registered");
125}
126
127static bool findModulesAndOffsets(void **StackTrace, int Depth,
128 const char **Modules, intptr_t *Offsets,
129 const char *MainExecutableName,
130 StringSaver &StrPool);
131
132/// Format a pointer value as hexadecimal. Zero pad it out so its always the
133/// same width.
134static FormattedNumber format_ptr(void *PC) {
135 // Each byte is two hex digits plus 2 for the 0x prefix.
136 unsigned PtrWidth = 2 + 2 * sizeof(void *);
137 return format_hex((uint64_t)PC, PtrWidth);
138}
139
140/// Helper that launches llvm-symbolizer and symbolizes a backtrace.
142static bool printSymbolizedStackTrace(StringRef Argv0, void **StackTrace,
143 int Depth, llvm::raw_ostream &OS) {
145 return false;
146
147 // Don't recursively invoke the llvm-symbolizer binary.
148 if (Argv0.contains("llvm-symbolizer"))
149 return false;
150
151 // FIXME: Subtract necessary number from StackTrace entries to turn return addresses
152 // into actual instruction addresses.
153 // Use llvm-symbolizer tool to symbolize the stack traces. First look for it
154 // alongside our binary, then in $PATH.
155 ErrorOr<std::string> LLVMSymbolizerPathOrErr = std::error_code();
156 if (const char *Path = getenv(LLVMSymbolizerPathEnv)) {
157 LLVMSymbolizerPathOrErr = sys::findProgramByName(Path);
158 } else if (!Argv0.empty()) {
160 if (!Parent.empty())
161 LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer", Parent);
162 }
163 if (!LLVMSymbolizerPathOrErr)
164 LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer");
165 if (!LLVMSymbolizerPathOrErr)
166 return false;
167 const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
168
169 // If we don't know argv0 or the address of main() at this point, try
170 // to guess it anyway (it's possible on some platforms).
171 std::string MainExecutableName =
172 sys::fs::exists(Argv0) ? (std::string)std::string(Argv0)
173 : sys::fs::getMainExecutable(nullptr, nullptr);
175 StringSaver StrPool(Allocator);
176 std::vector<const char *> Modules(Depth, nullptr);
177 std::vector<intptr_t> Offsets(Depth, 0);
178 if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(),
179 MainExecutableName.c_str(), StrPool))
180 return false;
181 int InputFD;
182 SmallString<32> InputFile, OutputFile;
183 sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile);
184 sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile);
185 FileRemover InputRemover(InputFile.c_str());
186 FileRemover OutputRemover(OutputFile.c_str());
187
188 {
189 raw_fd_ostream Input(InputFD, true);
190 for (int i = 0; i < Depth; i++) {
191 if (Modules[i])
192 Input << Modules[i] << " " << (void*)Offsets[i] << "\n";
193 }
194 }
195
196 std::optional<StringRef> Redirects[] = {InputFile.str(), OutputFile.str(),
197 StringRef("")};
198 StringRef Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
199#ifdef _WIN32
200 // Pass --relative-address on Windows so that we don't
201 // have to add ImageBase from PE file.
202 // FIXME: Make this the default for llvm-symbolizer.
203 "--relative-address",
204#endif
205 "--demangle"};
206 int RunResult =
207 sys::ExecuteAndWait(LLVMSymbolizerPath, Args, std::nullopt, Redirects);
208 if (RunResult != 0)
209 return false;
210
211 // This report format is based on the sanitizer stack trace printer. See
212 // sanitizer_stacktrace_printer.cc in compiler-rt.
213 auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str());
214 if (!OutputBuf)
215 return false;
216 StringRef Output = OutputBuf.get()->getBuffer();
218 Output.split(Lines, "\n");
219 auto CurLine = Lines.begin();
220 int frame_no = 0;
221 for (int i = 0; i < Depth; i++) {
222 auto PrintLineHeader = [&]() {
223 OS << right_justify(formatv("#{0}", frame_no++).str(),
224 std::log10(Depth) + 2)
225 << ' ' << format_ptr(StackTrace[i]) << ' ';
226 };
227 if (!Modules[i]) {
228 PrintLineHeader();
229 OS << '\n';
230 continue;
231 }
232 // Read pairs of lines (function name and file/line info) until we
233 // encounter empty line.
234 for (;;) {
235 if (CurLine == Lines.end())
236 return false;
237 StringRef FunctionName = *CurLine++;
238 if (FunctionName.empty())
239 break;
240 PrintLineHeader();
241 if (!FunctionName.starts_with("??"))
242 OS << FunctionName << ' ';
243 if (CurLine == Lines.end())
244 return false;
245 StringRef FileLineInfo = *CurLine++;
246 if (!FileLineInfo.starts_with("??"))
247 OS << FileLineInfo;
248 else
249 OS << "(" << Modules[i] << '+' << format_hex(Offsets[i], 0) << ")";
250 OS << "\n";
251 }
252 }
253 return true;
254}
255
256static bool printMarkupContext(raw_ostream &OS, const char *MainExecutableName);
257
259static bool printMarkupStackTrace(StringRef Argv0, void **StackTrace, int Depth,
260 raw_ostream &OS) {
261 const char *Env = getenv(EnableSymbolizerMarkupEnv);
262 if (!Env || !*Env)
263 return false;
264
265 std::string MainExecutableName =
266 sys::fs::exists(Argv0) ? std::string(Argv0)
267 : sys::fs::getMainExecutable(nullptr, nullptr);
268 if (!printMarkupContext(OS, MainExecutableName.c_str()))
269 return false;
270 for (int I = 0; I < Depth; I++)
271 OS << format("{{{bt:%d:%#016x}}}\n", I, StackTrace[I]);
272 return true;
273}
274
275// Include the platform-specific parts of this class.
276#ifdef LLVM_ON_UNIX
277#include "Unix/Signals.inc"
278#endif
279#ifdef _WIN32
280#include "Windows/Signals.inc"
281#endif
#define LLVM_ATTRIBUTE_USED
Definition: Compiler.h:151
Provides ErrorOr<T> smart pointer.
#define I(x, y, z)
Definition: MD5.cpp:58
Basic Register Allocator
raw_pwrite_stream & OS
static FormattedNumber format_ptr(void *PC)
Format a pointer value as hexadecimal.
Definition: Signals.cpp:134
constexpr char DisableSymbolizationEnv[]
Definition: Signals.cpp:73
static LLVM_ATTRIBUTE_USED bool printSymbolizedStackTrace(StringRef Argv0, void **StackTrace, int Depth, llvm::raw_ostream &OS)
Helper that launches llvm-symbolizer and symbolizes a backtrace.
Definition: Signals.cpp:142
static std::array< CallbackAndCookie, MaxSignalHandlerCallbacks > & CallBacksToRun()
Definition: Signals.cpp:92
static bool findModulesAndOffsets(void **StackTrace, int Depth, const char **Modules, intptr_t *Offsets, const char *MainExecutableName, StringSaver &StrPool)
static bool DisableSymbolicationFlag
Definition: Signals.cpp:44
static ManagedStatic< std::string > CrashDiagnosticsDirectory
Definition: Signals.cpp:45
static constexpr size_t MaxSignalHandlerCallbacks
Definition: Signals.cpp:87
constexpr char LLVMSymbolizerPathEnv[]
Definition: Signals.cpp:74
static bool printMarkupContext(raw_ostream &OS, const char *MainExecutableName)
static LLVM_ATTRIBUTE_USED bool printMarkupStackTrace(StringRef Argv0, void **StackTrace, int Depth, raw_ostream &OS)
Definition: Signals.cpp:259
static void insertSignalHandler(sys::SignalHandlerCallback FnPtr, void *Cookie)
Definition: Signals.cpp:112
constexpr char EnableSymbolizerMarkupEnv[]
Definition: Signals.cpp:75
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:66
Represents either an error or a value T.
Definition: ErrorOr.h:56
Tagged union holding either a T or a Error.
Definition: Error.h:481
FileRemover - This class is a simple object meant to be stack allocated.
Definition: FileUtilities.h:42
This is a helper class used for format_hex() and format_decimal().
Definition: Format.h:165
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
Definition: ManagedStatic.h:83
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
const char * c_str()
Definition: SmallString.h:259
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:254
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1210
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:685
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:250
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition: StringRef.h:409
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition: StringSaver.h:21
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:460
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
LocationClass< Ty > location(Ty &L)
Definition: CommandLine.h:463
std::string getMainExecutable(const char *argv0, void *MainExecAddr)
Return the path to the main executable, given the value of argv[0] from program startup and the addre...
bool exists(const basic_file_status &status)
Does file exist?
Definition: Path.cpp:1078
std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD, SmallVectorImpl< char > &ResultPath, OpenFlags Flags=OF_None)
Create a file in the system temporary directory.
Definition: Path.cpp:864
StringRef parent_path(StringRef path, Style style=Style::native)
Get parent path.
Definition: Path.cpp:468
void(*)(void *) SignalHandlerCallback
Definition: Signals.h:61
void RunSignalHandlers()
Definition: Signals.cpp:98
int ExecuteAndWait(StringRef Program, ArrayRef< StringRef > Args, std::optional< ArrayRef< StringRef > > Env=std::nullopt, ArrayRef< std::optional< StringRef > > Redirects={}, unsigned SecondsToWait=0, unsigned MemoryLimit=0, std::string *ErrMsg=nullptr, bool *ExecutionFailed=nullptr, std::optional< ProcessStatistics > *ProcStat=nullptr, BitVector *AffinityMask=nullptr)
This function executes the program using the arguments provided.
Definition: Program.cpp:32
ErrorOr< std::string > findProgramByName(StringRef Name, ArrayRef< StringRef > Paths={})
Find the first executable file Name in Paths.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
FormattedString right_justify(StringRef Str, unsigned Width)
right_justify - add spaces before string so total output is Width characters.
Definition: Format.h:153
auto formatv(const char *Fmt, Ts &&...Vals) -> formatv_object< decltype(std::make_tuple(support::detail::build_format_adapter(std::forward< Ts >(Vals))...))>
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
void initSignalsOptions()
Definition: Signals.cpp:64
FormattedNumber format_hex(uint64_t N, unsigned Width, bool Upper=false)
format_hex - Output N as a fixed width hexadecimal.
Definition: Format.h:187
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:125
sys::SignalHandlerCallback Callback
Definition: Signals.cpp:81
std::atomic< Status > Flag
Definition: Signals.cpp:84