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/ADT/STLExtras.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/Config/config.h"
18 #include "llvm/Support/ErrorOr.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/FileUtilities.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/Mutex.h"
25 #include "llvm/Support/Program.h"
26 #include "llvm/Support/Signals.h"
27 #include "llvm/Support/StringSaver.h"
28 #include "llvm/Support/raw_ostream.h"
33 //===----------------------------------------------------------------------===//
34 //=== WARNING: Implementation here must contain only TRULY operating system
35 //=== independent code.
36 //===----------------------------------------------------------------------===//
38 static ManagedStatic<std::vector<std::pair<void (*)(void *), void *>>>
40 void sys::RunSignalHandlers() {
41 if (!CallBacksToRun.isConstructed())
43 for (auto &I : *CallBacksToRun)
45 CallBacksToRun->clear();
51 static bool findModulesAndOffsets(void **StackTrace, int Depth,
52 const char **Modules, intptr_t *Offsets,
53 const char *MainExecutableName,
54 StringSaver &StrPool);
56 /// Format a pointer value as hexadecimal. Zero pad it out so its always the
58 static FormattedNumber format_ptr(void *PC) {
59 // Each byte is two hex digits plus 2 for the 0x prefix.
60 unsigned PtrWidth = 2 + 2 * sizeof(void *);
61 return format_hex((uint64_t)PC, PtrWidth);
64 static bool printSymbolizedStackTrace(StringRef Argv0,
65 void **StackTrace, int Depth,
66 llvm::raw_ostream &OS)
69 /// Helper that launches llvm-symbolizer and symbolizes a backtrace.
70 static bool printSymbolizedStackTrace(StringRef Argv0,
71 void **StackTrace, int Depth,
72 llvm::raw_ostream &OS) {
73 // Don't recursively invoke the llvm-symbolizer binary.
74 if (Argv0.find("llvm-symbolizer") != std::string::npos)
77 // FIXME: Subtract necessary number from StackTrace entries to turn return addresses
78 // into actual instruction addresses.
79 // Use llvm-symbolizer tool to symbolize the stack traces. First look for it
80 // alongside our binary, then in $PATH.
81 ErrorOr<std::string> LLVMSymbolizerPathOrErr = std::error_code();
83 StringRef Parent = llvm::sys::path::parent_path(Argv0);
85 LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer", Parent);
87 if (!LLVMSymbolizerPathOrErr)
88 LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer");
89 if (!LLVMSymbolizerPathOrErr)
91 const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
93 // If we don't know argv0 or the address of main() at this point, try
94 // to guess it anyway (it's possible on some platforms).
95 std::string MainExecutableName =
96 Argv0.empty() ? sys::fs::getMainExecutable(nullptr, nullptr)
98 BumpPtrAllocator Allocator;
99 StringSaver StrPool(Allocator);
100 std::vector<const char *> Modules(Depth, nullptr);
101 std::vector<intptr_t> Offsets(Depth, 0);
102 if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(),
103 MainExecutableName.c_str(), StrPool))
106 SmallString<32> InputFile, OutputFile;
107 sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile);
108 sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile);
109 FileRemover InputRemover(InputFile.c_str());
110 FileRemover OutputRemover(OutputFile.c_str());
113 raw_fd_ostream Input(InputFD, true);
114 for (int i = 0; i < Depth; i++) {
116 Input << Modules[i] << " " << (void*)Offsets[i] << "\n";
120 StringRef InputFileStr(InputFile);
121 StringRef OutputFileStr(OutputFile);
122 StringRef StderrFileStr;
123 const StringRef *Redirects[] = {&InputFileStr, &OutputFileStr,
125 const char *Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
127 // Pass --relative-address on Windows so that we don't
128 // have to add ImageBase from PE file.
129 // FIXME: Make this the default for llvm-symbolizer.
130 "--relative-address",
132 "--demangle", nullptr};
134 sys::ExecuteAndWait(LLVMSymbolizerPath, Args, nullptr, Redirects);
138 // This report format is based on the sanitizer stack trace printer. See
139 // sanitizer_stacktrace_printer.cc in compiler-rt.
140 auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str());
143 StringRef Output = OutputBuf.get()->getBuffer();
144 SmallVector<StringRef, 32> Lines;
145 Output.split(Lines, "\n");
146 auto CurLine = Lines.begin();
148 for (int i = 0; i < Depth; i++) {
150 OS << '#' << frame_no++ << ' ' << format_ptr(StackTrace[i]) << '\n';
153 // Read pairs of lines (function name and file/line info) until we
154 // encounter empty line.
156 if (CurLine == Lines.end())
158 StringRef FunctionName = *CurLine++;
159 if (FunctionName.empty())
161 OS << '#' << frame_no++ << ' ' << format_ptr(StackTrace[i]) << ' ';
162 if (!FunctionName.startswith("??"))
163 OS << FunctionName << ' ';
164 if (CurLine == Lines.end())
166 StringRef FileLineInfo = *CurLine++;
167 if (!FileLineInfo.startswith("??"))
170 OS << "(" << Modules[i] << '+' << format_hex(Offsets[i], 0) << ")";
177 // Include the platform-specific parts of this class.
179 #include "Unix/Signals.inc"
182 #include "Windows/Signals.inc"