1 //===- Signals.cpp - Generic Unix Signals Implementation -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines some helpful functions for dealing with the possibility of
11 // Unix signals occurring while your program is running.
13 //===----------------------------------------------------------------------===//
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/Support/Format.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/FileUtilities.h"
20 #include "llvm/Support/ManagedStatic.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/Mutex.h"
23 #include "llvm/Support/Program.h"
24 #include "llvm/Support/UniqueLock.h"
25 #include "llvm/Support/raw_ostream.h"
30 # include <execinfo.h> // For backtrace().
45 #include <mach/mach.h>
53 static RETSIGTYPE SignalHandler(int Sig); // defined below.
55 static ManagedStatic<SmartMutex<true> > SignalsMutex;
57 /// InterruptFunction - The function to call if ctrl-c is pressed.
58 static void (*InterruptFunction)() = nullptr;
60 static ManagedStatic<std::vector<std::string>> FilesToRemove;
61 static ManagedStatic<std::vector<std::pair<void (*)(void *), void *>>>
64 // IntSigs - Signals that represent requested termination. There's no bug
65 // or failure, or if there is, it's not our direct responsibility. For whatever
66 // reason, our continued execution is no longer desirable.
67 static const int IntSigs[] = {
68 SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
71 // KillSigs - Signals that represent that we have a bug, and our prompt
72 // termination has been ordered.
73 static const int KillSigs[] = {
74 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
89 static unsigned NumRegisteredSignals = 0;
93 } RegisteredSignalInfo[(sizeof(IntSigs)+sizeof(KillSigs))/sizeof(KillSigs[0])];
96 static void RegisterHandler(int Signal) {
97 assert(NumRegisteredSignals <
98 sizeof(RegisteredSignalInfo)/sizeof(RegisteredSignalInfo[0]) &&
99 "Out of space for signal handlers!");
101 struct sigaction NewHandler;
103 NewHandler.sa_handler = SignalHandler;
104 NewHandler.sa_flags = SA_NODEFER|SA_RESETHAND;
105 sigemptyset(&NewHandler.sa_mask);
107 // Install the new handler, save the old one in RegisteredSignalInfo.
108 sigaction(Signal, &NewHandler,
109 &RegisteredSignalInfo[NumRegisteredSignals].SA);
110 RegisteredSignalInfo[NumRegisteredSignals].SigNo = Signal;
111 ++NumRegisteredSignals;
114 static void RegisterHandlers() {
115 // We need to dereference the signals mutex during handler registration so
116 // that we force its construction. This is to prevent the first use being
117 // during handling an actual signal because you can't safely call new in a
121 // If the handlers are already registered, we're done.
122 if (NumRegisteredSignals != 0) return;
124 for (auto S : IntSigs) RegisterHandler(S);
125 for (auto S : KillSigs) RegisterHandler(S);
128 static void UnregisterHandlers() {
129 // Restore all of the signal handlers to how they were before we showed up.
130 for (unsigned i = 0, e = NumRegisteredSignals; i != e; ++i)
131 sigaction(RegisteredSignalInfo[i].SigNo,
132 &RegisteredSignalInfo[i].SA, nullptr);
133 NumRegisteredSignals = 0;
137 /// RemoveFilesToRemove - Process the FilesToRemove list. This function
138 /// should be called with the SignalsMutex lock held.
139 /// NB: This must be an async signal safe function. It cannot allocate or free
140 /// memory, even in debug builds.
141 static void RemoveFilesToRemove() {
142 // We avoid iterators in case of debug iterators that allocate or release
144 std::vector<std::string>& FilesToRemoveRef = *FilesToRemove;
145 for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i) {
146 // We rely on a std::string implementation for which repeated calls to
147 // 'c_str()' don't allocate memory. We pre-call 'c_str()' on all of these
148 // strings to try to ensure this is safe.
149 const char *path = FilesToRemoveRef[i].c_str();
151 // Get the status so we can determine if it's a file or directory. If we
152 // can't stat the file, ignore it.
154 if (stat(path, &buf) != 0)
157 // If this is not a regular file, ignore it. We want to prevent removal of
158 // special files like /dev/null, even if the compiler is being run with the
159 // super-user permissions.
160 if (!S_ISREG(buf.st_mode))
163 // Otherwise, remove the file. We ignore any errors here as there is nothing
169 // SignalHandler - The signal handler that runs.
170 static RETSIGTYPE SignalHandler(int Sig) {
171 // Restore the signal behavior to default, so that the program actually
172 // crashes when we return and the signal reissues. This also ensures that if
173 // we crash in our signal handler that the program will terminate immediately
174 // instead of recursing in the signal handler.
175 UnregisterHandlers();
177 // Unmask all potentially blocked kill signals.
179 sigfillset(&SigMask);
180 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
183 unique_lock<SmartMutex<true>> Guard(*SignalsMutex);
184 RemoveFilesToRemove();
186 if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
187 != std::end(IntSigs)) {
188 if (InterruptFunction) {
189 void (*IF)() = InterruptFunction;
191 InterruptFunction = nullptr;
192 IF(); // run the interrupt function.
197 raise(Sig); // Execute the default handler.
202 // Otherwise if it is a fault (like SEGV) run any handler.
203 std::vector<std::pair<void (*)(void *), void *>>& CallBacksToRunRef =
205 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
206 CallBacksToRunRef[i].first(CallBacksToRunRef[i].second);
209 // On S/390, certain signals are delivered with PSW Address pointing to
210 // *after* the faulting instruction. Simply returning from the signal
211 // handler would continue execution after that point, instead of
212 // re-raising the signal. Raise the signal manually in those cases.
213 if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
218 void llvm::sys::RunInterruptHandlers() {
219 sys::SmartScopedLock<true> Guard(*SignalsMutex);
220 RemoveFilesToRemove();
223 void llvm::sys::SetInterruptFunction(void (*IF)()) {
225 sys::SmartScopedLock<true> Guard(*SignalsMutex);
226 InterruptFunction = IF;
231 // RemoveFileOnSignal - The public API
232 bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
233 std::string* ErrMsg) {
235 sys::SmartScopedLock<true> Guard(*SignalsMutex);
236 std::vector<std::string>& FilesToRemoveRef = *FilesToRemove;
237 std::string *OldPtr =
238 FilesToRemoveRef.empty() ? nullptr : &FilesToRemoveRef[0];
239 FilesToRemoveRef.push_back(Filename);
241 // We want to call 'c_str()' on every std::string in this vector so that if
242 // the underlying implementation requires a re-allocation, it happens here
243 // rather than inside of the signal handler. If we see the vector grow, we
244 // have to call it on every entry. If it remains in place, we only need to
245 // call it on the latest one.
246 if (OldPtr == &FilesToRemoveRef[0])
247 FilesToRemoveRef.back().c_str();
249 for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i)
250 FilesToRemoveRef[i].c_str();
257 // DontRemoveFileOnSignal - The public API
258 void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
259 sys::SmartScopedLock<true> Guard(*SignalsMutex);
260 std::vector<std::string>::reverse_iterator RI =
261 std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
262 std::vector<std::string>::iterator I = FilesToRemove->end();
263 if (RI != FilesToRemove->rend())
264 I = FilesToRemove->erase(RI.base()-1);
266 // We need to call c_str() on every element which would have been moved by
267 // the erase. These elements, in a C++98 implementation where c_str()
268 // requires a reallocation on the first call may have had the call to c_str()
269 // made on insertion become invalid by being copied down an element.
270 for (std::vector<std::string>::iterator E = FilesToRemove->end(); I != E; ++I)
274 /// AddSignalHandler - Add a function to be called when a signal is delivered
275 /// to the process. The handler can have a cookie passed to it to identify
276 /// what instance of the handler it is.
277 void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
278 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
282 #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
284 #if HAVE_LINK_H && (defined(__linux__) || defined(__FreeBSD__) || \
285 defined(__FreeBSD_kernel__) || defined(__NetBSD__))
286 struct DlIteratePhdrData {
290 const char **modules;
292 const char *main_exec_name;
295 static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
296 DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
297 const char *name = data->first ? data->main_exec_name : info->dlpi_name;
299 for (int i = 0; i < info->dlpi_phnum; i++) {
300 const auto *phdr = &info->dlpi_phdr[i];
301 if (phdr->p_type != PT_LOAD)
303 intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
304 intptr_t end = beg + phdr->p_memsz;
305 for (int j = 0; j < data->depth; j++) {
306 if (data->modules[j])
308 intptr_t addr = (intptr_t)data->StackTrace[j];
309 if (beg <= addr && addr < end) {
310 data->modules[j] = name;
311 data->offsets[j] = addr - info->dlpi_addr;
318 static bool findModulesAndOffsets(void **StackTrace, int Depth,
319 const char **Modules, intptr_t *Offsets,
320 const char *MainExecutableName) {
321 DlIteratePhdrData data = {StackTrace, Depth, true,
322 Modules, Offsets, MainExecutableName};
323 dl_iterate_phdr(dl_iterate_phdr_cb, &data);
327 static bool findModulesAndOffsets(void **StackTrace, int Depth,
328 const char **Modules, intptr_t *Offsets,
329 const char *MainExecutableName) {
334 static bool printSymbolizedStackTrace(void **StackTrace, int Depth,
335 llvm::raw_ostream &OS) {
336 // FIXME: Subtract necessary number from StackTrace entries to turn return addresses
337 // into actual instruction addresses.
338 // Use llvm-symbolizer tool to symbolize the stack traces.
339 ErrorOr<std::string> LLVMSymbolizerPathOrErr =
340 sys::findProgramByName("llvm-symbolizer");
341 if (!LLVMSymbolizerPathOrErr)
343 const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
344 // We don't know argv0 or the address of main() at this point, but try
345 // to guess it anyway (it's possible on some platforms).
346 std::string MainExecutableName = sys::fs::getMainExecutable(nullptr, nullptr);
347 if (MainExecutableName.empty() ||
348 MainExecutableName.find("llvm-symbolizer") != std::string::npos)
351 std::vector<const char *> Modules(Depth, nullptr);
352 std::vector<intptr_t> Offsets(Depth, 0);
353 if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(),
354 MainExecutableName.c_str()))
357 SmallString<32> InputFile, OutputFile;
358 sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile);
359 sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile);
360 FileRemover InputRemover(InputFile.c_str());
361 FileRemover OutputRemover(OutputFile.c_str());
364 raw_fd_ostream Input(InputFD, true);
365 for (int i = 0; i < Depth; i++) {
367 Input << Modules[i] << " " << (void*)Offsets[i] << "\n";
371 StringRef InputFileStr(InputFile);
372 StringRef OutputFileStr(OutputFile);
373 StringRef StderrFileStr;
374 const StringRef *Redirects[] = {&InputFileStr, &OutputFileStr,
376 const char *Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
377 "--demangle", nullptr};
379 sys::ExecuteAndWait(LLVMSymbolizerPath, Args, nullptr, Redirects);
383 auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str());
386 StringRef Output = OutputBuf.get()->getBuffer();
387 SmallVector<StringRef, 32> Lines;
388 Output.split(Lines, "\n");
389 auto CurLine = Lines.begin();
391 for (int i = 0; i < Depth; i++) {
393 OS << format("#%d %p\n", frame_no++, StackTrace[i]);
396 // Read pairs of lines (function name and file/line info) until we
397 // encounter empty line.
399 if (CurLine == Lines.end())
401 StringRef FunctionName = *CurLine++;
402 if (FunctionName.empty())
404 OS << format("#%d %p ", frame_no++, StackTrace[i]);
405 if (!FunctionName.startswith("??"))
406 OS << format("%s ", FunctionName.str().c_str());
407 if (CurLine == Lines.end())
409 StringRef FileLineInfo = *CurLine++;
410 if (!FileLineInfo.startswith("??"))
411 OS << format("%s", FileLineInfo.str().c_str());
413 OS << format("(%s+%p)", Modules[i], (void *)Offsets[i]);
419 #endif // defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
421 // PrintStackTrace - In the case of a program crash or fault, print out a stack
422 // trace so that the user has an indication of why and where we died.
424 // On glibc systems we have the 'backtrace' function, which works nicely, but
425 // doesn't demangle symbols.
426 void llvm::sys::PrintStackTrace(raw_ostream &OS) {
427 #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
428 static void* StackTrace[256];
429 // Use backtrace() to output a backtrace on Linux systems with glibc.
430 int depth = backtrace(StackTrace,
431 static_cast<int>(array_lengthof(StackTrace)));
432 if (printSymbolizedStackTrace(StackTrace, depth, OS))
434 #if HAVE_DLFCN_H && __GNUG__
436 for (int i = 0; i < depth; ++i) {
438 dladdr(StackTrace[i], &dlinfo);
439 const char* name = strrchr(dlinfo.dli_fname, '/');
442 if (!name) nwidth = strlen(dlinfo.dli_fname);
443 else nwidth = strlen(name) - 1;
445 if (nwidth > width) width = nwidth;
448 for (int i = 0; i < depth; ++i) {
450 dladdr(StackTrace[i], &dlinfo);
452 OS << format("%-2d", i);
454 const char* name = strrchr(dlinfo.dli_fname, '/');
455 if (!name) OS << format(" %-*s", width, dlinfo.dli_fname);
456 else OS << format(" %-*s", width, name+1);
458 OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2,
459 (unsigned long)StackTrace[i]);
461 if (dlinfo.dli_sname != nullptr) {
465 char* d = abi::__cxa_demangle(dlinfo.dli_sname, nullptr, nullptr, &res);
469 if (!d) OS << dlinfo.dli_sname;
473 // FIXME: When we move to C++11, use %t length modifier. It's not in
474 // C++03 and causes gcc to issue warnings. Losing the upper 32 bits of
475 // the stack offset for a stack dump isn't likely to cause any problems.
476 OS << format(" + %u",(unsigned)((char*)StackTrace[i]-
477 (char*)dlinfo.dli_saddr));
482 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
487 static void PrintStackTraceSignalHandler(void *) {
488 PrintStackTrace(llvm::errs());
491 void llvm::sys::DisableSystemDialogsOnCrash() {}
493 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIGABRT or
494 /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
495 void llvm::sys::PrintStackTraceOnErrorSignal(bool DisableCrashReporting) {
496 AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
498 #if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES)
499 // Environment variable to disable any kind of crash dialog.
500 if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) {
501 mach_port_t self = mach_task_self();
503 exception_mask_t mask = EXC_MASK_CRASH;
505 kern_return_t ret = task_set_exception_ports(self,
508 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
518 // On Darwin, raise sends a signal to the main thread instead of the current
519 // thread. This has the unfortunate effect that assert() and abort() will end up
520 // bypassing our crash recovery attempts. We work around this for anything in
521 // the same linkage unit by just defining our own versions of the assert handler
524 #if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES)
530 return pthread_kill(pthread_self(), sig);
533 void __assert_rtn(const char *func,
538 fprintf(stderr, "Assertion failed: (%s), function %s, file %s, line %d.\n",
539 expr, func, file, line);
541 fprintf(stderr, "Assertion failed: (%s), file %s, line %d.\n",