1 //===- Signals.cpp - Signal Handling support --------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines some helpful functions for dealing with the possibility of
11 // Unix signals occurring while your program is running.
13 //===----------------------------------------------------------------------===//
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"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/FileUtilities.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/Mutex.h"
26 #include "llvm/Support/Program.h"
27 #include "llvm/Support/StringSaver.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Support/Options.h"
32 //===----------------------------------------------------------------------===//
33 //=== WARNING: Implementation here must contain only TRULY operating system
34 //=== independent code.
35 //===----------------------------------------------------------------------===//
40 DisableSymbolication("disable-symbolication",
41 cl::desc("Disable symbolizing crash backtraces."),
42 cl::init(false), cl::Hidden);
44 static ManagedStatic<std::vector<std::pair<void (*)(void *), void *>>>
46 void sys::RunSignalHandlers() {
47 if (!CallBacksToRun.isConstructed())
49 for (auto &I : *CallBacksToRun)
51 CallBacksToRun->clear();
54 static bool findModulesAndOffsets(void **StackTrace, int Depth,
55 const char **Modules, intptr_t *Offsets,
56 const char *MainExecutableName,
57 StringSaver &StrPool);
59 /// Format a pointer value as hexadecimal. Zero pad it out so its always the
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);
67 static bool printSymbolizedStackTrace(StringRef Argv0,
68 void **StackTrace, int Depth,
69 llvm::raw_ostream &OS)
72 /// Helper that launches llvm-symbolizer and symbolizes a backtrace.
73 static bool printSymbolizedStackTrace(StringRef Argv0,
74 void **StackTrace, int Depth,
75 llvm::raw_ostream &OS) {
76 if (DisableSymbolication)
79 // Don't recursively invoke the llvm-symbolizer binary.
80 if (Argv0.find("llvm-symbolizer") != std::string::npos)
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();
89 StringRef Parent = llvm::sys::path::parent_path(Argv0);
91 LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer", Parent);
93 if (!LLVMSymbolizerPathOrErr)
94 LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer");
95 if (!LLVMSymbolizerPathOrErr)
97 const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
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;
104 BumpPtrAllocator Allocator;
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))
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());
119 raw_fd_ostream Input(InputFD, true);
120 for (int i = 0; i < Depth; i++) {
122 Input << Modules[i] << " " << (void*)Offsets[i] << "\n";
126 Optional<StringRef> Redirects[] = {InputFile.str(), OutputFile.str(), llvm::None};
127 const char *Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
129 // Pass --relative-address on Windows so that we don't
130 // have to add ImageBase from PE file.
131 // FIXME: Make this the default for llvm-symbolizer.
132 "--relative-address",
134 "--demangle", nullptr};
136 sys::ExecuteAndWait(LLVMSymbolizerPath, Args, nullptr, Redirects);
140 // This report format is based on the sanitizer stack trace printer. See
141 // sanitizer_stacktrace_printer.cc in compiler-rt.
142 auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str());
145 StringRef Output = OutputBuf.get()->getBuffer();
146 SmallVector<StringRef, 32> Lines;
147 Output.split(Lines, "\n");
148 auto CurLine = Lines.begin();
150 for (int i = 0; i < Depth; i++) {
152 OS << '#' << frame_no++ << ' ' << format_ptr(StackTrace[i]) << '\n';
155 // Read pairs of lines (function name and file/line info) until we
156 // encounter empty line.
158 if (CurLine == Lines.end())
160 StringRef FunctionName = *CurLine++;
161 if (FunctionName.empty())
163 OS << '#' << frame_no++ << ' ' << format_ptr(StackTrace[i]) << ' ';
164 if (!FunctionName.startswith("??"))
165 OS << FunctionName << ' ';
166 if (CurLine == Lines.end())
168 StringRef FileLineInfo = *CurLine++;
169 if (!FileLineInfo.startswith("??"))
172 OS << "(" << Modules[i] << '+' << format_hex(Offsets[i], 0) << ")";
179 // Include the platform-specific parts of this class.
181 #include "Unix/Signals.inc"
184 #include "Windows/Signals.inc"