blob: cf64fa8f38537bd925b1098992e7fb63f238f469 [file] [log] [blame]
Reid Spencer496c2772004-08-29 19:22:48 +00001//===- Signals.cpp - Generic Unix Signals Implementation -----*- C++ -*-===//
Michael J. Spencer1f6efa32010-11-29 18:16:10 +00002//
Reid Spencer496c2772004-08-29 19:22:48 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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. Spencer1f6efa32010-11-29 18:16:10 +00007//
Reid Spencer496c2772004-08-29 19:22:48 +00008//===----------------------------------------------------------------------===//
9//
10// This file defines some helpful functions for dealing with the possibility of
Chris Lattner7a2bdde2011-04-15 05:18:47 +000011// Unix signals occurring while your program is running.
Reid Spencer496c2772004-08-29 19:22:48 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "Unix.h"
Owen Anderson718cb662007-09-07 04:06:50 +000016#include "llvm/ADT/STLExtras.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000017#include "llvm/Support/Mutex.h"
Chandler Carruth0b8b3ba2012-06-16 00:09:41 +000018#include <string>
Reid Spencer496c2772004-08-29 19:22:48 +000019#include <vector>
20#include <algorithm>
Reid Spencercdf54d02004-12-27 06:16:52 +000021#if HAVE_EXECINFO_H
Reid Spencer496c2772004-08-29 19:22:48 +000022# include <execinfo.h> // For backtrace().
23#endif
Reid Spencercdf54d02004-12-27 06:16:52 +000024#if HAVE_SIGNAL_H
Reid Spencer496c2772004-08-29 19:22:48 +000025#include <signal.h>
Reid Spencercdf54d02004-12-27 06:16:52 +000026#endif
Reid Spencer2ae9d112007-04-07 18:52:17 +000027#if HAVE_SYS_STAT_H
28#include <sys/stat.h>
29#endif
Dan Gohman56d9b6d2008-12-05 20:12:48 +000030#if HAVE_DLFCN_H && __GNUG__
31#include <dlfcn.h>
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000032#include <cxxabi.h>
Dan Gohman56d9b6d2008-12-05 20:12:48 +000033#endif
Argyrios Kyrtzidis08713b32012-01-11 20:53:25 +000034#if HAVE_MACH_MACH_H
35#include <mach/mach.h>
36#endif
37
Chris Lattner89615012006-08-01 17:59:14 +000038using namespace llvm;
Reid Spencer496c2772004-08-29 19:22:48 +000039
Chris Lattner1c4d8a02009-03-23 05:42:29 +000040static RETSIGTYPE SignalHandler(int Sig); // defined below.
41
Owen Anderson6ae8c732009-08-17 17:07:22 +000042static SmartMutex<true> SignalsMutex;
43
Chris Lattnerfa8c2922005-08-02 02:14:22 +000044/// InterruptFunction - The function to call if ctrl-c is pressed.
Dan Gohman3bd659b2008-04-10 21:11:47 +000045static void (*InterruptFunction)() = 0;
Chris Lattnerfa8c2922005-08-02 02:14:22 +000046
Chandler Carruth0b8b3ba2012-06-16 00:09:41 +000047static std::vector<std::string> FilesToRemove;
Jeffrey Yasskinb7ccf752010-03-17 07:08:12 +000048static std::vector<std::pair<void(*)(void*), void*> > CallBacksToRun;
Reid Spencer496c2772004-08-29 19:22:48 +000049
50// IntSigs - Signals that may interrupt the program at any time.
Dan Gohman3bd659b2008-04-10 21:11:47 +000051static const int IntSigs[] = {
Reid Spencer496c2772004-08-29 19:22:48 +000052 SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
53};
Dan Gohman4d9dd6b2008-05-14 00:42:30 +000054static const int *const IntSigsEnd =
55 IntSigs + sizeof(IntSigs) / sizeof(IntSigs[0]);
Reid Spencer496c2772004-08-29 19:22:48 +000056
57// KillSigs - Signals that are synchronous with the program that will cause it
58// to die.
Dan Gohman3bd659b2008-04-10 21:11:47 +000059static const int KillSigs[] = {
Chris Lattner6ae7bbb2010-02-12 00:37:46 +000060 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV
61#ifdef SIGSYS
62 , SIGSYS
63#endif
64#ifdef SIGXCPU
65 , SIGXCPU
66#endif
Chris Lattner782ab582010-02-14 18:20:09 +000067#ifdef SIGXFSZ
Chris Lattner6ae7bbb2010-02-12 00:37:46 +000068 , SIGXFSZ
69#endif
Reid Spencer496c2772004-08-29 19:22:48 +000070#ifdef SIGEMT
71 , SIGEMT
72#endif
73};
Dan Gohman4d9dd6b2008-05-14 00:42:30 +000074static const int *const KillSigsEnd =
75 KillSigs + sizeof(KillSigs) / sizeof(KillSigs[0]);
Reid Spencer496c2772004-08-29 19:22:48 +000076
Chris Lattnereab5cb32009-03-23 05:55:36 +000077static unsigned NumRegisteredSignals = 0;
78static struct {
79 struct sigaction SA;
80 int SigNo;
81} RegisteredSignalInfo[(sizeof(IntSigs)+sizeof(KillSigs))/sizeof(KillSigs[0])];
82
83
Chris Lattner1c4d8a02009-03-23 05:42:29 +000084static void RegisterHandler(int Signal) {
Chris Lattnereab5cb32009-03-23 05:55:36 +000085 assert(NumRegisteredSignals <
86 sizeof(RegisteredSignalInfo)/sizeof(RegisteredSignalInfo[0]) &&
87 "Out of space for signal handlers!");
88
89 struct sigaction NewHandler;
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000090
Chris Lattnereab5cb32009-03-23 05:55:36 +000091 NewHandler.sa_handler = SignalHandler;
92 NewHandler.sa_flags = SA_NODEFER|SA_RESETHAND;
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000093 sigemptyset(&NewHandler.sa_mask);
94
Chris Lattnereab5cb32009-03-23 05:55:36 +000095 // Install the new handler, save the old one in RegisteredSignalInfo.
96 sigaction(Signal, &NewHandler,
97 &RegisteredSignalInfo[NumRegisteredSignals].SA);
98 RegisteredSignalInfo[NumRegisteredSignals].SigNo = Signal;
99 ++NumRegisteredSignals;
Chris Lattner922a8812009-03-07 08:15:47 +0000100}
101
Chris Lattner1c4d8a02009-03-23 05:42:29 +0000102static void RegisterHandlers() {
Chris Lattnereab5cb32009-03-23 05:55:36 +0000103 // If the handlers are already registered, we're done.
104 if (NumRegisteredSignals != 0) return;
105
Chris Lattner1c4d8a02009-03-23 05:42:29 +0000106 std::for_each(IntSigs, IntSigsEnd, RegisterHandler);
107 std::for_each(KillSigs, KillSigsEnd, RegisterHandler);
108}
109
Chris Lattner1c4d8a02009-03-23 05:42:29 +0000110static void UnregisterHandlers() {
Chris Lattnereab5cb32009-03-23 05:55:36 +0000111 // Restore all of the signal handlers to how they were before we showed up.
112 for (unsigned i = 0, e = NumRegisteredSignals; i != e; ++i)
Chris Lattnera8bd27f2009-03-23 06:46:20 +0000113 sigaction(RegisteredSignalInfo[i].SigNo,
114 &RegisteredSignalInfo[i].SA, 0);
Chris Lattnereab5cb32009-03-23 05:55:36 +0000115 NumRegisteredSignals = 0;
Chris Lattner1c4d8a02009-03-23 05:42:29 +0000116}
117
118
Dan Gohman39f76bb2010-05-27 23:11:55 +0000119/// RemoveFilesToRemove - Process the FilesToRemove list. This function
120/// should be called with the SignalsMutex lock held.
Chandler Carruth0b8b3ba2012-06-16 00:09:41 +0000121/// NB: This must be an async signal safe function. It cannot allocate or free
122/// memory, even in debug builds.
Dan Gohman39f76bb2010-05-27 23:11:55 +0000123static void RemoveFilesToRemove() {
Chandler Carruth0b8b3ba2012-06-16 00:09:41 +0000124 // Note: avoid iterators in case of debug iterators that allocate or release
125 // memory.
126 for (unsigned i = 0, e = FilesToRemove.size(); i != e; ++i) {
127 // Note that we don't want to use any external code here, and we don't care
128 // about errors. We're going to try as hard as we can as often as we need
129 // to to make these files go away. If these aren't files, too bad.
130 //
131 // We do however rely on a std::string implementation for which repeated
132 // calls to 'c_str()' don't allocate memory. We pre-call 'c_str()' on all
133 // of these strings to try to ensure this is safe.
134 unlink(FilesToRemove[i].c_str());
Dan Gohman39f76bb2010-05-27 23:11:55 +0000135 }
136}
Chris Lattner922a8812009-03-07 08:15:47 +0000137
138// SignalHandler - The signal handler that runs.
Chris Lattner35033a52009-03-04 21:21:36 +0000139static RETSIGTYPE SignalHandler(int Sig) {
Chris Lattner0f6290d2009-03-05 18:22:14 +0000140 // Restore the signal behavior to default, so that the program actually
141 // crashes when we return and the signal reissues. This also ensures that if
142 // we crash in our signal handler that the program will terminate immediately
143 // instead of recursing in the signal handler.
Chris Lattner1c4d8a02009-03-23 05:42:29 +0000144 UnregisterHandlers();
Chris Lattner922a8812009-03-07 08:15:47 +0000145
146 // Unmask all potentially blocked kill signals.
147 sigset_t SigMask;
148 sigfillset(&SigMask);
149 sigprocmask(SIG_UNBLOCK, &SigMask, 0);
Chris Lattner0f6290d2009-03-05 18:22:14 +0000150
Owen Anderson6ae8c732009-08-17 17:07:22 +0000151 SignalsMutex.acquire();
Dan Gohman39f76bb2010-05-27 23:11:55 +0000152 RemoveFilesToRemove();
Chris Lattner35033a52009-03-04 21:21:36 +0000153
154 if (std::find(IntSigs, IntSigsEnd, Sig) != IntSigsEnd) {
155 if (InterruptFunction) {
156 void (*IF)() = InterruptFunction;
Owen Anderson6ae8c732009-08-17 17:07:22 +0000157 SignalsMutex.release();
Chris Lattner35033a52009-03-04 21:21:36 +0000158 InterruptFunction = 0;
159 IF(); // run the interrupt function.
160 return;
161 }
Michael J. Spencer1f6efa32010-11-29 18:16:10 +0000162
Owen Anderson6ae8c732009-08-17 17:07:22 +0000163 SignalsMutex.release();
Chris Lattnerb7253152009-04-12 23:33:13 +0000164 raise(Sig); // Execute the default handler.
165 return;
Chris Lattner35033a52009-03-04 21:21:36 +0000166 }
167
Owen Anderson6ae8c732009-08-17 17:07:22 +0000168 SignalsMutex.release();
169
Chris Lattner35033a52009-03-04 21:21:36 +0000170 // Otherwise if it is a fault (like SEGV) run any handler.
Jeffrey Yasskinb7ccf752010-03-17 07:08:12 +0000171 for (unsigned i = 0, e = CallBacksToRun.size(); i != e; ++i)
172 CallBacksToRun[i].first(CallBacksToRun[i].second);
Chris Lattner35033a52009-03-04 21:21:36 +0000173}
174
Daniel Dunbarfb89e082010-05-08 02:10:34 +0000175void llvm::sys::RunInterruptHandlers() {
Dan Gohman39f76bb2010-05-27 23:11:55 +0000176 SignalsMutex.acquire();
177 RemoveFilesToRemove();
178 SignalsMutex.release();
Daniel Dunbarfb89e082010-05-08 02:10:34 +0000179}
Chris Lattner35033a52009-03-04 21:21:36 +0000180
Chris Lattnerf48ba7b2009-03-08 19:13:45 +0000181void llvm::sys::SetInterruptFunction(void (*IF)()) {
Owen Anderson6ae8c732009-08-17 17:07:22 +0000182 SignalsMutex.acquire();
Chris Lattner35033a52009-03-04 21:21:36 +0000183 InterruptFunction = IF;
Owen Anderson6ae8c732009-08-17 17:07:22 +0000184 SignalsMutex.release();
Chris Lattner1c4d8a02009-03-23 05:42:29 +0000185 RegisterHandlers();
Chris Lattner35033a52009-03-04 21:21:36 +0000186}
187
188// RemoveFileOnSignal - The public API
Chris Lattnerf48ba7b2009-03-08 19:13:45 +0000189bool llvm::sys::RemoveFileOnSignal(const sys::Path &Filename,
190 std::string* ErrMsg) {
Owen Anderson6ae8c732009-08-17 17:07:22 +0000191 SignalsMutex.acquire();
Chandler Carruth29436622012-06-16 00:44:07 +0000192 std::string *OldPtr = FilesToRemove.empty() ? 0 : &FilesToRemove[0];
Chandler Carruth0b8b3ba2012-06-16 00:09:41 +0000193 FilesToRemove.push_back(Filename.str());
194
195 // We want to call 'c_str()' on every std::string in this vector so that if
196 // the underlying implementation requires a re-allocation, it happens here
197 // rather than inside of the signal handler. If we see the vector grow, we
198 // have to call it on every entry. If it remains in place, we only need to
199 // call it on the latest one.
200 if (OldPtr == &FilesToRemove[0])
201 FilesToRemove.back().c_str();
202 else
203 for (unsigned i = 0, e = FilesToRemove.size(); i != e; ++i)
204 FilesToRemove[i].c_str();
Chris Lattner35033a52009-03-04 21:21:36 +0000205
Owen Anderson6ae8c732009-08-17 17:07:22 +0000206 SignalsMutex.release();
207
Chris Lattner1c4d8a02009-03-23 05:42:29 +0000208 RegisterHandlers();
Chris Lattner35033a52009-03-04 21:21:36 +0000209 return false;
210}
211
Dan Gohman41154112010-09-01 14:17:34 +0000212// DontRemoveFileOnSignal - The public API
213void llvm::sys::DontRemoveFileOnSignal(const sys::Path &Filename) {
214 SignalsMutex.acquire();
Chandler Carruth0b8b3ba2012-06-16 00:09:41 +0000215 std::vector<std::string>::reverse_iterator RI =
216 std::find(FilesToRemove.rbegin(), FilesToRemove.rend(), Filename.str());
217 std::vector<std::string>::iterator I = FilesToRemove.end();
218 if (RI != FilesToRemove.rend())
219 I = FilesToRemove.erase(RI.base()-1);
220
221 // We need to call c_str() on every element which would have been moved by
222 // the erase. These elements, in a C++98 implementation where c_str()
223 // requires a reallocation on the first call may have had the call to c_str()
224 // made on insertion become invalid by being copied down an element.
225 for (std::vector<std::string>::iterator E = FilesToRemove.end(); I != E; ++I)
226 I->c_str();
227
Dan Gohman41154112010-09-01 14:17:34 +0000228 SignalsMutex.release();
229}
230
Chris Lattner35033a52009-03-04 21:21:36 +0000231/// AddSignalHandler - Add a function to be called when a signal is delivered
232/// to the process. The handler can have a cookie passed to it to identify
233/// what instance of the handler it is.
Chris Lattnerf48ba7b2009-03-08 19:13:45 +0000234void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
Jeffrey Yasskinb7ccf752010-03-17 07:08:12 +0000235 CallBacksToRun.push_back(std::make_pair(FnPtr, Cookie));
Chris Lattner1c4d8a02009-03-23 05:42:29 +0000236 RegisterHandlers();
Chris Lattner35033a52009-03-04 21:21:36 +0000237}
238
Reid Spencer496c2772004-08-29 19:22:48 +0000239
240// PrintStackTrace - In the case of a program crash or fault, print out a stack
241// trace so that the user has an indication of why and where we died.
242//
243// On glibc systems we have the 'backtrace' function, which works nicely, but
Michael J. Spencer1f6efa32010-11-29 18:16:10 +0000244// doesn't demangle symbols.
Chris Lattner35033a52009-03-04 21:21:36 +0000245static void PrintStackTrace(void *) {
Benjamin Kramer53347ed2012-09-28 10:10:46 +0000246#if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
Chris Lattner35033a52009-03-04 21:21:36 +0000247 static void* StackTrace[256];
Reid Spencer496c2772004-08-29 19:22:48 +0000248 // Use backtrace() to output a backtrace on Linux systems with glibc.
Evan Cheng34cd4a42008-05-05 18:30:58 +0000249 int depth = backtrace(StackTrace,
250 static_cast<int>(array_lengthof(StackTrace)));
Dan Gohman56d9b6d2008-12-05 20:12:48 +0000251#if HAVE_DLFCN_H && __GNUG__
252 int width = 0;
253 for (int i = 0; i < depth; ++i) {
254 Dl_info dlinfo;
255 dladdr(StackTrace[i], &dlinfo);
Dan Gohmand4e18452009-02-10 17:56:28 +0000256 const char* name = strrchr(dlinfo.dli_fname, '/');
Dan Gohman56d9b6d2008-12-05 20:12:48 +0000257
258 int nwidth;
259 if (name == NULL) nwidth = strlen(dlinfo.dli_fname);
260 else nwidth = strlen(name) - 1;
261
262 if (nwidth > width) width = nwidth;
263 }
264
265 for (int i = 0; i < depth; ++i) {
266 Dl_info dlinfo;
267 dladdr(StackTrace[i], &dlinfo);
268
Dan Gohman0b81e192009-10-30 02:45:10 +0000269 fprintf(stderr, "%-2d", i);
Dan Gohman56d9b6d2008-12-05 20:12:48 +0000270
Dan Gohmand4e18452009-02-10 17:56:28 +0000271 const char* name = strrchr(dlinfo.dli_fname, '/');
Dan Gohman56d9b6d2008-12-05 20:12:48 +0000272 if (name == NULL) fprintf(stderr, " %-*s", width, dlinfo.dli_fname);
273 else fprintf(stderr, " %-*s", width, name+1);
274
Dan Gohmandd17b252008-12-05 23:39:24 +0000275 fprintf(stderr, " %#0*lx",
276 (int)(sizeof(void*) * 2) + 2, (unsigned long)StackTrace[i]);
Dan Gohman56d9b6d2008-12-05 20:12:48 +0000277
278 if (dlinfo.dli_sname != NULL) {
279 int res;
280 fputc(' ', stderr);
281 char* d = abi::__cxa_demangle(dlinfo.dli_sname, NULL, NULL, &res);
282 if (d == NULL) fputs(dlinfo.dli_sname, stderr);
283 else fputs(d, stderr);
284 free(d);
285
286 fprintf(stderr, " + %tu",(char*)StackTrace[i]-(char*)dlinfo.dli_saddr);
287 }
288 fputc('\n', stderr);
289 }
290#else
Lauro Ramos Venancio2e78b782008-02-15 18:05:54 +0000291 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
Reid Spencer496c2772004-08-29 19:22:48 +0000292#endif
Dan Gohman56d9b6d2008-12-05 20:12:48 +0000293#endif
Reid Spencer496c2772004-08-29 19:22:48 +0000294}
295
NAKAMURA Takumi383fb7f2012-09-06 03:01:43 +0000296/// PrintStackTraceOnErrorSignal - When an error signal (such as SIGABRT or
Reid Spencer496c2772004-08-29 19:22:48 +0000297/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
Chris Lattnerf48ba7b2009-03-08 19:13:45 +0000298void llvm::sys::PrintStackTraceOnErrorSignal() {
Chris Lattner35033a52009-03-04 21:21:36 +0000299 AddSignalHandler(PrintStackTrace, 0);
Argyrios Kyrtzidis08713b32012-01-11 20:53:25 +0000300
301#if defined(__APPLE__)
302 // Environment variable to disable any kind of crash dialog.
303 if (getenv("LLVM_DISABLE_CRASH_REPORT")) {
304 mach_port_t self = mach_task_self();
305
306 exception_mask_t mask = EXC_MASK_CRASH;
307
NAKAMURA Takumi2de91672012-09-06 03:02:56 +0000308 kern_return_t ret = task_set_exception_ports(self,
Argyrios Kyrtzidis08713b32012-01-11 20:53:25 +0000309 mask,
Jean-Daniel Dupas300361a2012-03-24 22:17:50 +0000310 MACH_PORT_NULL,
NAKAMURA Takumi2de91672012-09-06 03:02:56 +0000311 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
Jean-Daniel Dupas300361a2012-03-24 22:17:50 +0000312 THREAD_STATE_NONE);
Argyrios Kyrtzidis08713b32012-01-11 20:53:25 +0000313 (void)ret;
314 }
315#endif
Reid Spencer496c2772004-08-29 19:22:48 +0000316}
Chris Lattner35033a52009-03-04 21:21:36 +0000317
Daniel Dunbarb08ceb82010-08-19 23:45:39 +0000318
319/***/
320
321// On Darwin, raise sends a signal to the main thread instead of the current
322// thread. This has the unfortunate effect that assert() and abort() will end up
323// bypassing our crash recovery attempts. We work around this for anything in
324// the same linkage unit by just defining our own versions of the assert handler
325// and abort.
326
327#ifdef __APPLE__
328
Douglas Gregor72d30f62011-04-29 16:12:17 +0000329#include <signal.h>
330#include <pthread.h>
331
Daniel Dunbare4e06a82010-09-22 17:46:10 +0000332int raise(int sig) {
Daniel Dunbar95b46722010-10-08 18:31:34 +0000333 return pthread_kill(pthread_self(), sig);
Daniel Dunbare4e06a82010-09-22 17:46:10 +0000334}
335
Daniel Dunbarb08ceb82010-08-19 23:45:39 +0000336void __assert_rtn(const char *func,
337 const char *file,
338 int line,
339 const char *expr) {
340 if (func)
341 fprintf(stderr, "Assertion failed: (%s), function %s, file %s, line %d.\n",
342 expr, func, file, line);
343 else
344 fprintf(stderr, "Assertion failed: (%s), file %s, line %d.\n",
345 expr, file, line);
346 abort();
347}
348
Daniel Dunbarb08ceb82010-08-19 23:45:39 +0000349void abort() {
Daniel Dunbare4e06a82010-09-22 17:46:10 +0000350 raise(SIGABRT);
Daniel Dunbarb08ceb82010-08-19 23:45:39 +0000351 usleep(1000);
352 __builtin_trap();
353}
354
355#endif