blob: a19cc61c3c120a9a5865dde23127d2746f129c61 [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"
Alexey Samsonov8a584bb2014-10-10 22:06:59 +000017#include "llvm/Support/FileSystem.h"
18#include "llvm/Support/FileUtilities.h"
Alexey Samsonovafe67072014-10-08 23:07:59 +000019#include "llvm/Support/ManagedStatic.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 Spencer3d7a6142004-08-29 19:22:48 +000027#include <vector>
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
Reid Spencerd554bbc2004-12-27 06:16:52 +000031#if HAVE_SIGNAL_H
Reid Spencer3d7a6142004-08-29 19:22:48 +000032#include <signal.h>
Reid Spencerd554bbc2004-12-27 06:16:52 +000033#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_CXXABI_H
Joerg Sonnenberger44744092013-04-27 22:32:54 +000038#include <cxxabi.h>
Joerg Sonnenberger66241832013-04-27 22:12:32 +000039#endif
40#if HAVE_DLFCN_H
Dan Gohman7f079aa2008-12-05 20:12:48 +000041#include <dlfcn.h>
Dan Gohman7f079aa2008-12-05 20:12:48 +000042#endif
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +000043#if HAVE_MACH_MACH_H
44#include <mach/mach.h>
45#endif
Alexey Samsonov8a584bb2014-10-10 22:06:59 +000046#if HAVE_LINK_H
47#include <link.h>
48#endif
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +000049
Chris Lattner80df7c42006-08-01 17:59:14 +000050using namespace llvm;
Reid Spencer3d7a6142004-08-29 19:22:48 +000051
Chris Lattnerf299a682009-03-23 05:42:29 +000052static RETSIGTYPE SignalHandler(int Sig); // defined below.
53
Chris Bieneman186e7d12014-09-02 23:48:13 +000054static ManagedStatic<SmartMutex<true> > SignalsMutex;
Owen Anderson820739d2009-08-17 17:07:22 +000055
Chris Lattner6a5d6ec2005-08-02 02:14:22 +000056/// InterruptFunction - The function to call if ctrl-c is pressed.
Craig Toppere73658d2014-04-28 04:05:08 +000057static void (*InterruptFunction)() = nullptr;
Chris Lattner6a5d6ec2005-08-02 02:14:22 +000058
Chris Bieneman186e7d12014-09-02 23:48:13 +000059static ManagedStatic<std::vector<std::string>> FilesToRemove;
60static ManagedStatic<std::vector<std::pair<void (*)(void *), void *>>>
61 CallBacksToRun;
Reid Spencer3d7a6142004-08-29 19:22:48 +000062
Dan Gohmanf857cd72013-02-20 19:28:46 +000063// IntSigs - Signals that represent requested termination. There's no bug
64// or failure, or if there is, it's not our direct responsibility. For whatever
65// reason, our continued execution is no longer desirable.
Dan Gohmanf4bc7822008-04-10 21:11:47 +000066static const int IntSigs[] = {
Dan Gohman5cdb3452013-02-20 19:15:01 +000067 SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
Reid Spencer3d7a6142004-08-29 19:22:48 +000068};
Reid Spencer3d7a6142004-08-29 19:22:48 +000069
Dan Gohmanf857cd72013-02-20 19:28:46 +000070// KillSigs - Signals that represent that we have a bug, and our prompt
71// termination has been ordered.
Dan Gohmanf4bc7822008-04-10 21:11:47 +000072static const int KillSigs[] = {
Dan Gohman5cdb3452013-02-20 19:15:01 +000073 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
Chris Lattner62f50da2010-02-12 00:37:46 +000074#ifdef SIGSYS
75 , SIGSYS
76#endif
77#ifdef SIGXCPU
78 , SIGXCPU
79#endif
Chris Lattner3b38fd62010-02-14 18:20:09 +000080#ifdef SIGXFSZ
Chris Lattner62f50da2010-02-12 00:37:46 +000081 , SIGXFSZ
82#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +000083#ifdef SIGEMT
84 , SIGEMT
85#endif
86};
Reid Spencer3d7a6142004-08-29 19:22:48 +000087
Chris Lattnerfb954722009-03-23 05:55:36 +000088static unsigned NumRegisteredSignals = 0;
89static struct {
90 struct sigaction SA;
91 int SigNo;
92} RegisteredSignalInfo[(sizeof(IntSigs)+sizeof(KillSigs))/sizeof(KillSigs[0])];
93
94
Chris Lattnerf299a682009-03-23 05:42:29 +000095static void RegisterHandler(int Signal) {
Craig Topper26b45c22013-07-15 04:37:54 +000096 assert(NumRegisteredSignals <
97 sizeof(RegisteredSignalInfo)/sizeof(RegisteredSignalInfo[0]) &&
Chris Lattnerfb954722009-03-23 05:55:36 +000098 "Out of space for signal handlers!");
99
100 struct sigaction NewHandler;
Michael J. Spencer447762d2010-11-29 18:16:10 +0000101
Chris Lattnerfb954722009-03-23 05:55:36 +0000102 NewHandler.sa_handler = SignalHandler;
103 NewHandler.sa_flags = SA_NODEFER|SA_RESETHAND;
Michael J. Spencer447762d2010-11-29 18:16:10 +0000104 sigemptyset(&NewHandler.sa_mask);
105
Chris Lattnerfb954722009-03-23 05:55:36 +0000106 // Install the new handler, save the old one in RegisteredSignalInfo.
107 sigaction(Signal, &NewHandler,
108 &RegisteredSignalInfo[NumRegisteredSignals].SA);
109 RegisteredSignalInfo[NumRegisteredSignals].SigNo = Signal;
110 ++NumRegisteredSignals;
Chris Lattner6acb4d62009-03-07 08:15:47 +0000111}
112
Chris Lattnerf299a682009-03-23 05:42:29 +0000113static void RegisterHandlers() {
Chris Lattnerfb954722009-03-23 05:55:36 +0000114 // If the handlers are already registered, we're done.
115 if (NumRegisteredSignals != 0) return;
116
Chris Bienemanb1cd51e2014-08-29 01:05:16 +0000117 for (auto S : IntSigs) RegisterHandler(S);
118 for (auto S : KillSigs) RegisterHandler(S);
Chris Lattnerf299a682009-03-23 05:42:29 +0000119}
120
Chris Lattnerf299a682009-03-23 05:42:29 +0000121static void UnregisterHandlers() {
Chris Lattnerfb954722009-03-23 05:55:36 +0000122 // Restore all of the signal handlers to how they were before we showed up.
123 for (unsigned i = 0, e = NumRegisteredSignals; i != e; ++i)
Chris Lattnerf2b60652009-03-23 06:46:20 +0000124 sigaction(RegisteredSignalInfo[i].SigNo,
Craig Toppere73658d2014-04-28 04:05:08 +0000125 &RegisteredSignalInfo[i].SA, nullptr);
Chris Lattnerfb954722009-03-23 05:55:36 +0000126 NumRegisteredSignals = 0;
Chris Lattnerf299a682009-03-23 05:42:29 +0000127}
128
129
Dan Gohman288999b2010-05-27 23:11:55 +0000130/// RemoveFilesToRemove - Process the FilesToRemove list. This function
131/// should be called with the SignalsMutex lock held.
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000132/// NB: This must be an async signal safe function. It cannot allocate or free
133/// memory, even in debug builds.
Dan Gohman288999b2010-05-27 23:11:55 +0000134static void RemoveFilesToRemove() {
Daniel Dunbar511479d2012-10-17 16:30:54 +0000135 // We avoid iterators in case of debug iterators that allocate or release
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000136 // memory.
Chris Bieneman186e7d12014-09-02 23:48:13 +0000137 std::vector<std::string>& FilesToRemoveRef = *FilesToRemove;
138 for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i) {
Daniel Dunbar511479d2012-10-17 16:30:54 +0000139 // We rely on a std::string implementation for which repeated calls to
140 // 'c_str()' don't allocate memory. We pre-call 'c_str()' on all of these
141 // strings to try to ensure this is safe.
Chris Bieneman186e7d12014-09-02 23:48:13 +0000142 const char *path = FilesToRemoveRef[i].c_str();
Daniel Dunbar511479d2012-10-17 16:30:54 +0000143
144 // Get the status so we can determine if it's a file or directory. If we
145 // can't stat the file, ignore it.
146 struct stat buf;
147 if (stat(path, &buf) != 0)
148 continue;
149
150 // If this is not a regular file, ignore it. We want to prevent removal of
151 // special files like /dev/null, even if the compiler is being run with the
152 // super-user permissions.
153 if (!S_ISREG(buf.st_mode))
154 continue;
155
156 // Otherwise, remove the file. We ignore any errors here as there is nothing
157 // else we can do.
158 unlink(path);
Dan Gohman288999b2010-05-27 23:11:55 +0000159 }
160}
Chris Lattner6acb4d62009-03-07 08:15:47 +0000161
162// SignalHandler - The signal handler that runs.
Chris Lattner4fdd0422009-03-04 21:21:36 +0000163static RETSIGTYPE SignalHandler(int Sig) {
Chris Lattnerbbbbbf32009-03-05 18:22:14 +0000164 // Restore the signal behavior to default, so that the program actually
165 // crashes when we return and the signal reissues. This also ensures that if
166 // we crash in our signal handler that the program will terminate immediately
167 // instead of recursing in the signal handler.
Chris Lattnerf299a682009-03-23 05:42:29 +0000168 UnregisterHandlers();
Chris Lattner6acb4d62009-03-07 08:15:47 +0000169
170 // Unmask all potentially blocked kill signals.
171 sigset_t SigMask;
172 sigfillset(&SigMask);
Craig Toppere73658d2014-04-28 04:05:08 +0000173 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
Chris Lattnerbbbbbf32009-03-05 18:22:14 +0000174
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000175 {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000176 unique_lock<SmartMutex<true>> Guard(*SignalsMutex);
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000177 RemoveFilesToRemove();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000178
Chris Bienemanb1cd51e2014-08-29 01:05:16 +0000179 if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
180 != std::end(IntSigs)) {
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000181 if (InterruptFunction) {
182 void (*IF)() = InterruptFunction;
183 Guard.unlock();
184 InterruptFunction = nullptr;
185 IF(); // run the interrupt function.
186 return;
187 }
188
189 Guard.unlock();
190 raise(Sig); // Execute the default handler.
Chris Lattner4fdd0422009-03-04 21:21:36 +0000191 return;
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000192 }
Chris Lattner4fdd0422009-03-04 21:21:36 +0000193 }
194
195 // Otherwise if it is a fault (like SEGV) run any handler.
Chris Bieneman186e7d12014-09-02 23:48:13 +0000196 std::vector<std::pair<void (*)(void *), void *>>& CallBacksToRunRef =
197 *CallBacksToRun;
198 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
199 CallBacksToRunRef[i].first(CallBacksToRunRef[i].second);
Ulrich Weigand90c9abd2013-05-03 12:22:11 +0000200
201#ifdef __s390__
202 // On S/390, certain signals are delivered with PSW Address pointing to
203 // *after* the faulting instruction. Simply returning from the signal
204 // handler would continue execution after that point, instead of
205 // re-raising the signal. Raise the signal manually in those cases.
206 if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
207 raise(Sig);
208#endif
Chris Lattner4fdd0422009-03-04 21:21:36 +0000209}
210
Daniel Dunbar68272562010-05-08 02:10:34 +0000211void llvm::sys::RunInterruptHandlers() {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000212 sys::SmartScopedLock<true> Guard(*SignalsMutex);
Dan Gohman288999b2010-05-27 23:11:55 +0000213 RemoveFilesToRemove();
Daniel Dunbar68272562010-05-08 02:10:34 +0000214}
Chris Lattner4fdd0422009-03-04 21:21:36 +0000215
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000216void llvm::sys::SetInterruptFunction(void (*IF)()) {
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000217 {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000218 sys::SmartScopedLock<true> Guard(*SignalsMutex);
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000219 InterruptFunction = IF;
220 }
Chris Lattnerf299a682009-03-23 05:42:29 +0000221 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000222}
223
224// RemoveFileOnSignal - The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000225bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000226 std::string* ErrMsg) {
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000227 {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000228 sys::SmartScopedLock<true> Guard(*SignalsMutex);
229 std::vector<std::string>& FilesToRemoveRef = *FilesToRemove;
230 std::string *OldPtr =
231 FilesToRemoveRef.empty() ? nullptr : &FilesToRemoveRef[0];
232 FilesToRemoveRef.push_back(Filename);
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000233
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000234 // We want to call 'c_str()' on every std::string in this vector so that if
235 // the underlying implementation requires a re-allocation, it happens here
236 // rather than inside of the signal handler. If we see the vector grow, we
237 // have to call it on every entry. If it remains in place, we only need to
238 // call it on the latest one.
Chris Bieneman186e7d12014-09-02 23:48:13 +0000239 if (OldPtr == &FilesToRemoveRef[0])
240 FilesToRemoveRef.back().c_str();
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000241 else
Chris Bieneman186e7d12014-09-02 23:48:13 +0000242 for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i)
243 FilesToRemoveRef[i].c_str();
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000244 }
Owen Anderson820739d2009-08-17 17:07:22 +0000245
Chris Lattnerf299a682009-03-23 05:42:29 +0000246 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000247 return false;
248}
249
Dan Gohmane201c072010-09-01 14:17:34 +0000250// DontRemoveFileOnSignal - The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000251void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000252 sys::SmartScopedLock<true> Guard(*SignalsMutex);
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000253 std::vector<std::string>::reverse_iterator RI =
Chris Bieneman186e7d12014-09-02 23:48:13 +0000254 std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
255 std::vector<std::string>::iterator I = FilesToRemove->end();
256 if (RI != FilesToRemove->rend())
257 I = FilesToRemove->erase(RI.base()-1);
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000258
259 // We need to call c_str() on every element which would have been moved by
260 // the erase. These elements, in a C++98 implementation where c_str()
261 // requires a reallocation on the first call may have had the call to c_str()
262 // made on insertion become invalid by being copied down an element.
Chris Bieneman186e7d12014-09-02 23:48:13 +0000263 for (std::vector<std::string>::iterator E = FilesToRemove->end(); I != E; ++I)
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000264 I->c_str();
Dan Gohmane201c072010-09-01 14:17:34 +0000265}
266
Chris Lattner4fdd0422009-03-04 21:21:36 +0000267/// AddSignalHandler - Add a function to be called when a signal is delivered
268/// to the process. The handler can have a cookie passed to it to identify
269/// what instance of the handler it is.
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000270void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000271 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
Chris Lattnerf299a682009-03-23 05:42:29 +0000272 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000273}
274
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000275#if HAVE_LINK_H && (defined(__linux__) || defined(__FreeBSD__) || \
276 defined(__FreeBSD_kernel__) || defined(__NetBSD__))
277struct DlIteratePhdrData {
278 void **StackTrace;
279 int depth;
280 bool first;
281 const char **modules;
282 intptr_t *offsets;
283 const char *main_exec_name;
284};
285
286static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
287 DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
288 const char *name = data->first ? data->main_exec_name : info->dlpi_name;
289 data->first = false;
290 for (int i = 0; i < info->dlpi_phnum; i++) {
291 const auto *phdr = &info->dlpi_phdr[i];
292 if (phdr->p_type != PT_LOAD)
293 continue;
294 intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
295 intptr_t end = beg + phdr->p_memsz;
296 for (int j = 0; j < data->depth; j++) {
297 if (data->modules[j])
298 continue;
299 intptr_t addr = (intptr_t)data->StackTrace[j];
300 if (beg <= addr && addr < end) {
301 data->modules[j] = name;
302 data->offsets[j] = addr - info->dlpi_addr;
303 }
304 }
305 }
306 return 0;
307}
308
309static bool findModulesAndOffsets(void **StackTrace, int Depth,
310 const char **Modules, intptr_t *Offsets,
311 const char *MainExecutableName) {
312 DlIteratePhdrData data = {StackTrace, Depth, true,
313 Modules, Offsets, MainExecutableName};
314 dl_iterate_phdr(dl_iterate_phdr_cb, &data);
315 return true;
316}
317#else
318static bool findModulesAndOffsets(void **StackTrace, int Depth,
319 const char **Modules, intptr_t *Offsets,
320 const char *MainExecutableName) {
321 return false;
322}
323#endif
324
325static bool printSymbolizedStackTrace(void **StackTrace, int Depth, FILE *FD) {
326 // FIXME: Subtract necessary number from StackTrace entries to turn return addresses
327 // into actual instruction addresses.
328 // Use llvm-symbolizer tool to symbolize the stack traces.
329 std::string LLVMSymbolizerPath = sys::FindProgramByName("llvm-symbolizer");
330 if (LLVMSymbolizerPath.empty())
331 return false;
332 // We don't know argv0 or the address of main() at this point, but try
333 // to guess it anyway (it's possible on some platforms).
334 std::string MainExecutableName = sys::fs::getMainExecutable(nullptr, nullptr);
335 if (MainExecutableName.empty() ||
336 MainExecutableName.find("llvm-symbolizer") != std::string::npos)
337 return false;
338
339 std::vector<const char *> Modules(Depth, nullptr);
340 std::vector<intptr_t> Offsets(Depth, 0);
341 if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(),
342 MainExecutableName.c_str()))
343 return false;
344 int InputFD;
345 SmallString<32> InputFile, OutputFile;
346 sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile);
347 sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile);
348 FileRemover InputRemover(InputFile.c_str());
349 FileRemover OutputRemover(OutputFile.c_str());
350 std::vector<const StringRef *> Redirects(3, nullptr);
351 StringRef InputFileStr(InputFile);
352 StringRef OutputFileStr(OutputFile);
353 StringRef StderrFileStr;
354 Redirects[0] = &InputFileStr;
355 Redirects[1] = &OutputFileStr;
356 Redirects[2] = &StderrFileStr;
357
358 {
359 raw_fd_ostream Input(InputFD, true);
360 for (int i = 0; i < Depth; i++) {
361 if (Modules[i])
362 Input << Modules[i] << " " << (void*)Offsets[i] << "\n";
363 }
364 }
365
Alexey Samsonov96983b82014-10-10 22:58:26 +0000366 const char *Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
367 "--demangle", nullptr};
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000368 int RunResult =
Alexey Samsonov96983b82014-10-10 22:58:26 +0000369 sys::ExecuteAndWait(LLVMSymbolizerPath, Args, nullptr, Redirects.data());
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000370 if (RunResult != 0)
371 return false;
372
373 auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str());
374 if (!OutputBuf)
375 return false;
376 StringRef Output = OutputBuf.get()->getBuffer();
377 SmallVector<StringRef, 32> Lines;
378 Output.split(Lines, "\n");
379 auto CurLine = Lines.begin();
380 int frame_no = 0;
381 for (int i = 0; i < Depth; i++) {
382 if (!Modules[i]) {
383 fprintf(FD, "#%d %p\n", frame_no++, StackTrace[i]);
384 continue;
385 }
386 // Read pairs of lines (function name and file/line info) until we
387 // encounter empty line.
388 for (;;) {
Alexey Samsonov96983b82014-10-10 22:58:26 +0000389 if (CurLine == Lines.end())
390 return false;
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000391 StringRef FunctionName = *CurLine++;
392 if (FunctionName.empty())
393 break;
394 fprintf(FD, "#%d %p ", frame_no++, StackTrace[i]);
395 if (!FunctionName.startswith("??"))
396 fprintf(FD, "%s ", FunctionName.str().c_str());
Alexey Samsonov96983b82014-10-10 22:58:26 +0000397 if (CurLine == Lines.end())
398 return false;
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000399 StringRef FileLineInfo = *CurLine++;
400 if (!FileLineInfo.startswith("??"))
401 fprintf(FD, "%s", FileLineInfo.str().c_str());
402 else
403 fprintf(FD, "(%s+%p)", Modules[i], (void *)Offsets[i]);
404 fprintf(FD, "\n");
405 }
406 }
407 return true;
408}
Reid Spencer3d7a6142004-08-29 19:22:48 +0000409
410// PrintStackTrace - In the case of a program crash or fault, print out a stack
411// trace so that the user has an indication of why and where we died.
412//
413// On glibc systems we have the 'backtrace' function, which works nicely, but
Michael J. Spencer447762d2010-11-29 18:16:10 +0000414// doesn't demangle symbols.
Argyrios Kyrtzidiseb9ae762013-01-09 19:42:40 +0000415void llvm::sys::PrintStackTrace(FILE *FD) {
Benjamin Kramer5651cbd2012-09-28 10:10:46 +0000416#if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
Chris Lattner4fdd0422009-03-04 21:21:36 +0000417 static void* StackTrace[256];
Reid Spencer3d7a6142004-08-29 19:22:48 +0000418 // Use backtrace() to output a backtrace on Linux systems with glibc.
Evan Cheng86cb3182008-05-05 18:30:58 +0000419 int depth = backtrace(StackTrace,
420 static_cast<int>(array_lengthof(StackTrace)));
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000421 if (printSymbolizedStackTrace(StackTrace, depth, FD))
422 return;
Dan Gohman7f079aa2008-12-05 20:12:48 +0000423#if HAVE_DLFCN_H && __GNUG__
424 int width = 0;
425 for (int i = 0; i < depth; ++i) {
426 Dl_info dlinfo;
427 dladdr(StackTrace[i], &dlinfo);
Dan Gohman1f517dd2009-02-10 17:56:28 +0000428 const char* name = strrchr(dlinfo.dli_fname, '/');
Dan Gohman7f079aa2008-12-05 20:12:48 +0000429
430 int nwidth;
Craig Toppere73658d2014-04-28 04:05:08 +0000431 if (!name) nwidth = strlen(dlinfo.dli_fname);
432 else nwidth = strlen(name) - 1;
Dan Gohman7f079aa2008-12-05 20:12:48 +0000433
434 if (nwidth > width) width = nwidth;
435 }
436
437 for (int i = 0; i < depth; ++i) {
438 Dl_info dlinfo;
439 dladdr(StackTrace[i], &dlinfo);
440
Argyrios Kyrtzidiseb9ae762013-01-09 19:42:40 +0000441 fprintf(FD, "%-2d", i);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000442
Dan Gohman1f517dd2009-02-10 17:56:28 +0000443 const char* name = strrchr(dlinfo.dli_fname, '/');
Craig Toppere73658d2014-04-28 04:05:08 +0000444 if (!name) fprintf(FD, " %-*s", width, dlinfo.dli_fname);
445 else fprintf(FD, " %-*s", width, name+1);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000446
Argyrios Kyrtzidiseb9ae762013-01-09 19:42:40 +0000447 fprintf(FD, " %#0*lx",
Dan Gohman35e2cfc2008-12-05 23:39:24 +0000448 (int)(sizeof(void*) * 2) + 2, (unsigned long)StackTrace[i]);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000449
Craig Toppere73658d2014-04-28 04:05:08 +0000450 if (dlinfo.dli_sname != nullptr) {
Argyrios Kyrtzidiseb9ae762013-01-09 19:42:40 +0000451 fputc(' ', FD);
Joerg Sonnenberger66241832013-04-27 22:12:32 +0000452# if HAVE_CXXABI_H
Benjamin Kramer83e2a442013-04-28 07:47:04 +0000453 int res;
Craig Toppere73658d2014-04-28 04:05:08 +0000454 char* d = abi::__cxa_demangle(dlinfo.dli_sname, nullptr, nullptr, &res);
Joerg Sonnenberger66241832013-04-27 22:12:32 +0000455# else
456 char* d = NULL;
457# endif
Craig Toppere73658d2014-04-28 04:05:08 +0000458 if (!d) fputs(dlinfo.dli_sname, FD);
459 else fputs(d, FD);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000460 free(d);
461
Edwin Vane44338e02013-01-28 19:34:42 +0000462 // FIXME: When we move to C++11, use %t length modifier. It's not in
463 // C++03 and causes gcc to issue warnings. Losing the upper 32 bits of
464 // the stack offset for a stack dump isn't likely to cause any problems.
465 fprintf(FD, " + %u",(unsigned)((char*)StackTrace[i]-
466 (char*)dlinfo.dli_saddr));
Dan Gohman7f079aa2008-12-05 20:12:48 +0000467 }
Argyrios Kyrtzidiseb9ae762013-01-09 19:42:40 +0000468 fputc('\n', FD);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000469 }
470#else
Lauro Ramos Venancioeab51d32008-02-15 18:05:54 +0000471 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
Reid Spencer3d7a6142004-08-29 19:22:48 +0000472#endif
Dan Gohman7f079aa2008-12-05 20:12:48 +0000473#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +0000474}
475
Argyrios Kyrtzidiseb9ae762013-01-09 19:42:40 +0000476static void PrintStackTraceSignalHandler(void *) {
477 PrintStackTrace(stderr);
478}
479
NAKAMURA Takumi8a54d812012-09-06 03:01:43 +0000480/// PrintStackTraceOnErrorSignal - When an error signal (such as SIGABRT or
Reid Spencer3d7a6142004-08-29 19:22:48 +0000481/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000482void llvm::sys::PrintStackTraceOnErrorSignal() {
Craig Toppere73658d2014-04-28 04:05:08 +0000483 AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000484
Daniel Dunbareb6c7082013-08-30 20:39:21 +0000485#if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES)
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000486 // Environment variable to disable any kind of crash dialog.
487 if (getenv("LLVM_DISABLE_CRASH_REPORT")) {
488 mach_port_t self = mach_task_self();
489
490 exception_mask_t mask = EXC_MASK_CRASH;
491
NAKAMURA Takumiffa15712012-09-06 03:02:56 +0000492 kern_return_t ret = task_set_exception_ports(self,
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000493 mask,
Jean-Daniel Dupasa573b222012-03-24 22:17:50 +0000494 MACH_PORT_NULL,
NAKAMURA Takumiffa15712012-09-06 03:02:56 +0000495 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
Jean-Daniel Dupasa573b222012-03-24 22:17:50 +0000496 THREAD_STATE_NONE);
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000497 (void)ret;
498 }
499#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +0000500}
Chris Lattner4fdd0422009-03-04 21:21:36 +0000501
Daniel Dunbarf14d9462010-08-19 23:45:39 +0000502
503/***/
504
505// On Darwin, raise sends a signal to the main thread instead of the current
506// thread. This has the unfortunate effect that assert() and abort() will end up
507// bypassing our crash recovery attempts. We work around this for anything in
508// the same linkage unit by just defining our own versions of the assert handler
509// and abort.
510
Daniel Dunbareb6c7082013-08-30 20:39:21 +0000511#if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES)
Daniel Dunbarf14d9462010-08-19 23:45:39 +0000512
Douglas Gregor0e506822011-04-29 16:12:17 +0000513#include <signal.h>
514#include <pthread.h>
515
Daniel Dunbar18456f32010-09-22 17:46:10 +0000516int raise(int sig) {
Daniel Dunbarcc0e18d2010-10-08 18:31:34 +0000517 return pthread_kill(pthread_self(), sig);
Daniel Dunbar18456f32010-09-22 17:46:10 +0000518}
519
Daniel Dunbarf14d9462010-08-19 23:45:39 +0000520void __assert_rtn(const char *func,
521 const char *file,
522 int line,
523 const char *expr) {
524 if (func)
525 fprintf(stderr, "Assertion failed: (%s), function %s, file %s, line %d.\n",
526 expr, func, file, line);
527 else
528 fprintf(stderr, "Assertion failed: (%s), file %s, line %d.\n",
529 expr, file, line);
530 abort();
531}
532
Daniel Dunbarf14d9462010-08-19 23:45:39 +0000533void abort() {
Daniel Dunbar18456f32010-09-22 17:46:10 +0000534 raise(SIGABRT);
Daniel Dunbarf14d9462010-08-19 23:45:39 +0000535 usleep(1000);
536 __builtin_trap();
537}
538
539#endif