blob: 51e15071aa418cb0e02ed17acc6992eb32fb5738 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Michael J. Spencer447762d2010-11-29 18:16:10 +00006//
Reid Spencer3d7a6142004-08-29 19:22:48 +00007//===----------------------------------------------------------------------===//
8//
9// This file defines some helpful functions for dealing with the possibility of
Chris Lattner0ab5e2c2011-04-15 05:18:47 +000010// Unix signals occurring while your program is running.
Reid Spencer3d7a6142004-08-29 19:22:48 +000011//
12//===----------------------------------------------------------------------===//
JF Bastienaa1333a2018-05-16 17:25:35 +000013//
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//===----------------------------------------------------------------------===//
Reid Spencer3d7a6142004-08-29 19:22:48 +000034
35#include "Unix.h"
Owen Andersone2f23a32007-09-07 04:06:50 +000036#include "llvm/ADT/STLExtras.h"
Nico Weber432a3882018-04-30 14:59:11 +000037#include "llvm/Config/config.h"
Rafael Espindolab940b662016-09-06 19:16:48 +000038#include "llvm/Demangle/Demangle.h"
Alexey Samsonov8a584bb2014-10-10 22:06:59 +000039#include "llvm/Support/FileSystem.h"
40#include "llvm/Support/FileUtilities.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000041#include "llvm/Support/Format.h"
Alexey Samsonov8a584bb2014-10-10 22:06:59 +000042#include "llvm/Support/MemoryBuffer.h"
43#include "llvm/Support/Mutex.h"
44#include "llvm/Support/Program.h"
45#include "llvm/Support/UniqueLock.h"
46#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000047#include <algorithm>
Chandler Carruthe6196eb2012-06-16 00:09:41 +000048#include <string>
Nick Desaulniers727891c2018-10-12 17:22:07 +000049#include <sysexits.h>
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
Benjamin Kramer1193bbf2018-06-16 13:37:52 +000089namespace {
JF Bastienaa1333a2018-05-16 17:25:35 +000090/// Signal-safe removal of files.
91/// Inserting and erasing from the list isn't signal-safe, but removal of files
92/// themselves is signal-safe. Memory is freed when the head is freed, deletion
93/// is therefore not signal-safe either.
94class FileToRemoveList {
95 std::atomic<char *> Filename = ATOMIC_VAR_INIT(nullptr);
96 std::atomic<FileToRemoveList *> Next = ATOMIC_VAR_INIT(nullptr);
97
98 FileToRemoveList() = default;
99 // Not signal-safe.
100 FileToRemoveList(const std::string &str) : Filename(strdup(str.c_str())) {}
101
102public:
103 // Not signal-safe.
104 ~FileToRemoveList() {
105 if (FileToRemoveList *N = Next.exchange(nullptr))
106 delete N;
107 if (char *F = Filename.exchange(nullptr))
108 free(F);
109 }
110
111 // Not signal-safe.
112 static void insert(std::atomic<FileToRemoveList *> &Head,
113 const std::string &Filename) {
114 // Insert the new file at the end of the list.
115 FileToRemoveList *NewHead = new FileToRemoveList(Filename);
116 std::atomic<FileToRemoveList *> *InsertionPoint = &Head;
117 FileToRemoveList *OldHead = nullptr;
118 while (!InsertionPoint->compare_exchange_strong(OldHead, NewHead)) {
119 InsertionPoint = &OldHead->Next;
120 OldHead = nullptr;
121 }
122 }
123
124 // Not signal-safe.
125 static void erase(std::atomic<FileToRemoveList *> &Head,
126 const std::string &Filename) {
127 // Use a lock to avoid concurrent erase: the comparison would access
128 // free'd memory.
129 static ManagedStatic<sys::SmartMutex<true>> Lock;
130 sys::SmartScopedLock<true> Writer(*Lock);
131
132 for (FileToRemoveList *Current = Head.load(); Current;
133 Current = Current->Next.load()) {
134 if (char *OldFilename = Current->Filename.load()) {
135 if (OldFilename != Filename)
136 continue;
137 // Leave an empty filename.
138 OldFilename = Current->Filename.exchange(nullptr);
139 // The filename might have become null between the time we
140 // compared it and we exchanged it.
141 if (OldFilename)
142 free(OldFilename);
143 }
144 }
145 }
146
147 // Signal-safe.
148 static void removeAllFiles(std::atomic<FileToRemoveList *> &Head) {
149 // If cleanup were to occur while we're removing files we'd have a bad time.
150 // Make sure we're OK by preventing cleanup from doing anything while we're
151 // removing files. If cleanup races with us and we win we'll have a leak,
152 // but we won't crash.
153 FileToRemoveList *OldHead = Head.exchange(nullptr);
154
155 for (FileToRemoveList *currentFile = OldHead; currentFile;
156 currentFile = currentFile->Next.load()) {
157 // If erasing was occuring while we're trying to remove files we'd look
158 // at free'd data. Take away the path and put it back when done.
159 if (char *path = currentFile->Filename.exchange(nullptr)) {
160 // Get the status so we can determine if it's a file or directory. If we
161 // can't stat the file, ignore it.
162 struct stat buf;
163 if (stat(path, &buf) != 0)
164 continue;
165
166 // If this is not a regular file, ignore it. We want to prevent removal
167 // of special files like /dev/null, even if the compiler is being run
168 // with the super-user permissions.
169 if (!S_ISREG(buf.st_mode))
170 continue;
171
172 // Otherwise, remove the file. We ignore any errors here as there is
173 // nothing else we can do.
174 unlink(path);
175
176 // We're done removing the file, erasing can safely proceed.
177 currentFile->Filename.exchange(path);
178 }
179 }
180
181 // We're done removing files, cleanup can safely proceed.
182 Head.exchange(OldHead);
183 }
184};
185static std::atomic<FileToRemoveList *> FilesToRemove = ATOMIC_VAR_INIT(nullptr);
186
187/// Clean up the list in a signal-friendly manner.
188/// Recall that signals can fire during llvm_shutdown. If this occurs we should
189/// either clean something up or nothing at all, but we shouldn't crash!
190struct FilesToRemoveCleanup {
191 // Not signal-safe.
192 ~FilesToRemoveCleanup() {
193 FileToRemoveList *Head = FilesToRemove.exchange(nullptr);
194 if (Head)
195 delete Head;
196 }
197};
Benjamin Kramer1193bbf2018-06-16 13:37:52 +0000198} // namespace
Reid Spencer3d7a6142004-08-29 19:22:48 +0000199
Richard Smith2ad6d482016-06-09 00:53:21 +0000200static StringRef Argv0;
201
JF Bastien93bce512018-05-15 04:06:28 +0000202// Signals that represent requested termination. There's no bug or failure, or
203// if there is, it's not our direct responsibility. For whatever reason, our
204// continued execution is no longer desirable.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000205static const int IntSigs[] = {
Dan Gohman5cdb3452013-02-20 19:15:01 +0000206 SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
Reid Spencer3d7a6142004-08-29 19:22:48 +0000207};
Reid Spencer3d7a6142004-08-29 19:22:48 +0000208
JF Bastien93bce512018-05-15 04:06:28 +0000209// Signals that represent that we have a bug, and our prompt termination has
210// been ordered.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000211static const int KillSigs[] = {
Dan Gohman5cdb3452013-02-20 19:15:01 +0000212 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
Chris Lattner62f50da2010-02-12 00:37:46 +0000213#ifdef SIGSYS
214 , SIGSYS
215#endif
216#ifdef SIGXCPU
217 , SIGXCPU
218#endif
Chris Lattner3b38fd62010-02-14 18:20:09 +0000219#ifdef SIGXFSZ
Chris Lattner62f50da2010-02-12 00:37:46 +0000220 , SIGXFSZ
221#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +0000222#ifdef SIGEMT
223 , SIGEMT
224#endif
225};
Reid Spencer3d7a6142004-08-29 19:22:48 +0000226
JF Bastienaa1333a2018-05-16 17:25:35 +0000227static std::atomic<unsigned> NumRegisteredSignals = ATOMIC_VAR_INIT(0);
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000228static struct {
Chris Lattnerfb954722009-03-23 05:55:36 +0000229 struct sigaction SA;
230 int SigNo;
Craig Topperfac90572015-12-01 06:12:59 +0000231} RegisteredSignalInfo[array_lengthof(IntSigs) + array_lengthof(KillSigs)];
Chris Lattnerfb954722009-03-23 05:55:36 +0000232
Richard Smithabab5d22016-05-20 21:26:00 +0000233#if defined(HAVE_SIGALTSTACK)
Chandler Carrutheb232dc2016-08-24 03:42:51 +0000234// Hold onto both the old and new alternate signal stack so that it's not
235// reported as a leak. We don't make any attempt to remove our alt signal
236// stack if we remove our signal handlers; that can't be done reliably if
237// someone else is also trying to do the same thing.
Richard Smith4b735c52016-05-20 21:38:15 +0000238static stack_t OldAltStack;
Chandler Carrutheb232dc2016-08-24 03:42:51 +0000239static void* NewAltStackPointer;
Richard Smithe8811342016-05-20 21:07:41 +0000240
241static void CreateSigAltStack() {
Richard Smithb3116312016-08-24 00:54:49 +0000242 const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024;
Richard Smithe8811342016-05-20 21:07:41 +0000243
244 // If we're executing on the alternate stack, or we already have an alternate
245 // signal stack that we're happy with, there's nothing for us to do. Don't
246 // reduce the size, some other part of the process might need a larger stack
247 // than we do.
248 if (sigaltstack(nullptr, &OldAltStack) != 0 ||
249 OldAltStack.ss_flags & SS_ONSTACK ||
250 (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize))
251 return;
252
Richard Smith4b735c52016-05-20 21:38:15 +0000253 stack_t AltStack = {};
Serge Pavlov76d8cce2018-02-20 05:41:26 +0000254 AltStack.ss_sp = static_cast<char *>(safe_malloc(AltStackSize));
Chandler Carrutheb232dc2016-08-24 03:42:51 +0000255 NewAltStackPointer = AltStack.ss_sp; // Save to avoid reporting a leak.
Richard Smithe8811342016-05-20 21:07:41 +0000256 AltStack.ss_size = AltStackSize;
257 if (sigaltstack(&AltStack, &OldAltStack) != 0)
258 free(AltStack.ss_sp);
259}
Richard Smithabab5d22016-05-20 21:26:00 +0000260#else
261static void CreateSigAltStack() {}
262#endif
Richard Smithe8811342016-05-20 21:07:41 +0000263
JF Bastienaa1333a2018-05-16 17:25:35 +0000264static void RegisterHandlers() { // Not signal-safe.
265 // The mutex prevents other threads from registering handlers while we're
266 // doing it. We also have to protect the handlers and their count because
267 // a signal handler could fire while we're registeting handlers.
268 static ManagedStatic<sys::SmartMutex<true>> SignalHandlerRegistrationMutex;
269 sys::SmartScopedLock<true> Guard(*SignalHandlerRegistrationMutex);
Mehdi Amini766d05b2015-11-05 02:29:53 +0000270
Chris Lattnerfb954722009-03-23 05:55:36 +0000271 // If the handlers are already registered, we're done.
JF Bastienaa1333a2018-05-16 17:25:35 +0000272 if (NumRegisteredSignals.load() != 0)
273 return;
Chris Lattnerfb954722009-03-23 05:55:36 +0000274
Richard Smithe8811342016-05-20 21:07:41 +0000275 // Create an alternate stack for signal handling. This is necessary for us to
276 // be able to reliably handle signals due to stack overflow.
277 CreateSigAltStack();
278
JF Bastien9f62b4c2018-05-15 04:23:48 +0000279 auto registerHandler = [&](int Signal) {
JF Bastienaa1333a2018-05-16 17:25:35 +0000280 unsigned Index = NumRegisteredSignals.load();
281 assert(Index < array_lengthof(RegisteredSignalInfo) &&
JF Bastien9f62b4c2018-05-15 04:23:48 +0000282 "Out of space for signal handlers!");
283
284 struct sigaction NewHandler;
285
286 NewHandler.sa_handler = SignalHandler;
287 NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK;
288 sigemptyset(&NewHandler.sa_mask);
289
290 // Install the new handler, save the old one in RegisteredSignalInfo.
JF Bastienaa1333a2018-05-16 17:25:35 +0000291 sigaction(Signal, &NewHandler, &RegisteredSignalInfo[Index].SA);
292 RegisteredSignalInfo[Index].SigNo = Signal;
JF Bastien9f62b4c2018-05-15 04:23:48 +0000293 ++NumRegisteredSignals;
294 };
295
296 for (auto S : IntSigs)
297 registerHandler(S);
298 for (auto S : KillSigs)
299 registerHandler(S);
Chris Lattnerf299a682009-03-23 05:42:29 +0000300}
301
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000302static void UnregisterHandlers() {
Chris Lattnerfb954722009-03-23 05:55:36 +0000303 // Restore all of the signal handlers to how they were before we showed up.
JF Bastienaa1333a2018-05-16 17:25:35 +0000304 for (unsigned i = 0, e = NumRegisteredSignals.load(); i != e; ++i) {
Chris Lattnerf2b60652009-03-23 06:46:20 +0000305 sigaction(RegisteredSignalInfo[i].SigNo,
Craig Toppere73658d2014-04-28 04:05:08 +0000306 &RegisteredSignalInfo[i].SA, nullptr);
JF Bastienaa1333a2018-05-16 17:25:35 +0000307 --NumRegisteredSignals;
308 }
Chris Lattnerf299a682009-03-23 05:42:29 +0000309}
310
JF Bastienaa1333a2018-05-16 17:25:35 +0000311/// Process the FilesToRemove list.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000312static void RemoveFilesToRemove() {
JF Bastienaa1333a2018-05-16 17:25:35 +0000313 FileToRemoveList::removeAllFiles(FilesToRemove);
Dan Gohman288999b2010-05-27 23:11:55 +0000314}
Chris Lattner6acb4d62009-03-07 08:15:47 +0000315
JF Bastien93bce512018-05-15 04:06:28 +0000316// The signal handler that runs.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000317static RETSIGTYPE SignalHandler(int Sig) {
Chris Lattnerbbbbbf32009-03-05 18:22:14 +0000318 // Restore the signal behavior to default, so that the program actually
319 // crashes when we return and the signal reissues. This also ensures that if
320 // we crash in our signal handler that the program will terminate immediately
321 // instead of recursing in the signal handler.
Chris Lattnerf299a682009-03-23 05:42:29 +0000322 UnregisterHandlers();
Chris Lattner6acb4d62009-03-07 08:15:47 +0000323
324 // Unmask all potentially blocked kill signals.
325 sigset_t SigMask;
326 sigfillset(&SigMask);
Craig Toppere73658d2014-04-28 04:05:08 +0000327 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
Chris Lattnerbbbbbf32009-03-05 18:22:14 +0000328
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000329 {
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000330 RemoveFilesToRemove();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000331
Chris Bienemanb1cd51e2014-08-29 01:05:16 +0000332 if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
333 != std::end(IntSigs)) {
JF Bastienaa1333a2018-05-16 17:25:35 +0000334 if (auto OldInterruptFunction = InterruptFunction.exchange(nullptr))
335 return OldInterruptFunction();
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000336
Nick Desaulniers727891c2018-10-12 17:22:07 +0000337 // Send a special return code that drivers can check for, from sysexits.h.
338 if (Sig == SIGPIPE)
339 exit(EX_IOERR);
340
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000341 raise(Sig); // Execute the default handler.
Chris Lattner4fdd0422009-03-04 21:21:36 +0000342 return;
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000343 }
Chris Lattner4fdd0422009-03-04 21:21:36 +0000344 }
345
346 // Otherwise if it is a fault (like SEGV) run any handler.
Yaron Keren28738102015-07-22 21:11:17 +0000347 llvm::sys::RunSignalHandlers();
Ulrich Weigand90c9abd2013-05-03 12:22:11 +0000348
349#ifdef __s390__
350 // On S/390, certain signals are delivered with PSW Address pointing to
351 // *after* the faulting instruction. Simply returning from the signal
352 // handler would continue execution after that point, instead of
353 // re-raising the signal. Raise the signal manually in those cases.
354 if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
355 raise(Sig);
356#endif
Chris Lattner4fdd0422009-03-04 21:21:36 +0000357}
358
Daniel Dunbar68272562010-05-08 02:10:34 +0000359void llvm::sys::RunInterruptHandlers() {
Dan Gohman288999b2010-05-27 23:11:55 +0000360 RemoveFilesToRemove();
Daniel Dunbar68272562010-05-08 02:10:34 +0000361}
Chris Lattner4fdd0422009-03-04 21:21:36 +0000362
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000363void llvm::sys::SetInterruptFunction(void (*IF)()) {
JF Bastienaa1333a2018-05-16 17:25:35 +0000364 InterruptFunction.exchange(IF);
Chris Lattnerf299a682009-03-23 05:42:29 +0000365 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000366}
367
JF Bastien93bce512018-05-15 04:06:28 +0000368// The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000369bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000370 std::string* ErrMsg) {
JF Bastienaa1333a2018-05-16 17:25:35 +0000371 // Ensure that cleanup will occur as soon as one file is added.
372 static ManagedStatic<FilesToRemoveCleanup> FilesToRemoveCleanup;
373 *FilesToRemoveCleanup;
374 FileToRemoveList::insert(FilesToRemove, Filename.str());
Chris Lattnerf299a682009-03-23 05:42:29 +0000375 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000376 return false;
377}
378
JF Bastien93bce512018-05-15 04:06:28 +0000379// The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000380void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
JF Bastienaa1333a2018-05-16 17:25:35 +0000381 FileToRemoveList::erase(FilesToRemove, Filename.str());
Dan Gohmane201c072010-09-01 14:17:34 +0000382}
383
JF Bastien93bce512018-05-15 04:06:28 +0000384/// Add a function to be called when a signal is delivered to the process. The
385/// handler can have a cookie passed to it to identify what instance of the
386/// handler it is.
JF Bastienaa1333a2018-05-16 17:25:35 +0000387void llvm::sys::AddSignalHandler(sys::SignalHandlerCallback FnPtr,
388 void *Cookie) { // Signal-safe.
389 insertSignalHandler(FnPtr, Cookie);
Chris Lattnerf299a682009-03-23 05:42:29 +0000390 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000391}
392
Joerg Sonnenberger0e3cc3c2016-09-30 20:04:24 +0000393#if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && HAVE_LINK_H && \
Reid Kleckner40aa9c62015-11-09 23:10:29 +0000394 (defined(__linux__) || defined(__FreeBSD__) || \
395 defined(__FreeBSD_kernel__) || defined(__NetBSD__))
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000396struct DlIteratePhdrData {
397 void **StackTrace;
398 int depth;
399 bool first;
400 const char **modules;
401 intptr_t *offsets;
402 const char *main_exec_name;
403};
404
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000405static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000406 DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
407 const char *name = data->first ? data->main_exec_name : info->dlpi_name;
408 data->first = false;
409 for (int i = 0; i < info->dlpi_phnum; i++) {
410 const auto *phdr = &info->dlpi_phdr[i];
411 if (phdr->p_type != PT_LOAD)
412 continue;
413 intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
414 intptr_t end = beg + phdr->p_memsz;
415 for (int j = 0; j < data->depth; j++) {
416 if (data->modules[j])
417 continue;
418 intptr_t addr = (intptr_t)data->StackTrace[j];
419 if (beg <= addr && addr < end) {
420 data->modules[j] = name;
421 data->offsets[j] = addr - info->dlpi_addr;
422 }
423 }
424 }
425 return 0;
426}
427
Reid Kleckner40aa9c62015-11-09 23:10:29 +0000428/// If this is an ELF platform, we can find all loaded modules and their virtual
429/// addresses with dl_iterate_phdr.
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000430static bool findModulesAndOffsets(void **StackTrace, int Depth,
431 const char **Modules, intptr_t *Offsets,
Reid Klecknerba5757d2015-11-05 01:07:54 +0000432 const char *MainExecutableName,
433 StringSaver &StrPool) {
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000434 DlIteratePhdrData data = {StackTrace, Depth, true,
435 Modules, Offsets, MainExecutableName};
436 dl_iterate_phdr(dl_iterate_phdr_cb, &data);
437 return true;
438}
439#else
Reid Kleckner40aa9c62015-11-09 23:10:29 +0000440/// This platform does not have dl_iterate_phdr, so we do not yet know how to
441/// find all loaded DSOs.
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000442static bool findModulesAndOffsets(void **StackTrace, int Depth,
443 const char **Modules, intptr_t *Offsets,
Mehdi Amini7ae928e2015-11-05 02:29:57 +0000444 const char *MainExecutableName,
445 StringSaver &StrPool) {
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000446 return false;
447}
Joerg Sonnenberger0e3cc3c2016-09-30 20:04:24 +0000448#endif // defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && ...
Reid Spencer3d7a6142004-08-29 19:22:48 +0000449
Joerg Sonnenberger0e3cc3c2016-09-30 20:04:24 +0000450#if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE)
Richard Smith14d96512016-05-20 21:18:12 +0000451static int unwindBacktrace(void **StackTrace, int MaxEntries) {
452 if (MaxEntries < 0)
453 return 0;
454
455 // Skip the first frame ('unwindBacktrace' itself).
456 int Entries = -1;
457
458 auto HandleFrame = [&](_Unwind_Context *Context) -> _Unwind_Reason_Code {
459 // Apparently we need to detect reaching the end of the stack ourselves.
460 void *IP = (void *)_Unwind_GetIP(Context);
461 if (!IP)
462 return _URC_END_OF_STACK;
463
464 assert(Entries < MaxEntries && "recursively called after END_OF_STACK?");
465 if (Entries >= 0)
466 StackTrace[Entries] = IP;
467
468 if (++Entries == MaxEntries)
469 return _URC_END_OF_STACK;
470 return _URC_NO_REASON;
471 };
472
473 _Unwind_Backtrace(
474 [](_Unwind_Context *Context, void *Handler) {
475 return (*static_cast<decltype(HandleFrame) *>(Handler))(Context);
476 },
477 static_cast<void *>(&HandleFrame));
478 return std::max(Entries, 0);
479}
480#endif
481
JF Bastien93bce512018-05-15 04:06:28 +0000482// In the case of a program crash or fault, print out a stack trace so that the
483// user has an indication of why and where we died.
Reid Spencer3d7a6142004-08-29 19:22:48 +0000484//
485// On glibc systems we have the 'backtrace' function, which works nicely, but
Michael J. Spencer447762d2010-11-29 18:16:10 +0000486// doesn't demangle symbols.
Zachary Turnercd132c92015-03-05 19:10:52 +0000487void llvm::sys::PrintStackTrace(raw_ostream &OS) {
Joerg Sonnenberger0e3cc3c2016-09-30 20:04:24 +0000488#if ENABLE_BACKTRACES
Richard Smith14d96512016-05-20 21:18:12 +0000489 static void *StackTrace[256];
490 int depth = 0;
491#if defined(HAVE_BACKTRACE)
Reid Spencer3d7a6142004-08-29 19:22:48 +0000492 // Use backtrace() to output a backtrace on Linux systems with glibc.
Richard Smith14d96512016-05-20 21:18:12 +0000493 if (!depth)
494 depth = backtrace(StackTrace, static_cast<int>(array_lengthof(StackTrace)));
495#endif
Joerg Sonnenberger5c505392016-09-29 21:07:57 +0000496#if defined(HAVE__UNWIND_BACKTRACE)
Richard Smith14d96512016-05-20 21:18:12 +0000497 // Try _Unwind_Backtrace() if backtrace() failed.
498 if (!depth)
499 depth = unwindBacktrace(StackTrace,
Evan Cheng86cb3182008-05-05 18:30:58 +0000500 static_cast<int>(array_lengthof(StackTrace)));
Richard Smith14d96512016-05-20 21:18:12 +0000501#endif
502 if (!depth)
503 return;
504
Richard Smith2ad6d482016-06-09 00:53:21 +0000505 if (printSymbolizedStackTrace(Argv0, StackTrace, depth, OS))
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000506 return;
Omair Javaidf5d560bc842017-02-02 01:17:49 +0000507#if HAVE_DLFCN_H && HAVE_DLADDR
Dan Gohman7f079aa2008-12-05 20:12:48 +0000508 int width = 0;
509 for (int i = 0; i < depth; ++i) {
510 Dl_info dlinfo;
511 dladdr(StackTrace[i], &dlinfo);
Dan Gohman1f517dd2009-02-10 17:56:28 +0000512 const char* name = strrchr(dlinfo.dli_fname, '/');
Dan Gohman7f079aa2008-12-05 20:12:48 +0000513
514 int nwidth;
Craig Toppere73658d2014-04-28 04:05:08 +0000515 if (!name) nwidth = strlen(dlinfo.dli_fname);
516 else nwidth = strlen(name) - 1;
Dan Gohman7f079aa2008-12-05 20:12:48 +0000517
518 if (nwidth > width) width = nwidth;
519 }
520
521 for (int i = 0; i < depth; ++i) {
522 Dl_info dlinfo;
523 dladdr(StackTrace[i], &dlinfo);
524
Zachary Turnercd132c92015-03-05 19:10:52 +0000525 OS << format("%-2d", i);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000526
Dan Gohman1f517dd2009-02-10 17:56:28 +0000527 const char* name = strrchr(dlinfo.dli_fname, '/');
Zachary Turnercd132c92015-03-05 19:10:52 +0000528 if (!name) OS << format(" %-*s", width, dlinfo.dli_fname);
529 else OS << format(" %-*s", width, name+1);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000530
Zachary Turnercd132c92015-03-05 19:10:52 +0000531 OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2,
532 (unsigned long)StackTrace[i]);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000533
Craig Toppere73658d2014-04-28 04:05:08 +0000534 if (dlinfo.dli_sname != nullptr) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000535 OS << ' ';
Benjamin Kramer83e2a442013-04-28 07:47:04 +0000536 int res;
Rafael Espindolab940b662016-09-06 19:16:48 +0000537 char* d = itaniumDemangle(dlinfo.dli_sname, nullptr, nullptr, &res);
Zachary Turnercd132c92015-03-05 19:10:52 +0000538 if (!d) OS << dlinfo.dli_sname;
539 else OS << d;
Dan Gohman7f079aa2008-12-05 20:12:48 +0000540 free(d);
541
Edwin Vane44338e02013-01-28 19:34:42 +0000542 // FIXME: When we move to C++11, use %t length modifier. It's not in
543 // C++03 and causes gcc to issue warnings. Losing the upper 32 bits of
544 // the stack offset for a stack dump isn't likely to cause any problems.
Zachary Turnercd132c92015-03-05 19:10:52 +0000545 OS << format(" + %u",(unsigned)((char*)StackTrace[i]-
546 (char*)dlinfo.dli_saddr));
Dan Gohman7f079aa2008-12-05 20:12:48 +0000547 }
Zachary Turnercd132c92015-03-05 19:10:52 +0000548 OS << '\n';
Dan Gohman7f079aa2008-12-05 20:12:48 +0000549 }
Richard Smith14d96512016-05-20 21:18:12 +0000550#elif defined(HAVE_BACKTRACE)
Lauro Ramos Venancioeab51d32008-02-15 18:05:54 +0000551 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
Reid Spencer3d7a6142004-08-29 19:22:48 +0000552#endif
Dan Gohman7f079aa2008-12-05 20:12:48 +0000553#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +0000554}
555
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000556static void PrintStackTraceSignalHandler(void *) {
Kristof Beyls7adf8c52017-03-31 14:58:52 +0000557 sys::PrintStackTrace(llvm::errs());
Argyrios Kyrtzidiseb9ae762013-01-09 19:42:40 +0000558}
559
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000560void llvm::sys::DisableSystemDialogsOnCrash() {}
561
JF Bastien93bce512018-05-15 04:06:28 +0000562/// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
563/// process, print a stack trace and then exit.
Richard Smith2ad6d482016-06-09 00:53:21 +0000564void llvm::sys::PrintStackTraceOnErrorSignal(StringRef Argv0,
565 bool DisableCrashReporting) {
566 ::Argv0 = Argv0;
567
Craig Toppere73658d2014-04-28 04:05:08 +0000568 AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000569
Joerg Sonnenberger2cd87a02016-09-30 20:06:19 +0000570#if defined(__APPLE__) && ENABLE_CRASH_OVERRIDES
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000571 // Environment variable to disable any kind of crash dialog.
Pete Cooper6bea2f42015-04-07 20:43:23 +0000572 if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) {
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000573 mach_port_t self = mach_task_self();
574
575 exception_mask_t mask = EXC_MASK_CRASH;
576
NAKAMURA Takumiffa15712012-09-06 03:02:56 +0000577 kern_return_t ret = task_set_exception_ports(self,
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000578 mask,
Jean-Daniel Dupasa573b222012-03-24 22:17:50 +0000579 MACH_PORT_NULL,
NAKAMURA Takumiffa15712012-09-06 03:02:56 +0000580 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
Jean-Daniel Dupasa573b222012-03-24 22:17:50 +0000581 THREAD_STATE_NONE);
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000582 (void)ret;
583 }
584#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +0000585}