]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Support/Signals.cpp
Merge ^/head r317281 through r317502.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Support / Signals.cpp
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/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"
29 #include <vector>
30
31 namespace llvm {
32
33 //===----------------------------------------------------------------------===//
34 //=== WARNING: Implementation here must contain only TRULY operating system
35 //===          independent code.
36 //===----------------------------------------------------------------------===//
37
38 static ManagedStatic<std::vector<std::pair<void (*)(void *), void *>>>
39     CallBacksToRun;
40 void sys::RunSignalHandlers() {
41   if (!CallBacksToRun.isConstructed())
42     return;
43   for (auto &I : *CallBacksToRun)
44     I.first(I.second);
45   CallBacksToRun->clear();
46 }
47 }
48
49 using namespace llvm;
50
51 static 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.
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);
62 }
63
64 static bool printSymbolizedStackTrace(StringRef Argv0,
65                                       void **StackTrace, int Depth,
66                                       llvm::raw_ostream &OS)
67   LLVM_ATTRIBUTE_USED;
68
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)
75     return false;
76
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();
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");
89   if (!LLVMSymbolizerPathOrErr)
90     return false;
91   const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
92
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)
97                     : (std::string)Argv0;
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))
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
177 // Include the platform-specific parts of this class.
178 #ifdef LLVM_ON_UNIX
179 #include "Unix/Signals.inc"
180 #endif
181 #ifdef LLVM_ON_WIN32
182 #include "Windows/Signals.inc"
183 #endif