blob: 97b8394f02347dd6d85fc4559b5d984603935ad9 [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//===----------------------------------------------------------------------===//
14
15#include "Unix.h"
Owen Andersone2f23a32007-09-07 04:06:50 +000016#include "llvm/ADT/STLExtras.h"
Zachary Turnercd132c92015-03-05 19:10:52 +000017#include "llvm/Support/Format.h"
Alexey Samsonov8a584bb2014-10-10 22:06:59 +000018#include "llvm/Support/FileSystem.h"
19#include "llvm/Support/FileUtilities.h"
Alexey Samsonov8a584bb2014-10-10 22:06:59 +000020#include "llvm/Support/MemoryBuffer.h"
21#include "llvm/Support/Mutex.h"
22#include "llvm/Support/Program.h"
23#include "llvm/Support/UniqueLock.h"
24#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include <algorithm>
Chandler Carruthe6196eb2012-06-16 00:09:41 +000026#include <string>
Reid Spencerd554bbc2004-12-27 06:16:52 +000027#if HAVE_EXECINFO_H
Reid Spencer3d7a6142004-08-29 19:22:48 +000028# include <execinfo.h> // For backtrace().
29#endif
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000030#if HAVE_SIGNAL_H
31#include <signal.h>
32#endif
Reid Spencerceeb9182007-04-07 18:52:17 +000033#if HAVE_SYS_STAT_H
34#include <sys/stat.h>
35#endif
Joerg Sonnenberger66241832013-04-27 22:12:32 +000036#if HAVE_CXXABI_H
Joerg Sonnenberger44744092013-04-27 22:32:54 +000037#include <cxxabi.h>
Joerg Sonnenberger66241832013-04-27 22:12:32 +000038#endif
39#if HAVE_DLFCN_H
Dan Gohman7f079aa2008-12-05 20:12:48 +000040#include <dlfcn.h>
Dan Gohman7f079aa2008-12-05 20:12:48 +000041#endif
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +000042#if HAVE_MACH_MACH_H
43#include <mach/mach.h>
44#endif
Alexey Samsonov8a584bb2014-10-10 22:06:59 +000045#if HAVE_LINK_H
46#include <link.h>
47#endif
Richard Smith14d96512016-05-20 21:18:12 +000048#if HAVE_UNWIND_BACKTRACE
49// FIXME: We should be able to use <unwind.h> for any target that has an
50// _Unwind_Backtrace function, but on FreeBSD the configure test passes
51// despite the function not existing, and on Android, <unwind.h> conflicts
52// with <link.h>.
53#ifdef __GLIBC__
54#include <unwind.h>
55#else
56#undef HAVE_UNWIND_BACKTRACE
57#endif
58#endif
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +000059
Chris Lattner80df7c42006-08-01 17:59:14 +000060using namespace llvm;
Reid Spencer3d7a6142004-08-29 19:22:48 +000061
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000062static RETSIGTYPE SignalHandler(int Sig); // defined below.
Chris Lattnerf299a682009-03-23 05:42:29 +000063
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000064static ManagedStatic<SmartMutex<true> > SignalsMutex;
Owen Anderson820739d2009-08-17 17:07:22 +000065
Chris Lattner6a5d6ec2005-08-02 02:14:22 +000066/// InterruptFunction - The function to call if ctrl-c is pressed.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000067static void (*InterruptFunction)() = nullptr;
Chris Lattner6a5d6ec2005-08-02 02:14:22 +000068
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000069static ManagedStatic<std::vector<std::string>> FilesToRemove;
Reid Spencer3d7a6142004-08-29 19:22:48 +000070
Richard Smith2ad6d482016-06-09 00:53:21 +000071static StringRef Argv0;
72
Dan Gohmanf857cd72013-02-20 19:28:46 +000073// IntSigs - Signals that represent requested termination. There's no bug
74// or failure, or if there is, it's not our direct responsibility. For whatever
75// reason, our continued execution is no longer desirable.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000076static const int IntSigs[] = {
Dan Gohman5cdb3452013-02-20 19:15:01 +000077 SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
Reid Spencer3d7a6142004-08-29 19:22:48 +000078};
Reid Spencer3d7a6142004-08-29 19:22:48 +000079
Dan Gohmanf857cd72013-02-20 19:28:46 +000080// KillSigs - Signals that represent that we have a bug, and our prompt
81// termination has been ordered.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000082static const int KillSigs[] = {
Dan Gohman5cdb3452013-02-20 19:15:01 +000083 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
Chris Lattner62f50da2010-02-12 00:37:46 +000084#ifdef SIGSYS
85 , SIGSYS
86#endif
87#ifdef SIGXCPU
88 , SIGXCPU
89#endif
Chris Lattner3b38fd62010-02-14 18:20:09 +000090#ifdef SIGXFSZ
Chris Lattner62f50da2010-02-12 00:37:46 +000091 , SIGXFSZ
92#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +000093#ifdef SIGEMT
94 , SIGEMT
95#endif
96};
Reid Spencer3d7a6142004-08-29 19:22:48 +000097
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000098static unsigned NumRegisteredSignals = 0;
99static struct {
Chris Lattnerfb954722009-03-23 05:55:36 +0000100 struct sigaction SA;
101 int SigNo;
Craig Topperfac90572015-12-01 06:12:59 +0000102} RegisteredSignalInfo[array_lengthof(IntSigs) + array_lengthof(KillSigs)];
Chris Lattnerfb954722009-03-23 05:55:36 +0000103
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000104
105static void RegisterHandler(int Signal) {
Craig Topperfac90572015-12-01 06:12:59 +0000106 assert(NumRegisteredSignals < array_lengthof(RegisteredSignalInfo) &&
Chris Lattnerfb954722009-03-23 05:55:36 +0000107 "Out of space for signal handlers!");
108
109 struct sigaction NewHandler;
Michael J. Spencer447762d2010-11-29 18:16:10 +0000110
Chris Lattnerfb954722009-03-23 05:55:36 +0000111 NewHandler.sa_handler = SignalHandler;
Richard Smithb8b0be92016-05-23 06:47:37 +0000112 NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK;
Michael J. Spencer447762d2010-11-29 18:16:10 +0000113 sigemptyset(&NewHandler.sa_mask);
114
Chris Lattnerfb954722009-03-23 05:55:36 +0000115 // Install the new handler, save the old one in RegisteredSignalInfo.
116 sigaction(Signal, &NewHandler,
117 &RegisteredSignalInfo[NumRegisteredSignals].SA);
118 RegisteredSignalInfo[NumRegisteredSignals].SigNo = Signal;
119 ++NumRegisteredSignals;
Chris Lattner6acb4d62009-03-07 08:15:47 +0000120}
121
Richard Smithabab5d22016-05-20 21:26:00 +0000122#if defined(HAVE_SIGALTSTACK)
Richard Smithe8811342016-05-20 21:07:41 +0000123// Hold onto the old alternate signal stack so that it's not reported as a leak.
124// We don't make any attempt to remove our alt signal stack if we remove our
125// signal handlers; that can't be done reliably if someone else is also trying
126// to do the same thing.
Richard Smith4b735c52016-05-20 21:38:15 +0000127static stack_t OldAltStack;
Richard Smithe8811342016-05-20 21:07:41 +0000128
129static void CreateSigAltStack() {
130 const size_t AltStackSize = MINSIGSTKSZ + 8192;
131
132 // If we're executing on the alternate stack, or we already have an alternate
133 // signal stack that we're happy with, there's nothing for us to do. Don't
134 // reduce the size, some other part of the process might need a larger stack
135 // than we do.
136 if (sigaltstack(nullptr, &OldAltStack) != 0 ||
137 OldAltStack.ss_flags & SS_ONSTACK ||
138 (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize))
139 return;
140
Richard Smith4b735c52016-05-20 21:38:15 +0000141 stack_t AltStack = {};
Chris Bienemanf2363472016-05-21 00:36:47 +0000142 AltStack.ss_sp = reinterpret_cast<char *>(malloc(AltStackSize));
Richard Smithe8811342016-05-20 21:07:41 +0000143 AltStack.ss_size = AltStackSize;
144 if (sigaltstack(&AltStack, &OldAltStack) != 0)
145 free(AltStack.ss_sp);
146}
Richard Smithabab5d22016-05-20 21:26:00 +0000147#else
148static void CreateSigAltStack() {}
149#endif
Richard Smithe8811342016-05-20 21:07:41 +0000150
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000151static void RegisterHandlers() {
Chris Bieneman017ebf02015-04-27 20:45:35 +0000152 // We need to dereference the signals mutex during handler registration so
153 // that we force its construction. This is to prevent the first use being
154 // during handling an actual signal because you can't safely call new in a
155 // signal handler.
156 *SignalsMutex;
Mehdi Amini766d05b2015-11-05 02:29:53 +0000157
Chris Lattnerfb954722009-03-23 05:55:36 +0000158 // If the handlers are already registered, we're done.
159 if (NumRegisteredSignals != 0) return;
160
Richard Smithe8811342016-05-20 21:07:41 +0000161 // Create an alternate stack for signal handling. This is necessary for us to
162 // be able to reliably handle signals due to stack overflow.
163 CreateSigAltStack();
164
Chris Bienemanb1cd51e2014-08-29 01:05:16 +0000165 for (auto S : IntSigs) RegisterHandler(S);
166 for (auto S : KillSigs) RegisterHandler(S);
Chris Lattnerf299a682009-03-23 05:42:29 +0000167}
168
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000169static void UnregisterHandlers() {
Chris Lattnerfb954722009-03-23 05:55:36 +0000170 // Restore all of the signal handlers to how they were before we showed up.
171 for (unsigned i = 0, e = NumRegisteredSignals; i != e; ++i)
Chris Lattnerf2b60652009-03-23 06:46:20 +0000172 sigaction(RegisteredSignalInfo[i].SigNo,
Craig Toppere73658d2014-04-28 04:05:08 +0000173 &RegisteredSignalInfo[i].SA, nullptr);
Chris Lattnerfb954722009-03-23 05:55:36 +0000174 NumRegisteredSignals = 0;
Chris Lattnerf299a682009-03-23 05:42:29 +0000175}
176
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000177
Dan Gohman288999b2010-05-27 23:11:55 +0000178/// RemoveFilesToRemove - Process the FilesToRemove list. This function
179/// should be called with the SignalsMutex lock held.
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000180/// NB: This must be an async signal safe function. It cannot allocate or free
181/// memory, even in debug builds.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000182static void RemoveFilesToRemove() {
Steven Wu94746692015-05-07 16:20:51 +0000183 // Avoid constructing ManagedStatic in the signal handler.
184 // If FilesToRemove is not constructed, there are no files to remove.
185 if (!FilesToRemove.isConstructed())
186 return;
187
Daniel Dunbar511479d2012-10-17 16:30:54 +0000188 // We avoid iterators in case of debug iterators that allocate or release
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000189 // memory.
Chris Bieneman186e7d12014-09-02 23:48:13 +0000190 std::vector<std::string>& FilesToRemoveRef = *FilesToRemove;
191 for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i) {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000192 const char *path = FilesToRemoveRef[i].c_str();
Daniel Dunbar511479d2012-10-17 16:30:54 +0000193
194 // Get the status so we can determine if it's a file or directory. If we
195 // can't stat the file, ignore it.
196 struct stat buf;
197 if (stat(path, &buf) != 0)
198 continue;
199
200 // If this is not a regular file, ignore it. We want to prevent removal of
201 // special files like /dev/null, even if the compiler is being run with the
202 // super-user permissions.
203 if (!S_ISREG(buf.st_mode))
204 continue;
Mehdi Amini766d05b2015-11-05 02:29:53 +0000205
Daniel Dunbar511479d2012-10-17 16:30:54 +0000206 // Otherwise, remove the file. We ignore any errors here as there is nothing
207 // else we can do.
208 unlink(path);
Dan Gohman288999b2010-05-27 23:11:55 +0000209 }
210}
Chris Lattner6acb4d62009-03-07 08:15:47 +0000211
212// SignalHandler - The signal handler that runs.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000213static RETSIGTYPE SignalHandler(int Sig) {
Chris Lattnerbbbbbf32009-03-05 18:22:14 +0000214 // Restore the signal behavior to default, so that the program actually
215 // crashes when we return and the signal reissues. This also ensures that if
216 // we crash in our signal handler that the program will terminate immediately
217 // instead of recursing in the signal handler.
Chris Lattnerf299a682009-03-23 05:42:29 +0000218 UnregisterHandlers();
Chris Lattner6acb4d62009-03-07 08:15:47 +0000219
220 // Unmask all potentially blocked kill signals.
221 sigset_t SigMask;
222 sigfillset(&SigMask);
Craig Toppere73658d2014-04-28 04:05:08 +0000223 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
Chris Lattnerbbbbbf32009-03-05 18:22:14 +0000224
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000225 {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000226 unique_lock<SmartMutex<true>> Guard(*SignalsMutex);
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000227 RemoveFilesToRemove();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000228
Chris Bienemanb1cd51e2014-08-29 01:05:16 +0000229 if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
230 != std::end(IntSigs)) {
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000231 if (InterruptFunction) {
232 void (*IF)() = InterruptFunction;
233 Guard.unlock();
234 InterruptFunction = nullptr;
235 IF(); // run the interrupt function.
236 return;
237 }
238
239 Guard.unlock();
240 raise(Sig); // Execute the default handler.
Chris Lattner4fdd0422009-03-04 21:21:36 +0000241 return;
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000242 }
Chris Lattner4fdd0422009-03-04 21:21:36 +0000243 }
244
245 // Otherwise if it is a fault (like SEGV) run any handler.
Yaron Keren28738102015-07-22 21:11:17 +0000246 llvm::sys::RunSignalHandlers();
Ulrich Weigand90c9abd2013-05-03 12:22:11 +0000247
248#ifdef __s390__
249 // On S/390, certain signals are delivered with PSW Address pointing to
250 // *after* the faulting instruction. Simply returning from the signal
251 // handler would continue execution after that point, instead of
252 // re-raising the signal. Raise the signal manually in those cases.
253 if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
254 raise(Sig);
255#endif
Chris Lattner4fdd0422009-03-04 21:21:36 +0000256}
257
Daniel Dunbar68272562010-05-08 02:10:34 +0000258void llvm::sys::RunInterruptHandlers() {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000259 sys::SmartScopedLock<true> Guard(*SignalsMutex);
Dan Gohman288999b2010-05-27 23:11:55 +0000260 RemoveFilesToRemove();
Daniel Dunbar68272562010-05-08 02:10:34 +0000261}
Chris Lattner4fdd0422009-03-04 21:21:36 +0000262
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000263void llvm::sys::SetInterruptFunction(void (*IF)()) {
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000264 {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000265 sys::SmartScopedLock<true> Guard(*SignalsMutex);
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000266 InterruptFunction = IF;
267 }
Chris Lattnerf299a682009-03-23 05:42:29 +0000268 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000269}
270
271// RemoveFileOnSignal - The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000272bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000273 std::string* ErrMsg) {
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000274 {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000275 sys::SmartScopedLock<true> Guard(*SignalsMutex);
Yaron Keren4135e4c2015-07-23 05:49:29 +0000276 FilesToRemove->push_back(Filename);
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000277 }
Owen Anderson820739d2009-08-17 17:07:22 +0000278
Chris Lattnerf299a682009-03-23 05:42:29 +0000279 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000280 return false;
281}
282
Dan Gohmane201c072010-09-01 14:17:34 +0000283// DontRemoveFileOnSignal - The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000284void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000285 sys::SmartScopedLock<true> Guard(*SignalsMutex);
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000286 std::vector<std::string>::reverse_iterator RI =
David Majnemer42531262016-08-12 03:55:06 +0000287 find(reverse(*FilesToRemove), Filename);
Chris Bieneman186e7d12014-09-02 23:48:13 +0000288 std::vector<std::string>::iterator I = FilesToRemove->end();
289 if (RI != FilesToRemove->rend())
290 I = FilesToRemove->erase(RI.base()-1);
Dan Gohmane201c072010-09-01 14:17:34 +0000291}
292
Chris Lattner4fdd0422009-03-04 21:21:36 +0000293/// AddSignalHandler - Add a function to be called when a signal is delivered
294/// to the process. The handler can have a cookie passed to it to identify
295/// what instance of the handler it is.
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000296void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000297 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
Chris Lattnerf299a682009-03-23 05:42:29 +0000298 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000299}
300
Reid Kleckner40aa9c62015-11-09 23:10:29 +0000301#if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES) && HAVE_LINK_H && \
302 (defined(__linux__) || defined(__FreeBSD__) || \
303 defined(__FreeBSD_kernel__) || defined(__NetBSD__))
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000304struct DlIteratePhdrData {
305 void **StackTrace;
306 int depth;
307 bool first;
308 const char **modules;
309 intptr_t *offsets;
310 const char *main_exec_name;
311};
312
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000313static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000314 DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
315 const char *name = data->first ? data->main_exec_name : info->dlpi_name;
316 data->first = false;
317 for (int i = 0; i < info->dlpi_phnum; i++) {
318 const auto *phdr = &info->dlpi_phdr[i];
319 if (phdr->p_type != PT_LOAD)
320 continue;
321 intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
322 intptr_t end = beg + phdr->p_memsz;
323 for (int j = 0; j < data->depth; j++) {
324 if (data->modules[j])
325 continue;
326 intptr_t addr = (intptr_t)data->StackTrace[j];
327 if (beg <= addr && addr < end) {
328 data->modules[j] = name;
329 data->offsets[j] = addr - info->dlpi_addr;
330 }
331 }
332 }
333 return 0;
334}
335
Reid Kleckner40aa9c62015-11-09 23:10:29 +0000336/// If this is an ELF platform, we can find all loaded modules and their virtual
337/// addresses with dl_iterate_phdr.
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000338static bool findModulesAndOffsets(void **StackTrace, int Depth,
339 const char **Modules, intptr_t *Offsets,
Reid Klecknerba5757d2015-11-05 01:07:54 +0000340 const char *MainExecutableName,
341 StringSaver &StrPool) {
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000342 DlIteratePhdrData data = {StackTrace, Depth, true,
343 Modules, Offsets, MainExecutableName};
344 dl_iterate_phdr(dl_iterate_phdr_cb, &data);
345 return true;
346}
347#else
Reid Kleckner40aa9c62015-11-09 23:10:29 +0000348/// This platform does not have dl_iterate_phdr, so we do not yet know how to
349/// find all loaded DSOs.
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000350static bool findModulesAndOffsets(void **StackTrace, int Depth,
351 const char **Modules, intptr_t *Offsets,
Mehdi Amini7ae928e2015-11-05 02:29:57 +0000352 const char *MainExecutableName,
353 StringSaver &StrPool) {
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000354 return false;
355}
Reid Kleckner40aa9c62015-11-09 23:10:29 +0000356#endif // defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES) && ...
Reid Spencer3d7a6142004-08-29 19:22:48 +0000357
Richard Smith14d96512016-05-20 21:18:12 +0000358#if defined(ENABLE_BACKTRACES) && defined(HAVE_UNWIND_BACKTRACE)
359static int unwindBacktrace(void **StackTrace, int MaxEntries) {
360 if (MaxEntries < 0)
361 return 0;
362
363 // Skip the first frame ('unwindBacktrace' itself).
364 int Entries = -1;
365
366 auto HandleFrame = [&](_Unwind_Context *Context) -> _Unwind_Reason_Code {
367 // Apparently we need to detect reaching the end of the stack ourselves.
368 void *IP = (void *)_Unwind_GetIP(Context);
369 if (!IP)
370 return _URC_END_OF_STACK;
371
372 assert(Entries < MaxEntries && "recursively called after END_OF_STACK?");
373 if (Entries >= 0)
374 StackTrace[Entries] = IP;
375
376 if (++Entries == MaxEntries)
377 return _URC_END_OF_STACK;
378 return _URC_NO_REASON;
379 };
380
381 _Unwind_Backtrace(
382 [](_Unwind_Context *Context, void *Handler) {
383 return (*static_cast<decltype(HandleFrame) *>(Handler))(Context);
384 },
385 static_cast<void *>(&HandleFrame));
386 return std::max(Entries, 0);
387}
388#endif
389
Reid Spencer3d7a6142004-08-29 19:22:48 +0000390// PrintStackTrace - In the case of a program crash or fault, print out a stack
391// trace so that the user has an indication of why and where we died.
392//
393// On glibc systems we have the 'backtrace' function, which works nicely, but
Michael J. Spencer447762d2010-11-29 18:16:10 +0000394// doesn't demangle symbols.
Zachary Turnercd132c92015-03-05 19:10:52 +0000395void llvm::sys::PrintStackTrace(raw_ostream &OS) {
Richard Smith14d96512016-05-20 21:18:12 +0000396#if defined(ENABLE_BACKTRACES)
397 static void *StackTrace[256];
398 int depth = 0;
399#if defined(HAVE_BACKTRACE)
Reid Spencer3d7a6142004-08-29 19:22:48 +0000400 // Use backtrace() to output a backtrace on Linux systems with glibc.
Richard Smith14d96512016-05-20 21:18:12 +0000401 if (!depth)
402 depth = backtrace(StackTrace, static_cast<int>(array_lengthof(StackTrace)));
403#endif
404#if defined(HAVE_UNWIND_BACKTRACE)
405 // Try _Unwind_Backtrace() if backtrace() failed.
406 if (!depth)
407 depth = unwindBacktrace(StackTrace,
Evan Cheng86cb3182008-05-05 18:30:58 +0000408 static_cast<int>(array_lengthof(StackTrace)));
Richard Smith14d96512016-05-20 21:18:12 +0000409#endif
410 if (!depth)
411 return;
412
Richard Smith2ad6d482016-06-09 00:53:21 +0000413 if (printSymbolizedStackTrace(Argv0, StackTrace, depth, OS))
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000414 return;
Dan Gohman7f079aa2008-12-05 20:12:48 +0000415#if HAVE_DLFCN_H && __GNUG__
416 int width = 0;
417 for (int i = 0; i < depth; ++i) {
418 Dl_info dlinfo;
419 dladdr(StackTrace[i], &dlinfo);
Dan Gohman1f517dd2009-02-10 17:56:28 +0000420 const char* name = strrchr(dlinfo.dli_fname, '/');
Dan Gohman7f079aa2008-12-05 20:12:48 +0000421
422 int nwidth;
Craig Toppere73658d2014-04-28 04:05:08 +0000423 if (!name) nwidth = strlen(dlinfo.dli_fname);
424 else nwidth = strlen(name) - 1;
Dan Gohman7f079aa2008-12-05 20:12:48 +0000425
426 if (nwidth > width) width = nwidth;
427 }
428
429 for (int i = 0; i < depth; ++i) {
430 Dl_info dlinfo;
431 dladdr(StackTrace[i], &dlinfo);
432
Zachary Turnercd132c92015-03-05 19:10:52 +0000433 OS << format("%-2d", i);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000434
Dan Gohman1f517dd2009-02-10 17:56:28 +0000435 const char* name = strrchr(dlinfo.dli_fname, '/');
Zachary Turnercd132c92015-03-05 19:10:52 +0000436 if (!name) OS << format(" %-*s", width, dlinfo.dli_fname);
437 else OS << format(" %-*s", width, name+1);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000438
Zachary Turnercd132c92015-03-05 19:10:52 +0000439 OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2,
440 (unsigned long)StackTrace[i]);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000441
Craig Toppere73658d2014-04-28 04:05:08 +0000442 if (dlinfo.dli_sname != nullptr) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000443 OS << ' ';
Joerg Sonnenberger66241832013-04-27 22:12:32 +0000444# if HAVE_CXXABI_H
Benjamin Kramer83e2a442013-04-28 07:47:04 +0000445 int res;
Craig Toppere73658d2014-04-28 04:05:08 +0000446 char* d = abi::__cxa_demangle(dlinfo.dli_sname, nullptr, nullptr, &res);
Joerg Sonnenberger66241832013-04-27 22:12:32 +0000447# else
448 char* d = NULL;
449# endif
Zachary Turnercd132c92015-03-05 19:10:52 +0000450 if (!d) OS << dlinfo.dli_sname;
451 else OS << d;
Dan Gohman7f079aa2008-12-05 20:12:48 +0000452 free(d);
453
Edwin Vane44338e02013-01-28 19:34:42 +0000454 // FIXME: When we move to C++11, use %t length modifier. It's not in
455 // C++03 and causes gcc to issue warnings. Losing the upper 32 bits of
456 // the stack offset for a stack dump isn't likely to cause any problems.
Zachary Turnercd132c92015-03-05 19:10:52 +0000457 OS << format(" + %u",(unsigned)((char*)StackTrace[i]-
458 (char*)dlinfo.dli_saddr));
Dan Gohman7f079aa2008-12-05 20:12:48 +0000459 }
Zachary Turnercd132c92015-03-05 19:10:52 +0000460 OS << '\n';
Dan Gohman7f079aa2008-12-05 20:12:48 +0000461 }
Richard Smith14d96512016-05-20 21:18:12 +0000462#elif defined(HAVE_BACKTRACE)
Lauro Ramos Venancioeab51d32008-02-15 18:05:54 +0000463 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
Reid Spencer3d7a6142004-08-29 19:22:48 +0000464#endif
Dan Gohman7f079aa2008-12-05 20:12:48 +0000465#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +0000466}
467
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000468static void PrintStackTraceSignalHandler(void *) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000469 PrintStackTrace(llvm::errs());
Argyrios Kyrtzidiseb9ae762013-01-09 19:42:40 +0000470}
471
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000472void llvm::sys::DisableSystemDialogsOnCrash() {}
473
NAKAMURA Takumi8a54d812012-09-06 03:01:43 +0000474/// PrintStackTraceOnErrorSignal - When an error signal (such as SIGABRT or
Reid Spencer3d7a6142004-08-29 19:22:48 +0000475/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
Richard Smith2ad6d482016-06-09 00:53:21 +0000476void llvm::sys::PrintStackTraceOnErrorSignal(StringRef Argv0,
477 bool DisableCrashReporting) {
478 ::Argv0 = Argv0;
479
Craig Toppere73658d2014-04-28 04:05:08 +0000480 AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000481
Daniel Dunbareb6c7082013-08-30 20:39:21 +0000482#if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES)
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000483 // Environment variable to disable any kind of crash dialog.
Pete Cooper6bea2f42015-04-07 20:43:23 +0000484 if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) {
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000485 mach_port_t self = mach_task_self();
486
487 exception_mask_t mask = EXC_MASK_CRASH;
488
NAKAMURA Takumiffa15712012-09-06 03:02:56 +0000489 kern_return_t ret = task_set_exception_ports(self,
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000490 mask,
Jean-Daniel Dupasa573b222012-03-24 22:17:50 +0000491 MACH_PORT_NULL,
NAKAMURA Takumiffa15712012-09-06 03:02:56 +0000492 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
Jean-Daniel Dupasa573b222012-03-24 22:17:50 +0000493 THREAD_STATE_NONE);
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000494 (void)ret;
495 }
496#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +0000497}