blob: a9b48e0b059b4db0742747f931cc3fd18bddb15f [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 Samsonovafe67072014-10-08 23:07:59 +000020#include "llvm/Support/ManagedStatic.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 Spencer3d7a6142004-08-29 19:22:48 +000028#include <vector>
Reid Spencerd554bbc2004-12-27 06:16:52 +000029#if HAVE_EXECINFO_H
Reid Spencer3d7a6142004-08-29 19:22:48 +000030# include <execinfo.h> // For backtrace().
31#endif
Reid Spencerd554bbc2004-12-27 06:16:52 +000032#if HAVE_SIGNAL_H
Reid Spencer3d7a6142004-08-29 19:22:48 +000033#include <signal.h>
Reid Spencerd554bbc2004-12-27 06:16:52 +000034#endif
Reid Spencerceeb9182007-04-07 18:52:17 +000035#if HAVE_SYS_STAT_H
36#include <sys/stat.h>
37#endif
Joerg Sonnenberger66241832013-04-27 22:12:32 +000038#if HAVE_CXXABI_H
Joerg Sonnenberger44744092013-04-27 22:32:54 +000039#include <cxxabi.h>
Joerg Sonnenberger66241832013-04-27 22:12:32 +000040#endif
41#if HAVE_DLFCN_H
Dan Gohman7f079aa2008-12-05 20:12:48 +000042#include <dlfcn.h>
Dan Gohman7f079aa2008-12-05 20:12:48 +000043#endif
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +000044#if HAVE_MACH_MACH_H
45#include <mach/mach.h>
46#endif
Alexey Samsonov8a584bb2014-10-10 22:06:59 +000047#if HAVE_LINK_H
48#include <link.h>
49#endif
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +000050
Chris Lattner80df7c42006-08-01 17:59:14 +000051using namespace llvm;
Reid Spencer3d7a6142004-08-29 19:22:48 +000052
Chris Lattnerf299a682009-03-23 05:42:29 +000053static RETSIGTYPE SignalHandler(int Sig); // defined below.
54
Chris Bieneman186e7d12014-09-02 23:48:13 +000055static ManagedStatic<SmartMutex<true> > SignalsMutex;
Owen Anderson820739d2009-08-17 17:07:22 +000056
Chris Lattner6a5d6ec2005-08-02 02:14:22 +000057/// InterruptFunction - The function to call if ctrl-c is pressed.
Craig Toppere73658d2014-04-28 04:05:08 +000058static void (*InterruptFunction)() = nullptr;
Chris Lattner6a5d6ec2005-08-02 02:14:22 +000059
Chris Bieneman186e7d12014-09-02 23:48:13 +000060static ManagedStatic<std::vector<std::string>> FilesToRemove;
61static ManagedStatic<std::vector<std::pair<void (*)(void *), void *>>>
62 CallBacksToRun;
Reid Spencer3d7a6142004-08-29 19:22:48 +000063
Dan Gohmanf857cd72013-02-20 19:28:46 +000064// IntSigs - Signals that represent requested termination. There's no bug
65// or failure, or if there is, it's not our direct responsibility. For whatever
66// reason, our continued execution is no longer desirable.
Dan Gohmanf4bc7822008-04-10 21:11:47 +000067static const int IntSigs[] = {
Dan Gohman5cdb3452013-02-20 19:15:01 +000068 SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
Reid Spencer3d7a6142004-08-29 19:22:48 +000069};
Reid Spencer3d7a6142004-08-29 19:22:48 +000070
Dan Gohmanf857cd72013-02-20 19:28:46 +000071// KillSigs - Signals that represent that we have a bug, and our prompt
72// termination has been ordered.
Dan Gohmanf4bc7822008-04-10 21:11:47 +000073static const int KillSigs[] = {
Dan Gohman5cdb3452013-02-20 19:15:01 +000074 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
Chris Lattner62f50da2010-02-12 00:37:46 +000075#ifdef SIGSYS
76 , SIGSYS
77#endif
78#ifdef SIGXCPU
79 , SIGXCPU
80#endif
Chris Lattner3b38fd62010-02-14 18:20:09 +000081#ifdef SIGXFSZ
Chris Lattner62f50da2010-02-12 00:37:46 +000082 , SIGXFSZ
83#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +000084#ifdef SIGEMT
85 , SIGEMT
86#endif
87};
Reid Spencer3d7a6142004-08-29 19:22:48 +000088
Chris Lattnerfb954722009-03-23 05:55:36 +000089static unsigned NumRegisteredSignals = 0;
90static struct {
91 struct sigaction SA;
92 int SigNo;
93} RegisteredSignalInfo[(sizeof(IntSigs)+sizeof(KillSigs))/sizeof(KillSigs[0])];
94
95
Chris Lattnerf299a682009-03-23 05:42:29 +000096static void RegisterHandler(int Signal) {
Craig Topper26b45c22013-07-15 04:37:54 +000097 assert(NumRegisteredSignals <
98 sizeof(RegisteredSignalInfo)/sizeof(RegisteredSignalInfo[0]) &&
Chris Lattnerfb954722009-03-23 05:55:36 +000099 "Out of space for signal handlers!");
100
101 struct sigaction NewHandler;
Michael J. Spencer447762d2010-11-29 18:16:10 +0000102
Chris Lattnerfb954722009-03-23 05:55:36 +0000103 NewHandler.sa_handler = SignalHandler;
104 NewHandler.sa_flags = SA_NODEFER|SA_RESETHAND;
Michael J. Spencer447762d2010-11-29 18:16:10 +0000105 sigemptyset(&NewHandler.sa_mask);
106
Chris Lattnerfb954722009-03-23 05:55:36 +0000107 // Install the new handler, save the old one in RegisteredSignalInfo.
108 sigaction(Signal, &NewHandler,
109 &RegisteredSignalInfo[NumRegisteredSignals].SA);
110 RegisteredSignalInfo[NumRegisteredSignals].SigNo = Signal;
111 ++NumRegisteredSignals;
Chris Lattner6acb4d62009-03-07 08:15:47 +0000112}
113
Chris Lattnerf299a682009-03-23 05:42:29 +0000114static void RegisterHandlers() {
Chris Lattnerfb954722009-03-23 05:55:36 +0000115 // If the handlers are already registered, we're done.
116 if (NumRegisteredSignals != 0) return;
117
Chris Bienemanb1cd51e2014-08-29 01:05:16 +0000118 for (auto S : IntSigs) RegisterHandler(S);
119 for (auto S : KillSigs) RegisterHandler(S);
Chris Lattnerf299a682009-03-23 05:42:29 +0000120}
121
Chris Lattnerf299a682009-03-23 05:42:29 +0000122static void UnregisterHandlers() {
Chris Lattnerfb954722009-03-23 05:55:36 +0000123 // Restore all of the signal handlers to how they were before we showed up.
124 for (unsigned i = 0, e = NumRegisteredSignals; i != e; ++i)
Chris Lattnerf2b60652009-03-23 06:46:20 +0000125 sigaction(RegisteredSignalInfo[i].SigNo,
Craig Toppere73658d2014-04-28 04:05:08 +0000126 &RegisteredSignalInfo[i].SA, nullptr);
Chris Lattnerfb954722009-03-23 05:55:36 +0000127 NumRegisteredSignals = 0;
Chris Lattnerf299a682009-03-23 05:42:29 +0000128}
129
130
Dan Gohman288999b2010-05-27 23:11:55 +0000131/// RemoveFilesToRemove - Process the FilesToRemove list. This function
132/// should be called with the SignalsMutex lock held.
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000133/// NB: This must be an async signal safe function. It cannot allocate or free
134/// memory, even in debug builds.
Dan Gohman288999b2010-05-27 23:11:55 +0000135static void RemoveFilesToRemove() {
Daniel Dunbar511479d2012-10-17 16:30:54 +0000136 // We avoid iterators in case of debug iterators that allocate or release
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000137 // memory.
Chris Bieneman186e7d12014-09-02 23:48:13 +0000138 std::vector<std::string>& FilesToRemoveRef = *FilesToRemove;
139 for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i) {
Daniel Dunbar511479d2012-10-17 16:30:54 +0000140 // We rely on a std::string implementation for which repeated calls to
141 // 'c_str()' don't allocate memory. We pre-call 'c_str()' on all of these
142 // strings to try to ensure this is safe.
Chris Bieneman186e7d12014-09-02 23:48:13 +0000143 const char *path = FilesToRemoveRef[i].c_str();
Daniel Dunbar511479d2012-10-17 16:30:54 +0000144
145 // Get the status so we can determine if it's a file or directory. If we
146 // can't stat the file, ignore it.
147 struct stat buf;
148 if (stat(path, &buf) != 0)
149 continue;
150
151 // If this is not a regular file, ignore it. We want to prevent removal of
152 // special files like /dev/null, even if the compiler is being run with the
153 // super-user permissions.
154 if (!S_ISREG(buf.st_mode))
155 continue;
156
157 // Otherwise, remove the file. We ignore any errors here as there is nothing
158 // else we can do.
159 unlink(path);
Dan Gohman288999b2010-05-27 23:11:55 +0000160 }
161}
Chris Lattner6acb4d62009-03-07 08:15:47 +0000162
163// SignalHandler - The signal handler that runs.
Chris Lattner4fdd0422009-03-04 21:21:36 +0000164static RETSIGTYPE SignalHandler(int Sig) {
Chris Lattnerbbbbbf32009-03-05 18:22:14 +0000165 // Restore the signal behavior to default, so that the program actually
166 // crashes when we return and the signal reissues. This also ensures that if
167 // we crash in our signal handler that the program will terminate immediately
168 // instead of recursing in the signal handler.
Chris Lattnerf299a682009-03-23 05:42:29 +0000169 UnregisterHandlers();
Chris Lattner6acb4d62009-03-07 08:15:47 +0000170
171 // Unmask all potentially blocked kill signals.
172 sigset_t SigMask;
173 sigfillset(&SigMask);
Craig Toppere73658d2014-04-28 04:05:08 +0000174 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
Chris Lattnerbbbbbf32009-03-05 18:22:14 +0000175
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000176 {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000177 unique_lock<SmartMutex<true>> Guard(*SignalsMutex);
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000178 RemoveFilesToRemove();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000179
Chris Bienemanb1cd51e2014-08-29 01:05:16 +0000180 if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
181 != std::end(IntSigs)) {
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000182 if (InterruptFunction) {
183 void (*IF)() = InterruptFunction;
184 Guard.unlock();
185 InterruptFunction = nullptr;
186 IF(); // run the interrupt function.
187 return;
188 }
189
190 Guard.unlock();
191 raise(Sig); // Execute the default handler.
Chris Lattner4fdd0422009-03-04 21:21:36 +0000192 return;
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000193 }
Chris Lattner4fdd0422009-03-04 21:21:36 +0000194 }
195
196 // Otherwise if it is a fault (like SEGV) run any handler.
Chris Bieneman186e7d12014-09-02 23:48:13 +0000197 std::vector<std::pair<void (*)(void *), void *>>& CallBacksToRunRef =
198 *CallBacksToRun;
199 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
200 CallBacksToRunRef[i].first(CallBacksToRunRef[i].second);
Ulrich Weigand90c9abd2013-05-03 12:22:11 +0000201
202#ifdef __s390__
203 // On S/390, certain signals are delivered with PSW Address pointing to
204 // *after* the faulting instruction. Simply returning from the signal
205 // handler would continue execution after that point, instead of
206 // re-raising the signal. Raise the signal manually in those cases.
207 if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
208 raise(Sig);
209#endif
Chris Lattner4fdd0422009-03-04 21:21:36 +0000210}
211
Daniel Dunbar68272562010-05-08 02:10:34 +0000212void llvm::sys::RunInterruptHandlers() {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000213 sys::SmartScopedLock<true> Guard(*SignalsMutex);
Dan Gohman288999b2010-05-27 23:11:55 +0000214 RemoveFilesToRemove();
Daniel Dunbar68272562010-05-08 02:10:34 +0000215}
Chris Lattner4fdd0422009-03-04 21:21:36 +0000216
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000217void llvm::sys::SetInterruptFunction(void (*IF)()) {
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000218 {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000219 sys::SmartScopedLock<true> Guard(*SignalsMutex);
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000220 InterruptFunction = IF;
221 }
Chris Lattnerf299a682009-03-23 05:42:29 +0000222 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000223}
224
225// RemoveFileOnSignal - The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000226bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000227 std::string* ErrMsg) {
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000228 {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000229 sys::SmartScopedLock<true> Guard(*SignalsMutex);
230 std::vector<std::string>& FilesToRemoveRef = *FilesToRemove;
231 std::string *OldPtr =
232 FilesToRemoveRef.empty() ? nullptr : &FilesToRemoveRef[0];
233 FilesToRemoveRef.push_back(Filename);
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000234
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000235 // We want to call 'c_str()' on every std::string in this vector so that if
236 // the underlying implementation requires a re-allocation, it happens here
237 // rather than inside of the signal handler. If we see the vector grow, we
238 // have to call it on every entry. If it remains in place, we only need to
239 // call it on the latest one.
Chris Bieneman186e7d12014-09-02 23:48:13 +0000240 if (OldPtr == &FilesToRemoveRef[0])
241 FilesToRemoveRef.back().c_str();
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000242 else
Chris Bieneman186e7d12014-09-02 23:48:13 +0000243 for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i)
244 FilesToRemoveRef[i].c_str();
Dylan Noblesmith4704ffe2014-08-23 22:49:17 +0000245 }
Owen Anderson820739d2009-08-17 17:07:22 +0000246
Chris Lattnerf299a682009-03-23 05:42:29 +0000247 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000248 return false;
249}
250
Dan Gohmane201c072010-09-01 14:17:34 +0000251// DontRemoveFileOnSignal - The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000252void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000253 sys::SmartScopedLock<true> Guard(*SignalsMutex);
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000254 std::vector<std::string>::reverse_iterator RI =
Chris Bieneman186e7d12014-09-02 23:48:13 +0000255 std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
256 std::vector<std::string>::iterator I = FilesToRemove->end();
257 if (RI != FilesToRemove->rend())
258 I = FilesToRemove->erase(RI.base()-1);
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000259
260 // We need to call c_str() on every element which would have been moved by
261 // the erase. These elements, in a C++98 implementation where c_str()
262 // requires a reallocation on the first call may have had the call to c_str()
263 // made on insertion become invalid by being copied down an element.
Chris Bieneman186e7d12014-09-02 23:48:13 +0000264 for (std::vector<std::string>::iterator E = FilesToRemove->end(); I != E; ++I)
Chandler Carruthe6196eb2012-06-16 00:09:41 +0000265 I->c_str();
Dan Gohmane201c072010-09-01 14:17:34 +0000266}
267
Chris Lattner4fdd0422009-03-04 21:21:36 +0000268/// AddSignalHandler - Add a function to be called when a signal is delivered
269/// to the process. The handler can have a cookie passed to it to identify
270/// what instance of the handler it is.
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000271void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
Chris Bieneman186e7d12014-09-02 23:48:13 +0000272 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
Chris Lattnerf299a682009-03-23 05:42:29 +0000273 RegisterHandlers();
Chris Lattner4fdd0422009-03-04 21:21:36 +0000274}
275
NAKAMURA Takumi59fe0d42014-10-13 04:32:43 +0000276#if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
277
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000278#if HAVE_LINK_H && (defined(__linux__) || defined(__FreeBSD__) || \
279 defined(__FreeBSD_kernel__) || defined(__NetBSD__))
280struct DlIteratePhdrData {
281 void **StackTrace;
282 int depth;
283 bool first;
284 const char **modules;
285 intptr_t *offsets;
286 const char *main_exec_name;
287};
288
289static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
290 DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
291 const char *name = data->first ? data->main_exec_name : info->dlpi_name;
292 data->first = false;
293 for (int i = 0; i < info->dlpi_phnum; i++) {
294 const auto *phdr = &info->dlpi_phdr[i];
295 if (phdr->p_type != PT_LOAD)
296 continue;
297 intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
298 intptr_t end = beg + phdr->p_memsz;
299 for (int j = 0; j < data->depth; j++) {
300 if (data->modules[j])
301 continue;
302 intptr_t addr = (intptr_t)data->StackTrace[j];
303 if (beg <= addr && addr < end) {
304 data->modules[j] = name;
305 data->offsets[j] = addr - info->dlpi_addr;
306 }
307 }
308 }
309 return 0;
310}
311
312static bool findModulesAndOffsets(void **StackTrace, int Depth,
313 const char **Modules, intptr_t *Offsets,
314 const char *MainExecutableName) {
315 DlIteratePhdrData data = {StackTrace, Depth, true,
316 Modules, Offsets, MainExecutableName};
317 dl_iterate_phdr(dl_iterate_phdr_cb, &data);
318 return true;
319}
320#else
321static bool findModulesAndOffsets(void **StackTrace, int Depth,
322 const char **Modules, intptr_t *Offsets,
323 const char *MainExecutableName) {
324 return false;
325}
326#endif
327
Zachary Turnercd132c92015-03-05 19:10:52 +0000328static bool printSymbolizedStackTrace(void **StackTrace, int Depth,
329 llvm::raw_ostream &OS) {
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000330 // FIXME: Subtract necessary number from StackTrace entries to turn return addresses
331 // into actual instruction addresses.
332 // Use llvm-symbolizer tool to symbolize the stack traces.
Rafael Espindolac1f30872014-11-04 12:35:47 +0000333 ErrorOr<std::string> LLVMSymbolizerPathOrErr =
334 sys::findProgramByName("llvm-symbolizer");
335 if (!LLVMSymbolizerPathOrErr)
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000336 return false;
Rafael Espindolac1f30872014-11-04 12:35:47 +0000337 const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000338 // We don't know argv0 or the address of main() at this point, but try
339 // to guess it anyway (it's possible on some platforms).
340 std::string MainExecutableName = sys::fs::getMainExecutable(nullptr, nullptr);
341 if (MainExecutableName.empty() ||
342 MainExecutableName.find("llvm-symbolizer") != std::string::npos)
343 return false;
344
345 std::vector<const char *> Modules(Depth, nullptr);
346 std::vector<intptr_t> Offsets(Depth, 0);
347 if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(),
348 MainExecutableName.c_str()))
349 return false;
350 int InputFD;
351 SmallString<32> InputFile, OutputFile;
352 sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile);
353 sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile);
354 FileRemover InputRemover(InputFile.c_str());
355 FileRemover OutputRemover(OutputFile.c_str());
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000356
357 {
358 raw_fd_ostream Input(InputFD, true);
359 for (int i = 0; i < Depth; i++) {
360 if (Modules[i])
361 Input << Modules[i] << " " << (void*)Offsets[i] << "\n";
362 }
363 }
364
Benjamin Kramer7ad22402014-10-22 19:55:26 +0000365 StringRef InputFileStr(InputFile);
366 StringRef OutputFileStr(OutputFile);
367 StringRef StderrFileStr;
368 const StringRef *Redirects[] = {&InputFileStr, &OutputFileStr,
369 &StderrFileStr};
Alexey Samsonov96983b82014-10-10 22:58:26 +0000370 const char *Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
371 "--demangle", nullptr};
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000372 int RunResult =
Benjamin Kramer7ad22402014-10-22 19:55:26 +0000373 sys::ExecuteAndWait(LLVMSymbolizerPath, Args, nullptr, Redirects);
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000374 if (RunResult != 0)
375 return false;
376
377 auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str());
378 if (!OutputBuf)
379 return false;
380 StringRef Output = OutputBuf.get()->getBuffer();
381 SmallVector<StringRef, 32> Lines;
382 Output.split(Lines, "\n");
383 auto CurLine = Lines.begin();
384 int frame_no = 0;
385 for (int i = 0; i < Depth; i++) {
386 if (!Modules[i]) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000387 OS << format("#%d %p\n", frame_no++, StackTrace[i]);
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000388 continue;
389 }
390 // Read pairs of lines (function name and file/line info) until we
391 // encounter empty line.
392 for (;;) {
Alexey Samsonov96983b82014-10-10 22:58:26 +0000393 if (CurLine == Lines.end())
394 return false;
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000395 StringRef FunctionName = *CurLine++;
396 if (FunctionName.empty())
397 break;
Zachary Turnercd132c92015-03-05 19:10:52 +0000398 OS << format("#%d %p ", frame_no++, StackTrace[i]);
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000399 if (!FunctionName.startswith("??"))
Zachary Turnercd132c92015-03-05 19:10:52 +0000400 OS << format("%s ", FunctionName.str().c_str());
Alexey Samsonov96983b82014-10-10 22:58:26 +0000401 if (CurLine == Lines.end())
402 return false;
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000403 StringRef FileLineInfo = *CurLine++;
404 if (!FileLineInfo.startswith("??"))
Zachary Turnercd132c92015-03-05 19:10:52 +0000405 OS << format("%s", FileLineInfo.str().c_str());
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000406 else
Zachary Turnercd132c92015-03-05 19:10:52 +0000407 OS << format("(%s+%p)", Modules[i], (void *)Offsets[i]);
408 OS << "\n";
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000409 }
410 }
411 return true;
412}
NAKAMURA Takumi59fe0d42014-10-13 04:32:43 +0000413#endif // defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
Reid Spencer3d7a6142004-08-29 19:22:48 +0000414
415// PrintStackTrace - In the case of a program crash or fault, print out a stack
416// trace so that the user has an indication of why and where we died.
417//
418// On glibc systems we have the 'backtrace' function, which works nicely, but
Michael J. Spencer447762d2010-11-29 18:16:10 +0000419// doesn't demangle symbols.
Zachary Turnercd132c92015-03-05 19:10:52 +0000420void llvm::sys::PrintStackTrace(raw_ostream &OS) {
Benjamin Kramer5651cbd2012-09-28 10:10:46 +0000421#if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
Chris Lattner4fdd0422009-03-04 21:21:36 +0000422 static void* StackTrace[256];
Reid Spencer3d7a6142004-08-29 19:22:48 +0000423 // Use backtrace() to output a backtrace on Linux systems with glibc.
Evan Cheng86cb3182008-05-05 18:30:58 +0000424 int depth = backtrace(StackTrace,
425 static_cast<int>(array_lengthof(StackTrace)));
Zachary Turnercd132c92015-03-05 19:10:52 +0000426 if (printSymbolizedStackTrace(StackTrace, depth, OS))
Alexey Samsonov8a584bb2014-10-10 22:06:59 +0000427 return;
Dan Gohman7f079aa2008-12-05 20:12:48 +0000428#if HAVE_DLFCN_H && __GNUG__
429 int width = 0;
430 for (int i = 0; i < depth; ++i) {
431 Dl_info dlinfo;
432 dladdr(StackTrace[i], &dlinfo);
Dan Gohman1f517dd2009-02-10 17:56:28 +0000433 const char* name = strrchr(dlinfo.dli_fname, '/');
Dan Gohman7f079aa2008-12-05 20:12:48 +0000434
435 int nwidth;
Craig Toppere73658d2014-04-28 04:05:08 +0000436 if (!name) nwidth = strlen(dlinfo.dli_fname);
437 else nwidth = strlen(name) - 1;
Dan Gohman7f079aa2008-12-05 20:12:48 +0000438
439 if (nwidth > width) width = nwidth;
440 }
441
442 for (int i = 0; i < depth; ++i) {
443 Dl_info dlinfo;
444 dladdr(StackTrace[i], &dlinfo);
445
Zachary Turnercd132c92015-03-05 19:10:52 +0000446 OS << format("%-2d", i);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000447
Dan Gohman1f517dd2009-02-10 17:56:28 +0000448 const char* name = strrchr(dlinfo.dli_fname, '/');
Zachary Turnercd132c92015-03-05 19:10:52 +0000449 if (!name) OS << format(" %-*s", width, dlinfo.dli_fname);
450 else OS << format(" %-*s", width, name+1);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000451
Zachary Turnercd132c92015-03-05 19:10:52 +0000452 OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2,
453 (unsigned long)StackTrace[i]);
Dan Gohman7f079aa2008-12-05 20:12:48 +0000454
Craig Toppere73658d2014-04-28 04:05:08 +0000455 if (dlinfo.dli_sname != nullptr) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000456 OS << ' ';
Joerg Sonnenberger66241832013-04-27 22:12:32 +0000457# if HAVE_CXXABI_H
Benjamin Kramer83e2a442013-04-28 07:47:04 +0000458 int res;
Craig Toppere73658d2014-04-28 04:05:08 +0000459 char* d = abi::__cxa_demangle(dlinfo.dli_sname, nullptr, nullptr, &res);
Joerg Sonnenberger66241832013-04-27 22:12:32 +0000460# else
461 char* d = NULL;
462# endif
Zachary Turnercd132c92015-03-05 19:10:52 +0000463 if (!d) OS << dlinfo.dli_sname;
464 else OS << d;
Dan Gohman7f079aa2008-12-05 20:12:48 +0000465 free(d);
466
Edwin Vane44338e02013-01-28 19:34:42 +0000467 // FIXME: When we move to C++11, use %t length modifier. It's not in
468 // C++03 and causes gcc to issue warnings. Losing the upper 32 bits of
469 // the stack offset for a stack dump isn't likely to cause any problems.
Zachary Turnercd132c92015-03-05 19:10:52 +0000470 OS << format(" + %u",(unsigned)((char*)StackTrace[i]-
471 (char*)dlinfo.dli_saddr));
Dan Gohman7f079aa2008-12-05 20:12:48 +0000472 }
Zachary Turnercd132c92015-03-05 19:10:52 +0000473 OS << '\n';
Dan Gohman7f079aa2008-12-05 20:12:48 +0000474 }
475#else
Lauro Ramos Venancioeab51d32008-02-15 18:05:54 +0000476 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
Reid Spencer3d7a6142004-08-29 19:22:48 +0000477#endif
Dan Gohman7f079aa2008-12-05 20:12:48 +0000478#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +0000479}
480
Argyrios Kyrtzidiseb9ae762013-01-09 19:42:40 +0000481static void PrintStackTraceSignalHandler(void *) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000482 PrintStackTrace(llvm::errs());
Argyrios Kyrtzidiseb9ae762013-01-09 19:42:40 +0000483}
484
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000485void llvm::sys::DisableSystemDialogsOnCrash() {}
486
NAKAMURA Takumi8a54d812012-09-06 03:01:43 +0000487/// PrintStackTraceOnErrorSignal - When an error signal (such as SIGABRT or
Reid Spencer3d7a6142004-08-29 19:22:48 +0000488/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
Chris Lattnerbb1ba7b2009-03-08 19:13:45 +0000489void llvm::sys::PrintStackTraceOnErrorSignal() {
Craig Toppere73658d2014-04-28 04:05:08 +0000490 AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000491
Daniel Dunbareb6c7082013-08-30 20:39:21 +0000492#if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES)
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000493 // Environment variable to disable any kind of crash dialog.
494 if (getenv("LLVM_DISABLE_CRASH_REPORT")) {
495 mach_port_t self = mach_task_self();
496
497 exception_mask_t mask = EXC_MASK_CRASH;
498
NAKAMURA Takumiffa15712012-09-06 03:02:56 +0000499 kern_return_t ret = task_set_exception_ports(self,
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000500 mask,
Jean-Daniel Dupasa573b222012-03-24 22:17:50 +0000501 MACH_PORT_NULL,
NAKAMURA Takumiffa15712012-09-06 03:02:56 +0000502 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
Jean-Daniel Dupasa573b222012-03-24 22:17:50 +0000503 THREAD_STATE_NONE);
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000504 (void)ret;
505 }
506#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +0000507}
Chris Lattner4fdd0422009-03-04 21:21:36 +0000508
Daniel Dunbarf14d9462010-08-19 23:45:39 +0000509
510/***/
511
512// On Darwin, raise sends a signal to the main thread instead of the current
513// thread. This has the unfortunate effect that assert() and abort() will end up
514// bypassing our crash recovery attempts. We work around this for anything in
515// the same linkage unit by just defining our own versions of the assert handler
516// and abort.
517
Daniel Dunbareb6c7082013-08-30 20:39:21 +0000518#if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES)
Daniel Dunbarf14d9462010-08-19 23:45:39 +0000519
Douglas Gregor0e506822011-04-29 16:12:17 +0000520#include <signal.h>
521#include <pthread.h>
522
Daniel Dunbar18456f32010-09-22 17:46:10 +0000523int raise(int sig) {
Daniel Dunbarcc0e18d2010-10-08 18:31:34 +0000524 return pthread_kill(pthread_self(), sig);
Daniel Dunbar18456f32010-09-22 17:46:10 +0000525}
526
Daniel Dunbarf14d9462010-08-19 23:45:39 +0000527void __assert_rtn(const char *func,
528 const char *file,
529 int line,
530 const char *expr) {
531 if (func)
532 fprintf(stderr, "Assertion failed: (%s), function %s, file %s, line %d.\n",
533 expr, func, file, line);
534 else
535 fprintf(stderr, "Assertion failed: (%s), file %s, line %d.\n",
536 expr, file, line);
537 abort();
538}
539
Daniel Dunbarf14d9462010-08-19 23:45:39 +0000540void abort() {
Daniel Dunbar18456f32010-09-22 17:46:10 +0000541 raise(SIGABRT);
Daniel Dunbarf14d9462010-08-19 23:45:39 +0000542 usleep(1000);
543 __builtin_trap();
544}
545
546#endif