blob: aba0f1ddeee86c4ada53494ba6909a34be887f43 [file] [log] [blame]
Daniel Dunbar19a3b372010-07-28 15:40:20 +00001//===--- CrashRecoveryContext.cpp - Crash Recovery ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar9789f812010-07-29 01:52:04 +000011#include "llvm/Config/config.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000012#include "llvm/Support/ErrorHandling.h"
Filip Pizlof2189bf2013-09-12 17:46:57 +000013#include "llvm/Support/ManagedStatic.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000014#include "llvm/Support/Mutex.h"
15#include "llvm/Support/ThreadLocal.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include <setjmp.h>
Daniel Dunbar19a3b372010-07-28 15:40:20 +000017using namespace llvm;
18
19namespace {
20
21struct CrashRecoveryContextImpl;
22
Zachary Turnera40ccf62014-06-10 18:03:04 +000023static ManagedStatic<
24 sys::ThreadLocal<const CrashRecoveryContextImpl> > CurrentContext;
Daniel Dunbaraf77e222010-07-29 01:21:47 +000025
Daniel Dunbar19a3b372010-07-28 15:40:20 +000026struct CrashRecoveryContextImpl {
Daniel Dunbarb30266e2010-08-17 22:32:37 +000027 CrashRecoveryContext *CRC;
Daniel Dunbar19a3b372010-07-28 15:40:20 +000028 std::string Backtrace;
29 ::jmp_buf JumpBuffer;
30 volatile unsigned Failed : 1;
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000031 unsigned SwitchedThread : 1;
Daniel Dunbar19a3b372010-07-28 15:40:20 +000032
33public:
Daniel Dunbarb30266e2010-08-17 22:32:37 +000034 CrashRecoveryContextImpl(CrashRecoveryContext *CRC) : CRC(CRC),
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000035 Failed(false),
36 SwitchedThread(false) {
Filip Pizlof2189bf2013-09-12 17:46:57 +000037 CurrentContext->set(this);
Daniel Dunbaraf77e222010-07-29 01:21:47 +000038 }
39 ~CrashRecoveryContextImpl() {
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000040 if (!SwitchedThread)
Filip Pizlof2189bf2013-09-12 17:46:57 +000041 CurrentContext->erase();
Daniel Dunbaraf77e222010-07-29 01:21:47 +000042 }
Daniel Dunbar19a3b372010-07-28 15:40:20 +000043
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000044 /// \brief Called when the separate crash-recovery thread was finished, to
45 /// indicate that we don't need to clear the thread-local CurrentContext.
46 void setSwitchedThread() { SwitchedThread = true; }
47
Daniel Dunbar19a3b372010-07-28 15:40:20 +000048 void HandleCrash() {
Daniel Dunbar09b0c782010-08-17 22:32:39 +000049 // Eliminate the current context entry, to avoid re-entering in case the
50 // cleanup code crashes.
Filip Pizlof2189bf2013-09-12 17:46:57 +000051 CurrentContext->erase();
Daniel Dunbar09b0c782010-08-17 22:32:39 +000052
Daniel Dunbar19a3b372010-07-28 15:40:20 +000053 assert(!Failed && "Crash recovery context already failed!");
54 Failed = true;
55
56 // FIXME: Stash the backtrace.
57
58 // Jump back to the RunSafely we were called under.
59 longjmp(JumpBuffer, 1);
60 }
61};
62
63}
64
Filip Pizlof2189bf2013-09-12 17:46:57 +000065static ManagedStatic<sys::Mutex> gCrashRecoveryContextMutex;
Daniel Dunbar19a3b372010-07-28 15:40:20 +000066static bool gCrashRecoveryEnabled = false;
67
Filip Pizlof2189bf2013-09-12 17:46:57 +000068static ManagedStatic<sys::ThreadLocal<const CrashRecoveryContextCleanup> >
Ted Kremenekab1a2422011-03-21 18:38:03 +000069 tlIsRecoveringFromCrash;
70
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000071CrashRecoveryContextCleanup::~CrashRecoveryContextCleanup() {}
72
Daniel Dunbar19a3b372010-07-28 15:40:20 +000073CrashRecoveryContext::~CrashRecoveryContext() {
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000074 // Reclaim registered resources.
75 CrashRecoveryContextCleanup *i = head;
Filip Pizlof2189bf2013-09-12 17:46:57 +000076 tlIsRecoveringFromCrash->set(head);
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000077 while (i) {
78 CrashRecoveryContextCleanup *tmp = i;
79 i = tmp->next;
Ted Kremenek32aea2e2011-03-19 00:59:37 +000080 tmp->cleanupFired = true;
Ted Kremenek857e5352011-03-22 04:33:13 +000081 tmp->recoverResources();
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000082 delete tmp;
83 }
Filip Pizlof2189bf2013-09-12 17:46:57 +000084 tlIsRecoveringFromCrash->erase();
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000085
Daniel Dunbar19a3b372010-07-28 15:40:20 +000086 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
87 delete CRCI;
88}
89
Ted Kremenekab1a2422011-03-21 18:38:03 +000090bool CrashRecoveryContext::isRecoveringFromCrash() {
Craig Topperc10719f2014-04-07 04:17:22 +000091 return tlIsRecoveringFromCrash->get() != nullptr;
Ted Kremenekab1a2422011-03-21 18:38:03 +000092}
93
Daniel Dunbarb30266e2010-08-17 22:32:37 +000094CrashRecoveryContext *CrashRecoveryContext::GetCurrent() {
Ted Kremenek794a0712011-03-19 00:59:33 +000095 if (!gCrashRecoveryEnabled)
Craig Topperc10719f2014-04-07 04:17:22 +000096 return nullptr;
Ted Kremenek794a0712011-03-19 00:59:33 +000097
Filip Pizlof2189bf2013-09-12 17:46:57 +000098 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
Daniel Dunbarb30266e2010-08-17 22:32:37 +000099 if (!CRCI)
Craig Topperc10719f2014-04-07 04:17:22 +0000100 return nullptr;
Daniel Dunbarb30266e2010-08-17 22:32:37 +0000101
102 return CRCI->CRC;
103}
104
Ted Kremenekc44d3cf2011-03-18 02:05:11 +0000105void CrashRecoveryContext::registerCleanup(CrashRecoveryContextCleanup *cleanup)
106{
107 if (!cleanup)
108 return;
109 if (head)
110 head->prev = cleanup;
111 cleanup->next = head;
112 head = cleanup;
113}
114
115void
116CrashRecoveryContext::unregisterCleanup(CrashRecoveryContextCleanup *cleanup) {
117 if (!cleanup)
118 return;
119 if (cleanup == head) {
120 head = cleanup->next;
121 if (head)
Craig Topperc10719f2014-04-07 04:17:22 +0000122 head->prev = nullptr;
Ted Kremenekc44d3cf2011-03-18 02:05:11 +0000123 }
124 else {
125 cleanup->prev->next = cleanup->next;
126 if (cleanup->next)
127 cleanup->next->prev = cleanup->prev;
128 }
129 delete cleanup;
130}
131
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000132#ifdef LLVM_ON_WIN32
133
Reid Klecknerd59e2fa2014-02-12 21:26:20 +0000134#include "Windows/WindowsSupport.h"
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000135
136// On Windows, we can make use of vectored exception handling to
137// catch most crashing situations. Note that this does mean
138// we will be alerted of exceptions *before* structured exception
139// handling has the opportunity to catch it. But that isn't likely
140// to cause problems because nowhere in the project is SEH being
141// used.
142//
143// Vectored exception handling is built on top of SEH, and so it
144// works on a per-thread basis.
145//
146// The vectored exception handler functionality was added in Windows
147// XP, so if support for older versions of Windows is required,
148// it will have to be added.
149//
150// If we want to support as far back as Win2k, we could use the
151// SetUnhandledExceptionFilter API, but there's a risk of that
152// being entirely overwritten (it's not a chain).
153
154static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
155{
156 // Lookup the current thread local recovery object.
Filip Pizlof2189bf2013-09-12 17:46:57 +0000157 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000158
159 if (!CRCI) {
160 // Something has gone horribly wrong, so let's just tell everyone
161 // to keep searching
162 CrashRecoveryContext::Disable();
163 return EXCEPTION_CONTINUE_SEARCH;
164 }
165
166 // TODO: We can capture the stack backtrace here and store it on the
167 // implementation if we so choose.
168
169 // Handle the crash
170 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
171
172 // Note that we don't actually get here because HandleCrash calls
173 // longjmp, which means the HandleCrash function never returns.
174 llvm_unreachable("Handled the crash, should have longjmp'ed out of here");
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000175}
176
177// Because the Enable and Disable calls are static, it means that
178// there may not actually be an Impl available, or even a current
179// CrashRecoveryContext at all. So we make use of a thread-local
180// exception table. The handles contained in here will either be
181// non-NULL, valid VEH handles, or NULL.
182static sys::ThreadLocal<const void> sCurrentExceptionHandle;
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000183
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000184void CrashRecoveryContext::Enable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000185 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000186
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000187 if (gCrashRecoveryEnabled)
188 return;
189
190 gCrashRecoveryEnabled = true;
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000191
192 // We can set up vectored exception handling now. We will install our
193 // handler as the front of the list, though there's no assurances that
194 // it will remain at the front (another call could install itself before
195 // our handler). This 1) isn't likely, and 2) shouldn't cause problems.
196 PVOID handle = ::AddVectoredExceptionHandler(1, ExceptionHandler);
197 sCurrentExceptionHandle.set(handle);
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000198}
199
200void CrashRecoveryContext::Disable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000201 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000202
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000203 if (!gCrashRecoveryEnabled)
204 return;
205
206 gCrashRecoveryEnabled = false;
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000207
208 PVOID currentHandle = const_cast<PVOID>(sCurrentExceptionHandle.get());
209 if (currentHandle) {
210 // Now we can remove the vectored exception handler from the chain
211 ::RemoveVectoredExceptionHandler(currentHandle);
212
213 // Reset the handle in our thread-local set.
214 sCurrentExceptionHandle.set(NULL);
215 }
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000216}
217
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000218#else
219
220// Generic POSIX implementation.
221//
222// This implementation relies on synchronous signals being delivered to the
223// current thread. We use a thread local object to keep track of the active
224// crash recovery context, and install signal handlers to invoke HandleCrash on
225// the active object.
226//
227// This implementation does not to attempt to chain signal handlers in any
228// reliable fashion -- if we get a signal outside of a crash recovery context we
229// simply disable crash recovery and raise the signal again.
230
231#include <signal.h>
232
Zachary Turnera40ccf62014-06-10 18:03:04 +0000233static const int Signals[] =
234 { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP };
Daniel Dunbarc90e82a2010-07-30 17:49:04 +0000235static const unsigned NumSignals = sizeof(Signals) / sizeof(Signals[0]);
236static struct sigaction PrevActions[NumSignals];
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000237
238static void CrashRecoverySignalHandler(int Signal) {
239 // Lookup the current thread local recovery object.
Filip Pizlof2189bf2013-09-12 17:46:57 +0000240 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000241
242 if (!CRCI) {
243 // We didn't find a crash recovery context -- this means either we got a
244 // signal on a thread we didn't expect it on, the application got a signal
245 // outside of a crash recovery context, or something else went horribly
246 // wrong.
247 //
248 // Disable crash recovery and raise the signal again. The assumption here is
249 // that the enclosing application will terminate soon, and we won't want to
250 // attempt crash recovery again.
251 //
252 // This call of Disable isn't thread safe, but it doesn't actually matter.
253 CrashRecoveryContext::Disable();
254 raise(Signal);
Daniel Dunbar418e7042010-10-18 21:55:18 +0000255
256 // The signal will be thrown once the signal mask is restored.
257 return;
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000258 }
259
260 // Unblock the signal we received.
261 sigset_t SigMask;
262 sigemptyset(&SigMask);
263 sigaddset(&SigMask, Signal);
Craig Topperc10719f2014-04-07 04:17:22 +0000264 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000265
266 if (CRCI)
267 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
268}
269
270void CrashRecoveryContext::Enable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000271 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000272
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000273 if (gCrashRecoveryEnabled)
274 return;
275
276 gCrashRecoveryEnabled = true;
277
278 // Setup the signal handler.
279 struct sigaction Handler;
280 Handler.sa_handler = CrashRecoverySignalHandler;
281 Handler.sa_flags = 0;
282 sigemptyset(&Handler.sa_mask);
283
284 for (unsigned i = 0; i != NumSignals; ++i) {
Daniel Dunbarc90e82a2010-07-30 17:49:04 +0000285 sigaction(Signals[i], &Handler, &PrevActions[i]);
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000286 }
287}
288
289void CrashRecoveryContext::Disable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000290 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000291
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000292 if (!gCrashRecoveryEnabled)
293 return;
294
295 gCrashRecoveryEnabled = false;
296
297 // Restore the previous signal handlers.
298 for (unsigned i = 0; i != NumSignals; ++i)
Craig Topperc10719f2014-04-07 04:17:22 +0000299 sigaction(Signals[i], &PrevActions[i], nullptr);
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000300}
301
302#endif
303
Richard Smithc167d652014-05-06 01:44:26 +0000304bool CrashRecoveryContext::RunSafely(function_ref<void()> Fn) {
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000305 // If crash recovery is disabled, do nothing.
306 if (gCrashRecoveryEnabled) {
307 assert(!Impl && "Crash recovery context already initialized!");
Daniel Dunbarb30266e2010-08-17 22:32:37 +0000308 CrashRecoveryContextImpl *CRCI = new CrashRecoveryContextImpl(this);
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000309 Impl = CRCI;
310
311 if (setjmp(CRCI->JumpBuffer) != 0) {
312 return false;
313 }
314 }
315
Richard Smithc167d652014-05-06 01:44:26 +0000316 Fn();
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000317 return true;
318}
319
320void CrashRecoveryContext::HandleCrash() {
321 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
322 assert(CRCI && "Crash recovery context never initialized!");
323 CRCI->HandleCrash();
324}
325
326const std::string &CrashRecoveryContext::getBacktrace() const {
327 CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *) Impl;
328 assert(CRC && "Crash recovery context never initialized!");
329 assert(CRC->Failed && "No crash was detected!");
330 return CRC->Backtrace;
331}
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000332
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000333// FIXME: Portability.
334static void setThreadBackgroundPriority() {
335#ifdef __APPLE__
336 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
337#endif
338}
339
340static bool hasThreadBackgroundPriority() {
341#ifdef __APPLE__
342 return getpriority(PRIO_DARWIN_THREAD, 0) == 1;
343#else
344 return false;
345#endif
346}
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000347
348namespace {
349struct RunSafelyOnThreadInfo {
Richard Smithc167d652014-05-06 01:44:26 +0000350 function_ref<void()> Fn;
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000351 CrashRecoveryContext *CRC;
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000352 bool UseBackgroundPriority;
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000353 bool Result;
354};
355}
356
357static void RunSafelyOnThread_Dispatch(void *UserData) {
358 RunSafelyOnThreadInfo *Info =
359 reinterpret_cast<RunSafelyOnThreadInfo*>(UserData);
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000360
361 if (Info->UseBackgroundPriority)
362 setThreadBackgroundPriority();
363
Richard Smithc167d652014-05-06 01:44:26 +0000364 Info->Result = Info->CRC->RunSafely(Info->Fn);
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000365}
Richard Smithc167d652014-05-06 01:44:26 +0000366bool CrashRecoveryContext::RunSafelyOnThread(function_ref<void()> Fn,
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000367 unsigned RequestedStackSize) {
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000368 bool UseBackgroundPriority = hasThreadBackgroundPriority();
369 RunSafelyOnThreadInfo Info = { Fn, this, UseBackgroundPriority, false };
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000370 llvm_execute_on_thread(RunSafelyOnThread_Dispatch, &Info, RequestedStackSize);
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +0000371 if (CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *)Impl)
372 CRC->setSwitchedThread();
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000373 return Info.Result;
374}