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/Support/Signals.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/Config/llvm-config.h"
19 #include "llvm/Support/ErrorOr.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/FileUtilities.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/Mutex.h"
26 #include "llvm/Support/Program.h"
27 #include "llvm/Support/StringSaver.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Support/Options.h"
30 #include <vector>
31 
32 //===----------------------------------------------------------------------===//
33 //=== WARNING: Implementation here must contain only TRULY operating system
34 //===          independent code.
35 //===----------------------------------------------------------------------===//
36 
37 using namespace llvm;
38 
39 // Use explicit storage to avoid accessing cl::opt in a signal handler.
40 static bool DisableSymbolicationFlag = false;
41 static cl::opt<bool, true>
42     DisableSymbolication("disable-symbolication",
43                          cl::desc("Disable symbolizing crash backtraces."),
44                          cl::location(DisableSymbolicationFlag), cl::Hidden);
45 
46 // Callbacks to run in signal handler must be lock-free because a signal handler
47 // could be running as we add new callbacks. We don't add unbounded numbers of
48 // callbacks, an array is therefore sufficient.
49 // Assume two pointers are always lock-free.
50 struct LLVM_ALIGNAS(sizeof(void *) * 2) CallbackAndCookie {
51   sys::SignalHandlerCallback Callback;
52   void *Cookie;
53 };
54 static constexpr size_t MaxSignalHandlerCallbacks = 8;
55 static std::atomic<CallbackAndCookie> CallBacksToRun[MaxSignalHandlerCallbacks];
56 
57 void sys::RunSignalHandlers() { // Signal-safe.
58   for (size_t I = 0; I < MaxSignalHandlerCallbacks; ++I) {
59     CallbackAndCookie DoNothing{nullptr, nullptr};
60     auto Entry = CallBacksToRun[I].exchange(DoNothing);
61     if (Entry.Callback)
62       (*Entry.Callback)(Entry.Cookie);
63   }
64 }
65 
66 static void insertSignalHandler(sys::SignalHandlerCallback FnPtr,
67                                 void *Cookie) { // Signal-safe.
68   CallbackAndCookie Entry = CallbackAndCookie{FnPtr, Cookie};
69   for (size_t I = 0; I < MaxSignalHandlerCallbacks; ++I) {
70     CallbackAndCookie Expected{nullptr, nullptr};
71     if (CallBacksToRun[I].compare_exchange_strong(Expected, Entry))
72       return;
73   }
74   llvm_unreachable("too many signal callbacks already registered");
75 }
76 
77 static bool findModulesAndOffsets(void **StackTrace, int Depth,
78                                   const char **Modules, intptr_t *Offsets,
79                                   const char *MainExecutableName,
80                                   StringSaver &StrPool);
81 
82 /// Format a pointer value as hexadecimal. Zero pad it out so its always the
83 /// same width.
84 static FormattedNumber format_ptr(void *PC) {
85   // Each byte is two hex digits plus 2 for the 0x prefix.
86   unsigned PtrWidth = 2 + 2 * sizeof(void *);
87   return format_hex((uint64_t)PC, PtrWidth);
88 }
89 
90 /// Helper that launches llvm-symbolizer and symbolizes a backtrace.
91 LLVM_ATTRIBUTE_USED
92 static bool printSymbolizedStackTrace(StringRef Argv0, void **StackTrace,
93                                       int Depth, llvm::raw_ostream &OS) {
94   if (DisableSymbolicationFlag)
95     return false;
96 
97   // Don't recursively invoke the llvm-symbolizer binary.
98   if (Argv0.find("llvm-symbolizer") != std::string::npos)
99     return false;
100 
101   // FIXME: Subtract necessary number from StackTrace entries to turn return addresses
102   // into actual instruction addresses.
103   // Use llvm-symbolizer tool to symbolize the stack traces. First look for it
104   // alongside our binary, then in $PATH.
105   ErrorOr<std::string> LLVMSymbolizerPathOrErr = std::error_code();
106   if (!Argv0.empty()) {
107     StringRef Parent = llvm::sys::path::parent_path(Argv0);
108     if (!Parent.empty())
109       LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer", Parent);
110   }
111   if (!LLVMSymbolizerPathOrErr)
112     LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer");
113   if (!LLVMSymbolizerPathOrErr)
114     return false;
115   const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
116 
117   // If we don't know argv0 or the address of main() at this point, try
118   // to guess it anyway (it's possible on some platforms).
119   std::string MainExecutableName =
120       Argv0.empty() ? sys::fs::getMainExecutable(nullptr, nullptr)
121                     : (std::string)Argv0;
122   BumpPtrAllocator Allocator;
123   StringSaver StrPool(Allocator);
124   std::vector<const char *> Modules(Depth, nullptr);
125   std::vector<intptr_t> Offsets(Depth, 0);
126   if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(),
127                              MainExecutableName.c_str(), StrPool))
128     return false;
129   int InputFD;
130   SmallString<32> InputFile, OutputFile;
131   sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile);
132   sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile);
133   FileRemover InputRemover(InputFile.c_str());
134   FileRemover OutputRemover(OutputFile.c_str());
135 
136   {
137     raw_fd_ostream Input(InputFD, true);
138     for (int i = 0; i < Depth; i++) {
139       if (Modules[i])
140         Input << Modules[i] << " " << (void*)Offsets[i] << "\n";
141     }
142   }
143 
144   Optional<StringRef> Redirects[] = {InputFile.str(), OutputFile.str(), llvm::None};
145   const char *Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
146 #ifdef _WIN32
147                         // Pass --relative-address on Windows so that we don't
148                         // have to add ImageBase from PE file.
149                         // FIXME: Make this the default for llvm-symbolizer.
150                         "--relative-address",
151 #endif
152                         "--demangle", nullptr};
153   int RunResult =
154       sys::ExecuteAndWait(LLVMSymbolizerPath, Args, nullptr, Redirects);
155   if (RunResult != 0)
156     return false;
157 
158   // This report format is based on the sanitizer stack trace printer.  See
159   // sanitizer_stacktrace_printer.cc in compiler-rt.
160   auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str());
161   if (!OutputBuf)
162     return false;
163   StringRef Output = OutputBuf.get()->getBuffer();
164   SmallVector<StringRef, 32> Lines;
165   Output.split(Lines, "\n");
166   auto CurLine = Lines.begin();
167   int frame_no = 0;
168   for (int i = 0; i < Depth; i++) {
169     if (!Modules[i]) {
170       OS << '#' << frame_no++ << ' ' << format_ptr(StackTrace[i]) << '\n';
171       continue;
172     }
173     // Read pairs of lines (function name and file/line info) until we
174     // encounter empty line.
175     for (;;) {
176       if (CurLine == Lines.end())
177         return false;
178       StringRef FunctionName = *CurLine++;
179       if (FunctionName.empty())
180         break;
181       OS << '#' << frame_no++ << ' ' << format_ptr(StackTrace[i]) << ' ';
182       if (!FunctionName.startswith("??"))
183         OS << FunctionName << ' ';
184       if (CurLine == Lines.end())
185         return false;
186       StringRef FileLineInfo = *CurLine++;
187       if (!FileLineInfo.startswith("??"))
188         OS << FileLineInfo;
189       else
190         OS << "(" << Modules[i] << '+' << format_hex(Offsets[i], 0) << ")";
191       OS << "\n";
192     }
193   }
194   return true;
195 }
196 
197 // Include the platform-specific parts of this class.
198 #ifdef LLVM_ON_UNIX
199 #include "Unix/Signals.inc"
200 #endif
201 #ifdef _WIN32
202 #include "Windows/Signals.inc"
203 #endif
204