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