1 //===- Signals.cpp - Generic Unix Signals Implementation -----*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines some helpful functions for dealing with the possibility of
10 // Unix signals occurring while your program is running.
12 //===----------------------------------------------------------------------===//
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:
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.
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!
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
33 //===----------------------------------------------------------------------===//
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/Config/config.h"
38 #include "llvm/Demangle/Demangle.h"
39 #include "llvm/Support/ExitCodes.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/FileUtilities.h"
42 #include "llvm/Support/Format.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/Mutex.h"
45 #include "llvm/Support/Program.h"
46 #include "llvm/Support/SaveAndRestore.h"
47 #include "llvm/Support/raw_ostream.h"
51 #include BACKTRACE_HEADER // For backtrace().
59 #include <mach/mach.h>
62 #include <mach-o/dyld.h>
64 #if __has_include(<link.h>)
67 #ifdef HAVE__UNWIND_BACKTRACE
68 // FIXME: We should be able to use <unwind.h> for any target that has an
69 // _Unwind_Backtrace function, but on FreeBSD the configure test passes
70 // despite the function not existing, and on Android, <unwind.h> conflicts
75 #undef HAVE__UNWIND_BACKTRACE
78 #if ENABLE_BACKTRACES && defined(__MVS__)
79 #include "llvm/Support/ConvertEBCDIC.h"
85 static void SignalHandler(int Sig); // defined below.
86 static void InfoSignalHandler(int Sig); // defined below.
88 using SignalHandlerFunctionType = void (*)();
89 /// The function to call if ctrl-c is pressed.
90 static std::atomic<SignalHandlerFunctionType> InterruptFunction = nullptr;
91 static std::atomic<SignalHandlerFunctionType> InfoSignalFunction = nullptr;
92 /// The function to call on SIGPIPE (one-time use only).
93 static std::atomic<SignalHandlerFunctionType> OneShotPipeSignalFunction =
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.
101 class FileToRemoveList {
102 std::atomic<char *> Filename = nullptr;
103 std::atomic<FileToRemoveList *> Next = nullptr;
105 FileToRemoveList() = default;
107 FileToRemoveList(const std::string &str) : Filename(strdup(str.c_str())) {}
111 ~FileToRemoveList() {
112 if (FileToRemoveList *N = Next.exchange(nullptr))
114 if (char *F = Filename.exchange(nullptr))
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;
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
136 static ManagedStatic<sys::SmartMutex<true>> Lock;
137 sys::SmartScopedLock<true> Writer(*Lock);
139 for (FileToRemoveList *Current = Head.load(); Current;
140 Current = Current->Next.load()) {
141 if (char *OldFilename = Current->Filename.load()) {
142 if (OldFilename != Filename)
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.
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);
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.
170 if (stat(path, &buf) != 0)
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))
179 // Otherwise, remove the file. We ignore any errors here as there is
180 // nothing else we can do.
183 // We're done removing the file, erasing can safely proceed.
184 currentFile->Filename.exchange(path);
188 // We're done removing files, cleanup can safely proceed.
189 Head.exchange(OldHead);
192 static std::atomic<FileToRemoveList *> FilesToRemove = nullptr;
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!
197 struct FilesToRemoveCleanup {
199 ~FilesToRemoveCleanup() {
200 FileToRemoveList *Head = FilesToRemove.exchange(nullptr);
207 static StringRef Argv0;
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.
212 static const int IntSigs[] = {SIGHUP, SIGINT, SIGTERM, SIGUSR2};
214 /// Signals that represent that we have a bug, and our prompt termination has
216 static const int KillSigs[] = {SIGILL,
241 /// Signals that represent requests for status.
242 static const int InfoSigs[] = {SIGUSR1
249 static const size_t NumSigs = std::size(IntSigs) + std::size(KillSigs) +
250 std::size(InfoSigs) + 1 /* SIGPIPE */;
252 static std::atomic<unsigned> NumRegisteredSignals = 0;
256 } RegisteredSignalInfo[NumSigs];
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.
263 static stack_t OldAltStack;
264 LLVM_ATTRIBUTE_USED static void *NewAltStackPointer;
266 static void CreateSigAltStack() {
267 const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024;
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
273 if (sigaltstack(nullptr, &OldAltStack) != 0 ||
274 OldAltStack.ss_flags & SS_ONSTACK ||
275 (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize))
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);
286 static void CreateSigAltStack() {}
289 static 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 registering handlers.
293 static ManagedStatic<sys::SmartMutex<true>> SignalHandlerRegistrationMutex;
294 sys::SmartScopedLock<true> Guard(*SignalHandlerRegistrationMutex);
296 // If the handlers are already registered, we're done.
297 if (NumRegisteredSignals.load() != 0)
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.
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!");
310 struct sigaction NewHandler;
313 case SignalKind::IsKill:
314 NewHandler.sa_handler = SignalHandler;
315 NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK;
317 case SignalKind::IsInfo:
318 NewHandler.sa_handler = InfoSignalHandler;
319 NewHandler.sa_flags = SA_ONSTACK;
322 sigemptyset(&NewHandler.sa_mask);
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;
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);
340 void 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,
345 --NumRegisteredSignals;
349 /// Process the FilesToRemove list.
350 static void RemoveFilesToRemove() {
351 FileToRemoveList::removeAllFiles(FilesToRemove);
354 void sys::CleanupOnSignal(uintptr_t Context) {
355 int Sig = (int)Context;
357 if (llvm::is_contained(InfoSigs, Sig)) {
358 InfoSignalHandler(Sig);
362 RemoveFilesToRemove();
364 if (llvm::is_contained(IntSigs, Sig) || Sig == SIGPIPE)
367 llvm::sys::RunSignalHandlers();
370 // The signal handler that runs.
371 static 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();
378 // Unmask all potentially blocked kill signals.
380 sigfillset(&SigMask);
381 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
384 RemoveFilesToRemove();
387 if (auto OldOneShotPipeFunction =
388 OneShotPipeSignalFunction.exchange(nullptr))
389 return OldOneShotPipeFunction();
391 bool IsIntSig = llvm::is_contained(IntSigs, Sig);
393 if (auto OldInterruptFunction = InterruptFunction.exchange(nullptr))
394 return OldInterruptFunction();
396 if (Sig == SIGPIPE || IsIntSig) {
397 raise(Sig); // Execute the default handler.
402 // Otherwise if it is a fault (like SEGV) run any handler.
403 llvm::sys::RunSignalHandlers();
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)
415 static void InfoSignalHandler(int Sig) {
416 SaveAndRestore SaveErrnoDuringASignalHandler(errno);
417 if (SignalHandlerFunctionType CurrentInfoFunction = InfoSignalFunction)
418 CurrentInfoFunction();
421 void llvm::sys::RunInterruptHandlers() { RemoveFilesToRemove(); }
423 void llvm::sys::SetInterruptFunction(void (*IF)()) {
424 InterruptFunction.exchange(IF);
428 void llvm::sys::SetInfoSignalFunction(void (*Handler)()) {
429 InfoSignalFunction.exchange(Handler);
433 void llvm::sys::SetOneShotPipeSignalFunction(void (*Handler)()) {
434 OneShotPipeSignalFunction.exchange(Handler);
438 void llvm::sys::DefaultOneShotPipeSignalHandler() {
439 // Send a special return code that drivers can check for, from sysexits.h.
444 bool 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());
454 void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
455 FileToRemoveList::erase(FilesToRemove, Filename.str());
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
461 void llvm::sys::AddSignalHandler(sys::SignalHandlerCallback FnPtr,
462 void *Cookie) { // Signal-safe.
463 insertSignalHandler(FnPtr, Cookie);
467 #if ENABLE_BACKTRACES && defined(HAVE_BACKTRACE) && \
468 (defined(__linux__) || defined(__FreeBSD__) || \
469 defined(__FreeBSD_kernel__) || defined(__NetBSD__))
470 struct DlIteratePhdrData {
474 const char **modules;
476 const char *main_exec_name;
479 static 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;
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)
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])
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;
502 /// If this is an ELF platform, we can find all loaded modules and their virtual
503 /// addresses with dl_iterate_phdr.
504 static 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);
514 class DSOMarkupPrinter {
515 llvm::raw_ostream &OS;
516 const char *MainExecutableName;
517 size_t ModuleCount = 0;
521 DSOMarkupPrinter(llvm::raw_ostream &OS, const char *MainExecutableName)
522 : OS(OS), MainExecutableName(MainExecutableName) {}
524 /// Print llvm-symbolizer markup describing the layout of the given DSO.
525 void printDSOMarkup(dl_phdr_info *Info) {
526 ArrayRef<uint8_t> BuildID = findBuildID(Info);
529 OS << format("{{{module:%d:%s:elf:", ModuleCount,
530 IsFirst ? MainExecutableName : Info->dlpi_name);
531 for (uint8_t X : BuildID)
532 OS << format("%02x", X);
535 for (int I = 0; I < Info->dlpi_phnum; I++) {
536 const auto *Phdr = &Info->dlpi_phdr[I];
537 if (Phdr->p_type != PT_LOAD)
539 uintptr_t StartAddress = Info->dlpi_addr + Phdr->p_vaddr;
540 uintptr_t ModuleRelativeAddress = Phdr->p_vaddr;
541 std::array<char, 4> ModeStr = modeStrFromFlags(Phdr->p_flags);
542 OS << format("{{{mmap:%#016x:%#x:load:%d:%s:%#016x}}}\n", StartAddress,
543 Phdr->p_memsz, ModuleCount, &ModeStr[0],
544 ModuleRelativeAddress);
550 /// Callback for use with dl_iterate_phdr. The last dl_iterate_phdr argument
551 /// must be a pointer to an instance of this class.
552 static int printDSOMarkup(dl_phdr_info *Info, size_t Size, void *Arg) {
553 static_cast<DSOMarkupPrinter *>(Arg)->printDSOMarkup(Info);
557 // Returns the build ID for the given DSO as an array of bytes. Returns an
558 // empty array if none could be found.
559 ArrayRef<uint8_t> findBuildID(dl_phdr_info *Info) {
560 for (int I = 0; I < Info->dlpi_phnum; I++) {
561 const auto *Phdr = &Info->dlpi_phdr[I];
562 if (Phdr->p_type != PT_NOTE)
565 ArrayRef<uint8_t> Notes(
566 reinterpret_cast<const uint8_t *>(Info->dlpi_addr + Phdr->p_vaddr),
568 while (Notes.size() > 12) {
569 uint32_t NameSize = *reinterpret_cast<const uint32_t *>(Notes.data());
570 Notes = Notes.drop_front(4);
571 uint32_t DescSize = *reinterpret_cast<const uint32_t *>(Notes.data());
572 Notes = Notes.drop_front(4);
573 uint32_t Type = *reinterpret_cast<const uint32_t *>(Notes.data());
574 Notes = Notes.drop_front(4);
576 ArrayRef<uint8_t> Name = Notes.take_front(NameSize);
577 auto CurPos = reinterpret_cast<uintptr_t>(Notes.data());
578 uint32_t BytesUntilDesc =
579 alignToPowerOf2(CurPos + NameSize, 4) - CurPos;
580 if (BytesUntilDesc >= Notes.size())
582 Notes = Notes.drop_front(BytesUntilDesc);
584 ArrayRef<uint8_t> Desc = Notes.take_front(DescSize);
585 CurPos = reinterpret_cast<uintptr_t>(Notes.data());
586 uint32_t BytesUntilNextNote =
587 alignToPowerOf2(CurPos + DescSize, 4) - CurPos;
588 if (BytesUntilNextNote > Notes.size())
590 Notes = Notes.drop_front(BytesUntilNextNote);
592 if (Type == 3 /*NT_GNU_BUILD_ID*/ && Name.size() >= 3 &&
593 Name[0] == 'G' && Name[1] == 'N' && Name[2] == 'U')
600 // Returns a symbolizer markup string describing the permissions on a DSO
601 // with the given p_flags.
602 std::array<char, 4> modeStrFromFlags(uint32_t Flags) {
603 std::array<char, 4> Mode;
604 char *Cur = &Mode[0];
616 static bool printMarkupContext(llvm::raw_ostream &OS,
617 const char *MainExecutableName) {
618 OS << "{{{reset}}}\n";
619 DSOMarkupPrinter MP(OS, MainExecutableName);
620 dl_iterate_phdr(DSOMarkupPrinter::printDSOMarkup, &MP);
624 #elif ENABLE_BACKTRACES && defined(__APPLE__) && defined(__LP64__)
625 static bool findModulesAndOffsets(void **StackTrace, int Depth,
626 const char **Modules, intptr_t *Offsets,
627 const char *MainExecutableName,
628 StringSaver &StrPool) {
629 uint32_t NumImgs = _dyld_image_count();
630 for (uint32_t ImageIndex = 0; ImageIndex < NumImgs; ImageIndex++) {
631 const char *Name = _dyld_get_image_name(ImageIndex);
632 intptr_t Slide = _dyld_get_image_vmaddr_slide(ImageIndex);
634 (const struct mach_header_64 *)_dyld_get_image_header(ImageIndex);
637 auto Cmd = (const struct load_command *)(&Header[1]);
638 for (uint32_t CmdNum = 0; CmdNum < Header->ncmds; ++CmdNum) {
639 uint32_t BaseCmd = Cmd->cmd & ~LC_REQ_DYLD;
640 if (BaseCmd == LC_SEGMENT_64) {
641 auto CmdSeg64 = (const struct segment_command_64 *)Cmd;
642 for (int j = 0; j < Depth; j++) {
645 intptr_t Addr = (intptr_t)StackTrace[j];
646 if ((intptr_t)CmdSeg64->vmaddr + Slide <= Addr &&
647 Addr < intptr_t(CmdSeg64->vmaddr + CmdSeg64->vmsize + Slide)) {
649 Offsets[j] = Addr - Slide;
653 Cmd = (const load_command *)(((const char *)Cmd) + (Cmd->cmdsize));
659 static bool printMarkupContext(llvm::raw_ostream &OS,
660 const char *MainExecutableName) {
664 /// Backtraces are not enabled or we don't yet know how to find all loaded DSOs
665 /// on this platform.
666 static bool findModulesAndOffsets(void **StackTrace, int Depth,
667 const char **Modules, intptr_t *Offsets,
668 const char *MainExecutableName,
669 StringSaver &StrPool) {
673 static bool printMarkupContext(llvm::raw_ostream &OS,
674 const char *MainExecutableName) {
677 #endif // ENABLE_BACKTRACES && ... (findModulesAndOffsets variants)
679 #if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE)
680 static int unwindBacktrace(void **StackTrace, int MaxEntries) {
684 // Skip the first frame ('unwindBacktrace' itself).
687 auto HandleFrame = [&](_Unwind_Context *Context) -> _Unwind_Reason_Code {
688 // Apparently we need to detect reaching the end of the stack ourselves.
689 void *IP = (void *)_Unwind_GetIP(Context);
691 return _URC_END_OF_STACK;
693 assert(Entries < MaxEntries && "recursively called after END_OF_STACK?");
695 StackTrace[Entries] = IP;
697 if (++Entries == MaxEntries)
698 return _URC_END_OF_STACK;
699 return _URC_NO_REASON;
703 [](_Unwind_Context *Context, void *Handler) {
704 return (*static_cast<decltype(HandleFrame) *>(Handler))(Context);
706 static_cast<void *>(&HandleFrame));
707 return std::max(Entries, 0);
711 #if ENABLE_BACKTRACES && defined(__MVS__)
712 static void zosbacktrace(raw_ostream &OS) {
713 // A function name in the PPA1 can have length 16k.
714 constexpr size_t MAX_ENTRY_NAME = UINT16_MAX;
715 // Limit all other strings to 8 byte.
716 constexpr size_t MAX_OTHER = 8;
717 int32_t dsa_format = -1; // Input/Output
718 void *caaptr = _gtca(); // Input
719 int32_t member_id; // Output
720 char compile_unit_name[MAX_OTHER]; // Output
721 void *compile_unit_address; // Output
722 void *call_instruction_address = nullptr; // Input/Output
723 char entry_name[MAX_ENTRY_NAME]; // Output
724 void *entry_address; // Output
725 void *callers_instruction_address; // Output
726 void *callers_dsaptr; // Output
727 int32_t callers_dsa_format; // Output
728 char statement_id[MAX_OTHER]; // Output
729 void *cibptr; // Output
730 int32_t main_program; // Output
731 _FEEDBACK fc; // Output
733 // The DSA pointer is the value of the stack pointer r4.
734 // __builtin_frame_address() returns a pointer to the stack frame, so the
735 // stack bias has to be considered to get the expected DSA value.
736 void *dsaptr = static_cast<char *>(__builtin_frame_address(0)) - 2048;
738 OS << " DSA Adr EP +EP DSA "
741 // After the call, these variables contain the length of the string.
742 int32_t compile_unit_name_length = sizeof(compile_unit_name);
743 int32_t entry_name_length = sizeof(entry_name);
744 int32_t statement_id_length = sizeof(statement_id);
746 // https://www.ibm.com/docs/en/zos/3.1.0?topic=cwicsa6a-celqtbck-also-known-as-celqtbck-64-bit-traceback-service
747 // for documentation of the parameters.
748 __CELQTBCK(&dsaptr, &dsa_format, &caaptr, &member_id, &compile_unit_name[0],
749 &compile_unit_name_length, &compile_unit_address,
750 &call_instruction_address, &entry_name[0], &entry_name_length,
751 &entry_address, &callers_instruction_address, &callers_dsaptr,
752 &callers_dsa_format, &statement_id[0], &statement_id_length,
753 &cibptr, &main_program, &fc);
755 OS << format("error: CELQTBCK returned severity %d message %d\n",
756 fc.tok_sev, fc.tok_msgno);
760 if (count) { // Omit first entry.
761 uintptr_t diff = reinterpret_cast<uintptr_t>(call_instruction_address) -
762 reinterpret_cast<uintptr_t>(entry_address);
763 OS << format(" %3d. 0x%016lX", count, call_instruction_address);
764 OS << format(" 0x%016lX +0x%08lX 0x%016lX", entry_address, diff, dsaptr);
765 SmallString<256> Str;
766 ConverterEBCDIC::convertToUTF8(StringRef(entry_name, entry_name_length),
768 OS << ' ' << Str << '\n';
771 if (callers_dsaptr) {
772 dsaptr = callers_dsaptr;
773 dsa_format = callers_dsa_format;
774 call_instruction_address = callers_instruction_address;
781 // In the case of a program crash or fault, print out a stack trace so that the
782 // user has an indication of why and where we died.
784 // On glibc systems we have the 'backtrace' function, which works nicely, but
785 // doesn't demangle symbols.
786 void llvm::sys::PrintStackTrace(raw_ostream &OS, int Depth) {
787 #if ENABLE_BACKTRACES
791 static void *StackTrace[256];
793 #if defined(HAVE_BACKTRACE)
794 // Use backtrace() to output a backtrace on Linux systems with glibc.
796 depth = backtrace(StackTrace, static_cast<int>(std::size(StackTrace)));
798 #if defined(HAVE__UNWIND_BACKTRACE)
799 // Try _Unwind_Backtrace() if backtrace() failed.
802 unwindBacktrace(StackTrace, static_cast<int>(std::size(StackTrace)));
806 // If "Depth" is not provided by the caller, use the return value of
807 // backtrace() for printing a symbolized stack trace.
810 if (printMarkupStackTrace(Argv0, StackTrace, Depth, OS))
812 if (printSymbolizedStackTrace(Argv0, StackTrace, Depth, OS))
814 OS << "Stack dump without symbol names (ensure you have llvm-symbolizer in "
815 "your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point "
817 #if HAVE_DLFCN_H && HAVE_DLADDR
819 for (int i = 0; i < depth; ++i) {
821 dladdr(StackTrace[i], &dlinfo);
822 const char *name = strrchr(dlinfo.dli_fname, '/');
826 nwidth = strlen(dlinfo.dli_fname);
828 nwidth = strlen(name) - 1;
834 for (int i = 0; i < depth; ++i) {
836 dladdr(StackTrace[i], &dlinfo);
838 OS << format("%-2d", i);
840 const char *name = strrchr(dlinfo.dli_fname, '/');
842 OS << format(" %-*s", width, dlinfo.dli_fname);
844 OS << format(" %-*s", width, name + 1);
846 OS << format(" %#0*lx", (int)(sizeof(void *) * 2) + 2,
847 (unsigned long)StackTrace[i]);
849 if (dlinfo.dli_sname != nullptr) {
851 if (char *d = itaniumDemangle(dlinfo.dli_sname)) {
855 OS << dlinfo.dli_sname;
858 OS << format(" + %tu", (static_cast<const char *>(StackTrace[i]) -
859 static_cast<const char *>(dlinfo.dli_saddr)));
863 #elif defined(HAVE_BACKTRACE)
864 backtrace_symbols_fd(StackTrace, Depth, STDERR_FILENO);
870 static void PrintStackTraceSignalHandler(void *) {
871 sys::PrintStackTrace(llvm::errs());
874 void llvm::sys::DisableSystemDialogsOnCrash() {}
876 /// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
877 /// process, print a stack trace and then exit.
878 void llvm::sys::PrintStackTraceOnErrorSignal(StringRef Argv0,
879 bool DisableCrashReporting) {
882 AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
884 #if defined(__APPLE__) && ENABLE_CRASH_OVERRIDES
885 // Environment variable to disable any kind of crash dialog.
886 if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) {
887 mach_port_t self = mach_task_self();
889 exception_mask_t mask = EXC_MASK_CRASH;
891 kern_return_t ret = task_set_exception_ports(
892 self, mask, MACH_PORT_NULL,
893 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES, THREAD_STATE_NONE);