LLVM  8.0.0svn
Signals.cpp
Go to the documentation of this file.
1 //===- Signals.cpp - Signal Handling support --------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines some helpful functions for dealing with the possibility of
11 // Unix signals occurring while your program is running.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Support/Signals.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/Config/llvm-config.h"
19 #include "llvm/Support/ErrorOr.h"
22 #include "llvm/Support/Format.h"
25 #include "llvm/Support/Mutex.h"
26 #include "llvm/Support/Program.h"
29 #include "llvm/Support/Options.h"
30 #include <vector>
31 
32 //===----------------------------------------------------------------------===//
33 //=== WARNING: Implementation here must contain only TRULY operating system
34 //=== independent code.
35 //===----------------------------------------------------------------------===//
36 
37 using namespace llvm;
38 
39 // Use explicit storage to avoid accessing cl::opt in a signal handler.
40 static bool DisableSymbolicationFlag = false;
42  DisableSymbolication("disable-symbolication",
43  cl::desc("Disable symbolizing crash backtraces."),
44  cl::location(DisableSymbolicationFlag), cl::Hidden);
45 
46 // Callbacks to run in signal handler must be lock-free because a signal handler
47 // could be running as we add new callbacks. We don't add unbounded numbers of
48 // callbacks, an array is therefore sufficient.
51  void *Cookie;
52  enum class Status { Empty, Initializing, Initialized, Executing };
53  std::atomic<Status> Flag;
54 };
55 static constexpr size_t MaxSignalHandlerCallbacks = 8;
57 
58 // Signal-safe.
60  for (size_t I = 0; I < MaxSignalHandlerCallbacks; ++I) {
61  auto &RunMe = CallBacksToRun[I];
64  if (!RunMe.Flag.compare_exchange_strong(Expected, Desired))
65  continue;
66  (*RunMe.Callback)(RunMe.Cookie);
67  RunMe.Callback = nullptr;
68  RunMe.Cookie = nullptr;
69  RunMe.Flag.store(CallbackAndCookie::Status::Empty);
70  }
71 }
72 
73 // Signal-safe.
75  void *Cookie) {
76  for (size_t I = 0; I < MaxSignalHandlerCallbacks; ++I) {
77  auto &SetMe = CallBacksToRun[I];
80  if (!SetMe.Flag.compare_exchange_strong(Expected, Desired))
81  continue;
82  SetMe.Callback = FnPtr;
83  SetMe.Cookie = Cookie;
85  return;
86  }
87  report_fatal_error("too many signal callbacks already registered");
88 }
89 
90 static bool findModulesAndOffsets(void **StackTrace, int Depth,
91  const char **Modules, intptr_t *Offsets,
92  const char *MainExecutableName,
93  StringSaver &StrPool);
94 
95 /// Format a pointer value as hexadecimal. Zero pad it out so its always the
96 /// same width.
97 static FormattedNumber format_ptr(void *PC) {
98  // Each byte is two hex digits plus 2 for the 0x prefix.
99  unsigned PtrWidth = 2 + 2 * sizeof(void *);
100  return format_hex((uint64_t)PC, PtrWidth);
101 }
102 
103 /// Helper that launches llvm-symbolizer and symbolizes a backtrace.
105 static bool printSymbolizedStackTrace(StringRef Argv0, void **StackTrace,
106  int Depth, llvm::raw_ostream &OS) {
107  if (DisableSymbolicationFlag)
108  return false;
109 
110  // Don't recursively invoke the llvm-symbolizer binary.
111  if (Argv0.find("llvm-symbolizer") != std::string::npos)
112  return false;
113 
114  // FIXME: Subtract necessary number from StackTrace entries to turn return addresses
115  // into actual instruction addresses.
116  // Use llvm-symbolizer tool to symbolize the stack traces. First look for it
117  // alongside our binary, then in $PATH.
118  ErrorOr<std::string> LLVMSymbolizerPathOrErr = std::error_code();
119  if (!Argv0.empty()) {
120  StringRef Parent = llvm::sys::path::parent_path(Argv0);
121  if (!Parent.empty())
122  LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer", Parent);
123  }
124  if (!LLVMSymbolizerPathOrErr)
125  LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer");
126  if (!LLVMSymbolizerPathOrErr)
127  return false;
128  const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
129 
130  // If we don't know argv0 or the address of main() at this point, try
131  // to guess it anyway (it's possible on some platforms).
132  std::string MainExecutableName =
133  Argv0.empty() ? sys::fs::getMainExecutable(nullptr, nullptr)
134  : (std::string)Argv0;
136  StringSaver StrPool(Allocator);
137  std::vector<const char *> Modules(Depth, nullptr);
138  std::vector<intptr_t> Offsets(Depth, 0);
139  if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(),
140  MainExecutableName.c_str(), StrPool))
141  return false;
142  int InputFD;
143  SmallString<32> InputFile, OutputFile;
144  sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile);
145  sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile);
146  FileRemover InputRemover(InputFile.c_str());
147  FileRemover OutputRemover(OutputFile.c_str());
148 
149  {
150  raw_fd_ostream Input(InputFD, true);
151  for (int i = 0; i < Depth; i++) {
152  if (Modules[i])
153  Input << Modules[i] << " " << (void*)Offsets[i] << "\n";
154  }
155  }
156 
157  Optional<StringRef> Redirects[] = {StringRef(InputFile),
158  StringRef(OutputFile), llvm::None};
159  StringRef Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
160 #ifdef _WIN32
161  // Pass --relative-address on Windows so that we don't
162  // have to add ImageBase from PE file.
163  // FIXME: Make this the default for llvm-symbolizer.
164  "--relative-address",
165 #endif
166  "--demangle"};
167  int RunResult =
168  sys::ExecuteAndWait(LLVMSymbolizerPath, Args, None, Redirects);
169  if (RunResult != 0)
170  return false;
171 
172  // This report format is based on the sanitizer stack trace printer. See
173  // sanitizer_stacktrace_printer.cc in compiler-rt.
174  auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str());
175  if (!OutputBuf)
176  return false;
177  StringRef Output = OutputBuf.get()->getBuffer();
179  Output.split(Lines, "\n");
180  auto CurLine = Lines.begin();
181  int frame_no = 0;
182  for (int i = 0; i < Depth; i++) {
183  if (!Modules[i]) {
184  OS << '#' << frame_no++ << ' ' << format_ptr(StackTrace[i]) << '\n';
185  continue;
186  }
187  // Read pairs of lines (function name and file/line info) until we
188  // encounter empty line.
189  for (;;) {
190  if (CurLine == Lines.end())
191  return false;
192  StringRef FunctionName = *CurLine++;
193  if (FunctionName.empty())
194  break;
195  OS << '#' << frame_no++ << ' ' << format_ptr(StackTrace[i]) << ' ';
196  if (!FunctionName.startswith("??"))
197  OS << FunctionName << ' ';
198  if (CurLine == Lines.end())
199  return false;
200  StringRef FileLineInfo = *CurLine++;
201  if (!FileLineInfo.startswith("??"))
202  OS << FileLineInfo;
203  else
204  OS << "(" << Modules[i] << '+' << format_hex(Offsets[i], 0) << ")";
205  OS << "\n";
206  }
207  }
208  return true;
209 }
210 
211 // Include the platform-specific parts of this class.
212 #ifdef LLVM_ON_UNIX
213 #include "Unix/Signals.inc"
214 #endif
215 #ifdef _WIN32
216 #include "Windows/Signals.inc"
217 #endif
Represents either an error or a value T.
Definition: ErrorOr.h:57
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:139
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
FormattedNumber format_hex(uint64_t N, unsigned Width, bool Upper=false)
format_hex - Output N as a fixed width hexadecimal.
Definition: Format.h:186
void(*)(void *) SignalHandlerCallback
Definition: Signals.h:59
ErrorOr< std::string > findProgramByName(StringRef Name, ArrayRef< StringRef > Paths={})
Find the first executable file Name in Paths.
sys::SignalHandlerCallback Callback
Definition: Signals.cpp:50
Offsets
Offsets in bytes from the start of the input buffer.
Definition: SIInstrInfo.h:977
static cl::opt< bool, true > DisableSymbolication("disable-symbolication", cl::desc("Disable symbolizing crash backtraces."), cl::location(DisableSymbolicationFlag), cl::Hidden)
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)
This function executes the program using the arguments provided.
Definition: Program.cpp:31
static bool findModulesAndOffsets(void **StackTrace, int Depth, const char **Modules, intptr_t *Offsets, const char *MainExecutableName, StringSaver &StrPool)
FileRemover - This class is a simple object meant to be stack allocated.
Definition: FileUtilities.h:40
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
static bool DisableSymbolicationFlag
Definition: Signals.cpp:40
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:267
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
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...
void RunSignalHandlers()
Definition: Signals.cpp:59
#define LLVM_ATTRIBUTE_USED
Definition: Compiler.h:56
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:141
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:129
std::atomic< Status > Flag
Definition: Signals.cpp:53
StringRef parent_path(StringRef path, Style style=Style::native)
Get parent path.
Definition: Path.cpp:491
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:105
Basic Register Allocator
This is a helper class used for format_hex() and format_decimal().
Definition: Format.h:164
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
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:727
This file declares helper objects for defining debug options that can be configured via the command l...
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer...
Definition: StringSaver.h:22
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:133
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:366
std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD, SmallVectorImpl< char > &ResultPath)
Create a file in the system temporary directory.
Definition: Path.cpp:811
const char * c_str()
Definition: SmallString.h:270
#define I(x, y, z)
Definition: MD5.cpp:58
static CallbackAndCookie CallBacksToRun[MaxSignalHandlerCallbacks]
Definition: Signals.cpp:56
Provides ErrorOr<T> smart pointer.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
static constexpr size_t MaxSignalHandlerCallbacks
Definition: Signals.cpp:55
static void insertSignalHandler(sys::SignalHandlerCallback FnPtr, void *Cookie)
Definition: Signals.cpp:74
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
static FormattedNumber format_ptr(void *PC)
Format a pointer value as hexadecimal.
Definition: Signals.cpp:97
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:298
LocationClass< Ty > location(Ty &L)
Definition: CommandLine.h:435
constexpr char Args[]
Key for Kernel::Metadata::mArgs.