blob: f4e99266459b020599ce6ecdbe3324013c13fa62 [file] [log] [blame]
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001//===- Signals.cpp - Generic Unix Signals Implementation -----*- C++ -*-===//
Michael J. Spencer447762d2010-11-29 18:16:10 +00002//
Reid Spencer3d7a6142004-08-29 19:22:48 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Michael J. Spencer447762d2010-11-29 18:16:10 +00007//
Reid Spencer3d7a6142004-08-29 19:22:48 +00008//===----------------------------------------------------------------------===//
9//
10// This file defines some helpful functions for dealing with the possibility of
Chris Lattner0ab5e2c2011-04-15 05:18:47 +000011// Unix signals occurring while your program is running.
Reid Spencer3d7a6142004-08-29 19:22:48 +000012//
13//===----------------------------------------------------------------------===//
JF Bastienaa1333a2018-05-16 17:25:35 +000014//
15// This file is extremely careful to only do signal-safe things while in a
16// signal handler. In particular, memory allocation and acquiring a mutex
17// while in a signal handler should never occur. ManagedStatic isn't usable from
18// a signal handler for 2 reasons:
19//
20// 1. Creating a new one allocates.
21// 2. The signal handler could fire while llvm_shutdown is being processed, in
22// which case the ManagedStatic is in an unknown state because it could
23// already have been destroyed, or be in the process of being destroyed.
24//
25// Modifying the behavior of the signal handlers (such as registering new ones)
26// can acquire a mutex, but all this guarantees is that the signal handler
27// behavior is only modified by one thread at a time. A signal handler can still
28// fire while this occurs!
29//
30// Adding work to a signal handler requires lock-freedom (and assume atomics are
31// always lock-free) because the signal handler could fire while new work is
32// being added.
33//
34//===----------------------------------------------------------------------===//
Reid Spencer3d7a6142004-08-29 19:22:48 +000035
36#include "Unix.h"
Owen Andersone2f23a32007-09-07 04:06:50 +000037#include "llvm/ADT/STLExtras.h"
Nico Weber432a3882018-04-30 14:59:11 +000038#include "llvm/Config/config.h"
Rafael Espindolab940b662016-09-06 19:16:48 +000039#include "llvm/Demangle/Demangle.h"
Alexey Samsonov8a584bb2014-10-10 22:06:59 +000040#include "llvm/Support/FileSystem.h"
41#include "llvm/Support/FileUtilities.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000042#include "llvm/Support/Format.h"
Alexey Samsonov8a584bb2014-10-10 22:06:59 +000043#include "llvm/Support/MemoryBuffer.h"
44#include "llvm/Support/Mutex.h"
45#include "llvm/Support/Program.h"
46#include "llvm/Support/UniqueLock.h"
47#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000048#include <algorithm>
Chandler Carruthe6196eb2012-06-16 00:09:41 +000049#include <string>
Ed Mastee5443792017-04-12 13:51:00 +000050#ifdef HAVE_BACKTRACE
51# include BACKTRACE_HEADER // For backtrace().
Reid Spencer3d7a6142004-08-29 19:22:48 +000052#endif
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000053#if HAVE_SIGNAL_H
54#include <signal.h>
55#endif
Reid Spencerceeb9182007-04-07 18:52:17 +000056#if HAVE_SYS_STAT_H
57#include <sys/stat.h>
58#endif
Joerg Sonnenberger66241832013-04-27 22:12:32 +000059#if HAVE_DLFCN_H
Dan Gohman7f079aa2008-12-05 20:12:48 +000060#include <dlfcn.h>
Dan Gohman7f079aa2008-12-05 20:12:48 +000061#endif
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +000062#if HAVE_MACH_MACH_H
63#include <mach/mach.h>
64#endif
Alexey Samsonov8a584bb2014-10-10 22:06:59 +000065#if HAVE_LINK_H
66#include <link.h>
67#endif
Joerg Sonnenberger5c505392016-09-29 21:07:57 +000068#ifdef HAVE__UNWIND_BACKTRACE
Richard Smith14d96512016-05-20 21:18:12 +000069// FIXME: We should be able to use <unwind.h> for any target that has an
70// _Unwind_Backtrace function, but on FreeBSD the configure test passes
71// despite the function not existing, and on Android, <unwind.h> conflicts
72// with <link.h>.
Bob Wilson37df90a2017-01-06 02:26:33 +000073#ifdef __GLIBC__
Richard Smith14d96512016-05-20 21:18:12 +000074#include <unwind.h>
75#else
Joerg Sonnenberger5c505392016-09-29 21:07:57 +000076#undef HAVE__UNWIND_BACKTRACE
Richard Smith14d96512016-05-20 21:18:12 +000077#endif
78#endif
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +000079
Chris Lattner80df7c42006-08-01 17:59:14 +000080using namespace llvm;
Reid Spencer3d7a6142004-08-29 19:22:48 +000081
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000082static RETSIGTYPE SignalHandler(int Sig); // defined below.
Chris Lattnerf299a682009-03-23 05:42:29 +000083
JF Bastien93bce512018-05-15 04:06:28 +000084/// The function to call if ctrl-c is pressed.
JF Bastienaa1333a2018-05-16 17:25:35 +000085using InterruptFunctionType = void (*)();
86static std::atomic<InterruptFunctionType> InterruptFunction =
87 ATOMIC_VAR_INIT(nullptr);
Chris Lattner6a5d6ec2005-08-02 02:14:22 +000088
JF Bastienaa1333a2018-05-16 17:25:35 +000089/// Signal-safe removal of files.
90/// Inserting and erasing from the list isn't signal-safe, but removal of files
91/// themselves is signal-safe. Memory is freed when the head is freed, deletion
92/// is therefore not signal-safe either.
93class FileToRemoveList {
94 std::atomic<char *> Filename = ATOMIC_VAR_INIT(nullptr);
95 std::atomic<FileToRemoveList *> Next = ATOMIC_VAR_INIT(nullptr);
96
97 FileToRemoveList() = default;
98 // Not signal-safe.
99 FileToRemoveList(const std::string &str) : Filename(strdup(str.c_str())) {}
100
101public:
102 // Not signal-safe.
103 ~FileToRemoveList() {
104 if (FileToRemoveList *N = Next.exchange(nullptr))
105 delete N;
106 if (char *F = Filename.exchange(nullptr))
107 free(F);
108 }
109
110 // Not signal-safe.
111 static void insert(std::atomic<FileToRemoveList *> &Head,
112 const std::string &Filename) {
113 // Insert the new file at the end of the list.
114 FileToRemoveList *NewHead = new FileToRemoveList(Filename);
115 std::atomic<FileToRemoveList *> *InsertionPoint = &Head;
116 FileToRemoveList *OldHead = nullptr;
117 while (!InsertionPoint->compare_exchange_strong(OldHead, NewHead)) {
118 InsertionPoint = &OldHead->Next;
119 OldHead = nullptr;
120 }
121 }
122
123 // Not signal-safe.
124 static void erase(std::atomic<FileToRemoveList *> &Head,
125 const std::string &Filename) {
126 // Use a lock to avoid concurrent erase: the comparison would access
127 // free'd memory.
128 static ManagedStatic<sys::SmartMutex<true>> Lock;
129 sys::SmartScopedLock<true> Writer(*Lock);
130
131 for (FileToRemoveList *Current = Head.load(); Current;
132 Current = Current->Next.load()) {
133 if (char *OldFilename = Current->Filename.load()) {
134 if (OldFilename != Filename)
135 continue;
136 // Leave an empty filename.
137 OldFilename = Current->Filename.exchange(nullptr);
138 // The filename might have become null between the time we
139 // compared it and we exchanged it.
140 if (OldFilename)
141 free(OldFilename);
142 }
143 }
144 }
145
146 // Signal-safe.
147 static void removeAllFiles(std::atomic<FileToRemoveList *> &Head) {
148 // If cleanup were to occur while we're removing files we'd have a bad time.
149 // Make sure we're OK by preventing cleanup from doing anything while we're
150 // removing files. If cleanup races with us and we win we'll have a leak,
151 // but we won't crash.
152 FileToRemoveList *OldHead = Head.exchange(nullptr);
153
154 for (FileToRemoveList *currentFile = OldHead; currentFile;
155 currentFile = currentFile->Next.load()) {
156 // If erasing was occuring while we're trying to remove files we'd look
157 // at free'd data. Take away the path and put it back when done.
158 if (char *path = currentFile->Filename.exchange(nullptr)) {
159 // Get the status so we can determine if it's a file or directory. If we
160 // can't stat the file, ignore it.
161 struct stat buf;
162 if (stat(path, &buf) != 0)
163 continue;
164
165 // If this is not a regular file, ignore it. We want to prevent removal
166 // of special files like /dev/null, even if the compiler is being run
167 // with the super-user permissions.
168 if (!S_ISREG(buf.st_mode))
169 continue;
170
171 // Otherwise, remove the file. We ignore any errors here as there is
172 // nothing else we can do.
173 unlink(path);
174
175 // We're done removing the file, erasing can safely proceed.
176 currentFile->Filename.exchange(path);
177 }
178 }
179
180 // We're done removing files, cleanup can safely proceed.
181 Head.exchange(OldHead);
182 }
183};
184static std::atomic<FileToRemoveList *> FilesToRemove = ATOMIC_VAR_INIT(nullptr);
185
186/// Clean up the list in a signal-friendly manner.
187/// Recall that signals can fire during llvm_shutdown. If this occurs we should
188/// either clean something up or nothing at all, but we shouldn't crash!
189struct FilesToRemoveCleanup {
190 // Not signal-safe.
191 ~FilesToRemoveCleanup() {
192 FileToRemoveList *Head = FilesToRemove.exchange(nullptr);
193 if (Head)
194 delete Head;
195 }
196};
Reid Spencer3d7a6142004-08-29 19:22:48 +0000197
Richard Smith2ad6d482016-06-09 00:53:21 +0000198static StringRef Argv0;
199
JF Bastien93bce512018-05-15 04:06:28 +0000200// Signals that represent requested termination. There's no bug or failure, or
201// if there is, it's not our direct responsibility. For whatever reason, our
202// continued execution is no longer desirable.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000203static const int IntSigs[] = {
Dan Gohman5cdb3452013-02-20 19:15:01 +0000204 SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
Reid Spencer3d7a6142004-08-29 19:22:48 +0000205};
Reid Spencer3d7a6142004-08-29 19:22:48 +0000206
JF Bastien93bce512018-05-15 04:06:28 +0000207// Signals that represent that we have a bug, and our prompt termination has
208// been ordered.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000209static const int KillSigs[] = {
Dan Gohman5cdb3452013-02-20 19:15:01 +0000210 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
Chris Lattner62f50da2010-02-12 00:37:46 +0000211#ifdef SIGSYS
212 , SIGSYS
213#endif
214#ifdef SIGXCPU
215 , SIGXCPU
216#endif
Chris Lattner3b38fd62010-02-14 18:20:09 +0000217#ifdef SIGXFSZ
Chris Lattner62f50da2010-02-12 00:37:46 +0000218 , SIGXFSZ
219#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +0000220#ifdef SIGEMT
221 , SIGEMT
222#endif
223};
Reid Spencer3d7a6142004-08-29 19:22:48 +0000224
JF Bastienaa1333a2018-05-16 17:25:35 +0000225static std::atomic<unsigned> NumRegisteredSignals = ATOMIC_VAR_INIT(0);
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000226static struct {
Chris Lattnerfb954722009-03-23 05:55:36 +0000227 struct sigaction SA;
228 int SigNo;
Craig Topperfac90572015-12-01 06:12:59 +0000229} RegisteredSignalInfo[array_lengthof(IntSigs) + array_lengthof(KillSigs)];
Chris Lattnerfb954722009-03-23 05:55:36 +0000230
Richard Smithabab5d22016-05-20 21:26:00 +0000231#if defined(HAVE_SIGALTSTACK)
Chandler Carrutheb232dc2016-08-24 03:42:51 +0000232// Hold onto both the old and new alternate signal stack so that it's not
233// reported as a leak. We don't make any attempt to remove our alt signal
234// stack if we remove our signal handlers; that can't be done reliably if
235// someone else is also trying to do the same thing.
Richard Smith4b735c52016-05-20 21:38:15 +0000236static stack_t OldAltStack;
Chandler Carrutheb232dc2016-08-24 03:42:51 +0000237static void* NewAltStackPointer;
Richard Smithe8811342016-05-20 21:07:41 +0000238
239static void CreateSigAltStack() {
Richard Smithb3116312016-08-24 00:54:49 +0000240 const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024;
Richard Smithe8811342016-05-20 21:07:41 +0000241
242 // If we're executing on the alternate stack, or we already have an alternate
243 // signal stack that we're happy with, there's nothing for us to do. Don't
244 // reduce the size, some other part of the process might need a larger stack
245 // than we do.
246 if (sigaltstack(nullptr, &OldAltStack) != 0 ||
247 OldAltStack.ss_flags & SS_ONSTACK ||
248 (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize))
249 return;
250
Richard Smith4b735c52016-05-20 21:38:15 +0000251 stack_t AltStack = {};
Serge Pavlov76d8cce2018-02-20 05:41:26 +0000252 AltStack.ss_sp = static_cast<char *>(safe_malloc(AltStackSize));
Chandler Carrutheb232dc2016-08-24 03:42:51 +0000253 NewAltStackPointer = AltStack.ss_sp; // Save to avoid reporting a leak.
Richard Smithe8811342016-05-20 21:07:41 +0000254 AltStack.ss_size = AltStackSize;
255 if (sigaltstack(&AltStack, &OldAltStack) != 0)
256 free(AltStack.ss_sp);
257}
Richard Smithabab5d22016-05-20 21:26:00 +0000258#else
259static void CreateSigAltStack() {}
260#endif
Richard Smithe8811342016-05-20 21:07:41 +0000261
JF Bastienaa1333a2018-05-16 17:25:35 +0000262static void RegisterHandlers() { // Not signal-safe.
263 // The mutex prevents other threads from registering handlers while we're
264 // doing it. We also have to protect the handlers and their count because
265 // a signal handler could fire while we're registeting handlers.
266 static ManagedStatic<sys::SmartMutex<true>> SignalHandlerRegistrationMutex;
267 sys::SmartScopedLock<true> Guard(*SignalHandlerRegistrationMutex);
Mehdi Amini766d05b2015-11-05 02:29:53 +0000268
Chris Lattnerfb954722009-03-23 05:55:36 +0000269 // If the handlers are already registered, we're done.
JF Bastienaa1333a2018-05-16 17:25:35 +0000270 if (NumRegisteredSignals.load() != 0)
271 return;
Chris Lattnerfb954722009-03-23 05:55:36 +0000272
Richard Smithe8811342016-05-20 21:07:41 +0000273 // Create an alternate stack for signal handling. This is necessary for us to
274 // be able to reliably handle signals due to stack overflow.
275 CreateSigAltStack();
276
JF Bastien9f62b4c2018-05-15 04:23:48 +0000277 auto registerHandler = [&](int Signal) {
JF Bastienaa1333a2018-05-16 17:25:35 +0000278 unsigned Index = NumRegisteredSignals.load();
279 assert(Index < array_lengthof(RegisteredSignalInfo) &&
JF Bastien9f62b4c2018-05-15 04:23:48 +0000280 "Out of space for signal handlers!");
281
282 struct sigaction NewHandler;
283
284 NewHandler.sa_handler = SignalHandler;
285 NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK;
286 sigemptyset(&NewHandler.sa_mask);
287
288 // Install the new handler, save the old one in RegisteredSignalInfo.
JF Bastienaa1333a2018-05-16 17:25:35 +0000289 sigaction(Signal, &NewHandler, &RegisteredSignalInfo[Index].SA);
290 RegisteredSignalInfo[Index].SigNo = Signal;
JF Bastien9f62b4c2018-05-15 04:23:48 +0000291 ++NumRegisteredSignals;
292 };
293
294 for (auto S : IntSigs)
295 registerHandler(S);
296 for (auto S : KillSigs)
297 registerHandler(S);
Chris Lattnerf299a682009-03-23 05:42:29 +0000298}
299
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000300static void UnregisterHandlers() {
Chris Lattnerfb954722009-03-23 05:55:36 +0000301 // Restore all of the signal handlers to how they were before we showed up.
JF Bastienaa1333a2018-05-16 17:25:35 +0000302 for (unsigned i = 0, e = NumRegisteredSignals.load(); i != e; ++i) {
Chris Lattnerf2b60652009-03-23 06:46:20 +0000303 sigaction(RegisteredSignalInfo[i].SigNo,
Craig Toppere73658d2014-04-28 04:05:08 +0000304 &RegisteredSignalInfo[i].SA, nullptr);
JF Bastienaa1333a2018-05-16 17:25:35 +0000305 --NumRegisteredSignals;
306 }
Chris Lattnerf299a682009-03-23 05:42:29 +0000307}
308
JF Bastienaa1333a2018-05-16 17:25:35 +0000309/// Process the FilesToRemove list.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000310static void RemoveFilesToRemove() {
JF Bastienaa1333a2018-05-16 17:25:35 +0000311 FileToRemoveList::removeAllFiles(FilesToRemove);
Dan Gohman288999b2010-05-27 23:11:55 +0000312}
Chris Lattner6acb4d62009-03-07 08:15:47 +0000313
JF Bastien93bce512018-05-15 04:06:28 +0000314// The signal handler that runs.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000315static RETSIGTYPE SignalHandler(int Sig) {
Chris Lattnerbbbbbf32009-03-05 18:22:14 +0000316 // Restore the signal behavior to default, so that the program actually
317 // crashes when we return and the signal reissues. This also ensures that if
318 // we crash in our signal handler that the program will terminate immediately
319 // instead of recursing in the signal handler.
Chris Lattnerf299a682009-03-23 05:42:29 +0000320 UnregisterHandlers();
Chris Lattner6acb4d62009-03-07 08:15:47 +0000321
322 // Unmask all potentially blocked kill signals.
323 sigset_t SigMask;
324 sigfillset(&SigMask);
Craig Toppere73658d2014-04-28 04:05:08 +0000325 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
Chris Lattnerbbbbbf32009-03-05 18:22:14 +0000326
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000327 {
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000328 RemoveFilesToRemove();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000329
Chris Bienemanb1cd51e2014-08-29 01:05:16 +0000330 if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
331 != std::end(IntSigs)) {
JF Bastienaa1333a2018-05-16 17:25:35 +0000332 if (auto OldInterruptFunction = InterruptFunction.exchange(nullptr))
333 return OldInterruptFunction();
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000334
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000335 raise(Sig); // Execute the default handler.
Chris Lattner4fdd0422009-03-04 21:21:36 +0000336 return;
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000337 }
Chris Lattner4fdd0422009-03-04 21:21:36 +0000338 }
339
340 // Otherwise if it is a fault (like SEGV) run any handler.
Yaron Keren28738102015-07-22 21:11:17 +0000341 llvm::sys::RunSignalHandlers();
Ulrich Weigand90c9abd2013-05-03 12:22:11 +0000342
343#ifdef __s390__
344 // On S/390, certain signals are delivered with PSW Address pointing to
345 // *after* the faulting instruction. Simply returning from the signal
346 // handler would continue execution after that point, instead of
347 // re-raising the signal. Raise the signal manually in those cases.
348 if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
349 raise(Sig);
350#endif
Chris Lattner4fdd0422009-03-04 21:21:36 +0000351}
352
Daniel Dunbar68272562010-05-08 02:10:34 +0000353void llvm::sys::RunInterruptHandlers() {
Dan Gohman288999b2010-05-27 23:11:55 +0000354 RemoveFilesToRemove();
Daniel Dunbar68272562010-05-08 02:10:34 +0000355}
Chris Lattner4fdd0422009-03-04 21:21:36 +0000356
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000357void llvm::sys::SetInterruptFunction(void (*IF)()) {
JF Bastienaa1333a2018-05-16 17:25:35 +0000358 InterruptFunction.exchange(IF);
Chris Lattnerf299a682009-03-23 05:42:29 +0000359 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000360}
361
JF Bastien93bce512018-05-15 04:06:28 +0000362// The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000363bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000364 std::string* ErrMsg) {
JF Bastienaa1333a2018-05-16 17:25:35 +0000365 // Ensure that cleanup will occur as soon as one file is added.
366 static ManagedStatic<FilesToRemoveCleanup> FilesToRemoveCleanup;
367 *FilesToRemoveCleanup;
368 FileToRemoveList::insert(FilesToRemove, Filename.str());
Chris Lattnerf299a682009-03-23 05:42:29 +0000369 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000370 return false;
371}
372
JF Bastien93bce512018-05-15 04:06:28 +0000373// The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000374void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
JF Bastienaa1333a2018-05-16 17:25:35 +0000375 FileToRemoveList::erase(FilesToRemove, Filename.str());
Dan Gohmane201c072010-09-01 14:17:34 +0000376}
377
JF Bastien93bce512018-05-15 04:06:28 +0000378/// Add a function to be called when a signal is delivered to the process. The
379/// handler can have a cookie passed to it to identify what instance of the
380/// handler it is.
JF Bastienaa1333a2018-05-16 17:25:35 +0000381void llvm::sys::AddSignalHandler(sys::SignalHandlerCallback FnPtr,
382 void *Cookie) { // Signal-safe.
383 insertSignalHandler(FnPtr, Cookie);
Chris Lattnerf299a682009-03-23 05:42:29 +0000384 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000385}
386
Joerg Sonnenberger0e3cc3c2016-09-30 20:04:24 +0000387#if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && HAVE_LINK_H && \
Reid Kleckner40aa9c62015-11-09 23:10:29 +0000388 (defined(__linux__) || defined(__FreeBSD__) || \
389 defined(__FreeBSD_kernel__) || defined(__NetBSD__))
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000390struct DlIteratePhdrData {
391 void **StackTrace;
392 int depth;
393 bool first;
394 const char **modules;
395 intptr_t *offsets;
396 const char *main_exec_name;
397};
398
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000399static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000400 DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
401 const char *name = data->first ? data->main_exec_name : info->dlpi_name;
402 data->first = false;
403 for (int i = 0; i < info->dlpi_phnum; i++) {
404 const auto *phdr = &info->dlpi_phdr[i];
405 if (phdr->p_type != PT_LOAD)
406 continue;
407 intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
408 intptr_t end = beg + phdr->p_memsz;
409 for (int j = 0; j < data->depth; j++) {
410 if (data->modules[j])
411 continue;
412 intptr_t addr = (intptr_t)data->StackTrace[j];
413 if (beg <= addr && addr < end) {
414 data->modules[j] = name;
415 data->offsets[j] = addr - info->dlpi_addr;
416 }
417 }
418 }
419 return 0;
420}
421
Reid Kleckner40aa9c62015-11-09 23:10:29 +0000422/// If this is an ELF platform, we can find all loaded modules and their virtual
423/// addresses with dl_iterate_phdr.
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000424static bool findModulesAndOffsets(void **StackTrace, int Depth,
425 const char **Modules, intptr_t *Offsets,
Reid Klecknerba5757d2015-11-05 01:07:54 +0000426 const char *MainExecutableName,
427 StringSaver &StrPool) {
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000428 DlIteratePhdrData data = {StackTrace, Depth, true,
429 Modules, Offsets, MainExecutableName};
430 dl_iterate_phdr(dl_iterate_phdr_cb, &data);
431 return true;
432}
433#else
Reid Kleckner40aa9c62015-11-09 23:10:29 +0000434/// This platform does not have dl_iterate_phdr, so we do not yet know how to
435/// find all loaded DSOs.
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000436static bool findModulesAndOffsets(void **StackTrace, int Depth,
437 const char **Modules, intptr_t *Offsets,
Mehdi Amini7ae928e2015-11-05 02:29:57 +0000438 const char *MainExecutableName,
439 StringSaver &StrPool) {
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000440 return false;
441}
Joerg Sonnenberger0e3cc3c2016-09-30 20:04:24 +0000442#endif // defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && ...
Reid Spencer3d7a6142004-08-29 19:22:48 +0000443
Joerg Sonnenberger0e3cc3c2016-09-30 20:04:24 +0000444#if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE)
Richard Smith14d96512016-05-20 21:18:12 +0000445static int unwindBacktrace(void **StackTrace, int MaxEntries) {
446 if (MaxEntries < 0)
447 return 0;
448
449 // Skip the first frame ('unwindBacktrace' itself).
450 int Entries = -1;
451
452 auto HandleFrame = [&](_Unwind_Context *Context) -> _Unwind_Reason_Code {
453 // Apparently we need to detect reaching the end of the stack ourselves.
454 void *IP = (void *)_Unwind_GetIP(Context);
455 if (!IP)
456 return _URC_END_OF_STACK;
457
458 assert(Entries < MaxEntries && "recursively called after END_OF_STACK?");
459 if (Entries >= 0)
460 StackTrace[Entries] = IP;
461
462 if (++Entries == MaxEntries)
463 return _URC_END_OF_STACK;
464 return _URC_NO_REASON;
465 };
466
467 _Unwind_Backtrace(
468 [](_Unwind_Context *Context, void *Handler) {
469 return (*static_cast<decltype(HandleFrame) *>(Handler))(Context);
470 },
471 static_cast<void *>(&HandleFrame));
472 return std::max(Entries, 0);
473}
474#endif
475
JF Bastien93bce512018-05-15 04:06:28 +0000476// In the case of a program crash or fault, print out a stack trace so that the
477// user has an indication of why and where we died.
Reid Spencer3d7a6142004-08-29 19:22:48 +0000478//
479// On glibc systems we have the 'backtrace' function, which works nicely, but
Michael J. Spencer447762d2010-11-29 18:16:10 +0000480// doesn't demangle symbols.
Zachary Turnercd132c92015-03-05 19:10:52 +0000481void llvm::sys::PrintStackTrace(raw_ostream &OS) {
Joerg Sonnenberger0e3cc3c2016-09-30 20:04:24 +0000482#if ENABLE_BACKTRACES
Richard Smith14d96512016-05-20 21:18:12 +0000483 static void *StackTrace[256];
484 int depth = 0;
485#if defined(HAVE_BACKTRACE)
Reid Spencer3d7a6142004-08-29 19:22:48 +0000486 // Use backtrace() to output a backtrace on Linux systems with glibc.
Richard Smith14d96512016-05-20 21:18:12 +0000487 if (!depth)
488 depth = backtrace(StackTrace, static_cast<int>(array_lengthof(StackTrace)));
489#endif
Joerg Sonnenberger5c505392016-09-29 21:07:57 +0000490#if defined(HAVE__UNWIND_BACKTRACE)
Richard Smith14d96512016-05-20 21:18:12 +0000491 // Try _Unwind_Backtrace() if backtrace() failed.
492 if (!depth)
493 depth = unwindBacktrace(StackTrace,
Evan Cheng86cb3182008-05-05 18:30:58 +0000494 static_cast<int>(array_lengthof(StackTrace)));
Richard Smith14d96512016-05-20 21:18:12 +0000495#endif
496 if (!depth)
497 return;
498
Richard Smith2ad6d482016-06-09 00:53:21 +0000499 if (printSymbolizedStackTrace(Argv0, StackTrace, depth, OS))
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000500 return;
Omair Javaidf5d560bc842017-02-02 01:17:49 +0000501#if HAVE_DLFCN_H && HAVE_DLADDR
Dan Gohman7f079aa2008-12-05 20:12:48 +0000502 int width = 0;
503 for (int i = 0; i < depth; ++i) {
504 Dl_info dlinfo;
505 dladdr(StackTrace[i], &dlinfo);
Dan Gohman1f517dd2009-02-10 17:56:28 +0000506 const char* name = strrchr(dlinfo.dli_fname, '/');
Dan Gohman7f079aa2008-12-05 20:12:48 +0000507
508 int nwidth;
Craig Toppere73658d2014-04-28 04:05:08 +0000509 if (!name) nwidth = strlen(dlinfo.dli_fname);
510 else nwidth = strlen(name) - 1;
Dan Gohman7f079aa2008-12-05 20:12:48 +0000511
512 if (nwidth > width) width = nwidth;
513 }
514
515 for (int i = 0; i < depth; ++i) {
516 Dl_info dlinfo;
517 dladdr(StackTrace[i], &dlinfo);
518
Zachary Turnercd132c92015-03-05 19:10:52 +0000519 OS << format("%-2d", i);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000520
Dan Gohman1f517dd2009-02-10 17:56:28 +0000521 const char* name = strrchr(dlinfo.dli_fname, '/');
Zachary Turnercd132c92015-03-05 19:10:52 +0000522 if (!name) OS << format(" %-*s", width, dlinfo.dli_fname);
523 else OS << format(" %-*s", width, name+1);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000524
Zachary Turnercd132c92015-03-05 19:10:52 +0000525 OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2,
526 (unsigned long)StackTrace[i]);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000527
Craig Toppere73658d2014-04-28 04:05:08 +0000528 if (dlinfo.dli_sname != nullptr) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000529 OS << ' ';
Benjamin Kramer83e2a442013-04-28 07:47:04 +0000530 int res;
Rafael Espindolab940b662016-09-06 19:16:48 +0000531 char* d = itaniumDemangle(dlinfo.dli_sname, nullptr, nullptr, &res);
Zachary Turnercd132c92015-03-05 19:10:52 +0000532 if (!d) OS << dlinfo.dli_sname;
533 else OS << d;
Dan Gohman7f079aa2008-12-05 20:12:48 +0000534 free(d);
535
Edwin Vane44338e02013-01-28 19:34:42 +0000536 // FIXME: When we move to C++11, use %t length modifier. It's not in
537 // C++03 and causes gcc to issue warnings. Losing the upper 32 bits of
538 // the stack offset for a stack dump isn't likely to cause any problems.
Zachary Turnercd132c92015-03-05 19:10:52 +0000539 OS << format(" + %u",(unsigned)((char*)StackTrace[i]-
540 (char*)dlinfo.dli_saddr));
Dan Gohman7f079aa2008-12-05 20:12:48 +0000541 }
Zachary Turnercd132c92015-03-05 19:10:52 +0000542 OS << '\n';
Dan Gohman7f079aa2008-12-05 20:12:48 +0000543 }
Richard Smith14d96512016-05-20 21:18:12 +0000544#elif defined(HAVE_BACKTRACE)
Lauro Ramos Venancioeab51d32008-02-15 18:05:54 +0000545 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
Reid Spencer3d7a6142004-08-29 19:22:48 +0000546#endif
Dan Gohman7f079aa2008-12-05 20:12:48 +0000547#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +0000548}
549
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000550static void PrintStackTraceSignalHandler(void *) {
Kristof Beyls7adf8c52017-03-31 14:58:52 +0000551 sys::PrintStackTrace(llvm::errs());
Argyrios Kyrtzidiseb9ae762013-01-09 19:42:40 +0000552}
553
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000554void llvm::sys::DisableSystemDialogsOnCrash() {}
555
JF Bastien93bce512018-05-15 04:06:28 +0000556/// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
557/// process, print a stack trace and then exit.
Richard Smith2ad6d482016-06-09 00:53:21 +0000558void llvm::sys::PrintStackTraceOnErrorSignal(StringRef Argv0,
559 bool DisableCrashReporting) {
560 ::Argv0 = Argv0;
561
Craig Toppere73658d2014-04-28 04:05:08 +0000562 AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000563
Joerg Sonnenberger2cd87a02016-09-30 20:06:19 +0000564#if defined(__APPLE__) && ENABLE_CRASH_OVERRIDES
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000565 // Environment variable to disable any kind of crash dialog.
Pete Cooper6bea2f42015-04-07 20:43:23 +0000566 if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) {
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000567 mach_port_t self = mach_task_self();
568
569 exception_mask_t mask = EXC_MASK_CRASH;
570
NAKAMURA Takumiffa15712012-09-06 03:02:56 +0000571 kern_return_t ret = task_set_exception_ports(self,
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000572 mask,
Jean-Daniel Dupasa573b222012-03-24 22:17:50 +0000573 MACH_PORT_NULL,
NAKAMURA Takumiffa15712012-09-06 03:02:56 +0000574 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
Jean-Daniel Dupasa573b222012-03-24 22:17:50 +0000575 THREAD_STATE_NONE);
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000576 (void)ret;
577 }
578#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +0000579}