LLVM  5.0.0
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/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 static cl::opt<bool>
40  DisableSymbolication("disable-symbolication",
41  cl::desc("Disable symbolizing crash backtraces."),
42  cl::init(false), cl::Hidden);
43 
47  if (!CallBacksToRun.isConstructed())
48  return;
49  for (auto &I : *CallBacksToRun)
50  I.first(I.second);
51  CallBacksToRun->clear();
52 }
53 
54 static bool findModulesAndOffsets(void **StackTrace, int Depth,
55  const char **Modules, intptr_t *Offsets,
56  const char *MainExecutableName,
57  StringSaver &StrPool);
58 
59 /// Format a pointer value as hexadecimal. Zero pad it out so its always the
60 /// same width.
61 static FormattedNumber format_ptr(void *PC) {
62  // Each byte is two hex digits plus 2 for the 0x prefix.
63  unsigned PtrWidth = 2 + 2 * sizeof(void *);
64  return format_hex((uint64_t)PC, PtrWidth);
65 }
66 
67 static bool printSymbolizedStackTrace(StringRef Argv0,
68  void **StackTrace, int Depth,
71 
72 /// Helper that launches llvm-symbolizer and symbolizes a backtrace.
74  void **StackTrace, int Depth,
75  llvm::raw_ostream &OS) {
77  return false;
78 
79  // Don't recursively invoke the llvm-symbolizer binary.
80  if (Argv0.find("llvm-symbolizer") != std::string::npos)
81  return false;
82 
83  // FIXME: Subtract necessary number from StackTrace entries to turn return addresses
84  // into actual instruction addresses.
85  // Use llvm-symbolizer tool to symbolize the stack traces. First look for it
86  // alongside our binary, then in $PATH.
87  ErrorOr<std::string> LLVMSymbolizerPathOrErr = std::error_code();
88  if (!Argv0.empty()) {
90  if (!Parent.empty())
91  LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer", Parent);
92  }
93  if (!LLVMSymbolizerPathOrErr)
94  LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer");
95  if (!LLVMSymbolizerPathOrErr)
96  return false;
97  const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
98 
99  // If we don't know argv0 or the address of main() at this point, try
100  // to guess it anyway (it's possible on some platforms).
101  std::string MainExecutableName =
102  Argv0.empty() ? sys::fs::getMainExecutable(nullptr, nullptr)
103  : (std::string)Argv0;
105  StringSaver StrPool(Allocator);
106  std::vector<const char *> Modules(Depth, nullptr);
107  std::vector<intptr_t> Offsets(Depth, 0);
108  if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(),
109  MainExecutableName.c_str(), StrPool))
110  return false;
111  int InputFD;
112  SmallString<32> InputFile, OutputFile;
113  sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile);
114  sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile);
115  FileRemover InputRemover(InputFile.c_str());
116  FileRemover OutputRemover(OutputFile.c_str());
117 
118  {
119  raw_fd_ostream Input(InputFD, true);
120  for (int i = 0; i < Depth; i++) {
121  if (Modules[i])
122  Input << Modules[i] << " " << (void*)Offsets[i] << "\n";
123  }
124  }
125 
126  StringRef InputFileStr(InputFile);
127  StringRef OutputFileStr(OutputFile);
128  StringRef StderrFileStr;
129  const StringRef *Redirects[] = {&InputFileStr, &OutputFileStr,
130  &StderrFileStr};
131  const char *Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
132 #ifdef LLVM_ON_WIN32
133  // Pass --relative-address on Windows so that we don't
134  // have to add ImageBase from PE file.
135  // FIXME: Make this the default for llvm-symbolizer.
136  "--relative-address",
137 #endif
138  "--demangle", nullptr};
139  int RunResult =
140  sys::ExecuteAndWait(LLVMSymbolizerPath, Args, nullptr, Redirects);
141  if (RunResult != 0)
142  return false;
143 
144  // This report format is based on the sanitizer stack trace printer. See
145  // sanitizer_stacktrace_printer.cc in compiler-rt.
146  auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str());
147  if (!OutputBuf)
148  return false;
149  StringRef Output = OutputBuf.get()->getBuffer();
151  Output.split(Lines, "\n");
152  auto CurLine = Lines.begin();
153  int frame_no = 0;
154  for (int i = 0; i < Depth; i++) {
155  if (!Modules[i]) {
156  OS << '#' << frame_no++ << ' ' << format_ptr(StackTrace[i]) << '\n';
157  continue;
158  }
159  // Read pairs of lines (function name and file/line info) until we
160  // encounter empty line.
161  for (;;) {
162  if (CurLine == Lines.end())
163  return false;
164  StringRef FunctionName = *CurLine++;
165  if (FunctionName.empty())
166  break;
167  OS << '#' << frame_no++ << ' ' << format_ptr(StackTrace[i]) << ' ';
168  if (!FunctionName.startswith("??"))
169  OS << FunctionName << ' ';
170  if (CurLine == Lines.end())
171  return false;
172  StringRef FileLineInfo = *CurLine++;
173  if (!FileLineInfo.startswith("??"))
174  OS << FileLineInfo;
175  else
176  OS << "(" << Modules[i] << '+' << format_hex(Offsets[i], 0) << ")";
177  OS << "\n";
178  }
179  }
180  return true;
181 }
182 
183 // Include the platform-specific parts of this class.
184 #ifdef LLVM_ON_UNIX
185 #include "Unix/Signals.inc"
186 #endif
187 #ifdef LLVM_ON_WIN32
188 #include "Windows/Signals.inc"
189 #endif
Represents either an error or a value T.
Definition: ErrorOr.h:69
FormattedNumber format_hex(uint64_t N, unsigned Width, bool Upper=false)
format_hex - Output N as a fixed width hexadecimal.
Definition: Format.h:186
Offsets
Offsets in bytes from the start of the input buffer.
Definition: SIInstrInfo.h:864
static FILE * OutputFile
Definition: FuzzerIO.cpp:24
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
static cl::opt< bool > DisableSymbolication("disable-symbolication", cl::desc("Disable symbolizing crash backtraces."), cl::init(false), cl::Hidden)
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:267
int ExecuteAndWait(StringRef Program, const char **args, const char **env=nullptr, const StringRef **redirects=nullptr, 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:30
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:46
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:401
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
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:138
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:115
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
StringRef parent_path(StringRef path, Style style=Style::native)
Get parent path.
Definition: Path.cpp:476
Basic Register Allocator
static bool printSymbolizedStackTrace(StringRef Argv0, void **StackTrace, int Depth, llvm::raw_ostream &OS) LLVM_ATTRIBUTE_USED
Helper that launches llvm-symbolizer and symbolizes a backtrace.
Definition: Signals.cpp:73
This is a helper class used for format_hex() and format_decimal().
Definition: Format.h:164
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
This file declares helper objects for defining debug options that can be configured via the command l...
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
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
Saves strings in the inheritor's stable storage and returns a StringRef with a stable character point...
Definition: StringSaver.h:21
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:119
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:357
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:783
const char * c_str()
Definition: SmallString.h:270
#define I(x, y, z)
Definition: MD5.cpp:58
ErrorOr< std::string > findProgramByName(StringRef Name, ArrayRef< StringRef > Paths=None)
Find the first executable file Name in Paths.
static ManagedStatic< std::vector< std::pair< void(*)(void *), void * > > > CallBacksToRun
Definition: Signals.cpp:45
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.
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
static FormattedNumber format_ptr(void *PC)
Format a pointer value as hexadecimal.
Definition: Signals.cpp:61
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
Definition: ManagedStatic.h:61
#define LLVM_ATTRIBUTE_USED
Definition: Compiler.h:117