blob: 98865f5e065e7ff664ac055974f33cfb7c480c86 [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"
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000016#include <setjmp.h>
Daniel Dunbar19a3b372010-07-28 15:40:20 +000017using namespace llvm;
18
19namespace {
20
21struct CrashRecoveryContextImpl;
22
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000023static ManagedStatic<
Zachary Turnera40ccf62014-06-10 18:03:04 +000024 sys::ThreadLocal<const CrashRecoveryContextImpl> > CurrentContext;
Daniel Dunbaraf77e222010-07-29 01:21:47 +000025
Daniel Dunbar19a3b372010-07-28 15:40:20 +000026struct CrashRecoveryContextImpl {
Nico Weber26928112015-08-07 17:32:06 +000027 // When threads are disabled, this links up all active
28 // CrashRecoveryContextImpls. When threads are enabled there's one thread
29 // per CrashRecoveryContext and CurrentContext is a thread-local, so only one
30 // CrashRecoveryContextImpl is active per thread and this is always null.
Nico Weber28dc4172015-08-06 19:21:25 +000031 const CrashRecoveryContextImpl *Next;
32
Daniel Dunbarb30266e2010-08-17 22:32:37 +000033 CrashRecoveryContext *CRC;
Daniel Dunbar19a3b372010-07-28 15:40:20 +000034 ::jmp_buf JumpBuffer;
35 volatile unsigned Failed : 1;
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000036 unsigned SwitchedThread : 1;
Daniel Dunbar19a3b372010-07-28 15:40:20 +000037
38public:
Daniel Dunbarb30266e2010-08-17 22:32:37 +000039 CrashRecoveryContextImpl(CrashRecoveryContext *CRC) : CRC(CRC),
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000040 Failed(false),
41 SwitchedThread(false) {
Nico Weber28dc4172015-08-06 19:21:25 +000042 Next = CurrentContext->get();
Filip Pizlof2189bf2013-09-12 17:46:57 +000043 CurrentContext->set(this);
Daniel Dunbaraf77e222010-07-29 01:21:47 +000044 }
45 ~CrashRecoveryContextImpl() {
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000046 if (!SwitchedThread)
Nico Weber28dc4172015-08-06 19:21:25 +000047 CurrentContext->set(Next);
Daniel Dunbaraf77e222010-07-29 01:21:47 +000048 }
Daniel Dunbar19a3b372010-07-28 15:40:20 +000049
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000050 /// \brief Called when the separate crash-recovery thread was finished, to
51 /// indicate that we don't need to clear the thread-local CurrentContext.
Nico Weber28dc4172015-08-06 19:21:25 +000052 void setSwitchedThread() {
53#if defined(LLVM_ENABLE_THREADS) && LLVM_ENABLE_THREADS != 0
54 SwitchedThread = true;
55#endif
56 }
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000057
Daniel Dunbar19a3b372010-07-28 15:40:20 +000058 void HandleCrash() {
Daniel Dunbar09b0c782010-08-17 22:32:39 +000059 // Eliminate the current context entry, to avoid re-entering in case the
60 // cleanup code crashes.
Nico Weber28dc4172015-08-06 19:21:25 +000061 CurrentContext->set(Next);
Daniel Dunbar09b0c782010-08-17 22:32:39 +000062
Daniel Dunbar19a3b372010-07-28 15:40:20 +000063 assert(!Failed && "Crash recovery context already failed!");
64 Failed = true;
65
66 // FIXME: Stash the backtrace.
67
68 // Jump back to the RunSafely we were called under.
69 longjmp(JumpBuffer, 1);
70 }
71};
72
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000073}
Daniel Dunbar19a3b372010-07-28 15:40:20 +000074
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000075static ManagedStatic<sys::Mutex> gCrashRecoveryContextMutex;
76static bool gCrashRecoveryEnabled = false;
77
78static ManagedStatic<sys::ThreadLocal<const CrashRecoveryContext>>
Ted Kremenekab1a2422011-03-21 18:38:03 +000079 tlIsRecoveringFromCrash;
80
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000081CrashRecoveryContextCleanup::~CrashRecoveryContextCleanup() {}
82
Daniel Dunbar19a3b372010-07-28 15:40:20 +000083CrashRecoveryContext::~CrashRecoveryContext() {
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000084 // Reclaim registered resources.
85 CrashRecoveryContextCleanup *i = head;
Nico Weber28dc4172015-08-06 19:21:25 +000086 const CrashRecoveryContext *PC = tlIsRecoveringFromCrash->get();
87 tlIsRecoveringFromCrash->set(this);
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000088 while (i) {
89 CrashRecoveryContextCleanup *tmp = i;
90 i = tmp->next;
Ted Kremenek32aea2e2011-03-19 00:59:37 +000091 tmp->cleanupFired = true;
Ted Kremenek857e5352011-03-22 04:33:13 +000092 tmp->recoverResources();
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000093 delete tmp;
94 }
Nico Weber28dc4172015-08-06 19:21:25 +000095 tlIsRecoveringFromCrash->set(PC);
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000096
Daniel Dunbar19a3b372010-07-28 15:40:20 +000097 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
98 delete CRCI;
99}
100
Ted Kremenekab1a2422011-03-21 18:38:03 +0000101bool CrashRecoveryContext::isRecoveringFromCrash() {
Craig Topperc10719f2014-04-07 04:17:22 +0000102 return tlIsRecoveringFromCrash->get() != nullptr;
Ted Kremenekab1a2422011-03-21 18:38:03 +0000103}
104
Daniel Dunbarb30266e2010-08-17 22:32:37 +0000105CrashRecoveryContext *CrashRecoveryContext::GetCurrent() {
Ted Kremenek794a0712011-03-19 00:59:33 +0000106 if (!gCrashRecoveryEnabled)
Craig Topperc10719f2014-04-07 04:17:22 +0000107 return nullptr;
Ted Kremenek794a0712011-03-19 00:59:33 +0000108
Filip Pizlof2189bf2013-09-12 17:46:57 +0000109 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
Daniel Dunbarb30266e2010-08-17 22:32:37 +0000110 if (!CRCI)
Craig Topperc10719f2014-04-07 04:17:22 +0000111 return nullptr;
Daniel Dunbarb30266e2010-08-17 22:32:37 +0000112
113 return CRCI->CRC;
114}
115
Ted Kremenekc44d3cf2011-03-18 02:05:11 +0000116void CrashRecoveryContext::registerCleanup(CrashRecoveryContextCleanup *cleanup)
117{
118 if (!cleanup)
119 return;
120 if (head)
121 head->prev = cleanup;
122 cleanup->next = head;
123 head = cleanup;
124}
125
126void
127CrashRecoveryContext::unregisterCleanup(CrashRecoveryContextCleanup *cleanup) {
128 if (!cleanup)
129 return;
130 if (cleanup == head) {
131 head = cleanup->next;
132 if (head)
Craig Topperc10719f2014-04-07 04:17:22 +0000133 head->prev = nullptr;
Ted Kremenekc44d3cf2011-03-18 02:05:11 +0000134 }
135 else {
136 cleanup->prev->next = cleanup->next;
137 if (cleanup->next)
138 cleanup->next->prev = cleanup->prev;
139 }
140 delete cleanup;
141}
142
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000143#ifdef LLVM_ON_WIN32
144
Reid Klecknerd59e2fa2014-02-12 21:26:20 +0000145#include "Windows/WindowsSupport.h"
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000146
147// On Windows, we can make use of vectored exception handling to
148// catch most crashing situations. Note that this does mean
149// we will be alerted of exceptions *before* structured exception
150// handling has the opportunity to catch it. But that isn't likely
151// to cause problems because nowhere in the project is SEH being
152// used.
153//
154// Vectored exception handling is built on top of SEH, and so it
155// works on a per-thread basis.
156//
157// The vectored exception handler functionality was added in Windows
158// XP, so if support for older versions of Windows is required,
159// it will have to be added.
160//
161// If we want to support as far back as Win2k, we could use the
162// SetUnhandledExceptionFilter API, but there's a risk of that
163// being entirely overwritten (it's not a chain).
164
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000165static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000166{
167 // Lookup the current thread local recovery object.
Filip Pizlof2189bf2013-09-12 17:46:57 +0000168 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000169
170 if (!CRCI) {
171 // Something has gone horribly wrong, so let's just tell everyone
172 // to keep searching
173 CrashRecoveryContext::Disable();
174 return EXCEPTION_CONTINUE_SEARCH;
175 }
176
177 // TODO: We can capture the stack backtrace here and store it on the
178 // implementation if we so choose.
179
180 // Handle the crash
181 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
182
183 // Note that we don't actually get here because HandleCrash calls
184 // longjmp, which means the HandleCrash function never returns.
185 llvm_unreachable("Handled the crash, should have longjmp'ed out of here");
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000186}
187
188// Because the Enable and Disable calls are static, it means that
189// there may not actually be an Impl available, or even a current
190// CrashRecoveryContext at all. So we make use of a thread-local
191// exception table. The handles contained in here will either be
192// non-NULL, valid VEH handles, or NULL.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000193static sys::ThreadLocal<const void> sCurrentExceptionHandle;
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000194
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000195void CrashRecoveryContext::Enable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000196 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000197
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000198 if (gCrashRecoveryEnabled)
199 return;
200
201 gCrashRecoveryEnabled = true;
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000202
203 // We can set up vectored exception handling now. We will install our
204 // handler as the front of the list, though there's no assurances that
205 // it will remain at the front (another call could install itself before
206 // our handler). This 1) isn't likely, and 2) shouldn't cause problems.
207 PVOID handle = ::AddVectoredExceptionHandler(1, ExceptionHandler);
208 sCurrentExceptionHandle.set(handle);
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000209}
210
211void CrashRecoveryContext::Disable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000212 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000213
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000214 if (!gCrashRecoveryEnabled)
215 return;
216
217 gCrashRecoveryEnabled = false;
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000218
219 PVOID currentHandle = const_cast<PVOID>(sCurrentExceptionHandle.get());
220 if (currentHandle) {
221 // Now we can remove the vectored exception handler from the chain
222 ::RemoveVectoredExceptionHandler(currentHandle);
223
224 // Reset the handle in our thread-local set.
225 sCurrentExceptionHandle.set(NULL);
226 }
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000227}
228
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000229#else
230
231// Generic POSIX implementation.
232//
233// This implementation relies on synchronous signals being delivered to the
234// current thread. We use a thread local object to keep track of the active
235// crash recovery context, and install signal handlers to invoke HandleCrash on
236// the active object.
237//
238// This implementation does not to attempt to chain signal handlers in any
239// reliable fashion -- if we get a signal outside of a crash recovery context we
240// simply disable crash recovery and raise the signal again.
241
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000242#include <signal.h>
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000243
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000244static const int Signals[] =
245 { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP };
246static const unsigned NumSignals = array_lengthof(Signals);
247static struct sigaction PrevActions[NumSignals];
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000248
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000249static void CrashRecoverySignalHandler(int Signal) {
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000250 // Lookup the current thread local recovery object.
Filip Pizlof2189bf2013-09-12 17:46:57 +0000251 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000252
253 if (!CRCI) {
254 // We didn't find a crash recovery context -- this means either we got a
255 // signal on a thread we didn't expect it on, the application got a signal
256 // outside of a crash recovery context, or something else went horribly
257 // wrong.
258 //
259 // Disable crash recovery and raise the signal again. The assumption here is
260 // that the enclosing application will terminate soon, and we won't want to
261 // attempt crash recovery again.
262 //
263 // This call of Disable isn't thread safe, but it doesn't actually matter.
264 CrashRecoveryContext::Disable();
265 raise(Signal);
Daniel Dunbar418e7042010-10-18 21:55:18 +0000266
267 // The signal will be thrown once the signal mask is restored.
268 return;
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000269 }
270
271 // Unblock the signal we received.
272 sigset_t SigMask;
273 sigemptyset(&SigMask);
274 sigaddset(&SigMask, Signal);
Craig Topperc10719f2014-04-07 04:17:22 +0000275 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000276
277 if (CRCI)
278 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
279}
280
281void CrashRecoveryContext::Enable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000282 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000283
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000284 if (gCrashRecoveryEnabled)
285 return;
286
287 gCrashRecoveryEnabled = true;
288
289 // Setup the signal handler.
290 struct sigaction Handler;
291 Handler.sa_handler = CrashRecoverySignalHandler;
292 Handler.sa_flags = 0;
293 sigemptyset(&Handler.sa_mask);
294
295 for (unsigned i = 0; i != NumSignals; ++i) {
Daniel Dunbarc90e82a2010-07-30 17:49:04 +0000296 sigaction(Signals[i], &Handler, &PrevActions[i]);
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000297 }
298}
299
300void CrashRecoveryContext::Disable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000301 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000302
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000303 if (!gCrashRecoveryEnabled)
304 return;
305
306 gCrashRecoveryEnabled = false;
307
308 // Restore the previous signal handlers.
309 for (unsigned i = 0; i != NumSignals; ++i)
Craig Topperc10719f2014-04-07 04:17:22 +0000310 sigaction(Signals[i], &PrevActions[i], nullptr);
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000311}
312
313#endif
314
Richard Smithc167d652014-05-06 01:44:26 +0000315bool CrashRecoveryContext::RunSafely(function_ref<void()> Fn) {
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000316 // If crash recovery is disabled, do nothing.
317 if (gCrashRecoveryEnabled) {
318 assert(!Impl && "Crash recovery context already initialized!");
Daniel Dunbarb30266e2010-08-17 22:32:37 +0000319 CrashRecoveryContextImpl *CRCI = new CrashRecoveryContextImpl(this);
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000320 Impl = CRCI;
321
322 if (setjmp(CRCI->JumpBuffer) != 0) {
323 return false;
324 }
325 }
326
Richard Smithc167d652014-05-06 01:44:26 +0000327 Fn();
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000328 return true;
329}
330
331void CrashRecoveryContext::HandleCrash() {
332 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
333 assert(CRCI && "Crash recovery context never initialized!");
334 CRCI->HandleCrash();
335}
336
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000337// FIXME: Portability.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000338static void setThreadBackgroundPriority() {
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000339#ifdef __APPLE__
340 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
341#endif
342}
343
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000344static bool hasThreadBackgroundPriority() {
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000345#ifdef __APPLE__
346 return getpriority(PRIO_DARWIN_THREAD, 0) == 1;
347#else
348 return false;
349#endif
350}
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000351
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000352namespace {
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000353struct RunSafelyOnThreadInfo {
Richard Smithc167d652014-05-06 01:44:26 +0000354 function_ref<void()> Fn;
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000355 CrashRecoveryContext *CRC;
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000356 bool UseBackgroundPriority;
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000357 bool Result;
358};
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000359}
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000360
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000361static void RunSafelyOnThread_Dispatch(void *UserData) {
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000362 RunSafelyOnThreadInfo *Info =
363 reinterpret_cast<RunSafelyOnThreadInfo*>(UserData);
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000364
365 if (Info->UseBackgroundPriority)
366 setThreadBackgroundPriority();
367
Richard Smithc167d652014-05-06 01:44:26 +0000368 Info->Result = Info->CRC->RunSafely(Info->Fn);
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000369}
Richard Smithc167d652014-05-06 01:44:26 +0000370bool CrashRecoveryContext::RunSafelyOnThread(function_ref<void()> Fn,
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000371 unsigned RequestedStackSize) {
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000372 bool UseBackgroundPriority = hasThreadBackgroundPriority();
373 RunSafelyOnThreadInfo Info = { Fn, this, UseBackgroundPriority, false };
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000374 llvm_execute_on_thread(RunSafelyOnThread_Dispatch, &Info, RequestedStackSize);
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +0000375 if (CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *)Impl)
376 CRC->setSwitchedThread();
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000377 return Info.Result;
378}