blob: 94336305d8473126dcef45683f1cba2c06c19ac8 [file] [log] [blame]
Reid Spencer3d7a6142004-08-29 19:22:48 +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
Reid Spencerd554bbc2004-12-27 06:16:52 +000030#if HAVE_SIGNAL_H
Reid Spencer3d7a6142004-08-29 19:22:48 +000031#include <signal.h>
Reid Spencerd554bbc2004-12-27 06:16:52 +000032#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
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +000048
Chris Lattner80df7c42006-08-01 17:59:14 +000049using namespace llvm;
Reid Spencer3d7a6142004-08-29 19:22:48 +000050
Chris Lattnerf299a682009-03-23 05:42:29 +000051static RETSIGTYPE SignalHandler(int Sig); // defined below.
52
Chris Bieneman186e7d12014-09-02 23:48:13 +000053static ManagedStatic<SmartMutex<true> > SignalsMutex;
Owen Anderson820739d2009-08-17 17:07:22 +000054
Chris Lattner6a5d6ec2005-08-02 02:14:22 +000055/// InterruptFunction - The function to call if ctrl-c is pressed.
Craig Toppere73658d2014-04-28 04:05:08 +000056static void (*InterruptFunction)() = nullptr;
Chris Lattner6a5d6ec2005-08-02 02:14:22 +000057
Chris Bieneman186e7d12014-09-02 23:48:13 +000058static ManagedStatic<std::vector<std::string>> FilesToRemove;
Reid Spencer3d7a6142004-08-29 19:22:48 +000059
Dan Gohmanf857cd72013-02-20 19:28:46 +000060// IntSigs - Signals that represent requested termination. There's no bug
61// or failure, or if there is, it's not our direct responsibility. For whatever
62// reason, our continued execution is no longer desirable.
Dan Gohmanf4bc7822008-04-10 21:11:47 +000063static const int IntSigs[] = {
Dan Gohman5cdb3452013-02-20 19:15:01 +000064 SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
Reid Spencer3d7a6142004-08-29 19:22:48 +000065};
Reid Spencer3d7a6142004-08-29 19:22:48 +000066
Dan Gohmanf857cd72013-02-20 19:28:46 +000067// KillSigs - Signals that represent that we have a bug, and our prompt
68// termination has been ordered.
Dan Gohmanf4bc7822008-04-10 21:11:47 +000069static const int KillSigs[] = {
Dan Gohman5cdb3452013-02-20 19:15:01 +000070 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
Chris Lattner62f50da2010-02-12 00:37:46 +000071#ifdef SIGSYS
72 , SIGSYS
73#endif
74#ifdef SIGXCPU
75 , SIGXCPU
76#endif
Chris Lattner3b38fd62010-02-14 18:20:09 +000077#ifdef SIGXFSZ
Chris Lattner62f50da2010-02-12 00:37:46 +000078 , SIGXFSZ
79#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +000080#ifdef SIGEMT
81 , SIGEMT
82#endif
83};
Reid Spencer3d7a6142004-08-29 19:22:48 +000084
Chris Lattnerfb954722009-03-23 05:55:36 +000085static unsigned NumRegisteredSignals = 0;
86static struct {
87 struct sigaction SA;
88 int SigNo;
89} RegisteredSignalInfo[(sizeof(IntSigs)+sizeof(KillSigs))/sizeof(KillSigs[0])];
90
91
Chris Lattnerf299a682009-03-23 05:42:29 +000092static void RegisterHandler(int Signal) {
Craig Topper26b45c22013-07-15 04:37:54 +000093 assert(NumRegisteredSignals <
94 sizeof(RegisteredSignalInfo)/sizeof(RegisteredSignalInfo[0]) &&
Chris Lattnerfb954722009-03-23 05:55:36 +000095 "Out of space for signal handlers!");
96
97 struct sigaction NewHandler;
Michael J. Spencer447762d2010-11-29 18:16:10 +000098
Chris Lattnerfb954722009-03-23 05:55:36 +000099 NewHandler.sa_handler = SignalHandler;
100 NewHandler.sa_flags = SA_NODEFER|SA_RESETHAND;
Michael J. Spencer447762d2010-11-29 18:16:10 +0000101 sigemptyset(&NewHandler.sa_mask);
102
Chris Lattnerfb954722009-03-23 05:55:36 +0000103 // Install the new handler, save the old one in RegisteredSignalInfo.
104 sigaction(Signal, &NewHandler,
105 &RegisteredSignalInfo[NumRegisteredSignals].SA);
106 RegisteredSignalInfo[NumRegisteredSignals].SigNo = Signal;
107 ++NumRegisteredSignals;
Chris Lattner6acb4d62009-03-07 08:15:47 +0000108}
109
Chris Lattnerf299a682009-03-23 05:42:29 +0000110static void RegisterHandlers() {
Chris Bieneman017ebf02015-04-27 20:45:35 +0000111 // We need to dereference the signals mutex during handler registration so
112 // that we force its construction. This is to prevent the first use being
113 // during handling an actual signal because you can't safely call new in a
114 // signal handler.
115 *SignalsMutex;
116
Chris Lattnerfb954722009-03-23 05:55:36 +0000117 // If the handlers are already registered, we're done.
118 if (NumRegisteredSignals != 0) return;
119
Chris Bienemanb1cd51e2014-08-29 01:05:16 +0000120 for (auto S : IntSigs) RegisterHandler(S);
121 for (auto S : KillSigs) RegisterHandler(S);
Chris Lattnerf299a682009-03-23 05:42:29 +0000122}
123
Chris Lattnerf299a682009-03-23 05:42:29 +0000124static void UnregisterHandlers() {
Chris Lattnerfb954722009-03-23 05:55:36 +0000125 // Restore all of the signal handlers to how they were before we showed up.
126 for (unsigned i = 0, e = NumRegisteredSignals; i != e; ++i)
Chris Lattnerf2b60652009-03-23 06:46:20 +0000127 sigaction(RegisteredSignalInfo[i].SigNo,
Craig Toppere73658d2014-04-28 04:05:08 +0000128 &RegisteredSignalInfo[i].SA, nullptr);
Chris Lattnerfb954722009-03-23 05:55:36 +0000129 NumRegisteredSignals = 0;
Chris Lattnerf299a682009-03-23 05:42:29 +0000130}
131
132
Dan Gohman288999b2010-05-27 23:11:55 +0000133/// RemoveFilesToRemove - Process the FilesToRemove list. This function
134/// should be called with the SignalsMutex lock held.
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000135/// NB: This must be an async signal safe function. It cannot allocate or free
136/// memory, even in debug builds.
Dan Gohman288999b2010-05-27 23:11:55 +0000137static void RemoveFilesToRemove() {
Steven Wu94746692015-05-07 16:20:51 +0000138 // Avoid constructing ManagedStatic in the signal handler.
139 // If FilesToRemove is not constructed, there are no files to remove.
140 if (!FilesToRemove.isConstructed())
141 return;
142
Daniel Dunbar511479d2012-10-17 16:30:54 +0000143 // We avoid iterators in case of debug iterators that allocate or release
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000144 // memory.
Chris Bieneman186e7d12014-09-02 23:48:13 +0000145 std::vector<std::string>& FilesToRemoveRef = *FilesToRemove;
146 for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i) {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000147 const char *path = FilesToRemoveRef[i].c_str();
Daniel Dunbar511479d2012-10-17 16:30:54 +0000148
149 // Get the status so we can determine if it's a file or directory. If we
150 // can't stat the file, ignore it.
151 struct stat buf;
152 if (stat(path, &buf) != 0)
153 continue;
154
155 // If this is not a regular file, ignore it. We want to prevent removal of
156 // special files like /dev/null, even if the compiler is being run with the
157 // super-user permissions.
158 if (!S_ISREG(buf.st_mode))
159 continue;
160
161 // Otherwise, remove the file. We ignore any errors here as there is nothing
162 // else we can do.
163 unlink(path);
Dan Gohman288999b2010-05-27 23:11:55 +0000164 }
165}
Chris Lattner6acb4d62009-03-07 08:15:47 +0000166
167// SignalHandler - The signal handler that runs.
Chris Lattner4fdd0422009-03-04 21:21:36 +0000168static RETSIGTYPE SignalHandler(int Sig) {
Chris Lattnerbbbbbf32009-03-05 18:22:14 +0000169 // Restore the signal behavior to default, so that the program actually
170 // crashes when we return and the signal reissues. This also ensures that if
171 // we crash in our signal handler that the program will terminate immediately
172 // instead of recursing in the signal handler.
Chris Lattnerf299a682009-03-23 05:42:29 +0000173 UnregisterHandlers();
Chris Lattner6acb4d62009-03-07 08:15:47 +0000174
175 // Unmask all potentially blocked kill signals.
176 sigset_t SigMask;
177 sigfillset(&SigMask);
Craig Toppere73658d2014-04-28 04:05:08 +0000178 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
Chris Lattnerbbbbbf32009-03-05 18:22:14 +0000179
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000180 {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000181 unique_lock<SmartMutex<true>> Guard(*SignalsMutex);
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000182 RemoveFilesToRemove();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000183
Chris Bienemanb1cd51e2014-08-29 01:05:16 +0000184 if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
185 != std::end(IntSigs)) {
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000186 if (InterruptFunction) {
187 void (*IF)() = InterruptFunction;
188 Guard.unlock();
189 InterruptFunction = nullptr;
190 IF(); // run the interrupt function.
191 return;
192 }
193
194 Guard.unlock();
195 raise(Sig); // Execute the default handler.
Chris Lattner4fdd0422009-03-04 21:21:36 +0000196 return;
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000197 }
Chris Lattner4fdd0422009-03-04 21:21:36 +0000198 }
199
200 // Otherwise if it is a fault (like SEGV) run any handler.
Yaron Keren28738102015-07-22 21:11:17 +0000201 llvm::sys::RunSignalHandlers();
Ulrich Weigand90c9abd2013-05-03 12:22:11 +0000202
203#ifdef __s390__
204 // On S/390, certain signals are delivered with PSW Address pointing to
205 // *after* the faulting instruction. Simply returning from the signal
206 // handler would continue execution after that point, instead of
207 // re-raising the signal. Raise the signal manually in those cases.
208 if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
209 raise(Sig);
210#endif
Chris Lattner4fdd0422009-03-04 21:21:36 +0000211}
212
Daniel Dunbar68272562010-05-08 02:10:34 +0000213void llvm::sys::RunInterruptHandlers() {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000214 sys::SmartScopedLock<true> Guard(*SignalsMutex);
Dan Gohman288999b2010-05-27 23:11:55 +0000215 RemoveFilesToRemove();
Daniel Dunbar68272562010-05-08 02:10:34 +0000216}
Chris Lattner4fdd0422009-03-04 21:21:36 +0000217
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000218void llvm::sys::SetInterruptFunction(void (*IF)()) {
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000219 {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000220 sys::SmartScopedLock<true> Guard(*SignalsMutex);
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000221 InterruptFunction = IF;
222 }
Chris Lattnerf299a682009-03-23 05:42:29 +0000223 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000224}
225
226// RemoveFileOnSignal - The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000227bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000228 std::string* ErrMsg) {
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000229 {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000230 sys::SmartScopedLock<true> Guard(*SignalsMutex);
Yaron Keren4135e4c2015-07-23 05:49:29 +0000231 FilesToRemove->push_back(Filename);
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000232 }
Owen Anderson820739d2009-08-17 17:07:22 +0000233
Chris Lattnerf299a682009-03-23 05:42:29 +0000234 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000235 return false;
236}
237
Dan Gohmane201c072010-09-01 14:17:34 +0000238// DontRemoveFileOnSignal - The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000239void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000240 sys::SmartScopedLock<true> Guard(*SignalsMutex);
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000241 std::vector<std::string>::reverse_iterator RI =
Chris Bieneman186e7d12014-09-02 23:48:13 +0000242 std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
243 std::vector<std::string>::iterator I = FilesToRemove->end();
244 if (RI != FilesToRemove->rend())
245 I = FilesToRemove->erase(RI.base()-1);
Dan Gohmane201c072010-09-01 14:17:34 +0000246}
247
Chris Lattner4fdd0422009-03-04 21:21:36 +0000248/// AddSignalHandler - Add a function to be called when a signal is delivered
249/// to the process. The handler can have a cookie passed to it to identify
250/// what instance of the handler it is.
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000251void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000252 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
Chris Lattnerf299a682009-03-23 05:42:29 +0000253 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000254}
255
NAKAMURA Takumi59fe0d42014-10-13 04:32:43 +0000256#if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
257
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000258#if HAVE_LINK_H && (defined(__linux__) || defined(__FreeBSD__) || \
259 defined(__FreeBSD_kernel__) || defined(__NetBSD__))
260struct DlIteratePhdrData {
261 void **StackTrace;
262 int depth;
263 bool first;
264 const char **modules;
265 intptr_t *offsets;
266 const char *main_exec_name;
267};
268
269static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
270 DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
271 const char *name = data->first ? data->main_exec_name : info->dlpi_name;
272 data->first = false;
273 for (int i = 0; i < info->dlpi_phnum; i++) {
274 const auto *phdr = &info->dlpi_phdr[i];
275 if (phdr->p_type != PT_LOAD)
276 continue;
277 intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
278 intptr_t end = beg + phdr->p_memsz;
279 for (int j = 0; j < data->depth; j++) {
280 if (data->modules[j])
281 continue;
282 intptr_t addr = (intptr_t)data->StackTrace[j];
283 if (beg <= addr && addr < end) {
284 data->modules[j] = name;
285 data->offsets[j] = addr - info->dlpi_addr;
286 }
287 }
288 }
289 return 0;
290}
291
292static bool findModulesAndOffsets(void **StackTrace, int Depth,
293 const char **Modules, intptr_t *Offsets,
294 const char *MainExecutableName) {
295 DlIteratePhdrData data = {StackTrace, Depth, true,
296 Modules, Offsets, MainExecutableName};
297 dl_iterate_phdr(dl_iterate_phdr_cb, &data);
298 return true;
299}
300#else
301static bool findModulesAndOffsets(void **StackTrace, int Depth,
302 const char **Modules, intptr_t *Offsets,
303 const char *MainExecutableName) {
304 return false;
305}
306#endif
307
Zachary Turnercd132c92015-03-05 19:10:52 +0000308static bool printSymbolizedStackTrace(void **StackTrace, int Depth,
309 llvm::raw_ostream &OS) {
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000310 // FIXME: Subtract necessary number from StackTrace entries to turn return addresses
311 // into actual instruction addresses.
312 // Use llvm-symbolizer tool to symbolize the stack traces.
Rafael Espindolac1f30872014-11-04 12:35:47 +0000313 ErrorOr<std::string> LLVMSymbolizerPathOrErr =
314 sys::findProgramByName("llvm-symbolizer");
315 if (!LLVMSymbolizerPathOrErr)
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000316 return false;
Rafael Espindolac1f30872014-11-04 12:35:47 +0000317 const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000318 // We don't know argv0 or the address of main() at this point, but try
319 // to guess it anyway (it's possible on some platforms).
320 std::string MainExecutableName = sys::fs::getMainExecutable(nullptr, nullptr);
321 if (MainExecutableName.empty() ||
322 MainExecutableName.find("llvm-symbolizer") != std::string::npos)
323 return false;
324
325 std::vector<const char *> Modules(Depth, nullptr);
326 std::vector<intptr_t> Offsets(Depth, 0);
327 if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(),
328 MainExecutableName.c_str()))
329 return false;
330 int InputFD;
331 SmallString<32> InputFile, OutputFile;
332 sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile);
333 sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile);
334 FileRemover InputRemover(InputFile.c_str());
335 FileRemover OutputRemover(OutputFile.c_str());
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000336
337 {
338 raw_fd_ostream Input(InputFD, true);
339 for (int i = 0; i < Depth; i++) {
340 if (Modules[i])
341 Input << Modules[i] << " " << (void*)Offsets[i] << "\n";
342 }
343 }
344
Benjamin Kramer7ad22402014-10-22 19:55:26 +0000345 StringRef InputFileStr(InputFile);
346 StringRef OutputFileStr(OutputFile);
347 StringRef StderrFileStr;
348 const StringRef *Redirects[] = {&InputFileStr, &OutputFileStr,
349 &StderrFileStr};
Alexey Samsonov96983b82014-10-10 22:58:26 +0000350 const char *Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
351 "--demangle", nullptr};
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000352 int RunResult =
Benjamin Kramer7ad22402014-10-22 19:55:26 +0000353 sys::ExecuteAndWait(LLVMSymbolizerPath, Args, nullptr, Redirects);
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000354 if (RunResult != 0)
355 return false;
356
357 auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str());
358 if (!OutputBuf)
359 return false;
360 StringRef Output = OutputBuf.get()->getBuffer();
361 SmallVector<StringRef, 32> Lines;
362 Output.split(Lines, "\n");
363 auto CurLine = Lines.begin();
364 int frame_no = 0;
365 for (int i = 0; i < Depth; i++) {
366 if (!Modules[i]) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000367 OS << format("#%d %p\n", frame_no++, StackTrace[i]);
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000368 continue;
369 }
370 // Read pairs of lines (function name and file/line info) until we
371 // encounter empty line.
372 for (;;) {
Alexey Samsonov96983b82014-10-10 22:58:26 +0000373 if (CurLine == Lines.end())
374 return false;
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000375 StringRef FunctionName = *CurLine++;
376 if (FunctionName.empty())
377 break;
Zachary Turnercd132c92015-03-05 19:10:52 +0000378 OS << format("#%d %p ", frame_no++, StackTrace[i]);
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000379 if (!FunctionName.startswith("??"))
Zachary Turnercd132c92015-03-05 19:10:52 +0000380 OS << format("%s ", FunctionName.str().c_str());
Alexey Samsonov96983b82014-10-10 22:58:26 +0000381 if (CurLine == Lines.end())
382 return false;
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000383 StringRef FileLineInfo = *CurLine++;
384 if (!FileLineInfo.startswith("??"))
Zachary Turnercd132c92015-03-05 19:10:52 +0000385 OS << format("%s", FileLineInfo.str().c_str());
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000386 else
Zachary Turnercd132c92015-03-05 19:10:52 +0000387 OS << format("(%s+%p)", Modules[i], (void *)Offsets[i]);
388 OS << "\n";
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000389 }
390 }
391 return true;
392}
NAKAMURA Takumi59fe0d42014-10-13 04:32:43 +0000393#endif // defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
Reid Spencer3d7a6142004-08-29 19:22:48 +0000394
395// PrintStackTrace - In the case of a program crash or fault, print out a stack
396// trace so that the user has an indication of why and where we died.
397//
398// On glibc systems we have the 'backtrace' function, which works nicely, but
Michael J. Spencer447762d2010-11-29 18:16:10 +0000399// doesn't demangle symbols.
Zachary Turnercd132c92015-03-05 19:10:52 +0000400void llvm::sys::PrintStackTrace(raw_ostream &OS) {
Benjamin Kramer5651cbd2012-09-28 10:10:46 +0000401#if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
Chris Lattner4fdd0422009-03-04 21:21:36 +0000402 static void* StackTrace[256];
Reid Spencer3d7a6142004-08-29 19:22:48 +0000403 // Use backtrace() to output a backtrace on Linux systems with glibc.
Evan Cheng86cb3182008-05-05 18:30:58 +0000404 int depth = backtrace(StackTrace,
405 static_cast<int>(array_lengthof(StackTrace)));
Zachary Turnercd132c92015-03-05 19:10:52 +0000406 if (printSymbolizedStackTrace(StackTrace, depth, OS))
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000407 return;
Dan Gohman7f079aa2008-12-05 20:12:48 +0000408#if HAVE_DLFCN_H && __GNUG__
409 int width = 0;
410 for (int i = 0; i < depth; ++i) {
411 Dl_info dlinfo;
412 dladdr(StackTrace[i], &dlinfo);
Dan Gohman1f517dd2009-02-10 17:56:28 +0000413 const char* name = strrchr(dlinfo.dli_fname, '/');
Dan Gohman7f079aa2008-12-05 20:12:48 +0000414
415 int nwidth;
Craig Toppere73658d2014-04-28 04:05:08 +0000416 if (!name) nwidth = strlen(dlinfo.dli_fname);
417 else nwidth = strlen(name) - 1;
Dan Gohman7f079aa2008-12-05 20:12:48 +0000418
419 if (nwidth > width) width = nwidth;
420 }
421
422 for (int i = 0; i < depth; ++i) {
423 Dl_info dlinfo;
424 dladdr(StackTrace[i], &dlinfo);
425
Zachary Turnercd132c92015-03-05 19:10:52 +0000426 OS << format("%-2d", i);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000427
Dan Gohman1f517dd2009-02-10 17:56:28 +0000428 const char* name = strrchr(dlinfo.dli_fname, '/');
Zachary Turnercd132c92015-03-05 19:10:52 +0000429 if (!name) OS << format(" %-*s", width, dlinfo.dli_fname);
430 else OS << format(" %-*s", width, name+1);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000431
Zachary Turnercd132c92015-03-05 19:10:52 +0000432 OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2,
433 (unsigned long)StackTrace[i]);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000434
Craig Toppere73658d2014-04-28 04:05:08 +0000435 if (dlinfo.dli_sname != nullptr) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000436 OS << ' ';
Joerg Sonnenberger66241832013-04-27 22:12:32 +0000437# if HAVE_CXXABI_H
Benjamin Kramer83e2a442013-04-28 07:47:04 +0000438 int res;
Craig Toppere73658d2014-04-28 04:05:08 +0000439 char* d = abi::__cxa_demangle(dlinfo.dli_sname, nullptr, nullptr, &res);
Joerg Sonnenberger66241832013-04-27 22:12:32 +0000440# else
441 char* d = NULL;
442# endif
Zachary Turnercd132c92015-03-05 19:10:52 +0000443 if (!d) OS << dlinfo.dli_sname;
444 else OS << d;
Dan Gohman7f079aa2008-12-05 20:12:48 +0000445 free(d);
446
Edwin Vane44338e02013-01-28 19:34:42 +0000447 // FIXME: When we move to C++11, use %t length modifier. It's not in
448 // C++03 and causes gcc to issue warnings. Losing the upper 32 bits of
449 // the stack offset for a stack dump isn't likely to cause any problems.
Zachary Turnercd132c92015-03-05 19:10:52 +0000450 OS << format(" + %u",(unsigned)((char*)StackTrace[i]-
451 (char*)dlinfo.dli_saddr));
Dan Gohman7f079aa2008-12-05 20:12:48 +0000452 }
Zachary Turnercd132c92015-03-05 19:10:52 +0000453 OS << '\n';
Dan Gohman7f079aa2008-12-05 20:12:48 +0000454 }
455#else
Lauro Ramos Venancioeab51d32008-02-15 18:05:54 +0000456 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
Reid Spencer3d7a6142004-08-29 19:22:48 +0000457#endif
Dan Gohman7f079aa2008-12-05 20:12:48 +0000458#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +0000459}
460
Argyrios Kyrtzidiseb9ae762013-01-09 19:42:40 +0000461static void PrintStackTraceSignalHandler(void *) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000462 PrintStackTrace(llvm::errs());
Argyrios Kyrtzidiseb9ae762013-01-09 19:42:40 +0000463}
464
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000465void llvm::sys::DisableSystemDialogsOnCrash() {}
466
NAKAMURA Takumi8a54d812012-09-06 03:01:43 +0000467/// PrintStackTraceOnErrorSignal - When an error signal (such as SIGABRT or
Reid Spencer3d7a6142004-08-29 19:22:48 +0000468/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
Pete Cooper6bea2f42015-04-07 20:43:23 +0000469void llvm::sys::PrintStackTraceOnErrorSignal(bool DisableCrashReporting) {
Craig Toppere73658d2014-04-28 04:05:08 +0000470 AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000471
Daniel Dunbareb6c7082013-08-30 20:39:21 +0000472#if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES)
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000473 // Environment variable to disable any kind of crash dialog.
Pete Cooper6bea2f42015-04-07 20:43:23 +0000474 if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) {
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000475 mach_port_t self = mach_task_self();
476
477 exception_mask_t mask = EXC_MASK_CRASH;
478
NAKAMURA Takumiffa15712012-09-06 03:02:56 +0000479 kern_return_t ret = task_set_exception_ports(self,
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000480 mask,
Jean-Daniel Dupasa573b222012-03-24 22:17:50 +0000481 MACH_PORT_NULL,
NAKAMURA Takumiffa15712012-09-06 03:02:56 +0000482 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
Jean-Daniel Dupasa573b222012-03-24 22:17:50 +0000483 THREAD_STATE_NONE);
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000484 (void)ret;
485 }
486#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +0000487}
Chris Lattner4fdd0422009-03-04 21:21:36 +0000488
Daniel Dunbarf14d9462010-08-19 23:45:39 +0000489
490/***/
491
492// On Darwin, raise sends a signal to the main thread instead of the current
493// thread. This has the unfortunate effect that assert() and abort() will end up
494// bypassing our crash recovery attempts. We work around this for anything in
495// the same linkage unit by just defining our own versions of the assert handler
496// and abort.
497
Daniel Dunbareb6c7082013-08-30 20:39:21 +0000498#if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES)
Daniel Dunbarf14d9462010-08-19 23:45:39 +0000499
Douglas Gregor0e506822011-04-29 16:12:17 +0000500#include <signal.h>
501#include <pthread.h>
502
Daniel Dunbar18456f32010-09-22 17:46:10 +0000503int raise(int sig) {
Daniel Dunbarcc0e18d2010-10-08 18:31:34 +0000504 return pthread_kill(pthread_self(), sig);
Daniel Dunbar18456f32010-09-22 17:46:10 +0000505}
506
Daniel Dunbarf14d9462010-08-19 23:45:39 +0000507void __assert_rtn(const char *func,
508 const char *file,
509 int line,
510 const char *expr) {
511 if (func)
512 fprintf(stderr, "Assertion failed: (%s), function %s, file %s, line %d.\n",
513 expr, func, file, line);
514 else
515 fprintf(stderr, "Assertion failed: (%s), file %s, line %d.\n",
516 expr, file, line);
517 abort();
518}
519
Daniel Dunbarf14d9462010-08-19 23:45:39 +0000520void abort() {
Daniel Dunbar18456f32010-09-22 17:46:10 +0000521 raise(SIGABRT);
Daniel Dunbarf14d9462010-08-19 23:45:39 +0000522 usleep(1000);
523 __builtin_trap();
524}
525
526#endif