blob: 68be010ff5c2e7afcbb712a2af9ffa0827c228fa [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"
Rafael Espindolab940b662016-09-06 19:16:48 +000017#include "llvm/Demangle/Demangle.h"
Zachary Turnercd132c92015-03-05 19:10:52 +000018#include "llvm/Support/Format.h"
Alexey Samsonov8a584bb2014-10-10 22:06:59 +000019#include "llvm/Support/FileSystem.h"
20#include "llvm/Support/FileUtilities.h"
Alexey Samsonov8a584bb2014-10-10 22:06:59 +000021#include "llvm/Support/MemoryBuffer.h"
22#include "llvm/Support/Mutex.h"
23#include "llvm/Support/Program.h"
24#include "llvm/Support/UniqueLock.h"
25#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include <algorithm>
Chandler Carruthe6196eb2012-06-16 00:09:41 +000027#include <string>
Reid Spencerd554bbc2004-12-27 06:16:52 +000028#if HAVE_EXECINFO_H
Reid Spencer3d7a6142004-08-29 19:22:48 +000029# include <execinfo.h> // For backtrace().
30#endif
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000031#if HAVE_SIGNAL_H
32#include <signal.h>
33#endif
Reid Spencerceeb9182007-04-07 18:52:17 +000034#if HAVE_SYS_STAT_H
35#include <sys/stat.h>
36#endif
Joerg Sonnenberger66241832013-04-27 22:12:32 +000037#if HAVE_DLFCN_H
Dan Gohman7f079aa2008-12-05 20:12:48 +000038#include <dlfcn.h>
Dan Gohman7f079aa2008-12-05 20:12:48 +000039#endif
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +000040#if HAVE_MACH_MACH_H
41#include <mach/mach.h>
42#endif
Alexey Samsonov8a584bb2014-10-10 22:06:59 +000043#if HAVE_LINK_H
44#include <link.h>
45#endif
Joerg Sonnenberger5c505392016-09-29 21:07:57 +000046#ifdef HAVE__UNWIND_BACKTRACE
Richard Smith14d96512016-05-20 21:18:12 +000047// FIXME: We should be able to use <unwind.h> for any target that has an
48// _Unwind_Backtrace function, but on FreeBSD the configure test passes
49// despite the function not existing, and on Android, <unwind.h> conflicts
50// with <link.h>.
Bob Wilson37df90a2017-01-06 02:26:33 +000051#ifdef __GLIBC__
Richard Smith14d96512016-05-20 21:18:12 +000052#include <unwind.h>
53#else
Joerg Sonnenberger5c505392016-09-29 21:07:57 +000054#undef HAVE__UNWIND_BACKTRACE
Richard Smith14d96512016-05-20 21:18:12 +000055#endif
56#endif
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +000057
Chris Lattner80df7c42006-08-01 17:59:14 +000058using namespace llvm;
Reid Spencer3d7a6142004-08-29 19:22:48 +000059
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000060static RETSIGTYPE SignalHandler(int Sig); // defined below.
Chris Lattnerf299a682009-03-23 05:42:29 +000061
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000062static ManagedStatic<SmartMutex<true> > SignalsMutex;
Owen Anderson820739d2009-08-17 17:07:22 +000063
Chris Lattner6a5d6ec2005-08-02 02:14:22 +000064/// InterruptFunction - The function to call if ctrl-c is pressed.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000065static void (*InterruptFunction)() = nullptr;
Chris Lattner6a5d6ec2005-08-02 02:14:22 +000066
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000067static ManagedStatic<std::vector<std::string>> FilesToRemove;
Reid Spencer3d7a6142004-08-29 19:22:48 +000068
Richard Smith2ad6d482016-06-09 00:53:21 +000069static StringRef Argv0;
70
Dan Gohmanf857cd72013-02-20 19:28:46 +000071// IntSigs - Signals that represent requested termination. There's no bug
72// or failure, or if there is, it's not our direct responsibility. For whatever
73// reason, our continued execution is no longer desirable.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000074static const int IntSigs[] = {
Dan Gohman5cdb3452013-02-20 19:15:01 +000075 SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
Reid Spencer3d7a6142004-08-29 19:22:48 +000076};
Reid Spencer3d7a6142004-08-29 19:22:48 +000077
Dan Gohmanf857cd72013-02-20 19:28:46 +000078// KillSigs - Signals that represent that we have a bug, and our prompt
79// termination has been ordered.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000080static const int KillSigs[] = {
Dan Gohman5cdb3452013-02-20 19:15:01 +000081 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
Chris Lattner62f50da2010-02-12 00:37:46 +000082#ifdef SIGSYS
83 , SIGSYS
84#endif
85#ifdef SIGXCPU
86 , SIGXCPU
87#endif
Chris Lattner3b38fd62010-02-14 18:20:09 +000088#ifdef SIGXFSZ
Chris Lattner62f50da2010-02-12 00:37:46 +000089 , SIGXFSZ
90#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +000091#ifdef SIGEMT
92 , SIGEMT
93#endif
94};
Reid Spencer3d7a6142004-08-29 19:22:48 +000095
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000096static unsigned NumRegisteredSignals = 0;
97static struct {
Chris Lattnerfb954722009-03-23 05:55:36 +000098 struct sigaction SA;
99 int SigNo;
Craig Topperfac90572015-12-01 06:12:59 +0000100} RegisteredSignalInfo[array_lengthof(IntSigs) + array_lengthof(KillSigs)];
Chris Lattnerfb954722009-03-23 05:55:36 +0000101
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000102
103static void RegisterHandler(int Signal) {
Craig Topperfac90572015-12-01 06:12:59 +0000104 assert(NumRegisteredSignals < array_lengthof(RegisteredSignalInfo) &&
Chris Lattnerfb954722009-03-23 05:55:36 +0000105 "Out of space for signal handlers!");
106
107 struct sigaction NewHandler;
Michael J. Spencer447762d2010-11-29 18:16:10 +0000108
Chris Lattnerfb954722009-03-23 05:55:36 +0000109 NewHandler.sa_handler = SignalHandler;
Richard Smithb8b0be92016-05-23 06:47:37 +0000110 NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK;
Michael J. Spencer447762d2010-11-29 18:16:10 +0000111 sigemptyset(&NewHandler.sa_mask);
112
Chris Lattnerfb954722009-03-23 05:55:36 +0000113 // Install the new handler, save the old one in RegisteredSignalInfo.
114 sigaction(Signal, &NewHandler,
115 &RegisteredSignalInfo[NumRegisteredSignals].SA);
116 RegisteredSignalInfo[NumRegisteredSignals].SigNo = Signal;
117 ++NumRegisteredSignals;
Chris Lattner6acb4d62009-03-07 08:15:47 +0000118}
119
Richard Smithabab5d22016-05-20 21:26:00 +0000120#if defined(HAVE_SIGALTSTACK)
Chandler Carrutheb232dc2016-08-24 03:42:51 +0000121// Hold onto both the old and new alternate signal stack so that it's not
122// reported as a leak. We don't make any attempt to remove our alt signal
123// stack if we remove our signal handlers; that can't be done reliably if
124// someone else is also trying to do the same thing.
Richard Smith4b735c52016-05-20 21:38:15 +0000125static stack_t OldAltStack;
Chandler Carrutheb232dc2016-08-24 03:42:51 +0000126static void* NewAltStackPointer;
Richard Smithe8811342016-05-20 21:07:41 +0000127
128static void CreateSigAltStack() {
Richard Smithb3116312016-08-24 00:54:49 +0000129 const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024;
Richard Smithe8811342016-05-20 21:07:41 +0000130
131 // If we're executing on the alternate stack, or we already have an alternate
132 // signal stack that we're happy with, there's nothing for us to do. Don't
133 // reduce the size, some other part of the process might need a larger stack
134 // than we do.
135 if (sigaltstack(nullptr, &OldAltStack) != 0 ||
136 OldAltStack.ss_flags & SS_ONSTACK ||
137 (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize))
138 return;
139
Richard Smith4b735c52016-05-20 21:38:15 +0000140 stack_t AltStack = {};
Chris Bienemanf2363472016-05-21 00:36:47 +0000141 AltStack.ss_sp = reinterpret_cast<char *>(malloc(AltStackSize));
Chandler Carrutheb232dc2016-08-24 03:42:51 +0000142 NewAltStackPointer = AltStack.ss_sp; // Save to avoid reporting a leak.
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() {
Bruno Cardoso Lopes1856cee2017-03-27 18:21:31 +0000152 sys::SmartScopedLock<true> Guard(*SignalsMutex);
Mehdi Amini766d05b2015-11-05 02:29:53 +0000153
Chris Lattnerfb954722009-03-23 05:55:36 +0000154 // If the handlers are already registered, we're done.
155 if (NumRegisteredSignals != 0) return;
156
Richard Smithe8811342016-05-20 21:07:41 +0000157 // Create an alternate stack for signal handling. This is necessary for us to
158 // be able to reliably handle signals due to stack overflow.
159 CreateSigAltStack();
160
Chris Bienemanb1cd51e2014-08-29 01:05:16 +0000161 for (auto S : IntSigs) RegisterHandler(S);
162 for (auto S : KillSigs) RegisterHandler(S);
Chris Lattnerf299a682009-03-23 05:42:29 +0000163}
164
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000165static void UnregisterHandlers() {
Chris Lattnerfb954722009-03-23 05:55:36 +0000166 // Restore all of the signal handlers to how they were before we showed up.
167 for (unsigned i = 0, e = NumRegisteredSignals; i != e; ++i)
Chris Lattnerf2b60652009-03-23 06:46:20 +0000168 sigaction(RegisteredSignalInfo[i].SigNo,
Craig Toppere73658d2014-04-28 04:05:08 +0000169 &RegisteredSignalInfo[i].SA, nullptr);
Chris Lattnerfb954722009-03-23 05:55:36 +0000170 NumRegisteredSignals = 0;
Chris Lattnerf299a682009-03-23 05:42:29 +0000171}
172
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000173
Dan Gohman288999b2010-05-27 23:11:55 +0000174/// RemoveFilesToRemove - Process the FilesToRemove list. This function
175/// should be called with the SignalsMutex lock held.
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000176/// NB: This must be an async signal safe function. It cannot allocate or free
177/// memory, even in debug builds.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000178static void RemoveFilesToRemove() {
Steven Wu94746692015-05-07 16:20:51 +0000179 // Avoid constructing ManagedStatic in the signal handler.
180 // If FilesToRemove is not constructed, there are no files to remove.
181 if (!FilesToRemove.isConstructed())
182 return;
183
Daniel Dunbar511479d2012-10-17 16:30:54 +0000184 // We avoid iterators in case of debug iterators that allocate or release
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000185 // memory.
Chris Bieneman186e7d12014-09-02 23:48:13 +0000186 std::vector<std::string>& FilesToRemoveRef = *FilesToRemove;
187 for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i) {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000188 const char *path = FilesToRemoveRef[i].c_str();
Daniel Dunbar511479d2012-10-17 16:30:54 +0000189
190 // Get the status so we can determine if it's a file or directory. If we
191 // can't stat the file, ignore it.
192 struct stat buf;
193 if (stat(path, &buf) != 0)
194 continue;
195
196 // If this is not a regular file, ignore it. We want to prevent removal of
197 // special files like /dev/null, even if the compiler is being run with the
198 // super-user permissions.
199 if (!S_ISREG(buf.st_mode))
200 continue;
Mehdi Amini766d05b2015-11-05 02:29:53 +0000201
Daniel Dunbar511479d2012-10-17 16:30:54 +0000202 // Otherwise, remove the file. We ignore any errors here as there is nothing
203 // else we can do.
204 unlink(path);
Dan Gohman288999b2010-05-27 23:11:55 +0000205 }
206}
Chris Lattner6acb4d62009-03-07 08:15:47 +0000207
208// SignalHandler - The signal handler that runs.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000209static RETSIGTYPE SignalHandler(int Sig) {
Chris Lattnerbbbbbf32009-03-05 18:22:14 +0000210 // Restore the signal behavior to default, so that the program actually
211 // crashes when we return and the signal reissues. This also ensures that if
212 // we crash in our signal handler that the program will terminate immediately
213 // instead of recursing in the signal handler.
Chris Lattnerf299a682009-03-23 05:42:29 +0000214 UnregisterHandlers();
Chris Lattner6acb4d62009-03-07 08:15:47 +0000215
216 // Unmask all potentially blocked kill signals.
217 sigset_t SigMask;
218 sigfillset(&SigMask);
Craig Toppere73658d2014-04-28 04:05:08 +0000219 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
Chris Lattnerbbbbbf32009-03-05 18:22:14 +0000220
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000221 {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000222 unique_lock<SmartMutex<true>> Guard(*SignalsMutex);
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000223 RemoveFilesToRemove();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000224
Chris Bienemanb1cd51e2014-08-29 01:05:16 +0000225 if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
226 != std::end(IntSigs)) {
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000227 if (InterruptFunction) {
228 void (*IF)() = InterruptFunction;
229 Guard.unlock();
230 InterruptFunction = nullptr;
231 IF(); // run the interrupt function.
232 return;
233 }
234
235 Guard.unlock();
236 raise(Sig); // Execute the default handler.
Chris Lattner4fdd0422009-03-04 21:21:36 +0000237 return;
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000238 }
Chris Lattner4fdd0422009-03-04 21:21:36 +0000239 }
240
241 // Otherwise if it is a fault (like SEGV) run any handler.
Yaron Keren28738102015-07-22 21:11:17 +0000242 llvm::sys::RunSignalHandlers();
Ulrich Weigand90c9abd2013-05-03 12:22:11 +0000243
244#ifdef __s390__
245 // On S/390, certain signals are delivered with PSW Address pointing to
246 // *after* the faulting instruction. Simply returning from the signal
247 // handler would continue execution after that point, instead of
248 // re-raising the signal. Raise the signal manually in those cases.
249 if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
250 raise(Sig);
251#endif
Chris Lattner4fdd0422009-03-04 21:21:36 +0000252}
253
Daniel Dunbar68272562010-05-08 02:10:34 +0000254void llvm::sys::RunInterruptHandlers() {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000255 sys::SmartScopedLock<true> Guard(*SignalsMutex);
Dan Gohman288999b2010-05-27 23:11:55 +0000256 RemoveFilesToRemove();
Daniel Dunbar68272562010-05-08 02:10:34 +0000257}
Chris Lattner4fdd0422009-03-04 21:21:36 +0000258
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000259void llvm::sys::SetInterruptFunction(void (*IF)()) {
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000260 {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000261 sys::SmartScopedLock<true> Guard(*SignalsMutex);
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000262 InterruptFunction = IF;
263 }
Chris Lattnerf299a682009-03-23 05:42:29 +0000264 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000265}
266
267// RemoveFileOnSignal - The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000268bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000269 std::string* ErrMsg) {
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000270 {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000271 sys::SmartScopedLock<true> Guard(*SignalsMutex);
Yaron Keren4135e4c2015-07-23 05:49:29 +0000272 FilesToRemove->push_back(Filename);
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000273 }
Owen Anderson820739d2009-08-17 17:07:22 +0000274
Chris Lattnerf299a682009-03-23 05:42:29 +0000275 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000276 return false;
277}
278
Dan Gohmane201c072010-09-01 14:17:34 +0000279// DontRemoveFileOnSignal - The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000280void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000281 sys::SmartScopedLock<true> Guard(*SignalsMutex);
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000282 std::vector<std::string>::reverse_iterator RI =
David Majnemer42531262016-08-12 03:55:06 +0000283 find(reverse(*FilesToRemove), Filename);
Chris Bieneman186e7d12014-09-02 23:48:13 +0000284 std::vector<std::string>::iterator I = FilesToRemove->end();
285 if (RI != FilesToRemove->rend())
286 I = FilesToRemove->erase(RI.base()-1);
Dan Gohmane201c072010-09-01 14:17:34 +0000287}
288
Chris Lattner4fdd0422009-03-04 21:21:36 +0000289/// AddSignalHandler - Add a function to be called when a signal is delivered
290/// to the process. The handler can have a cookie passed to it to identify
291/// what instance of the handler it is.
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000292void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000293 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
Chris Lattnerf299a682009-03-23 05:42:29 +0000294 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000295}
296
Joerg Sonnenberger0e3cc3c2016-09-30 20:04:24 +0000297#if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && HAVE_LINK_H && \
Reid Kleckner40aa9c62015-11-09 23:10:29 +0000298 (defined(__linux__) || defined(__FreeBSD__) || \
299 defined(__FreeBSD_kernel__) || defined(__NetBSD__))
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000300struct DlIteratePhdrData {
301 void **StackTrace;
302 int depth;
303 bool first;
304 const char **modules;
305 intptr_t *offsets;
306 const char *main_exec_name;
307};
308
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000309static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000310 DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
311 const char *name = data->first ? data->main_exec_name : info->dlpi_name;
312 data->first = false;
313 for (int i = 0; i < info->dlpi_phnum; i++) {
314 const auto *phdr = &info->dlpi_phdr[i];
315 if (phdr->p_type != PT_LOAD)
316 continue;
317 intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
318 intptr_t end = beg + phdr->p_memsz;
319 for (int j = 0; j < data->depth; j++) {
320 if (data->modules[j])
321 continue;
322 intptr_t addr = (intptr_t)data->StackTrace[j];
323 if (beg <= addr && addr < end) {
324 data->modules[j] = name;
325 data->offsets[j] = addr - info->dlpi_addr;
326 }
327 }
328 }
329 return 0;
330}
331
Reid Kleckner40aa9c62015-11-09 23:10:29 +0000332/// If this is an ELF platform, we can find all loaded modules and their virtual
333/// addresses with dl_iterate_phdr.
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000334static bool findModulesAndOffsets(void **StackTrace, int Depth,
335 const char **Modules, intptr_t *Offsets,
Reid Klecknerba5757d2015-11-05 01:07:54 +0000336 const char *MainExecutableName,
337 StringSaver &StrPool) {
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000338 DlIteratePhdrData data = {StackTrace, Depth, true,
339 Modules, Offsets, MainExecutableName};
340 dl_iterate_phdr(dl_iterate_phdr_cb, &data);
341 return true;
342}
343#else
Reid Kleckner40aa9c62015-11-09 23:10:29 +0000344/// This platform does not have dl_iterate_phdr, so we do not yet know how to
345/// find all loaded DSOs.
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000346static bool findModulesAndOffsets(void **StackTrace, int Depth,
347 const char **Modules, intptr_t *Offsets,
Mehdi Amini7ae928e2015-11-05 02:29:57 +0000348 const char *MainExecutableName,
349 StringSaver &StrPool) {
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000350 return false;
351}
Joerg Sonnenberger0e3cc3c2016-09-30 20:04:24 +0000352#endif // defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && ...
Reid Spencer3d7a6142004-08-29 19:22:48 +0000353
Joerg Sonnenberger0e3cc3c2016-09-30 20:04:24 +0000354#if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE)
Richard Smith14d96512016-05-20 21:18:12 +0000355static int unwindBacktrace(void **StackTrace, int MaxEntries) {
356 if (MaxEntries < 0)
357 return 0;
358
359 // Skip the first frame ('unwindBacktrace' itself).
360 int Entries = -1;
361
362 auto HandleFrame = [&](_Unwind_Context *Context) -> _Unwind_Reason_Code {
363 // Apparently we need to detect reaching the end of the stack ourselves.
364 void *IP = (void *)_Unwind_GetIP(Context);
365 if (!IP)
366 return _URC_END_OF_STACK;
367
368 assert(Entries < MaxEntries && "recursively called after END_OF_STACK?");
369 if (Entries >= 0)
370 StackTrace[Entries] = IP;
371
372 if (++Entries == MaxEntries)
373 return _URC_END_OF_STACK;
374 return _URC_NO_REASON;
375 };
376
377 _Unwind_Backtrace(
378 [](_Unwind_Context *Context, void *Handler) {
379 return (*static_cast<decltype(HandleFrame) *>(Handler))(Context);
380 },
381 static_cast<void *>(&HandleFrame));
382 return std::max(Entries, 0);
383}
384#endif
385
Reid Spencer3d7a6142004-08-29 19:22:48 +0000386// PrintStackTrace - In the case of a program crash or fault, print out a stack
387// trace so that the user has an indication of why and where we died.
388//
389// On glibc systems we have the 'backtrace' function, which works nicely, but
Michael J. Spencer447762d2010-11-29 18:16:10 +0000390// doesn't demangle symbols.
Zachary Turnercd132c92015-03-05 19:10:52 +0000391void llvm::sys::PrintStackTrace(raw_ostream &OS) {
Joerg Sonnenberger0e3cc3c2016-09-30 20:04:24 +0000392#if ENABLE_BACKTRACES
Richard Smith14d96512016-05-20 21:18:12 +0000393 static void *StackTrace[256];
394 int depth = 0;
395#if defined(HAVE_BACKTRACE)
Reid Spencer3d7a6142004-08-29 19:22:48 +0000396 // Use backtrace() to output a backtrace on Linux systems with glibc.
Richard Smith14d96512016-05-20 21:18:12 +0000397 if (!depth)
398 depth = backtrace(StackTrace, static_cast<int>(array_lengthof(StackTrace)));
399#endif
Joerg Sonnenberger5c505392016-09-29 21:07:57 +0000400#if defined(HAVE__UNWIND_BACKTRACE)
Richard Smith14d96512016-05-20 21:18:12 +0000401 // Try _Unwind_Backtrace() if backtrace() failed.
402 if (!depth)
403 depth = unwindBacktrace(StackTrace,
Evan Cheng86cb3182008-05-05 18:30:58 +0000404 static_cast<int>(array_lengthof(StackTrace)));
Richard Smith14d96512016-05-20 21:18:12 +0000405#endif
406 if (!depth)
407 return;
408
Richard Smith2ad6d482016-06-09 00:53:21 +0000409 if (printSymbolizedStackTrace(Argv0, StackTrace, depth, OS))
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000410 return;
Omair Javaidf5d560bc842017-02-02 01:17:49 +0000411#if HAVE_DLFCN_H && HAVE_DLADDR
Dan Gohman7f079aa2008-12-05 20:12:48 +0000412 int width = 0;
413 for (int i = 0; i < depth; ++i) {
414 Dl_info dlinfo;
415 dladdr(StackTrace[i], &dlinfo);
Dan Gohman1f517dd2009-02-10 17:56:28 +0000416 const char* name = strrchr(dlinfo.dli_fname, '/');
Dan Gohman7f079aa2008-12-05 20:12:48 +0000417
418 int nwidth;
Craig Toppere73658d2014-04-28 04:05:08 +0000419 if (!name) nwidth = strlen(dlinfo.dli_fname);
420 else nwidth = strlen(name) - 1;
Dan Gohman7f079aa2008-12-05 20:12:48 +0000421
422 if (nwidth > width) width = nwidth;
423 }
424
425 for (int i = 0; i < depth; ++i) {
426 Dl_info dlinfo;
427 dladdr(StackTrace[i], &dlinfo);
428
Zachary Turnercd132c92015-03-05 19:10:52 +0000429 OS << format("%-2d", i);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000430
Dan Gohman1f517dd2009-02-10 17:56:28 +0000431 const char* name = strrchr(dlinfo.dli_fname, '/');
Zachary Turnercd132c92015-03-05 19:10:52 +0000432 if (!name) OS << format(" %-*s", width, dlinfo.dli_fname);
433 else OS << format(" %-*s", width, name+1);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000434
Zachary Turnercd132c92015-03-05 19:10:52 +0000435 OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2,
436 (unsigned long)StackTrace[i]);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000437
Craig Toppere73658d2014-04-28 04:05:08 +0000438 if (dlinfo.dli_sname != nullptr) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000439 OS << ' ';
Benjamin Kramer83e2a442013-04-28 07:47:04 +0000440 int res;
Rafael Espindolab940b662016-09-06 19:16:48 +0000441 char* d = itaniumDemangle(dlinfo.dli_sname, nullptr, nullptr, &res);
Zachary Turnercd132c92015-03-05 19:10:52 +0000442 if (!d) OS << dlinfo.dli_sname;
443 else OS << d;
Dan Gohman7f079aa2008-12-05 20:12:48 +0000444 free(d);
445
Edwin Vane44338e02013-01-28 19:34:42 +0000446 // FIXME: When we move to C++11, use %t length modifier. It's not in
447 // C++03 and causes gcc to issue warnings. Losing the upper 32 bits of
448 // the stack offset for a stack dump isn't likely to cause any problems.
Zachary Turnercd132c92015-03-05 19:10:52 +0000449 OS << format(" + %u",(unsigned)((char*)StackTrace[i]-
450 (char*)dlinfo.dli_saddr));
Dan Gohman7f079aa2008-12-05 20:12:48 +0000451 }
Zachary Turnercd132c92015-03-05 19:10:52 +0000452 OS << '\n';
Dan Gohman7f079aa2008-12-05 20:12:48 +0000453 }
Richard Smith14d96512016-05-20 21:18:12 +0000454#elif defined(HAVE_BACKTRACE)
Lauro Ramos Venancioeab51d32008-02-15 18:05:54 +0000455 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
Reid Spencer3d7a6142004-08-29 19:22:48 +0000456#endif
Dan Gohman7f079aa2008-12-05 20:12:48 +0000457#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +0000458}
459
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000460static void PrintStackTraceSignalHandler(void *) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000461 PrintStackTrace(llvm::errs());
Argyrios Kyrtzidiseb9ae762013-01-09 19:42:40 +0000462}
463
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000464void llvm::sys::DisableSystemDialogsOnCrash() {}
465
NAKAMURA Takumi8a54d812012-09-06 03:01:43 +0000466/// PrintStackTraceOnErrorSignal - When an error signal (such as SIGABRT or
Reid Spencer3d7a6142004-08-29 19:22:48 +0000467/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
Richard Smith2ad6d482016-06-09 00:53:21 +0000468void llvm::sys::PrintStackTraceOnErrorSignal(StringRef Argv0,
469 bool DisableCrashReporting) {
470 ::Argv0 = Argv0;
471
Craig Toppere73658d2014-04-28 04:05:08 +0000472 AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000473
Joerg Sonnenberger2cd87a02016-09-30 20:06:19 +0000474#if defined(__APPLE__) && ENABLE_CRASH_OVERRIDES
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000475 // Environment variable to disable any kind of crash dialog.
Pete Cooper6bea2f42015-04-07 20:43:23 +0000476 if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) {
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000477 mach_port_t self = mach_task_self();
478
479 exception_mask_t mask = EXC_MASK_CRASH;
480
NAKAMURA Takumiffa15712012-09-06 03:02:56 +0000481 kern_return_t ret = task_set_exception_ports(self,
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000482 mask,
Jean-Daniel Dupasa573b222012-03-24 22:17:50 +0000483 MACH_PORT_NULL,
NAKAMURA Takumiffa15712012-09-06 03:02:56 +0000484 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
Jean-Daniel Dupasa573b222012-03-24 22:17:50 +0000485 THREAD_STATE_NONE);
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000486 (void)ret;
487 }
488#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +0000489}