37#include "llvm/Config/config.h"
51#include BACKTRACE_HEADER
60#include <mach-o/dyld.h>
62#if __has_include(<link.h>)
65#ifdef HAVE__UNWIND_BACKTRACE
73#undef HAVE__UNWIND_BACKTRACE
76#if ENABLE_BACKTRACES && defined(__MVS__)
82#include <sys/syscall.h>
87static void SignalHandler(
int Sig, siginfo_t *
Info,
void *);
88static void InfoSignalHandler(
int Sig);
90using SignalHandlerFunctionType = void (*)();
92static std::atomic<SignalHandlerFunctionType> InterruptFunction =
nullptr;
93static std::atomic<SignalHandlerFunctionType> InfoSignalFunction =
nullptr;
95static std::atomic<SignalHandlerFunctionType> OneShotPipeSignalFunction =
103class FileToRemoveList {
104 std::atomic<char *>
Filename =
nullptr;
105 std::atomic<FileToRemoveList *> Next =
nullptr;
107 FileToRemoveList() =
default;
109 FileToRemoveList(
const std::string &str) :
Filename(strdup(str.
c_str())) {}
113 ~FileToRemoveList() {
114 if (FileToRemoveList *
N = Next.exchange(
nullptr))
116 if (
char *
F =
Filename.exchange(
nullptr))
121 static void insert(std::atomic<FileToRemoveList *> &Head,
122 const std::string &Filename) {
124 FileToRemoveList *NewHead =
new FileToRemoveList(Filename);
126 FileToRemoveList *OldHead =
nullptr;
127 while (!
InsertionPoint->compare_exchange_strong(OldHead, NewHead)) {
134 static void erase(std::atomic<FileToRemoveList *> &Head,
135 const std::string &Filename) {
141 for (FileToRemoveList *Current = Head.load(); Current;
142 Current = Current->Next.load()) {
143 if (
char *OldFilename = Current->Filename.load()) {
144 if (OldFilename != Filename)
147 OldFilename = Current->Filename.exchange(
nullptr);
156 static void removeFile(
char *path) {
160 if (stat(path, &buf) != 0)
166 if (!S_ISREG(buf.st_mode))
175 static void removeAllFiles(std::atomic<FileToRemoveList *> &Head) {
180 FileToRemoveList *OldHead = Head.exchange(
nullptr);
182 for (FileToRemoveList *currentFile = OldHead; currentFile;
183 currentFile = currentFile->Next.load()) {
186 if (
char *path = currentFile->Filename.exchange(
nullptr)) {
190 currentFile->Filename.exchange(path);
195 Head.exchange(OldHead);
198static std::atomic<FileToRemoveList *> FilesToRemove =
nullptr;
203struct FilesToRemoveCleanup {
205 ~FilesToRemoveCleanup() {
206 FileToRemoveList *Head = FilesToRemove.exchange(
nullptr);
218static const int IntSigs[] = {SIGHUP, SIGINT, SIGTERM, SIGUSR2};
222static const int KillSigs[] = {SIGILL,
248static const int InfoSigs[] = {SIGUSR1
255static const size_t NumSigs = std::size(IntSigs) + std::size(KillSigs) +
256 std::size(InfoSigs) + 1 ;
258static std::atomic<unsigned> NumRegisteredSignals = 0;
262} RegisteredSignalInfo[NumSigs];
264#if defined(HAVE_SIGALTSTACK)
269static stack_t OldAltStack;
272static void CreateSigAltStack() {
273 const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024;
279 if (sigaltstack(
nullptr, &OldAltStack) != 0 ||
280 OldAltStack.ss_flags & SS_ONSTACK ||
281 (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize))
284 stack_t AltStack = {};
285 AltStack.ss_sp =
static_cast<char *
>(
safe_malloc(AltStackSize));
286 NewAltStackPointer = AltStack.ss_sp;
287 AltStack.ss_size = AltStackSize;
288 if (sigaltstack(&AltStack, &OldAltStack) != 0)
289 free(AltStack.ss_sp);
292static void CreateSigAltStack() {}
295static void RegisterHandlers() {
303 if (NumRegisteredSignals.load() != 0)
310 enum class SignalKind { IsKill, IsInfo };
311 auto registerHandler = [&](
int Signal, SignalKind
Kind) {
312 unsigned Index = NumRegisteredSignals.load();
314 "Out of space for signal handlers!");
316 struct sigaction NewHandler;
319 case SignalKind::IsKill:
320 NewHandler.sa_sigaction = SignalHandler;
321 NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK | SA_SIGINFO;
323 case SignalKind::IsInfo:
324 NewHandler.sa_handler = InfoSignalHandler;
325 NewHandler.sa_flags = SA_ONSTACK;
328 sigemptyset(&NewHandler.sa_mask);
331 sigaction(Signal, &NewHandler, &RegisteredSignalInfo[
Index].SA);
332 RegisteredSignalInfo[
Index].SigNo = Signal;
333 ++NumRegisteredSignals;
336 for (
auto S : IntSigs)
337 registerHandler(S, SignalKind::IsKill);
338 for (
auto S : KillSigs)
339 registerHandler(S, SignalKind::IsKill);
340 if (OneShotPipeSignalFunction)
341 registerHandler(SIGPIPE, SignalKind::IsKill);
342 for (
auto S : InfoSigs)
343 registerHandler(S, SignalKind::IsInfo);
346void sys::unregisterHandlers() {
348 for (
unsigned i = 0, e = NumRegisteredSignals.load(); i != e; ++i) {
349 sigaction(RegisteredSignalInfo[i].SigNo, &RegisteredSignalInfo[i].SA,
351 --NumRegisteredSignals;
356static void RemoveFilesToRemove() {
357 FileToRemoveList::removeAllFiles(FilesToRemove);
360void sys::CleanupOnSignal(uintptr_t Context) {
361 int Sig = (int)Context;
364 InfoSignalHandler(Sig);
368 RemoveFilesToRemove();
377static void SignalHandler(
int Sig, siginfo_t *
Info,
void *) {
382 sys::unregisterHandlers();
386 sigfillset(&SigMask);
387 sigprocmask(SIG_UNBLOCK, &SigMask,
nullptr);
390 RemoveFilesToRemove();
393 if (
auto OldOneShotPipeFunction =
394 OneShotPipeSignalFunction.exchange(
nullptr))
395 return OldOneShotPipeFunction();
399 if (
auto OldInterruptFunction = InterruptFunction.exchange(
nullptr))
400 return OldInterruptFunction();
402 if (Sig == SIGPIPE || IsIntSig) {
416 if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
420#if defined(__linux__)
426 syscall(SYS_rt_tgsigqueueinfo, getpid(), syscall(SYS_gettid), Sig,
Info);
427 if (retval != 0 && errno == EPERM)
432 if (
Info->si_pid != getpid() &&
Info->si_pid != 0)
437static void InfoSignalHandler(
int Sig) {
439 if (SignalHandlerFunctionType CurrentInfoFunction = InfoSignalFunction)
440 CurrentInfoFunction();
446 InterruptFunction.exchange(IF);
451 InfoSignalFunction.exchange(Handler);
456 OneShotPipeSignalFunction.exchange(Handler);
469 *FilesToRemoveCleanup;
470 FileToRemoveList::insert(FilesToRemove,
Filename.str());
477 FileToRemoveList::erase(FilesToRemove,
Filename.str());
489#if ENABLE_BACKTRACES && defined(HAVE_BACKTRACE) && \
490 (defined(__linux__) || defined(__FreeBSD__) || \
491 defined(__FreeBSD_kernel__) || defined(__NetBSD__) || \
492 defined(__OpenBSD__) || defined(__DragonFly__))
493struct DlIteratePhdrData {
497 const char **modules;
499 const char *main_exec_name;
502static int dl_iterate_phdr_cb(dl_phdr_info *
info,
size_t size,
void *arg) {
503 DlIteratePhdrData *
data = (DlIteratePhdrData *)arg;
506 for (
int i = 0; i <
info->dlpi_phnum; i++) {
507 const auto *phdr = &
info->dlpi_phdr[i];
508 if (phdr->p_type != PT_LOAD)
510 intptr_t beg =
info->dlpi_addr + phdr->p_vaddr;
511 intptr_t
end = beg + phdr->p_memsz;
512 for (
int j = 0;
j <
data->depth;
j++) {
513 if (
data->modules[j])
515 intptr_t addr = (intptr_t)
data->StackTrace[j];
516 if (beg <= addr && addr < end) {
518 data->offsets[
j] = addr -
info->dlpi_addr;
525#if LLVM_ENABLE_DEBUGLOC_TRACKING_ORIGIN
526#if !defined(HAVE_BACKTRACE)
527#error DebugLoc origin-tracking currently requires `backtrace()`.
531template <
unsigned long MaxDepth>
532int getStackTrace(std::array<void *, MaxDepth> &StackTrace) {
533 return backtrace(StackTrace.data(), MaxDepth);
535template int getStackTrace<16ul>(std::array<void *, 16ul> &);
543 const char **Modules, intptr_t *Offsets,
544 const char *MainExecutableName,
546 DlIteratePhdrData
data = {StackTrace,
Depth,
true,
547 Modules,
Offsets, MainExecutableName};
548 dl_iterate_phdr(dl_iterate_phdr_cb, &
data);
552class DSOMarkupPrinter {
554 const char *MainExecutableName;
555 size_t ModuleCount = 0;
560 :
OS(
OS), MainExecutableName(MainExecutableName) {}
563 void printDSOMarkup(dl_phdr_info *
Info) {
567 OS <<
format(
"{{{module:%d:%s:elf:", ModuleCount,
568 IsFirst ? MainExecutableName :
Info->dlpi_name);
573 for (
int I = 0;
I <
Info->dlpi_phnum;
I++) {
574 const auto *Phdr = &
Info->dlpi_phdr[
I];
575 if (Phdr->p_type != PT_LOAD)
577 uintptr_t StartAddress =
Info->dlpi_addr + Phdr->p_vaddr;
578 uintptr_t ModuleRelativeAddress = Phdr->p_vaddr;
579 std::array<char, 4> ModeStr = modeStrFromFlags(Phdr->p_flags);
580 OS <<
format(
"{{{mmap:%#016x:%#x:load:%d:%s:%#016x}}}\n", StartAddress,
581 Phdr->p_memsz, ModuleCount, &ModeStr[0],
582 ModuleRelativeAddress);
590 static int printDSOMarkup(dl_phdr_info *
Info,
size_t Size,
void *Arg) {
591 static_cast<DSOMarkupPrinter *
>(Arg)->printDSOMarkup(
Info);
598 for (
int I = 0;
I <
Info->dlpi_phnum;
I++) {
599 const auto *Phdr = &
Info->dlpi_phdr[
I];
600 if (Phdr->p_type != PT_NOTE)
604 reinterpret_cast<const uint8_t *
>(
Info->dlpi_addr + Phdr->p_vaddr),
606 while (Notes.size() > 12) {
608 Notes = Notes.drop_front(4);
610 Notes = Notes.drop_front(4);
612 Notes = Notes.drop_front(4);
615 auto CurPos =
reinterpret_cast<uintptr_t
>(Notes.data());
618 if (BytesUntilDesc >= Notes.size())
620 Notes = Notes.drop_front(BytesUntilDesc);
623 CurPos =
reinterpret_cast<uintptr_t
>(Notes.data());
626 if (BytesUntilNextNote > Notes.size())
628 Notes = Notes.drop_front(BytesUntilNextNote);
630 if (
Type == 3 &&
Name.size() >= 3 &&
640 std::array<char, 4> modeStrFromFlags(
uint32_t Flags) {
641 std::array<char, 4>
Mode;
642 char *Cur = &
Mode[0];
655 const char *MainExecutableName) {
656 OS <<
"{{{reset}}}\n";
657 DSOMarkupPrinter MP(
OS, MainExecutableName);
658 dl_iterate_phdr(DSOMarkupPrinter::printDSOMarkup, &MP);
662#elif ENABLE_BACKTRACES && defined(__APPLE__) && defined(__LP64__)
664 const char **Modules, intptr_t *Offsets,
665 const char *MainExecutableName,
667 uint32_t NumImgs = _dyld_image_count();
668 for (
uint32_t ImageIndex = 0; ImageIndex < NumImgs; ImageIndex++) {
669 const char *
Name = _dyld_get_image_name(ImageIndex);
670 intptr_t Slide = _dyld_get_image_vmaddr_slide(ImageIndex);
672 (
const struct mach_header_64 *)_dyld_get_image_header(ImageIndex);
675 auto Cmd = (
const struct load_command *)(&Header[1]);
676 for (
uint32_t CmdNum = 0; CmdNum < Header->ncmds; ++CmdNum) {
677 uint32_t BaseCmd = Cmd->cmd & ~LC_REQ_DYLD;
678 if (BaseCmd == LC_SEGMENT_64) {
679 auto CmdSeg64 = (
const struct segment_command_64 *)Cmd;
680 for (
int j = 0;
j <
Depth;
j++) {
683 intptr_t
Addr = (intptr_t)StackTrace[j];
684 if ((intptr_t)CmdSeg64->vmaddr + Slide <=
Addr &&
685 Addr < intptr_t(CmdSeg64->vmaddr + CmdSeg64->vmsize + Slide)) {
691 Cmd = (
const load_command *)(((
const char *)Cmd) + (Cmd->cmdsize));
698 const char *MainExecutableName) {
705 const char **Modules, intptr_t *Offsets,
706 const char *MainExecutableName,
712 const char *MainExecutableName) {
717#if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE)
718static int unwindBacktrace(
void **StackTrace,
int MaxEntries) {
725 auto HandleFrame = [&](_Unwind_Context *
Context) -> _Unwind_Reason_Code {
727 void *IP = (
void *)_Unwind_GetIP(Context);
729 return _URC_END_OF_STACK;
731 assert(Entries < MaxEntries &&
"recursively called after END_OF_STACK?");
733 StackTrace[Entries] = IP;
735 if (++Entries == MaxEntries)
736 return _URC_END_OF_STACK;
737 return _URC_NO_REASON;
741 [](_Unwind_Context *Context,
void *Handler) {
742 return (*
static_cast<decltype(HandleFrame) *
>(Handler))(Context);
744 static_cast<void *
>(&HandleFrame));
745 return std::max(Entries, 0);
749#if ENABLE_BACKTRACES && defined(__MVS__)
752 constexpr size_t MAX_ENTRY_NAME = UINT16_MAX;
754 constexpr size_t MAX_OTHER = 8;
755 int32_t dsa_format = -1;
756 void *caaptr = _gtca();
758 char compile_unit_name[MAX_OTHER];
759 void *compile_unit_address;
760 void *call_instruction_address =
nullptr;
761 char entry_name[MAX_ENTRY_NAME];
763 void *callers_instruction_address;
764 void *callers_dsaptr;
765 int32_t callers_dsa_format;
766 char statement_id[MAX_OTHER];
768 int32_t main_program;
774 void *dsaptr =
static_cast<char *
>(__builtin_frame_address(0)) - 2048;
776 OS <<
" DSA Adr EP +EP DSA "
780 int32_t compile_unit_name_length =
sizeof(compile_unit_name);
781 int32_t entry_name_length =
sizeof(entry_name);
782 int32_t statement_id_length =
sizeof(statement_id);
786 __CELQTBCK(&dsaptr, &dsa_format, &caaptr, &member_id, &compile_unit_name[0],
787 &compile_unit_name_length, &compile_unit_address,
788 &call_instruction_address, &entry_name[0], &entry_name_length,
789 &entry_address, &callers_instruction_address, &callers_dsaptr,
790 &callers_dsa_format, &statement_id[0], &statement_id_length,
791 &cibptr, &main_program, &fc);
793 OS <<
format(
"error: CELQTBCK returned severity %d message %d\n",
794 fc.tok_sev, fc.tok_msgno);
799 uintptr_t diff =
reinterpret_cast<uintptr_t
>(call_instruction_address) -
800 reinterpret_cast<uintptr_t
>(entry_address);
801 OS <<
format(
" %3d. 0x%016lX", count, call_instruction_address);
802 OS <<
format(
" 0x%016lX +0x%08lX 0x%016lX", entry_address, diff, dsaptr);
804 ConverterEBCDIC::convertToUTF8(
StringRef(entry_name, entry_name_length),
806 OS <<
' ' << Str <<
'\n';
809 if (callers_dsaptr) {
810 dsaptr = callers_dsaptr;
811 dsa_format = callers_dsa_format;
812 call_instruction_address = callers_instruction_address;
829 static void *StackTrace[256];
831#if defined(HAVE_BACKTRACE)
834 depth = backtrace(StackTrace,
static_cast<int>(std::size(StackTrace)));
836#if defined(HAVE__UNWIND_BACKTRACE)
840 unwindBacktrace(StackTrace,
static_cast<int>(std::size(StackTrace)));
852 OS <<
"Stack dump without symbol names (ensure you have llvm-symbolizer in "
853 "your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point "
855#if HAVE_DLOPEN && !defined(_AIX)
857 for (
int i = 0; i < depth; ++i) {
860 if (dladdr(StackTrace[i], &dlinfo) == 0) {
863 const char *
name = strrchr(dlinfo.dli_fname,
'/');
866 nwidth = strlen(dlinfo.dli_fname);
868 nwidth = strlen(
name) - 1;
875 for (
int i = 0; i < depth; ++i) {
880 if (dladdr(StackTrace[i], &dlinfo) == 0) {
881 OS <<
format(
" %-*s", width,
static_cast<const char *
>(
"(error)"));
882 dlinfo.dli_sname =
nullptr;
884 const char *
name = strrchr(dlinfo.dli_fname,
'/');
887 static_cast<const char *
>(dlinfo.dli_fname));
892 OS <<
format(
" %#0*lx", (
int)(
sizeof(
void *) * 2) + 2,
893 (
unsigned long)StackTrace[i]);
895 if (dlinfo.dli_sname !=
nullptr) {
901 OS << dlinfo.dli_sname;
904 OS <<
format(
" + %tu", (
static_cast<const char *
>(StackTrace[i]) -
905 static_cast<const char *
>(dlinfo.dli_saddr)));
909#elif defined(HAVE_BACKTRACE)
916static void PrintStackTraceSignalHandler(
void *) {
925 bool DisableCrashReporting) {
930#if defined(__APPLE__) && ENABLE_CRASH_OVERRIDES
932 if (DisableCrashReporting || getenv(
"LLVM_DISABLE_CRASH_REPORT")) {
933 mach_port_t
self = mach_task_self();
935 exception_mask_t
mask = EXC_MASK_CRASH;
937 kern_return_t ret = task_set_exception_ports(
938 self, mask, MACH_PORT_NULL,
939 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES, THREAD_STATE_NONE);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Analysis containing CSE Info
#define LLVM_ATTRIBUTE_USED
This file provides utility functions for converting between EBCDIC-1047 and UTF-8.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
This file contains definitions of exit codes for exit() function.
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
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.
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)
static void insertSignalHandler(sys::SignalHandlerCallback FnPtr, void *Cookie)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
StringRef - Represent a constant reference to a string, i.e.
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
The instances of the Type class are immutable: once they are created, they are never changed.
This class implements an extremely fast bulk output stream that can only output to a stream.
SmallVector< uint8_t, 10 > BuildID
A build ID in binary form.
LLVM_ABI const_iterator end(StringRef path LLVM_LIFETIME_BOUND)
Get end iterator over path.
LLVM_ABI void DefaultOneShotPipeSignalHandler()
On Unix systems and Windows, this function exits with an "IO error" exit code.
LLVM_ABI void PrintStackTrace(raw_ostream &OS, int Depth=0)
Print the stack trace using the given raw_ostream object.
LLVM_ABI void DisableSystemDialogsOnCrash()
Disable all system dialog boxes that appear when the process crashes.
LLVM_ABI void DontRemoveFileOnSignal(StringRef Filename)
This function removes a file from the list of files to be removed on signal delivery.
LLVM_ABI 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...
LLVM_ABI void SetInfoSignalFunction(void(*Handler)())
Registers a function to be called when an "info" signal is delivered to the process.
LLVM_ABI void SetOneShotPipeSignalFunction(void(*Handler)())
Registers a function to be called in a "one-shot" manner when a pipe signal is delivered to the proce...
std::lock_guard< SmartMutex< mt_only > > SmartScopedLock
LLVM_ABI void SetInterruptFunction(void(*IF)())
This function registers a function to be called when the user "interrupts" the program (typically by ...
void(*)(void *) SignalHandlerCallback
LLVM_ABI void RunSignalHandlers()
LLVM_ABI void AddSignalHandler(SignalHandlerCallback FnPtr, void *Cookie)
Add a function to be called when an abort/kill signal is delivered to the process.
LLVM_ABI void RunInterruptHandlers()
This function runs all the registered interrupt handlers, including the removal of files registered b...
LLVM_ABI 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...
This is an optimization pass for GlobalISel generic memory operations.
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
DEMANGLE_ABI 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.
LLVM_ATTRIBUTE_RETURNS_NONNULL void * safe_malloc(size_t Sz)
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
LLVM_ABI 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...
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
auto mask(ShuffFunc S, unsigned Length, OptArgs... args) -> MaskT
Description of the encoding of one expression Op.
A utility class that uses RAII to save and restore the value of a variable.