blob: 052a7424709cab5f994538f49431aeb64b846ce8 [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"
Yaron Keren240bd9c2015-07-22 19:01:14 +000029#include <vector>
Reid Spencer3d7a6142004-08-29 19:22:48 +000030
31namespace llvm {
Reid Spencer3d7a6142004-08-29 19:22:48 +000032
33//===----------------------------------------------------------------------===//
34//=== WARNING: Implementation here must contain only TRULY operating system
Misha Brukman10468d82005-04-21 22:55:34 +000035//=== independent code.
Reid Spencer3d7a6142004-08-29 19:22:48 +000036//===----------------------------------------------------------------------===//
37
Yaron Keren240bd9c2015-07-22 19:01:14 +000038static ManagedStatic<std::vector<std::pair<void (*)(void *), void *>>>
39 CallBacksToRun;
Yaron Keren28738102015-07-22 21:11:17 +000040void sys::RunSignalHandlers() {
Yaron Keren240bd9c2015-07-22 19:01:14 +000041 if (!CallBacksToRun.isConstructed())
42 return;
43 for (auto &I : *CallBacksToRun)
44 I.first(I.second);
45 CallBacksToRun->clear();
46}
Reid Spencer3d7a6142004-08-29 19:22:48 +000047}
48
Reid Klecknerba5757d2015-11-05 01:07:54 +000049using namespace llvm;
50
51static bool findModulesAndOffsets(void **StackTrace, int Depth,
52 const char **Modules, intptr_t *Offsets,
53 const char *MainExecutableName,
54 StringSaver &StrPool);
55
56/// Format a pointer value as hexadecimal. Zero pad it out so its always the
57/// same width.
58static 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);
62}
63
Richard Smith2ad6d482016-06-09 00:53:21 +000064static bool printSymbolizedStackTrace(StringRef Argv0,
65 void **StackTrace, int Depth,
NAKAMURA Takumi02d97aa2015-11-08 09:45:06 +000066 llvm::raw_ostream &OS)
67 LLVM_ATTRIBUTE_USED;
68
Reid Klecknerba5757d2015-11-05 01:07:54 +000069/// Helper that launches llvm-symbolizer and symbolizes a backtrace.
Richard Smith2ad6d482016-06-09 00:53:21 +000070static bool printSymbolizedStackTrace(StringRef Argv0,
71 void **StackTrace, int Depth,
Reid Klecknerba5757d2015-11-05 01:07:54 +000072 llvm::raw_ostream &OS) {
Richard Smith2ad6d482016-06-09 00:53:21 +000073 // Don't recursively invoke the llvm-symbolizer binary.
74 if (Argv0.find("llvm-symbolizer") != std::string::npos)
75 return false;
76
Reid Klecknerba5757d2015-11-05 01:07:54 +000077 // FIXME: Subtract necessary number from StackTrace entries to turn return addresses
78 // into actual instruction addresses.
Richard Smith2ad6d482016-06-09 00:53:21 +000079 // 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();
82 if (!Argv0.empty()) {
83 StringRef Parent = llvm::sys::path::parent_path(Argv0);
84 if (!Parent.empty())
85 LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer", Parent);
86 }
87 if (!LLVMSymbolizerPathOrErr)
88 LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer");
Reid Klecknerba5757d2015-11-05 01:07:54 +000089 if (!LLVMSymbolizerPathOrErr)
90 return false;
91 const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
Reid Klecknerba5757d2015-11-05 01:07:54 +000092
Richard Smith2ad6d482016-06-09 00:53:21 +000093 // 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)
97 : (std::string)Argv0;
Reid Klecknerba5757d2015-11-05 01:07:54 +000098 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))
104 return false;
105 int InputFD;
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());
111
112 {
113 raw_fd_ostream Input(InputFD, true);
114 for (int i = 0; i < Depth; i++) {
115 if (Modules[i])
116 Input << Modules[i] << " " << (void*)Offsets[i] << "\n";
117 }
118 }
119
120 StringRef InputFileStr(InputFile);
121 StringRef OutputFileStr(OutputFile);
122 StringRef StderrFileStr;
123 const StringRef *Redirects[] = {&InputFileStr, &OutputFileStr,
124 &StderrFileStr};
125 const char *Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
126#ifdef LLVM_ON_WIN32
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",
131#endif
132 "--demangle", nullptr};
133 int RunResult =
134 sys::ExecuteAndWait(LLVMSymbolizerPath, Args, nullptr, Redirects);
135 if (RunResult != 0)
136 return false;
137
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());
141 if (!OutputBuf)
142 return false;
143 StringRef Output = OutputBuf.get()->getBuffer();
144 SmallVector<StringRef, 32> Lines;
145 Output.split(Lines, "\n");
146 auto CurLine = Lines.begin();
147 int frame_no = 0;
148 for (int i = 0; i < Depth; i++) {
149 if (!Modules[i]) {
150 OS << '#' << frame_no++ << ' ' << format_ptr(StackTrace[i]) << '\n';
151 continue;
152 }
153 // Read pairs of lines (function name and file/line info) until we
154 // encounter empty line.
155 for (;;) {
156 if (CurLine == Lines.end())
157 return false;
158 StringRef FunctionName = *CurLine++;
159 if (FunctionName.empty())
160 break;
161 OS << '#' << frame_no++ << ' ' << format_ptr(StackTrace[i]) << ' ';
162 if (!FunctionName.startswith("??"))
163 OS << FunctionName << ' ';
164 if (CurLine == Lines.end())
165 return false;
166 StringRef FileLineInfo = *CurLine++;
167 if (!FileLineInfo.startswith("??"))
168 OS << FileLineInfo;
169 else
170 OS << "(" << Modules[i] << '+' << format_hex(Offsets[i], 0) << ")";
171 OS << "\n";
172 }
173 }
174 return true;
175}
176
Reid Spencer3d7a6142004-08-29 19:22:48 +0000177// Include the platform-specific parts of this class.
Reid Spencer844f3fe2004-12-27 06:16:11 +0000178#ifdef LLVM_ON_UNIX
Reid Spencerc892a0d2005-01-09 23:29:00 +0000179#include "Unix/Signals.inc"
Reid Spencer844f3fe2004-12-27 06:16:11 +0000180#endif
181#ifdef LLVM_ON_WIN32
Michael J. Spencer447762d2010-11-29 18:16:10 +0000182#include "Windows/Signals.inc"
Reid Spencer844f3fe2004-12-27 06:16:11 +0000183#endif