LLVM 17.0.0git
Signals.inc
Go to the documentation of this file.
1//===- Signals.cpp - Generic Unix Signals Implementation -----*- 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// This file is extremely careful to only do signal-safe things while in a
15// signal handler. In particular, memory allocation and acquiring a mutex
16// while in a signal handler should never occur. ManagedStatic isn't usable from
17// a signal handler for 2 reasons:
18//
19// 1. Creating a new one allocates.
20// 2. The signal handler could fire while llvm_shutdown is being processed, in
21// which case the ManagedStatic is in an unknown state because it could
22// already have been destroyed, or be in the process of being destroyed.
23//
24// Modifying the behavior of the signal handlers (such as registering new ones)
25// can acquire a mutex, but all this guarantees is that the signal handler
26// behavior is only modified by one thread at a time. A signal handler can still
27// fire while this occurs!
28//
29// Adding work to a signal handler requires lock-freedom (and assume atomics are
30// always lock-free) because the signal handler could fire while new work is
31// being added.
32//
33//===----------------------------------------------------------------------===//
34
35#include "Unix.h"
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/Config/config.h"
42#include "llvm/Support/Format.h"
44#include "llvm/Support/Mutex.h"
48#include <algorithm>
49#include <string>
50#ifdef HAVE_BACKTRACE
51#include BACKTRACE_HEADER // For backtrace().
52#endif
53#if HAVE_SIGNAL_H
54#include <signal.h>
55#endif
56#if HAVE_SYS_STAT_H
57#include <sys/stat.h>
58#endif
59#if HAVE_DLFCN_H
60#include <dlfcn.h>
61#endif
62#if HAVE_MACH_MACH_H
63#include <mach/mach.h>
64#endif
65#ifdef __APPLE__
66#include <mach-o/dyld.h>
67#endif
68#if HAVE_LINK_H
69#include <link.h>
70#endif
71#ifdef HAVE__UNWIND_BACKTRACE
72// FIXME: We should be able to use <unwind.h> for any target that has an
73// _Unwind_Backtrace function, but on FreeBSD the configure test passes
74// despite the function not existing, and on Android, <unwind.h> conflicts
75// with <link.h>.
76#ifdef __GLIBC__
77#include <unwind.h>
78#else
79#undef HAVE__UNWIND_BACKTRACE
80#endif
81#endif
82
83using namespace llvm;
84
85static void SignalHandler(int Sig); // defined below.
86static void InfoSignalHandler(int Sig); // defined below.
87
88using SignalHandlerFunctionType = void (*)();
89/// The function to call if ctrl-c is pressed.
90static std::atomic<SignalHandlerFunctionType> InterruptFunction = nullptr;
91static std::atomic<SignalHandlerFunctionType> InfoSignalFunction = nullptr;
92/// The function to call on SIGPIPE (one-time use only).
93static std::atomic<SignalHandlerFunctionType> OneShotPipeSignalFunction =
94 nullptr;
95
96namespace {
97/// Signal-safe removal of files.
98/// Inserting and erasing from the list isn't signal-safe, but removal of files
99/// themselves is signal-safe. Memory is freed when the head is freed, deletion
100/// is therefore not signal-safe either.
101class FileToRemoveList {
102 std::atomic<char *> Filename = nullptr;
103 std::atomic<FileToRemoveList *> Next = nullptr;
104
105 FileToRemoveList() = default;
106 // Not signal-safe.
107 FileToRemoveList(const std::string &str) : Filename(strdup(str.c_str())) {}
108
109public:
110 // Not signal-safe.
111 ~FileToRemoveList() {
112 if (FileToRemoveList *N = Next.exchange(nullptr))
113 delete N;
114 if (char *F = Filename.exchange(nullptr))
115 free(F);
116 }
117
118 // Not signal-safe.
119 static void insert(std::atomic<FileToRemoveList *> &Head,
120 const std::string &Filename) {
121 // Insert the new file at the end of the list.
122 FileToRemoveList *NewHead = new FileToRemoveList(Filename);
123 std::atomic<FileToRemoveList *> *InsertionPoint = &Head;
124 FileToRemoveList *OldHead = nullptr;
125 while (!InsertionPoint->compare_exchange_strong(OldHead, NewHead)) {
126 InsertionPoint = &OldHead->Next;
127 OldHead = nullptr;
128 }
129 }
130
131 // Not signal-safe.
132 static void erase(std::atomic<FileToRemoveList *> &Head,
133 const std::string &Filename) {
134 // Use a lock to avoid concurrent erase: the comparison would access
135 // free'd memory.
137 sys::SmartScopedLock<true> Writer(*Lock);
138
139 for (FileToRemoveList *Current = Head.load(); Current;
140 Current = Current->Next.load()) {
141 if (char *OldFilename = Current->Filename.load()) {
142 if (OldFilename != Filename)
143 continue;
144 // Leave an empty filename.
145 OldFilename = Current->Filename.exchange(nullptr);
146 // The filename might have become null between the time we
147 // compared it and we exchanged it.
148 if (OldFilename)
149 free(OldFilename);
150 }
151 }
152 }
153
154 // Signal-safe.
155 static void removeAllFiles(std::atomic<FileToRemoveList *> &Head) {
156 // If cleanup were to occur while we're removing files we'd have a bad time.
157 // Make sure we're OK by preventing cleanup from doing anything while we're
158 // removing files. If cleanup races with us and we win we'll have a leak,
159 // but we won't crash.
160 FileToRemoveList *OldHead = Head.exchange(nullptr);
161
162 for (FileToRemoveList *currentFile = OldHead; currentFile;
163 currentFile = currentFile->Next.load()) {
164 // If erasing was occuring while we're trying to remove files we'd look
165 // at free'd data. Take away the path and put it back when done.
166 if (char *path = currentFile->Filename.exchange(nullptr)) {
167 // Get the status so we can determine if it's a file or directory. If we
168 // can't stat the file, ignore it.
169 struct stat buf;
170 if (stat(path, &buf) != 0)
171 continue;
172
173 // If this is not a regular file, ignore it. We want to prevent removal
174 // of special files like /dev/null, even if the compiler is being run
175 // with the super-user permissions.
176 if (!S_ISREG(buf.st_mode))
177 continue;
178
179 // Otherwise, remove the file. We ignore any errors here as there is
180 // nothing else we can do.
181 unlink(path);
182
183 // We're done removing the file, erasing can safely proceed.
184 currentFile->Filename.exchange(path);
185 }
186 }
187
188 // We're done removing files, cleanup can safely proceed.
189 Head.exchange(OldHead);
190 }
191};
192static std::atomic<FileToRemoveList *> FilesToRemove = nullptr;
193
194/// Clean up the list in a signal-friendly manner.
195/// Recall that signals can fire during llvm_shutdown. If this occurs we should
196/// either clean something up or nothing at all, but we shouldn't crash!
197struct FilesToRemoveCleanup {
198 // Not signal-safe.
199 ~FilesToRemoveCleanup() {
200 FileToRemoveList *Head = FilesToRemove.exchange(nullptr);
201 if (Head)
202 delete Head;
203 }
204};
205} // namespace
206
207static StringRef Argv0;
208
209/// Signals that represent requested termination. There's no bug or failure, or
210/// if there is, it's not our direct responsibility. For whatever reason, our
211/// continued execution is no longer desirable.
212static const int IntSigs[] = {SIGHUP, SIGINT, SIGTERM, SIGUSR2};
213
214/// Signals that represent that we have a bug, and our prompt termination has
215/// been ordered.
216static const int KillSigs[] = {SIGILL,
217 SIGTRAP,
218 SIGABRT,
219 SIGFPE,
220 SIGBUS,
221 SIGSEGV,
222 SIGQUIT
223#ifdef SIGSYS
224 ,
225 SIGSYS
226#endif
227#ifdef SIGXCPU
228 ,
229 SIGXCPU
230#endif
231#ifdef SIGXFSZ
232 ,
233 SIGXFSZ
234#endif
235#ifdef SIGEMT
236 ,
237 SIGEMT
238#endif
239};
240
241/// Signals that represent requests for status.
242static const int InfoSigs[] = {SIGUSR1
243#ifdef SIGINFO
244 ,
245 SIGINFO
246#endif
247};
248
249static const size_t NumSigs = std::size(IntSigs) + std::size(KillSigs) +
250 std::size(InfoSigs) + 1 /* SIGPIPE */;
251
252static std::atomic<unsigned> NumRegisteredSignals = 0;
253static struct {
254 struct sigaction SA;
255 int SigNo;
256} RegisteredSignalInfo[NumSigs];
257
258#if defined(HAVE_SIGALTSTACK)
259// Hold onto both the old and new alternate signal stack so that it's not
260// reported as a leak. We don't make any attempt to remove our alt signal
261// stack if we remove our signal handlers; that can't be done reliably if
262// someone else is also trying to do the same thing.
263static stack_t OldAltStack;
264LLVM_ATTRIBUTE_USED static void *NewAltStackPointer;
265
266static void CreateSigAltStack() {
267 const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024;
268
269 // If we're executing on the alternate stack, or we already have an alternate
270 // signal stack that we're happy with, there's nothing for us to do. Don't
271 // reduce the size, some other part of the process might need a larger stack
272 // than we do.
273 if (sigaltstack(nullptr, &OldAltStack) != 0 ||
274 OldAltStack.ss_flags & SS_ONSTACK ||
275 (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize))
276 return;
277
278 stack_t AltStack = {};
279 AltStack.ss_sp = static_cast<char *>(safe_malloc(AltStackSize));
280 NewAltStackPointer = AltStack.ss_sp; // Save to avoid reporting a leak.
281 AltStack.ss_size = AltStackSize;
282 if (sigaltstack(&AltStack, &OldAltStack) != 0)
283 free(AltStack.ss_sp);
284}
285#else
286static void CreateSigAltStack() {}
287#endif
288
289static void RegisterHandlers() { // Not signal-safe.
290 // The mutex prevents other threads from registering handlers while we're
291 // doing it. We also have to protect the handlers and their count because
292 // a signal handler could fire while we're registeting handlers.
293 static ManagedStatic<sys::SmartMutex<true>> SignalHandlerRegistrationMutex;
294 sys::SmartScopedLock<true> Guard(*SignalHandlerRegistrationMutex);
295
296 // If the handlers are already registered, we're done.
297 if (NumRegisteredSignals.load() != 0)
298 return;
299
300 // Create an alternate stack for signal handling. This is necessary for us to
301 // be able to reliably handle signals due to stack overflow.
302 CreateSigAltStack();
303
304 enum class SignalKind { IsKill, IsInfo };
305 auto registerHandler = [&](int Signal, SignalKind Kind) {
306 unsigned Index = NumRegisteredSignals.load();
307 assert(Index < std::size(RegisteredSignalInfo) &&
308 "Out of space for signal handlers!");
309
310 struct sigaction NewHandler;
311
312 switch (Kind) {
313 case SignalKind::IsKill:
314 NewHandler.sa_handler = SignalHandler;
315 NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK;
316 break;
317 case SignalKind::IsInfo:
318 NewHandler.sa_handler = InfoSignalHandler;
319 NewHandler.sa_flags = SA_ONSTACK;
320 break;
321 }
322 sigemptyset(&NewHandler.sa_mask);
323
324 // Install the new handler, save the old one in RegisteredSignalInfo.
325 sigaction(Signal, &NewHandler, &RegisteredSignalInfo[Index].SA);
326 RegisteredSignalInfo[Index].SigNo = Signal;
327 ++NumRegisteredSignals;
328 };
329
330 for (auto S : IntSigs)
331 registerHandler(S, SignalKind::IsKill);
332 for (auto S : KillSigs)
333 registerHandler(S, SignalKind::IsKill);
334 if (OneShotPipeSignalFunction)
335 registerHandler(SIGPIPE, SignalKind::IsKill);
336 for (auto S : InfoSigs)
337 registerHandler(S, SignalKind::IsInfo);
338}
339
340void sys::unregisterHandlers() {
341 // Restore all of the signal handlers to how they were before we showed up.
342 for (unsigned i = 0, e = NumRegisteredSignals.load(); i != e; ++i) {
343 sigaction(RegisteredSignalInfo[i].SigNo, &RegisteredSignalInfo[i].SA,
344 nullptr);
345 --NumRegisteredSignals;
346 }
347}
348
349/// Process the FilesToRemove list.
350static void RemoveFilesToRemove() {
351 FileToRemoveList::removeAllFiles(FilesToRemove);
352}
353
354void sys::CleanupOnSignal(uintptr_t Context) {
355 int Sig = (int)Context;
356
357 if (llvm::is_contained(InfoSigs, Sig)) {
358 InfoSignalHandler(Sig);
359 return;
360 }
361
362 RemoveFilesToRemove();
363
364 if (llvm::is_contained(IntSigs, Sig) || Sig == SIGPIPE)
365 return;
366
368}
369
370// The signal handler that runs.
371static void SignalHandler(int Sig) {
372 // Restore the signal behavior to default, so that the program actually
373 // crashes when we return and the signal reissues. This also ensures that if
374 // we crash in our signal handler that the program will terminate immediately
375 // instead of recursing in the signal handler.
376 sys::unregisterHandlers();
377
378 // Unmask all potentially blocked kill signals.
379 sigset_t SigMask;
380 sigfillset(&SigMask);
381 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
382
383 {
384 RemoveFilesToRemove();
385
386 if (Sig == SIGPIPE)
387 if (auto OldOneShotPipeFunction =
388 OneShotPipeSignalFunction.exchange(nullptr))
389 return OldOneShotPipeFunction();
390
391 bool IsIntSig = llvm::is_contained(IntSigs, Sig);
392 if (IsIntSig)
393 if (auto OldInterruptFunction = InterruptFunction.exchange(nullptr))
394 return OldInterruptFunction();
395
396 if (Sig == SIGPIPE || IsIntSig) {
397 raise(Sig); // Execute the default handler.
398 return;
399 }
400 }
401
402 // Otherwise if it is a fault (like SEGV) run any handler.
404
405#ifdef __s390__
406 // On S/390, certain signals are delivered with PSW Address pointing to
407 // *after* the faulting instruction. Simply returning from the signal
408 // handler would continue execution after that point, instead of
409 // re-raising the signal. Raise the signal manually in those cases.
410 if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
411 raise(Sig);
412#endif
413}
414
415static void InfoSignalHandler(int Sig) {
416 SaveAndRestore SaveErrnoDuringASignalHandler(errno);
417 if (SignalHandlerFunctionType CurrentInfoFunction = InfoSignalFunction)
418 CurrentInfoFunction();
419}
420
421void llvm::sys::RunInterruptHandlers() { RemoveFilesToRemove(); }
422
423void llvm::sys::SetInterruptFunction(void (*IF)()) {
424 InterruptFunction.exchange(IF);
425 RegisterHandlers();
426}
427
428void llvm::sys::SetInfoSignalFunction(void (*Handler)()) {
429 InfoSignalFunction.exchange(Handler);
430 RegisterHandlers();
431}
432
433void llvm::sys::SetOneShotPipeSignalFunction(void (*Handler)()) {
434 OneShotPipeSignalFunction.exchange(Handler);
435 RegisterHandlers();
436}
437
439 // Send a special return code that drivers can check for, from sysexits.h.
440 exit(EX_IOERR);
441}
442
443// The public API
444bool llvm::sys::RemoveFileOnSignal(StringRef Filename, std::string *ErrMsg) {
445 // Ensure that cleanup will occur as soon as one file is added.
446 static ManagedStatic<FilesToRemoveCleanup> FilesToRemoveCleanup;
447 *FilesToRemoveCleanup;
448 FileToRemoveList::insert(FilesToRemove, Filename.str());
449 RegisterHandlers();
450 return false;
451}
452
453// The public API
455 FileToRemoveList::erase(FilesToRemove, Filename.str());
456}
457
458/// Add a function to be called when a signal is delivered to the process. The
459/// handler can have a cookie passed to it to identify what instance of the
460/// handler it is.
462 void *Cookie) { // Signal-safe.
463 insertSignalHandler(FnPtr, Cookie);
464 RegisterHandlers();
465}
466
467#if ENABLE_BACKTRACES && defined(HAVE_BACKTRACE) && HAVE_LINK_H && \
468 (defined(__linux__) || defined(__FreeBSD__) || \
469 defined(__FreeBSD_kernel__) || defined(__NetBSD__))
470struct DlIteratePhdrData {
471 void **StackTrace;
472 int depth;
473 bool first;
474 const char **modules;
475 intptr_t *offsets;
476 const char *main_exec_name;
477};
478
479static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
480 DlIteratePhdrData *data = (DlIteratePhdrData *)arg;
481 const char *name = data->first ? data->main_exec_name : info->dlpi_name;
482 data->first = false;
483 for (int i = 0; i < info->dlpi_phnum; i++) {
484 const auto *phdr = &info->dlpi_phdr[i];
485 if (phdr->p_type != PT_LOAD)
486 continue;
487 intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
488 intptr_t end = beg + phdr->p_memsz;
489 for (int j = 0; j < data->depth; j++) {
490 if (data->modules[j])
491 continue;
492 intptr_t addr = (intptr_t)data->StackTrace[j];
493 if (beg <= addr && addr < end) {
494 data->modules[j] = name;
495 data->offsets[j] = addr - info->dlpi_addr;
496 }
497 }
498 }
499 return 0;
500}
501
502/// If this is an ELF platform, we can find all loaded modules and their virtual
503/// addresses with dl_iterate_phdr.
504static bool findModulesAndOffsets(void **StackTrace, int Depth,
505 const char **Modules, intptr_t *Offsets,
506 const char *MainExecutableName,
507 StringSaver &StrPool) {
508 DlIteratePhdrData data = {StackTrace, Depth, true,
509 Modules, Offsets, MainExecutableName};
510 dl_iterate_phdr(dl_iterate_phdr_cb, &data);
511 return true;
512}
513#elif ENABLE_BACKTRACES && defined(__APPLE__) && defined(__LP64__)
514static bool findModulesAndOffsets(void **StackTrace, int Depth,
515 const char **Modules, intptr_t *Offsets,
516 const char *MainExecutableName,
517 StringSaver &StrPool) {
518 uint32_t NumImgs = _dyld_image_count();
519 for (uint32_t ImageIndex = 0; ImageIndex < NumImgs; ImageIndex++) {
520 const char *Name = _dyld_get_image_name(ImageIndex);
521 intptr_t Slide = _dyld_get_image_vmaddr_slide(ImageIndex);
522 auto *Header =
523 (const struct mach_header_64 *)_dyld_get_image_header(ImageIndex);
524 if (Header == NULL)
525 continue;
526 auto Cmd = (const struct load_command *)(&Header[1]);
527 for (uint32_t CmdNum = 0; CmdNum < Header->ncmds; ++CmdNum) {
528 uint32_t BaseCmd = Cmd->cmd & ~LC_REQ_DYLD;
529 if (BaseCmd == LC_SEGMENT_64) {
530 auto CmdSeg64 = (const struct segment_command_64 *)Cmd;
531 for (int j = 0; j < Depth; j++) {
532 if (Modules[j])
533 continue;
534 intptr_t Addr = (intptr_t)StackTrace[j];
535 if ((intptr_t)CmdSeg64->vmaddr + Slide <= Addr &&
536 Addr < intptr_t(CmdSeg64->vmaddr + CmdSeg64->vmsize + Slide)) {
537 Modules[j] = Name;
538 Offsets[j] = Addr - Slide;
539 }
540 }
541 }
542 Cmd = (const load_command *)(((const char *)Cmd) + (Cmd->cmdsize));
543 }
544 }
545 return true;
546}
547#else
548/// Backtraces are not enabled or we don't yet know how to find all loaded DSOs
549/// on this platform.
550static bool findModulesAndOffsets(void **StackTrace, int Depth,
551 const char **Modules, intptr_t *Offsets,
552 const char *MainExecutableName,
553 StringSaver &StrPool) {
554 return false;
555}
556#endif // ENABLE_BACKTRACES && ... (findModulesAndOffsets variants)
557
558#if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE)
559static int unwindBacktrace(void **StackTrace, int MaxEntries) {
560 if (MaxEntries < 0)
561 return 0;
562
563 // Skip the first frame ('unwindBacktrace' itself).
564 int Entries = -1;
565
566 auto HandleFrame = [&](_Unwind_Context *Context) -> _Unwind_Reason_Code {
567 // Apparently we need to detect reaching the end of the stack ourselves.
568 void *IP = (void *)_Unwind_GetIP(Context);
569 if (!IP)
570 return _URC_END_OF_STACK;
571
572 assert(Entries < MaxEntries && "recursively called after END_OF_STACK?");
573 if (Entries >= 0)
574 StackTrace[Entries] = IP;
575
576 if (++Entries == MaxEntries)
577 return _URC_END_OF_STACK;
578 return _URC_NO_REASON;
579 };
580
581 _Unwind_Backtrace(
582 [](_Unwind_Context *Context, void *Handler) {
583 return (*static_cast<decltype(HandleFrame) *>(Handler))(Context);
584 },
585 static_cast<void *>(&HandleFrame));
586 return std::max(Entries, 0);
587}
588#endif
589
590// In the case of a program crash or fault, print out a stack trace so that the
591// user has an indication of why and where we died.
592//
593// On glibc systems we have the 'backtrace' function, which works nicely, but
594// doesn't demangle symbols.
595void llvm::sys::PrintStackTrace(raw_ostream &OS, int Depth) {
596#if ENABLE_BACKTRACES
597 static void *StackTrace[256];
598 int depth = 0;
599#if defined(HAVE_BACKTRACE)
600 // Use backtrace() to output a backtrace on Linux systems with glibc.
601 if (!depth)
602 depth = backtrace(StackTrace, static_cast<int>(std::size(StackTrace)));
603#endif
604#if defined(HAVE__UNWIND_BACKTRACE)
605 // Try _Unwind_Backtrace() if backtrace() failed.
606 if (!depth)
607 depth =
608 unwindBacktrace(StackTrace, static_cast<int>(std::size(StackTrace)));
609#endif
610 if (!depth)
611 return;
612 // If "Depth" is not provided by the caller, use the return value of
613 // backtrace() for printing a symbolized stack trace.
614 if (!Depth)
615 Depth = depth;
616 if (printSymbolizedStackTrace(Argv0, StackTrace, Depth, OS))
617 return;
618 OS << "Stack dump without symbol names (ensure you have llvm-symbolizer in "
619 "your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point "
620 "to it):\n";
621#if HAVE_DLFCN_H && HAVE_DLADDR
622 int width = 0;
623 for (int i = 0; i < depth; ++i) {
624 Dl_info dlinfo;
625 dladdr(StackTrace[i], &dlinfo);
626 const char *name = strrchr(dlinfo.dli_fname, '/');
627
628 int nwidth;
629 if (!name)
630 nwidth = strlen(dlinfo.dli_fname);
631 else
632 nwidth = strlen(name) - 1;
633
634 if (nwidth > width)
635 width = nwidth;
636 }
637
638 for (int i = 0; i < depth; ++i) {
639 Dl_info dlinfo;
640 dladdr(StackTrace[i], &dlinfo);
641
642 OS << format("%-2d", i);
643
644 const char *name = strrchr(dlinfo.dli_fname, '/');
645 if (!name)
646 OS << format(" %-*s", width, dlinfo.dli_fname);
647 else
648 OS << format(" %-*s", width, name + 1);
649
650 OS << format(" %#0*lx", (int)(sizeof(void *) * 2) + 2,
651 (unsigned long)StackTrace[i]);
652
653 if (dlinfo.dli_sname != nullptr) {
654 OS << ' ';
655 if (char *d = itaniumDemangle(dlinfo.dli_sname)) {
656 OS << d;
657 free(d);
658 } else {
659 OS << dlinfo.dli_sname;
660 }
661
662 OS << format(" + %tu", (static_cast<const char *>(StackTrace[i]) -
663 static_cast<const char *>(dlinfo.dli_saddr)));
664 }
665 OS << '\n';
666 }
667#elif defined(HAVE_BACKTRACE)
668 backtrace_symbols_fd(StackTrace, Depth, STDERR_FILENO);
669#endif
670#endif
671}
672
673static void PrintStackTraceSignalHandler(void *) {
674 sys::PrintStackTrace(llvm::errs());
675}
676
678
679/// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
680/// process, print a stack trace and then exit.
682 bool DisableCrashReporting) {
683 ::Argv0 = Argv0;
684
685 AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
686
687#if defined(__APPLE__) && ENABLE_CRASH_OVERRIDES
688 // Environment variable to disable any kind of crash dialog.
689 if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) {
690 mach_port_t self = mach_task_self();
691
692 exception_mask_t mask = EXC_MASK_CRASH;
693
694 kern_return_t ret = task_set_exception_ports(
695 self, mask, MACH_PORT_NULL,
696 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES, THREAD_STATE_NONE);
697 (void)ret;
698 }
699#endif
700}
#define LLVM_ATTRIBUTE_USED
Definition: Compiler.h:139
uint64_t Addr
std::string Name
uint32_t Index
This file contains definitions of exit codes for exit() function.
lazy value info
#define F(x, y, z)
Definition: MD5.cpp:55
LLVMContext & Context
if(VerifyEach)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static const char * name
Definition: SMEABIPass.cpp:49
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
This file provides utility classes that use RAII to save and restore values.
static LLVM_ATTRIBUTE_USED bool printSymbolizedStackTrace(StringRef Argv0, void **StackTrace, int Depth, llvm::raw_ostream &OS)
Helper that launches llvm-symbolizer and symbolizes a backtrace.
Definition: Signals.cpp:141
static bool findModulesAndOffsets(void **StackTrace, int Depth, const char **Modules, intptr_t *Offsets, const char *MainExecutableName, StringSaver &StrPool)
static void insertSignalHandler(sys::SignalHandlerCallback FnPtr, void *Cookie)
Definition: Signals.cpp:111
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
Definition: ManagedStatic.h:83
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition: StringSaver.h:21
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
Offsets
Offsets in bytes from the start of the input buffer.
Definition: SIInstrInfo.h:1371
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:236
void SetInterruptFunction(void(*IF)())
This function registers a function to be called when the user "interrupts" the program (typically by ...
void PrintStackTrace(raw_ostream &OS, int Depth=0)
Print the stack trace using the given raw_ostream object.
void DisableSystemDialogsOnCrash()
Disable all system dialog boxes that appear when the process crashes.
void SetOneShotPipeSignalFunction(void(*Handler)())
Registers a function to be called in a "one-shot" manner when a pipe signal is delivered to the proce...
void DontRemoveFileOnSignal(StringRef Filename)
This function removes a file from the list of files to be removed on signal delivery.
void DefaultOneShotPipeSignalHandler()
On Unix systems and Windows, this function exits with an "IO error" exit code.
std::lock_guard< SmartMutex< mt_only > > SmartScopedLock
Definition: Mutex.h:69
void(*)(void *) SignalHandlerCallback
Definition: Signals.h:61
void AddSignalHandler(SignalHandlerCallback FnPtr, void *Cookie)
Add a function to be called when an abort/kill signal is delivered to the process.
void RunSignalHandlers()
Definition: Signals.cpp:97
void SetInfoSignalFunction(void(*Handler)())
Registers a function to be called when an "info" signal is delivered to the process.
void PrintStackTraceOnErrorSignal(StringRef Argv0, bool DisableCrashReporting=false)
When an error signal (such as SIGABRT or SIGSEGV) is delivered to the process, print a stack trace an...
void RunInterruptHandlers()
This function runs all the registered interrupt handlers, including the removal of files registered b...
bool RemoveFileOnSignal(StringRef Filename, std::string *ErrMsg=nullptr)
This function registers signal handlers to ensure that if a signal gets delivered that the named file...
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
LLVM_ATTRIBUTE_RETURNS_NONNULL void * safe_malloc(size_t Sz)
Definition: MemAlloc.h:25
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:124
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
char * itaniumDemangle(const char *mangled_name)
Returns a non-NULL pointer to a NUL-terminated C style string that should be explicitly freed,...
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1976
auto mask(ShuffFunc S, unsigned Length, OptArgs... args) -> MaskT
#define N
A utility class that uses RAII to save and restore the value of a variable.