blob: 661f4d649cdd66c244499adc26cf95284eecdb1f [file] [log] [blame]
Reid Spencer3d7a6142004-08-29 19:22:48 +00001//===- Signals.cpp - Signal Handling support --------------------*- C++ -*-===//
Misha Brukman10468d82005-04-21 22:55:34 +00002//
Reid Spencer3d7a6142004-08-29 19:22:48 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman10468d82005-04-21 22:55:34 +00007//
Reid Spencer3d7a6142004-08-29 19:22:48 +00008//===----------------------------------------------------------------------===//
9//
10// This file defines some helpful functions for dealing with the possibility of
Chris Lattner0ab5e2c2011-04-15 05:18:47 +000011// Unix signals occurring while your program is running.
Reid Spencer3d7a6142004-08-29 19:22:48 +000012//
13//===----------------------------------------------------------------------===//
14
Chandler Carruth6bda14b2017-06-06 11:49:48 +000015#include "llvm/Support/Signals.h"
Reid Klecknerba5757d2015-11-05 01:07:54 +000016#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/StringRef.h"
Reid Spencer844f3fe2004-12-27 06:16:11 +000018#include "llvm/Config/config.h"
Reid Klecknerba5757d2015-11-05 01:07:54 +000019#include "llvm/Support/ErrorOr.h"
20#include "llvm/Support/FileSystem.h"
21#include "llvm/Support/FileUtilities.h"
22#include "llvm/Support/Format.h"
Yaron Keren240bd9c2015-07-22 19:01:14 +000023#include "llvm/Support/ManagedStatic.h"
Reid Klecknerba5757d2015-11-05 01:07:54 +000024#include "llvm/Support/MemoryBuffer.h"
25#include "llvm/Support/Mutex.h"
26#include "llvm/Support/Program.h"
Reid Klecknerba5757d2015-11-05 01:07:54 +000027#include "llvm/Support/StringSaver.h"
28#include "llvm/Support/raw_ostream.h"
David Blaikie4a60d372017-06-09 07:29:03 +000029#include "llvm/Support/Options.h"
Yaron Keren240bd9c2015-07-22 19:01:14 +000030#include <vector>
Reid Spencer3d7a6142004-08-29 19:22:48 +000031
Reid Spencer3d7a6142004-08-29 19:22:48 +000032//===----------------------------------------------------------------------===//
33//=== WARNING: Implementation here must contain only TRULY operating system
Misha Brukman10468d82005-04-21 22:55:34 +000034//=== independent code.
Reid Spencer3d7a6142004-08-29 19:22:48 +000035//===----------------------------------------------------------------------===//
36
David Blaikie4a60d372017-06-09 07:29:03 +000037using namespace llvm;
38
39static cl::opt<bool>
40 DisableSymbolication("disable-symbolication",
41 cl::desc("Disable symbolizing crash backtraces."),
42 cl::init(false), cl::Hidden);
43
Yaron Keren240bd9c2015-07-22 19:01:14 +000044static ManagedStatic<std::vector<std::pair<void (*)(void *), void *>>>
45 CallBacksToRun;
Yaron Keren28738102015-07-22 21:11:17 +000046void sys::RunSignalHandlers() {
Yaron Keren240bd9c2015-07-22 19:01:14 +000047 if (!CallBacksToRun.isConstructed())
48 return;
49 for (auto &I : *CallBacksToRun)
50 I.first(I.second);
51 CallBacksToRun->clear();
52}
Reid Klecknerba5757d2015-11-05 01:07:54 +000053
54static 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.
61static 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
Richard Smith2ad6d482016-06-09 00:53:21 +000067static bool printSymbolizedStackTrace(StringRef Argv0,
68 void **StackTrace, int Depth,
NAKAMURA Takumi02d97aa2015-11-08 09:45:06 +000069 llvm::raw_ostream &OS)
70 LLVM_ATTRIBUTE_USED;
71
Reid Klecknerba5757d2015-11-05 01:07:54 +000072/// Helper that launches llvm-symbolizer and symbolizes a backtrace.
Richard Smith2ad6d482016-06-09 00:53:21 +000073static bool printSymbolizedStackTrace(StringRef Argv0,
74 void **StackTrace, int Depth,
Reid Klecknerba5757d2015-11-05 01:07:54 +000075 llvm::raw_ostream &OS) {
David Blaikie4a60d372017-06-09 07:29:03 +000076 if (DisableSymbolication)
77 return false;
78
Richard Smith2ad6d482016-06-09 00:53:21 +000079 // Don't recursively invoke the llvm-symbolizer binary.
80 if (Argv0.find("llvm-symbolizer") != std::string::npos)
81 return false;
82
Reid Klecknerba5757d2015-11-05 01:07:54 +000083 // FIXME: Subtract necessary number from StackTrace entries to turn return addresses
84 // into actual instruction addresses.
Richard Smith2ad6d482016-06-09 00:53:21 +000085 // 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()) {
89 StringRef Parent = llvm::sys::path::parent_path(Argv0);
90 if (!Parent.empty())
91 LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer", Parent);
92 }
93 if (!LLVMSymbolizerPathOrErr)
94 LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer");
Reid Klecknerba5757d2015-11-05 01:07:54 +000095 if (!LLVMSymbolizerPathOrErr)
96 return false;
97 const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
Reid Klecknerba5757d2015-11-05 01:07:54 +000098
Richard Smith2ad6d482016-06-09 00:53:21 +000099 // 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;
Reid Klecknerba5757d2015-11-05 01:07:54 +0000104 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))
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
Alexander Kornienko208eecd2017-09-13 17:03:37 +0000126 Optional<StringRef> Redirects[] = {InputFile.str(), OutputFile.str(), llvm::None};
Reid Klecknerba5757d2015-11-05 01:07:54 +0000127 const char *Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
128#ifdef LLVM_ON_WIN32
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",
133#endif
134 "--demangle", nullptr};
135 int RunResult =
136 sys::ExecuteAndWait(LLVMSymbolizerPath, Args, nullptr, Redirects);
137 if (RunResult != 0)
138 return false;
139
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());
143 if (!OutputBuf)
144 return false;
145 StringRef Output = OutputBuf.get()->getBuffer();
146 SmallVector<StringRef, 32> Lines;
147 Output.split(Lines, "\n");
148 auto CurLine = Lines.begin();
149 int frame_no = 0;
150 for (int i = 0; i < Depth; i++) {
151 if (!Modules[i]) {
152 OS << '#' << frame_no++ << ' ' << format_ptr(StackTrace[i]) << '\n';
153 continue;
154 }
155 // Read pairs of lines (function name and file/line info) until we
156 // encounter empty line.
157 for (;;) {
158 if (CurLine == Lines.end())
159 return false;
160 StringRef FunctionName = *CurLine++;
161 if (FunctionName.empty())
162 break;
163 OS << '#' << frame_no++ << ' ' << format_ptr(StackTrace[i]) << ' ';
164 if (!FunctionName.startswith("??"))
165 OS << FunctionName << ' ';
166 if (CurLine == Lines.end())
167 return false;
168 StringRef FileLineInfo = *CurLine++;
169 if (!FileLineInfo.startswith("??"))
170 OS << FileLineInfo;
171 else
172 OS << "(" << Modules[i] << '+' << format_hex(Offsets[i], 0) << ")";
173 OS << "\n";
174 }
175 }
176 return true;
177}
178
Reid Spencer3d7a6142004-08-29 19:22:48 +0000179// Include the platform-specific parts of this class.
Reid Spencer844f3fe2004-12-27 06:16:11 +0000180#ifdef LLVM_ON_UNIX
Reid Spencerc892a0d2005-01-09 23:29:00 +0000181#include "Unix/Signals.inc"
Reid Spencer844f3fe2004-12-27 06:16:11 +0000182#endif
183#ifdef LLVM_ON_WIN32
Michael J. Spencer447762d2010-11-29 18:16:10 +0000184#include "Windows/Signals.inc"
Reid Spencer844f3fe2004-12-27 06:16:11 +0000185#endif