xref: /freebsd-src/contrib/llvm-project/llvm/lib/Support/Signals.cpp (revision 0eae32dcef82f6f06de6419a0d623d7def0cc8f6)
1 //===- Signals.cpp - Signal Handling support --------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines some helpful functions for dealing with the possibility of
10 // Unix signals occurring while your program is running.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Support/Signals.h"
15 
16 #include "DebugOptions.h"
17 
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Config/llvm-config.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/ErrorOr.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/FileUtilities.h"
25 #include "llvm/Support/Format.h"
26 #include "llvm/Support/FormatAdapters.h"
27 #include "llvm/Support/FormatVariadic.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/Mutex.h"
31 #include "llvm/Support/Program.h"
32 #include "llvm/Support/StringSaver.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <vector>
35 
36 //===----------------------------------------------------------------------===//
37 //=== WARNING: Implementation here must contain only TRULY operating system
38 //===          independent code.
39 //===----------------------------------------------------------------------===//
40 
41 using namespace llvm;
42 
43 // Use explicit storage to avoid accessing cl::opt in a signal handler.
44 static bool DisableSymbolicationFlag = false;
45 static ManagedStatic<std::string> CrashDiagnosticsDirectory;
46 namespace {
47 struct CreateDisableSymbolication {
48   static void *call() {
49     return new cl::opt<bool, true>(
50         "disable-symbolication",
51         cl::desc("Disable symbolizing crash backtraces."),
52         cl::location(DisableSymbolicationFlag), cl::Hidden);
53   }
54 };
55 struct CreateCrashDiagnosticsDir {
56   static void *call() {
57     return new cl::opt<std::string, true>(
58         "crash-diagnostics-dir", cl::value_desc("directory"),
59         cl::desc("Directory for crash diagnostic files."),
60         cl::location(*CrashDiagnosticsDirectory), cl::Hidden);
61   }
62 };
63 } // namespace
64 void llvm::initSignalsOptions() {
65   static ManagedStatic<cl::opt<bool, true>, CreateDisableSymbolication>
66       DisableSymbolication;
67   static ManagedStatic<cl::opt<std::string, true>, CreateCrashDiagnosticsDir>
68       CrashDiagnosticsDir;
69   *DisableSymbolication;
70   *CrashDiagnosticsDir;
71 }
72 
73 constexpr char DisableSymbolizationEnv[] = "LLVM_DISABLE_SYMBOLIZATION";
74 constexpr char LLVMSymbolizerPathEnv[] = "LLVM_SYMBOLIZER_PATH";
75 
76 // Callbacks to run in signal handler must be lock-free because a signal handler
77 // could be running as we add new callbacks. We don't add unbounded numbers of
78 // callbacks, an array is therefore sufficient.
79 struct CallbackAndCookie {
80   sys::SignalHandlerCallback Callback;
81   void *Cookie;
82   enum class Status { Empty, Initializing, Initialized, Executing };
83   std::atomic<Status> Flag;
84 };
85 static constexpr size_t MaxSignalHandlerCallbacks = 8;
86 static CallbackAndCookie CallBacksToRun[MaxSignalHandlerCallbacks];
87 
88 // Signal-safe.
89 void sys::RunSignalHandlers() {
90   for (CallbackAndCookie &RunMe : CallBacksToRun) {
91     auto Expected = CallbackAndCookie::Status::Initialized;
92     auto Desired = CallbackAndCookie::Status::Executing;
93     if (!RunMe.Flag.compare_exchange_strong(Expected, Desired))
94       continue;
95     (*RunMe.Callback)(RunMe.Cookie);
96     RunMe.Callback = nullptr;
97     RunMe.Cookie = nullptr;
98     RunMe.Flag.store(CallbackAndCookie::Status::Empty);
99   }
100 }
101 
102 // Signal-safe.
103 static void insertSignalHandler(sys::SignalHandlerCallback FnPtr,
104                                 void *Cookie) {
105   for (CallbackAndCookie &SetMe : CallBacksToRun) {
106     auto Expected = CallbackAndCookie::Status::Empty;
107     auto Desired = CallbackAndCookie::Status::Initializing;
108     if (!SetMe.Flag.compare_exchange_strong(Expected, Desired))
109       continue;
110     SetMe.Callback = FnPtr;
111     SetMe.Cookie = Cookie;
112     SetMe.Flag.store(CallbackAndCookie::Status::Initialized);
113     return;
114   }
115   report_fatal_error("too many signal callbacks already registered");
116 }
117 
118 static bool findModulesAndOffsets(void **StackTrace, int Depth,
119                                   const char **Modules, intptr_t *Offsets,
120                                   const char *MainExecutableName,
121                                   StringSaver &StrPool);
122 
123 /// Format a pointer value as hexadecimal. Zero pad it out so its always the
124 /// same width.
125 static FormattedNumber format_ptr(void *PC) {
126   // Each byte is two hex digits plus 2 for the 0x prefix.
127   unsigned PtrWidth = 2 + 2 * sizeof(void *);
128   return format_hex((uint64_t)PC, PtrWidth);
129 }
130 
131 /// Helper that launches llvm-symbolizer and symbolizes a backtrace.
132 LLVM_ATTRIBUTE_USED
133 static bool printSymbolizedStackTrace(StringRef Argv0, void **StackTrace,
134                                       int Depth, llvm::raw_ostream &OS) {
135   if (DisableSymbolicationFlag || getenv(DisableSymbolizationEnv))
136     return false;
137 
138   // Don't recursively invoke the llvm-symbolizer binary.
139   if (Argv0.find("llvm-symbolizer") != std::string::npos)
140     return false;
141 
142   // FIXME: Subtract necessary number from StackTrace entries to turn return addresses
143   // into actual instruction addresses.
144   // Use llvm-symbolizer tool to symbolize the stack traces. First look for it
145   // alongside our binary, then in $PATH.
146   ErrorOr<std::string> LLVMSymbolizerPathOrErr = std::error_code();
147   if (const char *Path = getenv(LLVMSymbolizerPathEnv)) {
148     LLVMSymbolizerPathOrErr = sys::findProgramByName(Path);
149   } else if (!Argv0.empty()) {
150     StringRef Parent = llvm::sys::path::parent_path(Argv0);
151     if (!Parent.empty())
152       LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer", Parent);
153   }
154   if (!LLVMSymbolizerPathOrErr)
155     LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer");
156   if (!LLVMSymbolizerPathOrErr)
157     return false;
158   const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
159 
160   // If we don't know argv0 or the address of main() at this point, try
161   // to guess it anyway (it's possible on some platforms).
162   std::string MainExecutableName =
163       sys::fs::exists(Argv0) ? (std::string)std::string(Argv0)
164                              : sys::fs::getMainExecutable(nullptr, nullptr);
165   BumpPtrAllocator Allocator;
166   StringSaver StrPool(Allocator);
167   std::vector<const char *> Modules(Depth, nullptr);
168   std::vector<intptr_t> Offsets(Depth, 0);
169   if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(),
170                              MainExecutableName.c_str(), StrPool))
171     return false;
172   int InputFD;
173   SmallString<32> InputFile, OutputFile;
174   sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile);
175   sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile);
176   FileRemover InputRemover(InputFile.c_str());
177   FileRemover OutputRemover(OutputFile.c_str());
178 
179   {
180     raw_fd_ostream Input(InputFD, true);
181     for (int i = 0; i < Depth; i++) {
182       if (Modules[i])
183         Input << Modules[i] << " " << (void*)Offsets[i] << "\n";
184     }
185   }
186 
187   Optional<StringRef> Redirects[] = {InputFile.str(), OutputFile.str(),
188                                      StringRef("")};
189   StringRef Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
190 #ifdef _WIN32
191                       // Pass --relative-address on Windows so that we don't
192                       // have to add ImageBase from PE file.
193                       // FIXME: Make this the default for llvm-symbolizer.
194                       "--relative-address",
195 #endif
196                       "--demangle"};
197   int RunResult =
198       sys::ExecuteAndWait(LLVMSymbolizerPath, Args, None, Redirects);
199   if (RunResult != 0)
200     return false;
201 
202   // This report format is based on the sanitizer stack trace printer.  See
203   // sanitizer_stacktrace_printer.cc in compiler-rt.
204   auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str());
205   if (!OutputBuf)
206     return false;
207   StringRef Output = OutputBuf.get()->getBuffer();
208   SmallVector<StringRef, 32> Lines;
209   Output.split(Lines, "\n");
210   auto CurLine = Lines.begin();
211   int frame_no = 0;
212   for (int i = 0; i < Depth; i++) {
213     auto PrintLineHeader = [&]() {
214       OS << right_justify(formatv("#{0}", frame_no++).str(),
215                           std::log10(Depth) + 2)
216          << ' ' << format_ptr(StackTrace[i]) << ' ';
217     };
218     if (!Modules[i]) {
219       PrintLineHeader();
220       OS << '\n';
221       continue;
222     }
223     // Read pairs of lines (function name and file/line info) until we
224     // encounter empty line.
225     for (;;) {
226       if (CurLine == Lines.end())
227         return false;
228       StringRef FunctionName = *CurLine++;
229       if (FunctionName.empty())
230         break;
231       PrintLineHeader();
232       if (!FunctionName.startswith("??"))
233         OS << FunctionName << ' ';
234       if (CurLine == Lines.end())
235         return false;
236       StringRef FileLineInfo = *CurLine++;
237       if (!FileLineInfo.startswith("??"))
238         OS << FileLineInfo;
239       else
240         OS << "(" << Modules[i] << '+' << format_hex(Offsets[i], 0) << ")";
241       OS << "\n";
242     }
243   }
244   return true;
245 }
246 
247 // Include the platform-specific parts of this class.
248 #ifdef LLVM_ON_UNIX
249 #include "Unix/Signals.inc"
250 #endif
251 #ifdef _WIN32
252 #include "Windows/Signals.inc"
253 #endif
254