Fix OSX build after r252118 (missing parameter for findModulesAndOffsets())
[oota-llvm.git] / 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 using namespace sys;
33
34 //===----------------------------------------------------------------------===//
35 //=== WARNING: Implementation here must contain only TRULY operating system
36 //===          independent code.
37 //===----------------------------------------------------------------------===//
38
39 static ManagedStatic<std::vector<std::pair<void (*)(void *), void *>>>
40     CallBacksToRun;
41 void sys::RunSignalHandlers() {
42   if (!CallBacksToRun.isConstructed())
43     return;
44   for (auto &I : *CallBacksToRun)
45     I.first(I.second);
46   CallBacksToRun->clear();
47 }
48 }
49
50 using namespace llvm;
51
52 static bool findModulesAndOffsets(void **StackTrace, int Depth,
53                                   const char **Modules, intptr_t *Offsets,
54                                   const char *MainExecutableName,
55                                   StringSaver &StrPool);
56
57 /// Format a pointer value as hexadecimal. Zero pad it out so its always the
58 /// same width.
59 static FormattedNumber format_ptr(void *PC) {
60   // Each byte is two hex digits plus 2 for the 0x prefix.
61   unsigned PtrWidth = 2 + 2 * sizeof(void *);
62   return format_hex((uint64_t)PC, PtrWidth);
63 }
64
65 /// Helper that launches llvm-symbolizer and symbolizes a backtrace.
66 static bool printSymbolizedStackTrace(void **StackTrace, int Depth,
67                                       llvm::raw_ostream &OS) {
68   // FIXME: Subtract necessary number from StackTrace entries to turn return addresses
69   // into actual instruction addresses.
70   // Use llvm-symbolizer tool to symbolize the stack traces.
71   ErrorOr<std::string> LLVMSymbolizerPathOrErr =
72       sys::findProgramByName("llvm-symbolizer");
73   if (!LLVMSymbolizerPathOrErr)
74     return false;
75   const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
76   // We don't know argv0 or the address of main() at this point, but try
77   // to guess it anyway (it's possible on some platforms).
78   std::string MainExecutableName = sys::fs::getMainExecutable(nullptr, nullptr);
79   if (MainExecutableName.empty() ||
80       MainExecutableName.find("llvm-symbolizer") != std::string::npos)
81     return false;
82
83   BumpPtrAllocator Allocator;
84   StringSaver StrPool(Allocator);
85   std::vector<const char *> Modules(Depth, nullptr);
86   std::vector<intptr_t> Offsets(Depth, 0);
87   if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(),
88                              MainExecutableName.c_str(), StrPool))
89     return false;
90   int InputFD;
91   SmallString<32> InputFile, OutputFile;
92   sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile);
93   sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile);
94   FileRemover InputRemover(InputFile.c_str());
95   FileRemover OutputRemover(OutputFile.c_str());
96
97   {
98     raw_fd_ostream Input(InputFD, true);
99     for (int i = 0; i < Depth; i++) {
100       if (Modules[i])
101         Input << Modules[i] << " " << (void*)Offsets[i] << "\n";
102     }
103   }
104
105   StringRef InputFileStr(InputFile);
106   StringRef OutputFileStr(OutputFile);
107   StringRef StderrFileStr;
108   const StringRef *Redirects[] = {&InputFileStr, &OutputFileStr,
109                                   &StderrFileStr};
110   const char *Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
111 #ifdef LLVM_ON_WIN32
112                         // Pass --relative-address on Windows so that we don't
113                         // have to add ImageBase from PE file.
114                         // FIXME: Make this the default for llvm-symbolizer.
115                         "--relative-address",
116 #endif
117                         "--demangle", nullptr};
118   int RunResult =
119       sys::ExecuteAndWait(LLVMSymbolizerPath, Args, nullptr, Redirects);
120   if (RunResult != 0)
121     return false;
122
123   // This report format is based on the sanitizer stack trace printer.  See
124   // sanitizer_stacktrace_printer.cc in compiler-rt.
125   auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str());
126   if (!OutputBuf)
127     return false;
128   StringRef Output = OutputBuf.get()->getBuffer();
129   SmallVector<StringRef, 32> Lines;
130   Output.split(Lines, "\n");
131   auto CurLine = Lines.begin();
132   int frame_no = 0;
133   for (int i = 0; i < Depth; i++) {
134     if (!Modules[i]) {
135       OS << '#' << frame_no++ << ' ' << format_ptr(StackTrace[i]) << '\n';
136       continue;
137     }
138     // Read pairs of lines (function name and file/line info) until we
139     // encounter empty line.
140     for (;;) {
141       if (CurLine == Lines.end())
142         return false;
143       StringRef FunctionName = *CurLine++;
144       if (FunctionName.empty())
145         break;
146       OS << '#' << frame_no++ << ' ' << format_ptr(StackTrace[i]) << ' ';
147       if (!FunctionName.startswith("??"))
148         OS << FunctionName << ' ';
149       if (CurLine == Lines.end())
150         return false;
151       StringRef FileLineInfo = *CurLine++;
152       if (!FileLineInfo.startswith("??"))
153         OS << FileLineInfo;
154       else
155         OS << "(" << Modules[i] << '+' << format_hex(Offsets[i], 0) << ")";
156       OS << "\n";
157     }
158   }
159   return true;
160 }
161
162 // Include the platform-specific parts of this class.
163 #ifdef LLVM_ON_UNIX
164 #include "Unix/Signals.inc"
165 #endif
166 #ifdef LLVM_ON_WIN32
167 #include "Windows/Signals.inc"
168 #endif