LLVM  14.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 
14 #include "llvm/Support/Signals.h"
15 
16 #include "DebugOptions.h"
17 
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Config/llvm-config.h"
22 #include "llvm/Support/ErrorOr.h"
25 #include "llvm/Support/Format.h"
30 #include "llvm/Support/Mutex.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/Program.h"
35 #include <vector>
36 
37 //===----------------------------------------------------------------------===//
38 //=== WARNING: Implementation here must contain only TRULY operating system
39 //=== independent code.
40 //===----------------------------------------------------------------------===//
41 
42 using namespace llvm;
43 
44 // Use explicit storage to avoid accessing cl::opt in a signal handler.
45 static bool DisableSymbolicationFlag = false;
47 namespace {
48 struct CreateDisableSymbolication {
49  static void *call() {
50  return new cl::opt<bool, true>(
51  "disable-symbolication",
52  cl::desc("Disable symbolizing crash backtraces."),
54  }
55 };
56 struct CreateCrashDiagnosticsDir {
57  static void *call() {
58  return new cl::opt<std::string, true>(
59  "crash-diagnostics-dir", cl::value_desc("directory"),
60  cl::desc("Directory for crash diagnostic files."),
62  }
63 };
64 } // namespace
66  static ManagedStatic<cl::opt<bool, true>, CreateDisableSymbolication>
67  DisableSymbolication;
68  static ManagedStatic<cl::opt<std::string, true>, CreateCrashDiagnosticsDir>
69  CrashDiagnosticsDir;
70  *DisableSymbolication;
71  *CrashDiagnosticsDir;
72 }
73 
74 constexpr char DisableSymbolizationEnv[] = "LLVM_DISABLE_SYMBOLIZATION";
75 constexpr char LLVMSymbolizerPathEnv[] = "LLVM_SYMBOLIZER_PATH";
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;
83  enum class Status { Empty, Initializing, Initialized, Executing };
84  std::atomic<Status> Flag;
85 };
86 static constexpr size_t MaxSignalHandlerCallbacks = 8;
88 
89 // Signal-safe.
91  for (CallbackAndCookie &RunMe : CallBacksToRun) {
94  if (!RunMe.Flag.compare_exchange_strong(Expected, Desired))
95  continue;
96  (*RunMe.Callback)(RunMe.Cookie);
97  RunMe.Callback = nullptr;
98  RunMe.Cookie = nullptr;
99  RunMe.Flag.store(CallbackAndCookie::Status::Empty);
100  }
101 }
102 
103 // Signal-safe.
105  void *Cookie) {
106  for (CallbackAndCookie &SetMe : CallBacksToRun) {
109  if (!SetMe.Flag.compare_exchange_strong(Expected, Desired))
110  continue;
111  SetMe.Callback = FnPtr;
112  SetMe.Cookie = Cookie;
113  SetMe.Flag.store(CallbackAndCookie::Status::Initialized);
114  return;
115  }
116  report_fatal_error("too many signal callbacks already registered");
117 }
118 
119 static bool findModulesAndOffsets(void **StackTrace, int Depth,
120  const char **Modules, intptr_t *Offsets,
121  const char *MainExecutableName,
122  StringSaver &StrPool);
123 
124 /// Format a pointer value as hexadecimal. Zero pad it out so its always the
125 /// same width.
126 static FormattedNumber format_ptr(void *PC) {
127  // Each byte is two hex digits plus 2 for the 0x prefix.
128  unsigned PtrWidth = 2 + 2 * sizeof(void *);
129  return format_hex((uint64_t)PC, PtrWidth);
130 }
131 
132 /// Helper that launches llvm-symbolizer and symbolizes a backtrace.
134 static bool printSymbolizedStackTrace(StringRef Argv0, void **StackTrace,
135  int Depth, llvm::raw_ostream &OS) {
137  return false;
138 
139  // Don't recursively invoke the llvm-symbolizer binary.
140  if (Argv0.find("llvm-symbolizer") != std::string::npos)
141  return false;
142 
143  // FIXME: Subtract necessary number from StackTrace entries to turn return addresses
144  // into actual instruction addresses.
145  // Use llvm-symbolizer tool to symbolize the stack traces. First look for it
146  // alongside our binary, then in $PATH.
147  ErrorOr<std::string> LLVMSymbolizerPathOrErr = std::error_code();
148  if (const char *Path = getenv(LLVMSymbolizerPathEnv)) {
149  LLVMSymbolizerPathOrErr = sys::findProgramByName(Path);
150  } else if (!Argv0.empty()) {
151  StringRef Parent = llvm::sys::path::parent_path(Argv0);
152  if (!Parent.empty())
153  LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer", Parent);
154  }
155  if (!LLVMSymbolizerPathOrErr)
156  LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer");
157  if (!LLVMSymbolizerPathOrErr)
158  return false;
159  const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
160 
161  // If we don't know argv0 or the address of main() at this point, try
162  // to guess it anyway (it's possible on some platforms).
163  std::string MainExecutableName =
164  sys::fs::exists(Argv0) ? (std::string)std::string(Argv0)
165  : sys::fs::getMainExecutable(nullptr, nullptr);
167  StringSaver StrPool(Allocator);
168  std::vector<const char *> Modules(Depth, nullptr);
169  std::vector<intptr_t> Offsets(Depth, 0);
170  if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(),
171  MainExecutableName.c_str(), StrPool))
172  return false;
173  int InputFD;
174  SmallString<32> InputFile, OutputFile;
175  sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile);
176  sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile);
177  FileRemover InputRemover(InputFile.c_str());
178  FileRemover OutputRemover(OutputFile.c_str());
179 
180  {
181  raw_fd_ostream Input(InputFD, true);
182  for (int i = 0; i < Depth; i++) {
183  if (Modules[i])
184  Input << Modules[i] << " " << (void*)Offsets[i] << "\n";
185  }
186  }
187 
188  Optional<StringRef> Redirects[] = {InputFile.str(), OutputFile.str(),
189  StringRef("")};
190  StringRef Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
191 #ifdef _WIN32
192  // Pass --relative-address on Windows so that we don't
193  // have to add ImageBase from PE file.
194  // FIXME: Make this the default for llvm-symbolizer.
195  "--relative-address",
196 #endif
197  "--demangle"};
198  int RunResult =
199  sys::ExecuteAndWait(LLVMSymbolizerPath, Args, None, Redirects);
200  if (RunResult != 0)
201  return false;
202 
203  // This report format is based on the sanitizer stack trace printer. See
204  // sanitizer_stacktrace_printer.cc in compiler-rt.
205  auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str());
206  if (!OutputBuf)
207  return false;
208  StringRef Output = OutputBuf.get()->getBuffer();
210  Output.split(Lines, "\n");
211  auto CurLine = Lines.begin();
212  int frame_no = 0;
213  for (int i = 0; i < Depth; i++) {
214  auto PrintLineHeader = [&]() {
215  OS << right_justify(formatv("#{0}", frame_no++).str(),
216  std::log10(Depth) + 2)
217  << ' ' << format_ptr(StackTrace[i]) << ' ';
218  };
219  if (!Modules[i]) {
220  PrintLineHeader();
221  OS << '\n';
222  continue;
223  }
224  // Read pairs of lines (function name and file/line info) until we
225  // encounter empty line.
226  for (;;) {
227  if (CurLine == Lines.end())
228  return false;
229  StringRef FunctionName = *CurLine++;
230  if (FunctionName.empty())
231  break;
232  PrintLineHeader();
233  if (!FunctionName.startswith("??"))
234  OS << FunctionName << ' ';
235  if (CurLine == Lines.end())
236  return false;
237  StringRef FileLineInfo = *CurLine++;
238  if (!FileLineInfo.startswith("??"))
239  OS << FileLineInfo;
240  else
241  OS << "(" << Modules[i] << '+' << format_hex(Offsets[i], 0) << ")";
242  OS << "\n";
243  }
244  }
245  return true;
246 }
247 
248 // Include the platform-specific parts of this class.
249 #ifdef LLVM_ON_UNIX
250 #include "Unix/Signals.inc"
251 #endif
252 #ifdef _WIN32
253 #include "Windows/Signals.inc"
254 #endif
i
i
Definition: README.txt:29
llvm::sys::findProgramByName
ErrorOr< std::string > findProgramByName(StringRef Name, ArrayRef< StringRef > Paths={})
Find the first executable file Name in Paths.
MemoryBuffer.h
LLVM_ATTRIBUTE_USED
#define LLVM_ATTRIBUTE_USED
Definition: Compiler.h:145
llvm::StringRef::startswith
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:286
Signals.h
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AllocatorList.h:22
FileSystem.h
intptr_t
llvm::cl::location
LocationClass< Ty > location(Ty &L)
Definition: CommandLine.h:457
llvm::FileRemover
FileRemover - This class is a simple object meant to be stack allocated.
Definition: FileUtilities.h:42
StringRef.h
CallBacksToRun
static CallbackAndCookie CallBacksToRun[MaxSignalHandlerCallbacks]
Definition: Signals.cpp:87
llvm::StringRef::find
LLVM_NODISCARD size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:315
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1176
Path.h
llvm::FormattedNumber
This is a helper class used for format_hex() and format_decimal().
Definition: Format.h:164
ManagedStatic.h
llvm::cl::Hidden
@ Hidden
Definition: CommandLine.h:143
llvm::Depth
@ Depth
Definition: SIMachineScheduler.h:36
llvm::sys::RunSignalHandlers
void RunSignalHandlers()
Definition: Signals.cpp:90
DebugOptions.h
format_ptr
static FormattedNumber format_ptr(void *PC)
Format a pointer value as hexadecimal.
Definition: Signals.cpp:126
llvm::Optional
Definition: APInt.h:33
llvm::Expected
Tagged union holding either a T or a Error.
Definition: APFloat.h:42
STLExtras.h
Format.h
LLVMSymbolizerPathEnv
constexpr char LLVMSymbolizerPathEnv[]
Definition: Signals.cpp:75
CallbackAndCookie::Status::Initialized
@ Initialized
llvm::sys::SignalHandlerCallback
void(*)(void *) SignalHandlerCallback
Definition: Signals.h:60
CommandLine.h
llvm::formatv
auto formatv(const char *Fmt, Ts &&... Vals) -> formatv_object< decltype(std::make_tuple(detail::build_format_adapter(std::forward< Ts >(Vals))...))>
Definition: FormatVariadic.h:251
llvm::initSignalsOptions
void initSignalsOptions()
Definition: Signals.cpp:65
llvm::MemoryBuffer::getFile
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Definition: MemoryBuffer.cpp:236
CrashDiagnosticsDirectory
static ManagedStatic< std::string > CrashDiagnosticsDirectory
Definition: Signals.cpp:46
llvm::StringRef::split
LLVM_NODISCARD std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:749
CallbackAndCookie
Definition: Signals.cpp:80
llvm::ManagedStatic
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
Definition: ManagedStatic.h:83
CallbackAndCookie::Flag
std::atomic< Status > Flag
Definition: Signals.cpp:84
insertSignalHandler
static void insertSignalHandler(sys::SignalHandlerCallback FnPtr, void *Cookie)
Definition: Signals.cpp:104
llvm::report_fatal_error
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:143
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:54
CallbackAndCookie::Callback
sys::SignalHandlerCallback Callback
Definition: Signals.cpp:81
FormatVariadic.h
llvm::None
const NoneType None
Definition: None.h:23
llvm::SmallString< 32 >
StringSaver.h
llvm::cl::opt
Definition: CommandLine.h:1432
llvm::SmallString::c_str
const char * c_str()
Definition: SmallString.h:262
printSymbolizedStackTrace
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:134
llvm::sys::fs::exists
bool exists(const basic_file_status &status)
Does file exist?
Definition: Path.cpp:1074
llvm::StringRef::empty
constexpr LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:153
uint64_t
llvm::BumpPtrAllocatorImpl
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:63
ErrorOr.h
call
S is passed via registers r2 But gcc stores them to the and then reload them to and r3 before issuing the call(r0 contains the address of the format string)
Definition: README.txt:190
DisableSymbolicationFlag
static bool DisableSymbolicationFlag
Definition: Signals.cpp:45
llvm::sys::path::parent_path
StringRef parent_path(StringRef path, Style style=Style::native)
Get parent path.
Definition: Path.cpp:468
Status
Definition: SIModeRegister.cpp:28
llvm::StringSaver
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition: StringSaver.h:21
llvm::sys::fs::createTemporaryFile
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:860
FileUtilities.h
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:58
Mutex.h
llvm::raw_fd_ostream
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:444
CallbackAndCookie::Status::Empty
@ Empty
llvm::right_justify
FormattedString right_justify(StringRef Str, unsigned Width)
right_justify - add spaces before string so total output is Width characters.
Definition: Format.h:152
Signals.inc
llvm::sys::fs::getMainExecutable
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...
llvm::cl::value_desc
Definition: CommandLine.h:422
llvm::SmallString::str
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:259
Signals.inc
FormatAdapters.h
DisableSymbolizationEnv
constexpr char DisableSymbolizationEnv[]
Definition: Signals.cpp:74
CallbackAndCookie::Status::Executing
@ Executing
CallbackAndCookie::Status::Initializing
@ Initializing
Allocator
Basic Register Allocator
Definition: RegAllocBasic.cpp:146
Program.h
llvm::sys::ExecuteAndWait
int ExecuteAndWait(StringRef Program, ArrayRef< StringRef > Args, Optional< ArrayRef< StringRef >> Env=None, ArrayRef< Optional< StringRef >> Redirects={}, unsigned SecondsToWait=0, unsigned MemoryLimit=0, std::string *ErrMsg=nullptr, bool *ExecutionFailed=nullptr, Optional< ProcessStatistics > *ProcStat=nullptr, BitVector *AffinityMask=nullptr)
This function executes the program using the arguments provided.
Definition: Program.cpp:32
llvm::ErrorOr
Represents either an error or a value T.
Definition: ErrorOr.h:56
llvm::AMDGPU::HSAMD::Kernel::Key::Args
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
Definition: AMDGPUMetadata.h:389
llvm::cl::desc
Definition: CommandLine.h:412
findModulesAndOffsets
static bool findModulesAndOffsets(void **StackTrace, int Depth, const char **Modules, intptr_t *Offsets, const char *MainExecutableName, StringSaver &StrPool)
CallbackAndCookie::Cookie
void * Cookie
Definition: Signals.cpp:82
MaxSignalHandlerCallbacks
static constexpr size_t MaxSignalHandlerCallbacks
Definition: Signals.cpp:86
raw_ostream.h
llvm::SI::KernelInputOffsets::Offsets
Offsets
Offsets in bytes from the start of the input buffer.
Definition: SIInstrInfo.h:1264
llvm::format_hex
FormattedNumber format_hex(uint64_t N, unsigned Width, bool Upper=false)
format_hex - Output N as a fixed width hexadecimal.
Definition: Format.h:186