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/IOSandbox.h"
27#include "llvm/Support/ManagedStatic.h"
28#include "llvm/Support/MemoryBuffer.h"
29#include "llvm/Support/Path.h"
30#include "llvm/Support/Program.h"
31#include "llvm/Support/StringSaver.h"
32#include "llvm/Support/raw_ostream.h"
33#include <array>
34#include <cmath>
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;
45static ManagedStatic<std::string> CrashDiagnosticsDirectory;
46namespace {
47struct 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(L&: DisableSymbolicationFlag), cl::Hidden);
53 }
54};
55struct 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(L&: *CrashDiagnosticsDirectory), cl::Hidden);
61 }
62};
63} // namespace
64void 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
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.
80struct CallbackAndCookie {
81 sys::SignalHandlerCallback Callback;
82 void *Cookie;
83 enum class Status { Empty, Initializing, Initialized, Executing };
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> &
92CallBacksToRun() {
93 static std::array<CallbackAndCookie, MaxSignalHandlerCallbacks> callbacks;
94 return callbacks;
95}
96
97// Signal-safe.
98void sys::RunSignalHandlers() {
99 // Let's not interfere with stack trace symbolication and friends.
100 auto BypassSandbox = sandbox::scopedDisable();
101
102 for (CallbackAndCookie &RunMe : CallBacksToRun()) {
103 auto Expected = CallbackAndCookie::Status::Initialized;
104 auto Desired = CallbackAndCookie::Status::Executing;
105 if (!RunMe.Flag.compare_exchange_strong(e&: Expected, i: Desired))
106 continue;
107 (*RunMe.Callback)(RunMe.Cookie);
108 RunMe.Callback = nullptr;
109 RunMe.Cookie = nullptr;
110 RunMe.Flag.store(i: CallbackAndCookie::Status::Empty);
111 }
112}
113
114// Signal-safe.
115static void insertSignalHandler(sys::SignalHandlerCallback FnPtr,
116 void *Cookie) {
117 for (CallbackAndCookie &SetMe : CallBacksToRun()) {
118 auto Expected = CallbackAndCookie::Status::Empty;
119 auto Desired = CallbackAndCookie::Status::Initializing;
120 if (!SetMe.Flag.compare_exchange_strong(e&: Expected, i: Desired))
121 continue;
122 SetMe.Callback = FnPtr;
123 SetMe.Cookie = Cookie;
124 SetMe.Flag.store(i: CallbackAndCookie::Status::Initialized);
125 return;
126 }
127 report_fatal_error(reason: "too many signal callbacks already registered");
128}
129
130static bool findModulesAndOffsets(void **StackTrace, int Depth,
131 const char **Modules, intptr_t *Offsets,
132 const char *MainExecutableName,
133 StringSaver &StrPool);
134
135/// Format a pointer value as hexadecimal. Zero pad it out so its always the
136/// same width.
137static FormattedNumber format_ptr(void *PC) {
138 // Each byte is two hex digits plus 2 for the 0x prefix.
139 unsigned PtrWidth = 2 + 2 * sizeof(void *);
140 return format_hex(N: (uint64_t)PC, Width: PtrWidth);
141}
142
143/// Reads a file \p Filename written by llvm-symbolizer containing function
144/// names and source locations for the addresses in \p AddressList and returns
145/// the strings in a vector of pairs, where the first pair element is the index
146/// of the corresponding entry in AddressList and the second is the symbolized
147/// frame, in a format based on the sanitizer stack trace printer, with the
148/// exception that it does not write out frame numbers (i.e. "#2 " for the
149/// third address), as it is not assumed that \p AddressList corresponds to a
150/// single stack trace.
151/// There may be multiple returned entries for a single \p AddressList entry if
152/// that frame address corresponds to one or more inlined frames; in this case,
153/// all frames for an address will appear contiguously and in-order.
154std::optional<SmallVector<std::pair<unsigned, std::string>, 0>>
155collectAddressSymbols(void **AddressList, unsigned AddressCount,
156 const char *MainExecutableName,
157 const std::string &LLVMSymbolizerPath) {
158 BumpPtrAllocator Allocator;
159 StringSaver StrPool(Allocator);
160 SmallVector<const char *, 0> Modules(AddressCount, nullptr);
161 SmallVector<intptr_t, 0> Offsets(AddressCount, 0);
162 if (!findModulesAndOffsets(StackTrace: AddressList, Depth: AddressCount, Modules: Modules.data(),
163 Offsets: Offsets.data(), MainExecutableName, StrPool))
164 return {};
165 int InputFD;
166 SmallString<32> InputFile, OutputFile;
167 sys::fs::createTemporaryFile(Prefix: "symbolizer-input", Suffix: "", ResultFD&: InputFD, ResultPath&: InputFile);
168 sys::fs::createTemporaryFile(Prefix: "symbolizer-output", Suffix: "", ResultPath&: OutputFile);
169 FileRemover InputRemover(InputFile.c_str());
170 FileRemover OutputRemover(OutputFile.c_str());
171
172 {
173 raw_fd_ostream Input(InputFD, true);
174 for (unsigned AddrIdx = 0; AddrIdx < AddressCount; AddrIdx++) {
175 if (Modules[AddrIdx])
176 Input << Modules[AddrIdx] << " " << (void *)Offsets[AddrIdx] << "\n";
177 }
178 }
179
180 std::optional<StringRef> Redirects[] = {InputFile.str(), OutputFile.str(),
181 StringRef("")};
182 StringRef Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
183#ifdef _WIN32
184 // Pass --relative-address on Windows so that we don't
185 // have to add ImageBase from PE file.
186 // FIXME: Make this the default for llvm-symbolizer.
187 "--relative-address",
188#endif
189 "--demangle"};
190 int RunResult =
191 sys::ExecuteAndWait(Program: LLVMSymbolizerPath, Args, Env: std::nullopt, Redirects);
192 if (RunResult != 0)
193 return {};
194
195 SmallVector<std::pair<unsigned, std::string>, 0> Result;
196 auto OutputBuf = MemoryBuffer::getFile(Filename: OutputFile.c_str());
197 if (!OutputBuf)
198 return {};
199 StringRef Output = OutputBuf.get()->getBuffer();
200 SmallVector<StringRef, 32> Lines;
201 Output.split(A&: Lines, Separator: "\n");
202 auto *CurLine = Lines.begin();
203 // Lines contains the output from llvm-symbolizer, which should contain for
204 // each address with a module in order of appearance, one or more lines
205 // containing the function name and line associated with that address,
206 // followed by an empty line.
207 // For each address, adds an output entry for every real or inlined frame at
208 // that address. For addresses without known modules, we have a single entry
209 // containing just the formatted address; for all other output entries, we
210 // output the function entry if it is known, and either the line number if it
211 // is known or the module+address offset otherwise.
212 for (unsigned AddrIdx = 0; AddrIdx < AddressCount; AddrIdx++) {
213 if (!Modules[AddrIdx]) {
214 auto &SymbolizedFrame = Result.emplace_back(Args: std::make_pair(x&: AddrIdx, y: ""));
215 raw_string_ostream OS(SymbolizedFrame.second);
216 OS << format_ptr(PC: AddressList[AddrIdx]);
217 continue;
218 }
219 // Read pairs of lines (function name and file/line info) until we
220 // encounter empty line.
221 for (;;) {
222 if (CurLine == Lines.end())
223 return {};
224 StringRef FunctionName = *CurLine++;
225 if (FunctionName.empty())
226 break;
227 auto &SymbolizedFrame = Result.emplace_back(Args: std::make_pair(x&: AddrIdx, y: ""));
228 raw_string_ostream OS(SymbolizedFrame.second);
229 OS << format_ptr(PC: AddressList[AddrIdx]) << ' ';
230 if (!FunctionName.starts_with(Prefix: "??"))
231 OS << FunctionName << ' ';
232 if (CurLine == Lines.end())
233 return {};
234 StringRef FileLineInfo = *CurLine++;
235 if (!FileLineInfo.starts_with(Prefix: "??")) {
236 OS << FileLineInfo;
237 } else {
238 OS << "(" << Modules[AddrIdx] << '+' << format_hex(N: Offsets[AddrIdx], Width: 0)
239 << ")";
240 }
241 }
242 }
243 return Result;
244}
245
246ErrorOr<std::string> getLLVMSymbolizerPath(StringRef Argv0 = {}) {
247 ErrorOr<std::string> LLVMSymbolizerPathOrErr = std::error_code();
248 if (const char *Path = getenv(name: LLVMSymbolizerPathEnv)) {
249 LLVMSymbolizerPathOrErr = sys::findProgramByName(Name: Path);
250 } else if (!Argv0.empty()) {
251 StringRef Parent = llvm::sys::path::parent_path(path: Argv0);
252 if (!Parent.empty())
253 LLVMSymbolizerPathOrErr =
254 sys::findProgramByName(Name: "llvm-symbolizer", Paths: Parent);
255 }
256 if (!LLVMSymbolizerPathOrErr)
257 LLVMSymbolizerPathOrErr = sys::findProgramByName(Name: "llvm-symbolizer");
258 return LLVMSymbolizerPathOrErr;
259}
260
261/// Helper that launches llvm-symbolizer and symbolizes a backtrace.
262LLVM_ATTRIBUTE_USED
263static bool printSymbolizedStackTrace(StringRef Argv0, void **StackTrace,
264 int Depth, llvm::raw_ostream &OS) {
265 if (DisableSymbolicationFlag || getenv(name: DisableSymbolizationEnv))
266 return false;
267
268 // Don't recursively invoke the llvm-symbolizer binary.
269 if (Argv0.contains(Other: "llvm-symbolizer"))
270 return false;
271
272 // FIXME: Subtract necessary number from StackTrace entries to turn return
273 // addresses into actual instruction addresses.
274 // Use llvm-symbolizer tool to symbolize the stack traces. First look for it
275 // alongside our binary, then in $PATH.
276 ErrorOr<std::string> LLVMSymbolizerPathOrErr = getLLVMSymbolizerPath(Argv0);
277 if (!LLVMSymbolizerPathOrErr)
278 return false;
279 const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
280
281 // If we don't know argv0 or the address of main() at this point, try
282 // to guess it anyway (it's possible on some platforms).
283 std::string MainExecutableName =
284 sys::fs::exists(Path: Argv0) ? std::string(Argv0)
285 : sys::fs::getMainExecutable(argv0: nullptr, MainExecAddr: nullptr);
286
287 auto SymbolizedAddressesOpt = collectAddressSymbols(
288 AddressList: StackTrace, AddressCount: Depth, MainExecutableName: MainExecutableName.c_str(), LLVMSymbolizerPath);
289 if (!SymbolizedAddressesOpt)
290 return false;
291 for (unsigned FrameNo = 0; FrameNo < SymbolizedAddressesOpt->size();
292 ++FrameNo) {
293 OS << right_justify(Str: formatv(Fmt: "#{0}", Vals&: FrameNo).str(), Width: std::log10(x: Depth) + 2)
294 << ' ' << (*SymbolizedAddressesOpt)[FrameNo].second << '\n';
295 }
296 return true;
297}
298
299#if LLVM_ENABLE_DEBUGLOC_TRACKING_ORIGIN
300void sys::symbolizeAddresses(AddressSet &Addresses,
301 SymbolizedAddressMap &SymbolizedAddresses) {
302 assert(!DisableSymbolicationFlag && !getenv(DisableSymbolizationEnv) &&
303 "Debugify origin stacktraces require symbolization to be enabled.");
304
305 // Convert Set of Addresses to ordered list.
306 SmallVector<void *, 0> AddressList(Addresses.begin(), Addresses.end());
307 if (AddressList.empty())
308 return;
309 llvm::sort(AddressList);
310
311 // Use llvm-symbolizer tool to symbolize the stack traces. First look for it
312 // alongside our binary, then in $PATH.
313 ErrorOr<std::string> LLVMSymbolizerPathOrErr = getLLVMSymbolizerPath();
314 if (!LLVMSymbolizerPathOrErr)
315 report_fatal_error("Debugify origin stacktraces require llvm-symbolizer");
316 const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
317
318 // Try to guess the main executable name, since we don't have argv0 available
319 // here.
320 std::string MainExecutableName = sys::fs::getMainExecutable(nullptr, nullptr);
321
322 auto SymbolizedAddressesOpt =
323 collectAddressSymbols(AddressList.begin(), AddressList.size(),
324 MainExecutableName.c_str(), LLVMSymbolizerPath);
325 if (!SymbolizedAddressesOpt)
326 return;
327 for (auto SymbolizedFrame : *SymbolizedAddressesOpt) {
328 SmallVector<std::string, 0> &SymbolizedAddrs =
329 SymbolizedAddresses[AddressList[SymbolizedFrame.first]];
330 SymbolizedAddrs.push_back(SymbolizedFrame.second);
331 }
332 return;
333}
334#endif
335
336static bool printMarkupContext(raw_ostream &OS, const char *MainExecutableName);
337
338LLVM_ATTRIBUTE_USED
339static bool printMarkupStackTrace(StringRef Argv0, void **StackTrace, int Depth,
340 raw_ostream &OS) {
341 const char *Env = getenv(name: EnableSymbolizerMarkupEnv);
342 if (!Env || !*Env)
343 return false;
344
345 std::string MainExecutableName =
346 sys::fs::exists(Path: Argv0) ? std::string(Argv0)
347 : sys::fs::getMainExecutable(argv0: nullptr, MainExecAddr: nullptr);
348 if (!printMarkupContext(OS, MainExecutableName: MainExecutableName.c_str()))
349 return false;
350 for (int I = 0; I < Depth; I++)
351 OS << format(Fmt: "{{{bt:%d:%#016x}}}\n", Vals: I, Vals: StackTrace[I]);
352 return true;
353}
354
355// Include the platform-specific parts of this class.
356#ifdef LLVM_ON_UNIX
357#include "Unix/Signals.inc"
358#endif
359#ifdef _WIN32
360#include "Windows/Signals.inc"
361#endif
362