37 #include "llvm/Config/config.h" 51 # include BACKTRACE_HEADER // For backtrace(). 63 #include <mach/mach.h> 68 #ifdef HAVE__UNWIND_BACKTRACE 76 #undef HAVE__UNWIND_BACKTRACE 82 static RETSIGTYPE SignalHandler(
int Sig);
83 static RETSIGTYPE InfoSignalHandler(
int Sig);
85 using SignalHandlerFunctionType = void (*)();
87 static std::atomic<SignalHandlerFunctionType> InterruptFunction =
88 ATOMIC_VAR_INIT(
nullptr);
89 static std::atomic<SignalHandlerFunctionType> InfoSignalFunction =
90 ATOMIC_VAR_INIT(
nullptr);
92 static std::atomic<SignalHandlerFunctionType> OneShotPipeSignalFunction =
93 ATOMIC_VAR_INIT(
nullptr);
100 class FileToRemoveList {
101 std::atomic<char *> Filename = ATOMIC_VAR_INIT(
nullptr);
102 std::atomic<FileToRemoveList *> Next = ATOMIC_VAR_INIT(
nullptr);
104 FileToRemoveList() =
default;
106 FileToRemoveList(
const std::string &str) : Filename(strdup(str.
c_str())) {}
110 ~FileToRemoveList() {
111 if (FileToRemoveList *
N = Next.exchange(
nullptr))
113 if (
char *
F = Filename.exchange(
nullptr))
118 static void insert(std::atomic<FileToRemoveList *> &Head,
119 const std::string &Filename) {
121 FileToRemoveList *NewHead =
new FileToRemoveList(Filename);
122 std::atomic<FileToRemoveList *> *InsertionPoint = &Head;
123 FileToRemoveList *OldHead =
nullptr;
124 while (!InsertionPoint->compare_exchange_strong(OldHead, NewHead)) {
125 InsertionPoint = &OldHead->Next;
131 static void erase(std::atomic<FileToRemoveList *> &Head,
132 const std::string &Filename) {
138 for (FileToRemoveList *Current = Head.load(); Current;
139 Current = Current->Next.load()) {
140 if (
char *OldFilename = Current->Filename.load()) {
141 if (OldFilename != Filename)
144 OldFilename = Current->Filename.exchange(
nullptr);
154 static void removeAllFiles(std::atomic<FileToRemoveList *> &Head) {
159 FileToRemoveList *OldHead = Head.exchange(
nullptr);
161 for (FileToRemoveList *currentFile = OldHead; currentFile;
162 currentFile = currentFile->Next.load()) {
165 if (
char *path = currentFile->Filename.exchange(
nullptr)) {
169 if (stat(path, &buf) != 0)
175 if (!S_ISREG(buf.st_mode))
183 currentFile->Filename.exchange(path);
188 Head.exchange(OldHead);
191 static std::atomic<FileToRemoveList *> FilesToRemove = ATOMIC_VAR_INIT(
nullptr);
196 struct FilesToRemoveCleanup {
198 ~FilesToRemoveCleanup() {
199 FileToRemoveList *Head = FilesToRemove.exchange(
nullptr);
211 static const int IntSigs[] = {
212 SIGHUP, SIGINT, SIGTERM, SIGUSR2
217 static const int KillSigs[] = {
218 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
234 static const int InfoSigs[] = {
241 static const size_t NumSigs =
246 static std::atomic<unsigned> NumRegisteredSignals = ATOMIC_VAR_INIT(0);
250 } RegisteredSignalInfo[NumSigs];
252 #if defined(HAVE_SIGALTSTACK) 257 static stack_t OldAltStack;
258 static void* NewAltStackPointer;
260 static void CreateSigAltStack() {
261 const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024;
267 if (sigaltstack(
nullptr, &OldAltStack) != 0 ||
268 OldAltStack.ss_flags & SS_ONSTACK ||
269 (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize))
272 stack_t AltStack = {};
273 AltStack.ss_sp =
static_cast<char *
>(
safe_malloc(AltStackSize));
274 NewAltStackPointer = AltStack.ss_sp;
275 AltStack.ss_size = AltStackSize;
276 if (sigaltstack(&AltStack, &OldAltStack) != 0)
277 free(AltStack.ss_sp);
280 static void CreateSigAltStack() {}
283 static void RegisterHandlers() {
291 if (NumRegisteredSignals.load() != 0)
298 enum class SignalKind { IsKill, IsInfo };
299 auto registerHandler = [&](
int Signal, SignalKind
Kind) {
300 unsigned Index = NumRegisteredSignals.load();
302 "Out of space for signal handlers!");
304 struct sigaction NewHandler;
307 case SignalKind::IsKill:
308 NewHandler.sa_handler = SignalHandler;
309 NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK;
311 case SignalKind::IsInfo:
312 NewHandler.sa_handler = InfoSignalHandler;
313 NewHandler.sa_flags = SA_ONSTACK;
316 sigemptyset(&NewHandler.sa_mask);
319 sigaction(Signal, &NewHandler, &RegisteredSignalInfo[Index].SA);
320 RegisteredSignalInfo[
Index].SigNo = Signal;
321 ++NumRegisteredSignals;
324 for (
auto S : IntSigs)
325 registerHandler(S, SignalKind::IsKill);
326 for (
auto S : KillSigs)
327 registerHandler(S, SignalKind::IsKill);
328 if (OneShotPipeSignalFunction)
329 registerHandler(SIGPIPE, SignalKind::IsKill);
330 for (
auto S : InfoSigs)
331 registerHandler(S, SignalKind::IsInfo);
334 static void UnregisterHandlers() {
336 for (
unsigned i = 0,
e = NumRegisteredSignals.load(); i !=
e; ++i) {
337 sigaction(RegisteredSignalInfo[i].SigNo,
338 &RegisteredSignalInfo[i].SA,
nullptr);
339 --NumRegisteredSignals;
344 static void RemoveFilesToRemove() {
345 FileToRemoveList::removeAllFiles(FilesToRemove);
349 int Sig = (int)Context;
352 InfoSignalHandler(Sig);
356 RemoveFilesToRemove();
365 static RETSIGTYPE SignalHandler(
int Sig) {
370 UnregisterHandlers();
374 sigfillset(&SigMask);
375 sigprocmask(SIG_UNBLOCK, &SigMask,
nullptr);
378 RemoveFilesToRemove();
381 if (
auto OldOneShotPipeFunction =
382 OneShotPipeSignalFunction.exchange(
nullptr))
383 return OldOneShotPipeFunction();
387 if (
auto OldInterruptFunction = InterruptFunction.exchange(
nullptr))
388 return OldInterruptFunction();
403 if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
408 static RETSIGTYPE InfoSignalHandler(
int Sig) {
410 if (SignalHandlerFunctionType CurrentInfoFunction = InfoSignalFunction)
411 CurrentInfoFunction();
415 RemoveFilesToRemove();
419 InterruptFunction.exchange(
IF);
424 InfoSignalFunction.exchange(Handler);
429 OneShotPipeSignalFunction.exchange(Handler);
440 std::string* ErrMsg) {
443 *FilesToRemoveCleanup;
444 FileToRemoveList::insert(FilesToRemove, Filename.
str());
451 FileToRemoveList::erase(FilesToRemove, Filename.
str());
463 #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && HAVE_LINK_H && \ 464 (defined(__linux__) || defined(__FreeBSD__) || \ 465 defined(__FreeBSD_kernel__) || defined(__NetBSD__)) 466 struct DlIteratePhdrData {
470 const char **modules;
472 const char *main_exec_name;
475 static int dl_iterate_phdr_cb(dl_phdr_info *
info,
size_t size,
void *arg) {
476 DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
477 const char *
name = data->first ? data->main_exec_name : info->dlpi_name;
479 for (
int i = 0; i < info->dlpi_phnum; i++) {
480 const auto *phdr = &info->dlpi_phdr[i];
483 intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
485 for (
int j = 0; j < data->depth; j++) {
486 if (data->modules[j])
489 if (beg <= addr && addr < end) {
490 data->modules[j] =
name;
491 data->offsets[j] = addr - info->dlpi_addr;
502 const char *MainExecutableName,
504 DlIteratePhdrData data = {StackTrace,
Depth,
true,
505 Modules,
Offsets, MainExecutableName};
506 dl_iterate_phdr(dl_iterate_phdr_cb, &data);
514 const char *MainExecutableName,
518 #endif // defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && ... 520 #if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE) 521 static int unwindBacktrace(
void **StackTrace,
int MaxEntries) {
528 auto HandleFrame = [&](_Unwind_Context *
Context) -> _Unwind_Reason_Code {
530 void *IP = (
void *)_Unwind_GetIP(Context);
532 return _URC_END_OF_STACK;
534 assert(Entries < MaxEntries &&
"recursively called after END_OF_STACK?");
536 StackTrace[Entries] = IP;
538 if (++Entries == MaxEntries)
539 return _URC_END_OF_STACK;
540 return _URC_NO_REASON;
544 [](_Unwind_Context *Context,
void *Handler) {
545 return (*
static_cast<decltype(HandleFrame) *
>(Handler))(Context);
547 static_cast<void *
>(&HandleFrame));
558 #if ENABLE_BACKTRACES 559 static void *StackTrace[256];
561 #if defined(HAVE_BACKTRACE) 564 depth = backtrace(StackTrace, static_cast<int>(
array_lengthof(StackTrace)));
566 #if defined(HAVE__UNWIND_BACKTRACE) 569 depth = unwindBacktrace(StackTrace,
577 #if HAVE_DLFCN_H && HAVE_DLADDR 579 for (
int i = 0; i < depth; ++i) {
581 dladdr(StackTrace[i], &dlinfo);
582 const char* name = strrchr(dlinfo.dli_fname,
'/');
585 if (!name) nwidth = strlen(dlinfo.dli_fname);
586 else nwidth = strlen(name) - 1;
588 if (nwidth > width) width = nwidth;
591 for (
int i = 0; i < depth; ++i) {
593 dladdr(StackTrace[i], &dlinfo);
597 const char* name = strrchr(dlinfo.dli_fname,
'/');
598 if (!name) OS <<
format(
" %-*s", width, dlinfo.dli_fname);
599 else OS <<
format(
" %-*s", width, name+1);
601 OS <<
format(
" %#0*lx", (
int)(
sizeof(
void*) * 2) + 2,
602 (
unsigned long)StackTrace[i]);
604 if (dlinfo.dli_sname !=
nullptr) {
608 if (!d) OS << dlinfo.dli_sname;
612 OS <<
format(
" + %tu", (static_cast<const char*>(StackTrace[i])-
613 static_cast<const char*>(dlinfo.dli_saddr)));
617 #elif defined(HAVE_BACKTRACE) 618 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
623 static void PrintStackTraceSignalHandler(
void *) {
632 bool DisableCrashReporting) {
637 #if defined(__APPLE__) && ENABLE_CRASH_OVERRIDES 639 if (DisableCrashReporting || getenv(
"LLVM_DISABLE_CRASH_REPORT")) {
640 mach_port_t
self = mach_task_self();
642 exception_mask_t mask = EXC_MASK_CRASH;
644 kern_return_t ret = task_set_exception_ports(
self,
647 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
const_iterator end(StringRef path)
Get end iterator over path.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
char * itaniumDemangle(const char *mangled_name, char *buf, size_t *n, int *status)
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
This class represents lattice values for constants.
void(*)(void *) SignalHandlerCallback
void DefaultOneShotPipeSignalHandler()
On Unix systems, this function exits with an "IO error" exit code.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
void DisableSystemDialogsOnCrash()
Disable all system dialog boxes that appear when the process crashes.
static bool findModulesAndOffsets(void **StackTrace, int Depth, const char **Modules, intptr_t *Offsets, const char *MainExecutableName, StringSaver &StrPool)
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...
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
void PrintStackTrace(raw_ostream &OS)
Print the stack trace using the given raw_ostream object.
void RunInterruptHandlers()
This function runs all the registered interrupt handlers, including the removal of files registered b...
void DontRemoveFileOnSignal(StringRef Filename)
This function removes a file from the list of files to be removed on signal delivery.
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.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
LLVM_ATTRIBUTE_RETURNS_NONNULL void * safe_malloc(size_t Sz)
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Align max(MaybeAlign Lhs, Align Rhs)
constexpr size_t array_lengthof(T(&)[N])
Find the length of an array.
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...
std::lock_guard< SmartMutex< mt_only > > SmartScopedLock
A utility class that uses RAII to save and restore the value of a variable.
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer...
void CleanupOnSignal(uintptr_t Context)
This function does the following:
void AddSignalHandler(SignalHandlerCallback FnPtr, void *Cookie)
Add a function to be called when an abort/kill signal is delivered to the process.
void SetOneShotPipeSignalFunction(void(*Handler)())
Registers a function to be called in a "one-shot" manner when a pipe signal is delivered to the proce...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file provides utility classes that use RAII to save and restore values.
static void insertSignalHandler(sys::SignalHandlerCallback FnPtr, void *Cookie)
This class implements an extremely fast bulk output stream that can only output to a stream...
StringRef - Represent a constant reference to a string, i.e.
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
void SetInterruptFunction(void(*IF)())
This function registers a function to be called when the user "interrupts" the program (typically by ...
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.