LLVM 20.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#include <sys/stat.h>
57#if HAVE_DLFCN_H
58#include <dlfcn.h>
59#endif
60#if HAVE_MACH_MACH_H
61#include <mach/mach.h>
62#endif
63#ifdef __APPLE__
64#include <mach-o/dyld.h>
65#endif
66#if __has_include(<link.h>)
67#include <link.h>
68#endif
69#ifdef HAVE__UNWIND_BACKTRACE
70// FIXME: We should be able to use <unwind.h> for any target that has an
71// _Unwind_Backtrace function, but on FreeBSD the configure test passes
72// despite the function not existing, and on Android, <unwind.h> conflicts
73// with <link.h>.
74#ifdef __GLIBC__
75#include <unwind.h>
76#else
77#undef HAVE__UNWIND_BACKTRACE
78#endif
79#endif
80#if ENABLE_BACKTRACES && defined(__MVS__)
82#include <__le_cwi.h>
83#endif
84
85using namespace llvm;
86
87static void SignalHandler(int Sig); // defined below.
88static void InfoSignalHandler(int Sig); // defined below.
89
90using SignalHandlerFunctionType = void (*)();
91/// The function to call if ctrl-c is pressed.
92static std::atomic<SignalHandlerFunctionType> InterruptFunction = nullptr;
93static std::atomic<SignalHandlerFunctionType> InfoSignalFunction = nullptr;
94/// The function to call on SIGPIPE (one-time use only).
95static std::atomic<SignalHandlerFunctionType> OneShotPipeSignalFunction =
96 nullptr;
97
98namespace {
99/// Signal-safe removal of files.
100/// Inserting and erasing from the list isn't signal-safe, but removal of files
101/// themselves is signal-safe. Memory is freed when the head is freed, deletion
102/// is therefore not signal-safe either.
103class FileToRemoveList {
104 std::atomic<char *> Filename = nullptr;
105 std::atomic<FileToRemoveList *> Next = nullptr;
106
107 FileToRemoveList() = default;
108 // Not signal-safe.
109 FileToRemoveList(const std::string &str) : Filename(strdup(str.c_str())) {}
110
111public:
112 // Not signal-safe.
113 ~FileToRemoveList() {
114 if (FileToRemoveList *N = Next.exchange(nullptr))
115 delete N;
116 if (char *F = Filename.exchange(nullptr))
117 free(F);
118 }
119
120 // Not signal-safe.
121 static void insert(std::atomic<FileToRemoveList *> &Head,
122 const std::string &Filename) {
123 // Insert the new file at the end of the list.
124 FileToRemoveList *NewHead = new FileToRemoveList(Filename);
125 std::atomic<FileToRemoveList *> *InsertionPoint = &Head;
126 FileToRemoveList *OldHead = nullptr;
127 while (!InsertionPoint->compare_exchange_strong(OldHead, NewHead)) {
128 InsertionPoint = &OldHead->Next;
129 OldHead = nullptr;
130 }
131 }
132
133 // Not signal-safe.
134 static void erase(std::atomic<FileToRemoveList *> &Head,
135 const std::string &Filename) {
136 // Use a lock to avoid concurrent erase: the comparison would access
137 // free'd memory.
139 sys::SmartScopedLock<true> Writer(*Lock);
140
141 for (FileToRemoveList *Current = Head.load(); Current;
142 Current = Current->Next.load()) {
143 if (char *OldFilename = Current->Filename.load()) {
144 if (OldFilename != Filename)
145 continue;
146 // Leave an empty filename.
147 OldFilename = Current->Filename.exchange(nullptr);
148 // The filename might have become null between the time we
149 // compared it and we exchanged it.
150 if (OldFilename)
151 free(OldFilename);
152 }
153 }
154 }
155
156 // Signal-safe.
157 static void removeAllFiles(std::atomic<FileToRemoveList *> &Head) {
158 // If cleanup were to occur while we're removing files we'd have a bad time.
159 // Make sure we're OK by preventing cleanup from doing anything while we're
160 // removing files. If cleanup races with us and we win we'll have a leak,
161 // but we won't crash.
162 FileToRemoveList *OldHead = Head.exchange(nullptr);
163
164 for (FileToRemoveList *currentFile = OldHead; currentFile;
165 currentFile = currentFile->Next.load()) {
166 // If erasing was occuring while we're trying to remove files we'd look
167 // at free'd data. Take away the path and put it back when done.
168 if (char *path = currentFile->Filename.exchange(nullptr)) {
169 // Get the status so we can determine if it's a file or directory. If we
170 // can't stat the file, ignore it.
171 struct stat buf;
172 if (stat(path, &buf) != 0)
173 continue;
174
175 // If this is not a regular file, ignore it. We want to prevent removal
176 // of special files like /dev/null, even if the compiler is being run
177 // with the super-user permissions.
178 if (!S_ISREG(buf.st_mode))
179 continue;
180
181 // Otherwise, remove the file. We ignore any errors here as there is
182 // nothing else we can do.
183 unlink(path);
184
185 // We're done removing the file, erasing can safely proceed.
186 currentFile->Filename.exchange(path);
187 }
188 }
189
190 // We're done removing files, cleanup can safely proceed.
191 Head.exchange(OldHead);
192 }
193};
194static std::atomic<FileToRemoveList *> FilesToRemove = nullptr;
195
196/// Clean up the list in a signal-friendly manner.
197/// Recall that signals can fire during llvm_shutdown. If this occurs we should
198/// either clean something up or nothing at all, but we shouldn't crash!
199struct FilesToRemoveCleanup {
200 // Not signal-safe.
201 ~FilesToRemoveCleanup() {
202 FileToRemoveList *Head = FilesToRemove.exchange(nullptr);
203 if (Head)
204 delete Head;
205 }
206};
207} // namespace
208
209static StringRef Argv0;
210
211/// Signals that represent requested termination. There's no bug or failure, or
212/// if there is, it's not our direct responsibility. For whatever reason, our
213/// continued execution is no longer desirable.
214static const int IntSigs[] = {SIGHUP, SIGINT, SIGTERM, SIGUSR2};
215
216/// Signals that represent that we have a bug, and our prompt termination has
217/// been ordered.
218static const int KillSigs[] = {SIGILL,
219 SIGTRAP,
220 SIGABRT,
221 SIGFPE,
222 SIGBUS,
223 SIGSEGV,
224 SIGQUIT
225#ifdef SIGSYS
226 ,
227 SIGSYS
228#endif
229#ifdef SIGXCPU
230 ,
231 SIGXCPU
232#endif
233#ifdef SIGXFSZ
234 ,
235 SIGXFSZ
236#endif
237#ifdef SIGEMT
238 ,
239 SIGEMT
240#endif
241};
242
243/// Signals that represent requests for status.
244static const int InfoSigs[] = {SIGUSR1
245#ifdef SIGINFO
246 ,
247 SIGINFO
248#endif
249};
250
251static const size_t NumSigs = std::size(IntSigs) + std::size(KillSigs) +
252 std::size(InfoSigs) + 1 /* SIGPIPE */;
253
254static std::atomic<unsigned> NumRegisteredSignals = 0;
255static struct {
256 struct sigaction SA;
257 int SigNo;
258} RegisteredSignalInfo[NumSigs];
259
260#if defined(HAVE_SIGALTSTACK)
261// Hold onto both the old and new alternate signal stack so that it's not
262// reported as a leak. We don't make any attempt to remove our alt signal
263// stack if we remove our signal handlers; that can't be done reliably if
264// someone else is also trying to do the same thing.
265static stack_t OldAltStack;
266LLVM_ATTRIBUTE_USED static void *NewAltStackPointer;
267
268static void CreateSigAltStack() {
269 const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024;
270
271 // If we're executing on the alternate stack, or we already have an alternate
272 // signal stack that we're happy with, there's nothing for us to do. Don't
273 // reduce the size, some other part of the process might need a larger stack
274 // than we do.
275 if (sigaltstack(nullptr, &OldAltStack) != 0 ||
276 OldAltStack.ss_flags & SS_ONSTACK ||
277 (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize))
278 return;
279
280 stack_t AltStack = {};
281 AltStack.ss_sp = static_cast<char *>(safe_malloc(AltStackSize));
282 NewAltStackPointer = AltStack.ss_sp; // Save to avoid reporting a leak.
283 AltStack.ss_size = AltStackSize;
284 if (sigaltstack(&AltStack, &OldAltStack) != 0)
285 free(AltStack.ss_sp);
286}
287#else
288static void CreateSigAltStack() {}
289#endif
290
291static void RegisterHandlers() { // Not signal-safe.
292 // The mutex prevents other threads from registering handlers while we're
293 // doing it. We also have to protect the handlers and their count because
294 // a signal handler could fire while we're registering handlers.
295 static ManagedStatic<sys::SmartMutex<true>> SignalHandlerRegistrationMutex;
296 sys::SmartScopedLock<true> Guard(*SignalHandlerRegistrationMutex);
297
298 // If the handlers are already registered, we're done.
299 if (NumRegisteredSignals.load() != 0)
300 return;
301
302 // Create an alternate stack for signal handling. This is necessary for us to
303 // be able to reliably handle signals due to stack overflow.
304 CreateSigAltStack();
305
306 enum class SignalKind { IsKill, IsInfo };
307 auto registerHandler = [&](int Signal, SignalKind Kind) {
308 unsigned Index = NumRegisteredSignals.load();
309 assert(Index < std::size(RegisteredSignalInfo) &&
310 "Out of space for signal handlers!");
311
312 struct sigaction NewHandler;
313
314 switch (Kind) {
315 case SignalKind::IsKill:
316 NewHandler.sa_handler = SignalHandler;
317 NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK;
318 break;
319 case SignalKind::IsInfo:
320 NewHandler.sa_handler = InfoSignalHandler;
321 NewHandler.sa_flags = SA_ONSTACK;
322 break;
323 }
324 sigemptyset(&NewHandler.sa_mask);
325
326 // Install the new handler, save the old one in RegisteredSignalInfo.
327 sigaction(Signal, &NewHandler, &RegisteredSignalInfo[Index].SA);
328 RegisteredSignalInfo[Index].SigNo = Signal;
329 ++NumRegisteredSignals;
330 };
331
332 for (auto S : IntSigs)
333 registerHandler(S, SignalKind::IsKill);
334 for (auto S : KillSigs)
335 registerHandler(S, SignalKind::IsKill);
336 if (OneShotPipeSignalFunction)
337 registerHandler(SIGPIPE, SignalKind::IsKill);
338 for (auto S : InfoSigs)
339 registerHandler(S, SignalKind::IsInfo);
340}
341
342void sys::unregisterHandlers() {
343 // Restore all of the signal handlers to how they were before we showed up.
344 for (unsigned i = 0, e = NumRegisteredSignals.load(); i != e; ++i) {
345 sigaction(RegisteredSignalInfo[i].SigNo, &RegisteredSignalInfo[i].SA,
346 nullptr);
347 --NumRegisteredSignals;
348 }
349}
350
351/// Process the FilesToRemove list.
352static void RemoveFilesToRemove() {
353 FileToRemoveList::removeAllFiles(FilesToRemove);
354}
355
356void sys::CleanupOnSignal(uintptr_t Context) {
357 int Sig = (int)Context;
358
359 if (llvm::is_contained(InfoSigs, Sig)) {
360 InfoSignalHandler(Sig);
361 return;
362 }
363
364 RemoveFilesToRemove();
365
366 if (llvm::is_contained(IntSigs, Sig) || Sig == SIGPIPE)
367 return;
368
370}
371
372// The signal handler that runs.
373static void SignalHandler(int Sig) {
374 // Restore the signal behavior to default, so that the program actually
375 // crashes when we return and the signal reissues. This also ensures that if
376 // we crash in our signal handler that the program will terminate immediately
377 // instead of recursing in the signal handler.
378 sys::unregisterHandlers();
379
380 // Unmask all potentially blocked kill signals.
381 sigset_t SigMask;
382 sigfillset(&SigMask);
383 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
384
385 {
386 RemoveFilesToRemove();
387
388 if (Sig == SIGPIPE)
389 if (auto OldOneShotPipeFunction =
390 OneShotPipeSignalFunction.exchange(nullptr))
391 return OldOneShotPipeFunction();
392
393 bool IsIntSig = llvm::is_contained(IntSigs, Sig);
394 if (IsIntSig)
395 if (auto OldInterruptFunction = InterruptFunction.exchange(nullptr))
396 return OldInterruptFunction();
397
398 if (Sig == SIGPIPE || IsIntSig) {
399 raise(Sig); // Execute the default handler.
400 return;
401 }
402 }
403
404 // Otherwise if it is a fault (like SEGV) run any handler.
406
407#ifdef __s390__
408 // On S/390, certain signals are delivered with PSW Address pointing to
409 // *after* the faulting instruction. Simply returning from the signal
410 // handler would continue execution after that point, instead of
411 // re-raising the signal. Raise the signal manually in those cases.
412 if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
413 raise(Sig);
414#endif
415}
416
417static void InfoSignalHandler(int Sig) {
418 SaveAndRestore SaveErrnoDuringASignalHandler(errno);
419 if (SignalHandlerFunctionType CurrentInfoFunction = InfoSignalFunction)
420 CurrentInfoFunction();
421}
422
423void llvm::sys::RunInterruptHandlers() { RemoveFilesToRemove(); }
424
425void llvm::sys::SetInterruptFunction(void (*IF)()) {
426 InterruptFunction.exchange(IF);
427 RegisterHandlers();
428}
429
430void llvm::sys::SetInfoSignalFunction(void (*Handler)()) {
431 InfoSignalFunction.exchange(Handler);
432 RegisterHandlers();
433}
434
435void llvm::sys::SetOneShotPipeSignalFunction(void (*Handler)()) {
436 OneShotPipeSignalFunction.exchange(Handler);
437 RegisterHandlers();
438}
439
441 // Send a special return code that drivers can check for, from sysexits.h.
442 exit(EX_IOERR);
443}
444
445// The public API
446bool llvm::sys::RemoveFileOnSignal(StringRef Filename, std::string *ErrMsg) {
447 // Ensure that cleanup will occur as soon as one file is added.
448 static ManagedStatic<FilesToRemoveCleanup> FilesToRemoveCleanup;
449 *FilesToRemoveCleanup;
450 FileToRemoveList::insert(FilesToRemove, Filename.str());
451 RegisterHandlers();
452 return false;
453}
454
455// The public API
457 FileToRemoveList::erase(FilesToRemove, Filename.str());
458}
459
460/// Add a function to be called when a signal is delivered to the process. The
461/// handler can have a cookie passed to it to identify what instance of the
462/// handler it is.
464 void *Cookie) { // Signal-safe.
465 insertSignalHandler(FnPtr, Cookie);
466 RegisterHandlers();
467}
468
469#if ENABLE_BACKTRACES && defined(HAVE_BACKTRACE) && \
470 (defined(__linux__) || defined(__FreeBSD__) || \
471 defined(__FreeBSD_kernel__) || defined(__NetBSD__))
472struct DlIteratePhdrData {
473 void **StackTrace;
474 int depth;
475 bool first;
476 const char **modules;
477 intptr_t *offsets;
478 const char *main_exec_name;
479};
480
481static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
482 DlIteratePhdrData *data = (DlIteratePhdrData *)arg;
483 const char *name = data->first ? data->main_exec_name : info->dlpi_name;
484 data->first = false;
485 for (int i = 0; i < info->dlpi_phnum; i++) {
486 const auto *phdr = &info->dlpi_phdr[i];
487 if (phdr->p_type != PT_LOAD)
488 continue;
489 intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
490 intptr_t end = beg + phdr->p_memsz;
491 for (int j = 0; j < data->depth; j++) {
492 if (data->modules[j])
493 continue;
494 intptr_t addr = (intptr_t)data->StackTrace[j];
495 if (beg <= addr && addr < end) {
496 data->modules[j] = name;
497 data->offsets[j] = addr - info->dlpi_addr;
498 }
499 }
500 }
501 return 0;
502}
503
504/// If this is an ELF platform, we can find all loaded modules and their virtual
505/// addresses with dl_iterate_phdr.
506static bool findModulesAndOffsets(void **StackTrace, int Depth,
507 const char **Modules, intptr_t *Offsets,
508 const char *MainExecutableName,
509 StringSaver &StrPool) {
510 DlIteratePhdrData data = {StackTrace, Depth, true,
511 Modules, Offsets, MainExecutableName};
512 dl_iterate_phdr(dl_iterate_phdr_cb, &data);
513 return true;
514}
515
516class DSOMarkupPrinter {
518 const char *MainExecutableName;
519 size_t ModuleCount = 0;
520 bool IsFirst = true;
521
522public:
523 DSOMarkupPrinter(llvm::raw_ostream &OS, const char *MainExecutableName)
524 : OS(OS), MainExecutableName(MainExecutableName) {}
525
526 /// Print llvm-symbolizer markup describing the layout of the given DSO.
527 void printDSOMarkup(dl_phdr_info *Info) {
528 ArrayRef<uint8_t> BuildID = findBuildID(Info);
529 if (BuildID.empty())
530 return;
531 OS << format("{{{module:%d:%s:elf:", ModuleCount,
532 IsFirst ? MainExecutableName : Info->dlpi_name);
533 for (uint8_t X : BuildID)
534 OS << format("%02x", X);
535 OS << "}}}\n";
536
537 for (int I = 0; I < Info->dlpi_phnum; I++) {
538 const auto *Phdr = &Info->dlpi_phdr[I];
539 if (Phdr->p_type != PT_LOAD)
540 continue;
541 uintptr_t StartAddress = Info->dlpi_addr + Phdr->p_vaddr;
542 uintptr_t ModuleRelativeAddress = Phdr->p_vaddr;
543 std::array<char, 4> ModeStr = modeStrFromFlags(Phdr->p_flags);
544 OS << format("{{{mmap:%#016x:%#x:load:%d:%s:%#016x}}}\n", StartAddress,
545 Phdr->p_memsz, ModuleCount, &ModeStr[0],
546 ModuleRelativeAddress);
547 }
548 IsFirst = false;
549 ModuleCount++;
550 }
551
552 /// Callback for use with dl_iterate_phdr. The last dl_iterate_phdr argument
553 /// must be a pointer to an instance of this class.
554 static int printDSOMarkup(dl_phdr_info *Info, size_t Size, void *Arg) {
555 static_cast<DSOMarkupPrinter *>(Arg)->printDSOMarkup(Info);
556 return 0;
557 }
558
559 // Returns the build ID for the given DSO as an array of bytes. Returns an
560 // empty array if none could be found.
561 ArrayRef<uint8_t> findBuildID(dl_phdr_info *Info) {
562 for (int I = 0; I < Info->dlpi_phnum; I++) {
563 const auto *Phdr = &Info->dlpi_phdr[I];
564 if (Phdr->p_type != PT_NOTE)
565 continue;
566
567 ArrayRef<uint8_t> Notes(
568 reinterpret_cast<const uint8_t *>(Info->dlpi_addr + Phdr->p_vaddr),
569 Phdr->p_memsz);
570 while (Notes.size() > 12) {
571 uint32_t NameSize = *reinterpret_cast<const uint32_t *>(Notes.data());
572 Notes = Notes.drop_front(4);
573 uint32_t DescSize = *reinterpret_cast<const uint32_t *>(Notes.data());
574 Notes = Notes.drop_front(4);
575 uint32_t Type = *reinterpret_cast<const uint32_t *>(Notes.data());
576 Notes = Notes.drop_front(4);
577
578 ArrayRef<uint8_t> Name = Notes.take_front(NameSize);
579 auto CurPos = reinterpret_cast<uintptr_t>(Notes.data());
580 uint32_t BytesUntilDesc =
581 alignToPowerOf2(CurPos + NameSize, 4) - CurPos;
582 if (BytesUntilDesc >= Notes.size())
583 break;
584 Notes = Notes.drop_front(BytesUntilDesc);
585
586 ArrayRef<uint8_t> Desc = Notes.take_front(DescSize);
587 CurPos = reinterpret_cast<uintptr_t>(Notes.data());
588 uint32_t BytesUntilNextNote =
589 alignToPowerOf2(CurPos + DescSize, 4) - CurPos;
590 if (BytesUntilNextNote > Notes.size())
591 break;
592 Notes = Notes.drop_front(BytesUntilNextNote);
593
594 if (Type == 3 /*NT_GNU_BUILD_ID*/ && Name.size() >= 3 &&
595 Name[0] == 'G' && Name[1] == 'N' && Name[2] == 'U')
596 return Desc;
597 }
598 }
599 return {};
600 }
601
602 // Returns a symbolizer markup string describing the permissions on a DSO
603 // with the given p_flags.
604 std::array<char, 4> modeStrFromFlags(uint32_t Flags) {
605 std::array<char, 4> Mode;
606 char *Cur = &Mode[0];
607 if (Flags & PF_R)
608 *Cur++ = 'r';
609 if (Flags & PF_W)
610 *Cur++ = 'w';
611 if (Flags & PF_X)
612 *Cur++ = 'x';
613 *Cur = '\0';
614 return Mode;
615 }
616};
617
619 const char *MainExecutableName) {
620 OS << "{{{reset}}}\n";
621 DSOMarkupPrinter MP(OS, MainExecutableName);
622 dl_iterate_phdr(DSOMarkupPrinter::printDSOMarkup, &MP);
623 return true;
624}
625
626#elif ENABLE_BACKTRACES && defined(__APPLE__) && defined(__LP64__)
627static bool findModulesAndOffsets(void **StackTrace, int Depth,
628 const char **Modules, intptr_t *Offsets,
629 const char *MainExecutableName,
630 StringSaver &StrPool) {
631 uint32_t NumImgs = _dyld_image_count();
632 for (uint32_t ImageIndex = 0; ImageIndex < NumImgs; ImageIndex++) {
633 const char *Name = _dyld_get_image_name(ImageIndex);
634 intptr_t Slide = _dyld_get_image_vmaddr_slide(ImageIndex);
635 auto *Header =
636 (const struct mach_header_64 *)_dyld_get_image_header(ImageIndex);
637 if (Header == NULL)
638 continue;
639 auto Cmd = (const struct load_command *)(&Header[1]);
640 for (uint32_t CmdNum = 0; CmdNum < Header->ncmds; ++CmdNum) {
641 uint32_t BaseCmd = Cmd->cmd & ~LC_REQ_DYLD;
642 if (BaseCmd == LC_SEGMENT_64) {
643 auto CmdSeg64 = (const struct segment_command_64 *)Cmd;
644 for (int j = 0; j < Depth; j++) {
645 if (Modules[j])
646 continue;
647 intptr_t Addr = (intptr_t)StackTrace[j];
648 if ((intptr_t)CmdSeg64->vmaddr + Slide <= Addr &&
649 Addr < intptr_t(CmdSeg64->vmaddr + CmdSeg64->vmsize + Slide)) {
650 Modules[j] = Name;
651 Offsets[j] = Addr - Slide;
652 }
653 }
654 }
655 Cmd = (const load_command *)(((const char *)Cmd) + (Cmd->cmdsize));
656 }
657 }
658 return true;
659}
660
662 const char *MainExecutableName) {
663 return false;
664}
665#else
666/// Backtraces are not enabled or we don't yet know how to find all loaded DSOs
667/// on this platform.
668static bool findModulesAndOffsets(void **StackTrace, int Depth,
669 const char **Modules, intptr_t *Offsets,
670 const char *MainExecutableName,
671 StringSaver &StrPool) {
672 return false;
673}
674
676 const char *MainExecutableName) {
677 return false;
678}
679#endif // ENABLE_BACKTRACES && ... (findModulesAndOffsets variants)
680
681#if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE)
682static int unwindBacktrace(void **StackTrace, int MaxEntries) {
683 if (MaxEntries < 0)
684 return 0;
685
686 // Skip the first frame ('unwindBacktrace' itself).
687 int Entries = -1;
688
689 auto HandleFrame = [&](_Unwind_Context *Context) -> _Unwind_Reason_Code {
690 // Apparently we need to detect reaching the end of the stack ourselves.
691 void *IP = (void *)_Unwind_GetIP(Context);
692 if (!IP)
693 return _URC_END_OF_STACK;
694
695 assert(Entries < MaxEntries && "recursively called after END_OF_STACK?");
696 if (Entries >= 0)
697 StackTrace[Entries] = IP;
698
699 if (++Entries == MaxEntries)
700 return _URC_END_OF_STACK;
701 return _URC_NO_REASON;
702 };
703
704 _Unwind_Backtrace(
705 [](_Unwind_Context *Context, void *Handler) {
706 return (*static_cast<decltype(HandleFrame) *>(Handler))(Context);
707 },
708 static_cast<void *>(&HandleFrame));
709 return std::max(Entries, 0);
710}
711#endif
712
713#if ENABLE_BACKTRACES && defined(__MVS__)
714static void zosbacktrace(raw_ostream &OS) {
715 // A function name in the PPA1 can have length 16k.
716 constexpr size_t MAX_ENTRY_NAME = UINT16_MAX;
717 // Limit all other strings to 8 byte.
718 constexpr size_t MAX_OTHER = 8;
719 int32_t dsa_format = -1; // Input/Output
720 void *caaptr = _gtca(); // Input
721 int32_t member_id; // Output
722 char compile_unit_name[MAX_OTHER]; // Output
723 void *compile_unit_address; // Output
724 void *call_instruction_address = nullptr; // Input/Output
725 char entry_name[MAX_ENTRY_NAME]; // Output
726 void *entry_address; // Output
727 void *callers_instruction_address; // Output
728 void *callers_dsaptr; // Output
729 int32_t callers_dsa_format; // Output
730 char statement_id[MAX_OTHER]; // Output
731 void *cibptr; // Output
732 int32_t main_program; // Output
733 _FEEDBACK fc; // Output
734
735 // The DSA pointer is the value of the stack pointer r4.
736 // __builtin_frame_address() returns a pointer to the stack frame, so the
737 // stack bias has to be considered to get the expected DSA value.
738 void *dsaptr = static_cast<char *>(__builtin_frame_address(0)) - 2048;
739 int count = 0;
740 OS << " DSA Adr EP +EP DSA "
741 " Entry\n";
742 while (1) {
743 // After the call, these variables contain the length of the string.
744 int32_t compile_unit_name_length = sizeof(compile_unit_name);
745 int32_t entry_name_length = sizeof(entry_name);
746 int32_t statement_id_length = sizeof(statement_id);
747 // See
748 // https://www.ibm.com/docs/en/zos/3.1.0?topic=cwicsa6a-celqtbck-also-known-as-celqtbck-64-bit-traceback-service
749 // for documentation of the parameters.
750 __CELQTBCK(&dsaptr, &dsa_format, &caaptr, &member_id, &compile_unit_name[0],
751 &compile_unit_name_length, &compile_unit_address,
752 &call_instruction_address, &entry_name[0], &entry_name_length,
753 &entry_address, &callers_instruction_address, &callers_dsaptr,
754 &callers_dsa_format, &statement_id[0], &statement_id_length,
755 &cibptr, &main_program, &fc);
756 if (fc.tok_sev) {
757 OS << format("error: CELQTBCK returned severity %d message %d\n",
758 fc.tok_sev, fc.tok_msgno);
759 break;
760 }
761
762 if (count) { // Omit first entry.
763 uintptr_t diff = reinterpret_cast<uintptr_t>(call_instruction_address) -
764 reinterpret_cast<uintptr_t>(entry_address);
765 OS << format(" %3d. 0x%016lX", count, call_instruction_address);
766 OS << format(" 0x%016lX +0x%08lX 0x%016lX", entry_address, diff, dsaptr);
768 ConverterEBCDIC::convertToUTF8(StringRef(entry_name, entry_name_length),
769 Str);
770 OS << ' ' << Str << '\n';
771 }
772 ++count;
773 if (callers_dsaptr) {
774 dsaptr = callers_dsaptr;
775 dsa_format = callers_dsa_format;
776 call_instruction_address = callers_instruction_address;
777 } else
778 break;
779 }
780}
781#endif
782
783// In the case of a program crash or fault, print out a stack trace so that the
784// user has an indication of why and where we died.
785//
786// On glibc systems we have the 'backtrace' function, which works nicely, but
787// doesn't demangle symbols.
788void llvm::sys::PrintStackTrace(raw_ostream &OS, int Depth) {
789#if ENABLE_BACKTRACES
790#ifdef __MVS__
791 zosbacktrace(OS);
792#else
793 static void *StackTrace[256];
794 int depth = 0;
795#if defined(HAVE_BACKTRACE)
796 // Use backtrace() to output a backtrace on Linux systems with glibc.
797 if (!depth)
798 depth = backtrace(StackTrace, static_cast<int>(std::size(StackTrace)));
799#endif
800#if defined(HAVE__UNWIND_BACKTRACE)
801 // Try _Unwind_Backtrace() if backtrace() failed.
802 if (!depth)
803 depth =
804 unwindBacktrace(StackTrace, static_cast<int>(std::size(StackTrace)));
805#endif
806 if (!depth)
807 return;
808 // If "Depth" is not provided by the caller, use the return value of
809 // backtrace() for printing a symbolized stack trace.
810 if (!Depth)
811 Depth = depth;
812 if (printMarkupStackTrace(Argv0, StackTrace, Depth, OS))
813 return;
814 if (printSymbolizedStackTrace(Argv0, StackTrace, Depth, OS))
815 return;
816 OS << "Stack dump without symbol names (ensure you have llvm-symbolizer in "
817 "your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point "
818 "to it):\n";
819#if HAVE_DLFCN_H && HAVE_DLADDR
820 int width = 0;
821 for (int i = 0; i < depth; ++i) {
822 Dl_info dlinfo;
823 dladdr(StackTrace[i], &dlinfo);
824 const char *name = strrchr(dlinfo.dli_fname, '/');
825
826 int nwidth;
827 if (!name)
828 nwidth = strlen(dlinfo.dli_fname);
829 else
830 nwidth = strlen(name) - 1;
831
832 if (nwidth > width)
833 width = nwidth;
834 }
835
836 for (int i = 0; i < depth; ++i) {
837 Dl_info dlinfo;
838 dladdr(StackTrace[i], &dlinfo);
839
840 OS << format("%-2d", i);
841
842 const char *name = strrchr(dlinfo.dli_fname, '/');
843 if (!name)
844 OS << format(" %-*s", width, dlinfo.dli_fname);
845 else
846 OS << format(" %-*s", width, name + 1);
847
848 OS << format(" %#0*lx", (int)(sizeof(void *) * 2) + 2,
849 (unsigned long)StackTrace[i]);
850
851 if (dlinfo.dli_sname != nullptr) {
852 OS << ' ';
853 if (char *d = itaniumDemangle(dlinfo.dli_sname)) {
854 OS << d;
855 free(d);
856 } else {
857 OS << dlinfo.dli_sname;
858 }
859
860 OS << format(" + %tu", (static_cast<const char *>(StackTrace[i]) -
861 static_cast<const char *>(dlinfo.dli_saddr)));
862 }
863 OS << '\n';
864 }
865#elif defined(HAVE_BACKTRACE)
866 backtrace_symbols_fd(StackTrace, Depth, STDERR_FILENO);
867#endif
868#endif
869#endif
870}
871
872static void PrintStackTraceSignalHandler(void *) {
873 sys::PrintStackTrace(llvm::errs());
874}
875
877
878/// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
879/// process, print a stack trace and then exit.
881 bool DisableCrashReporting) {
882 ::Argv0 = Argv0;
883
884 AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
885
886#if defined(__APPLE__) && ENABLE_CRASH_OVERRIDES
887 // Environment variable to disable any kind of crash dialog.
888 if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) {
889 mach_port_t self = mach_task_self();
890
891 exception_mask_t mask = EXC_MASK_CRASH;
892
893 kern_return_t ret = task_set_exception_ports(
894 self, mask, MACH_PORT_NULL,
895 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES, THREAD_STATE_NONE);
896 (void)ret;
897 }
898#endif
899}
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
#define LLVM_ATTRIBUTE_USED
Definition: Compiler.h:230
This file provides utility functions for converting between EBCDIC-1047 and UTF-8.
uint64_t Addr
std::string Name
uint32_t Index
uint64_t Size
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
This file contains definitions of exit codes for exit() function.
lazy value info
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
ToRemove erase(NewLastIter, ToRemove.end())
if(PassOpts->AAPipeline)
static cl::opt< RegAllocEvictionAdvisorAnalysis::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Development, "development", "for training")))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static const char * name
Definition: SMEABIPass.cpp:46
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:142
static bool findModulesAndOffsets(void **StackTrace, int Depth, const char **Modules, intptr_t *Offsets, const char *MainExecutableName, StringSaver &StrPool)
static bool printMarkupContext(raw_ostream &OS, const char *MainExecutableName)
static LLVM_ATTRIBUTE_USED bool printMarkupStackTrace(StringRef Argv0, void **StackTrace, int Depth, raw_ostream &OS)
Definition: Signals.cpp:259
static void insertSignalHandler(sys::SignalHandlerCallback FnPtr, void *Cookie)
Definition: Signals.cpp:112
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
Definition: ManagedStatic.h:83
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition: StringSaver.h:21
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
@ NameSize
Definition: COFF.h:57
Offsets
Offsets in bytes from the start of the input buffer.
Definition: SIInstrInfo.h:1609
SmallVector< uint8_t, 10 > BuildID
A build ID in binary form.
Definition: BuildID.h:25
const_iterator end(StringRef path LLVM_LIFETIME_BOUND)
Get end iterator over path.
Definition: Path.cpp:235
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:98
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)
char * itaniumDemangle(std::string_view mangled_name, bool ParseParams=true)
Returns a non-NULL pointer to a NUL-terminated C style string that should be explicitly freed,...
constexpr T alignToPowerOf2(U Value, V Align)
Will overflow only if result is not representable in T.
Definition: MathExtras.h:504
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:125
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition: STLExtras.h:1938
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1903
auto mask(ShuffFunc S, unsigned Length, OptArgs... args) -> MaskT
#define N
Description of the encoding of one expression Op.
A utility class that uses RAII to save and restore the value of a variable.