blob: 352b519f9b4051450e13da738497f375ef2cbf6f [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 {
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 std::string Backtrace;
35 ::jmp_buf JumpBuffer;
36 volatile unsigned Failed : 1;
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000037 unsigned SwitchedThread : 1;
Daniel Dunbar19a3b372010-07-28 15:40:20 +000038
39public:
Daniel Dunbarb30266e2010-08-17 22:32:37 +000040 CrashRecoveryContextImpl(CrashRecoveryContext *CRC) : CRC(CRC),
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000041 Failed(false),
42 SwitchedThread(false) {
Nico Weber28dc4172015-08-06 19:21:25 +000043 Next = CurrentContext->get();
Filip Pizlof2189bf2013-09-12 17:46:57 +000044 CurrentContext->set(this);
Daniel Dunbaraf77e222010-07-29 01:21:47 +000045 }
46 ~CrashRecoveryContextImpl() {
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000047 if (!SwitchedThread)
Nico Weber28dc4172015-08-06 19:21:25 +000048 CurrentContext->set(Next);
Daniel Dunbaraf77e222010-07-29 01:21:47 +000049 }
Daniel Dunbar19a3b372010-07-28 15:40:20 +000050
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000051 /// \brief Called when the separate crash-recovery thread was finished, to
52 /// indicate that we don't need to clear the thread-local CurrentContext.
Nico Weber28dc4172015-08-06 19:21:25 +000053 void setSwitchedThread() {
54#if defined(LLVM_ENABLE_THREADS) && LLVM_ENABLE_THREADS != 0
55 SwitchedThread = true;
56#endif
57 }
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000058
Daniel Dunbar19a3b372010-07-28 15:40:20 +000059 void HandleCrash() {
Daniel Dunbar09b0c782010-08-17 22:32:39 +000060 // Eliminate the current context entry, to avoid re-entering in case the
61 // cleanup code crashes.
Nico Weber28dc4172015-08-06 19:21:25 +000062 CurrentContext->set(Next);
Daniel Dunbar09b0c782010-08-17 22:32:39 +000063
Daniel Dunbar19a3b372010-07-28 15:40:20 +000064 assert(!Failed && "Crash recovery context already failed!");
65 Failed = true;
66
67 // FIXME: Stash the backtrace.
68
69 // Jump back to the RunSafely we were called under.
70 longjmp(JumpBuffer, 1);
71 }
72};
73
Alexander Kornienkof00654e2015-06-23 09:49:53 +000074}
Daniel Dunbar19a3b372010-07-28 15:40:20 +000075
Filip Pizlof2189bf2013-09-12 17:46:57 +000076static ManagedStatic<sys::Mutex> gCrashRecoveryContextMutex;
Daniel Dunbar19a3b372010-07-28 15:40:20 +000077static bool gCrashRecoveryEnabled = false;
78
Nico Weber28dc4172015-08-06 19:21:25 +000079static ManagedStatic<sys::ThreadLocal<const CrashRecoveryContext>>
Ted Kremenekab1a2422011-03-21 18:38:03 +000080 tlIsRecoveringFromCrash;
81
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000082CrashRecoveryContextCleanup::~CrashRecoveryContextCleanup() {}
83
Daniel Dunbar19a3b372010-07-28 15:40:20 +000084CrashRecoveryContext::~CrashRecoveryContext() {
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000085 // Reclaim registered resources.
86 CrashRecoveryContextCleanup *i = head;
Nico Weber28dc4172015-08-06 19:21:25 +000087 const CrashRecoveryContext *PC = tlIsRecoveringFromCrash->get();
88 tlIsRecoveringFromCrash->set(this);
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000089 while (i) {
90 CrashRecoveryContextCleanup *tmp = i;
91 i = tmp->next;
Ted Kremenek32aea2e2011-03-19 00:59:37 +000092 tmp->cleanupFired = true;
Ted Kremenek857e5352011-03-22 04:33:13 +000093 tmp->recoverResources();
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000094 delete tmp;
95 }
Nico Weber28dc4172015-08-06 19:21:25 +000096 tlIsRecoveringFromCrash->set(PC);
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000097
Daniel Dunbar19a3b372010-07-28 15:40:20 +000098 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
99 delete CRCI;
100}
101
Ted Kremenekab1a2422011-03-21 18:38:03 +0000102bool CrashRecoveryContext::isRecoveringFromCrash() {
Craig Topperc10719f2014-04-07 04:17:22 +0000103 return tlIsRecoveringFromCrash->get() != nullptr;
Ted Kremenekab1a2422011-03-21 18:38:03 +0000104}
105
Daniel Dunbarb30266e2010-08-17 22:32:37 +0000106CrashRecoveryContext *CrashRecoveryContext::GetCurrent() {
Ted Kremenek794a0712011-03-19 00:59:33 +0000107 if (!gCrashRecoveryEnabled)
Craig Topperc10719f2014-04-07 04:17:22 +0000108 return nullptr;
Ted Kremenek794a0712011-03-19 00:59:33 +0000109
Filip Pizlof2189bf2013-09-12 17:46:57 +0000110 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
Daniel Dunbarb30266e2010-08-17 22:32:37 +0000111 if (!CRCI)
Craig Topperc10719f2014-04-07 04:17:22 +0000112 return nullptr;
Daniel Dunbarb30266e2010-08-17 22:32:37 +0000113
114 return CRCI->CRC;
115}
116
Ted Kremenekc44d3cf2011-03-18 02:05:11 +0000117void CrashRecoveryContext::registerCleanup(CrashRecoveryContextCleanup *cleanup)
118{
119 if (!cleanup)
120 return;
121 if (head)
122 head->prev = cleanup;
123 cleanup->next = head;
124 head = cleanup;
125}
126
127void
128CrashRecoveryContext::unregisterCleanup(CrashRecoveryContextCleanup *cleanup) {
129 if (!cleanup)
130 return;
131 if (cleanup == head) {
132 head = cleanup->next;
133 if (head)
Craig Topperc10719f2014-04-07 04:17:22 +0000134 head->prev = nullptr;
Ted Kremenekc44d3cf2011-03-18 02:05:11 +0000135 }
136 else {
137 cleanup->prev->next = cleanup->next;
138 if (cleanup->next)
139 cleanup->next->prev = cleanup->prev;
140 }
141 delete cleanup;
142}
143
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000144#ifdef LLVM_ON_WIN32
145
Reid Klecknerd59e2fa2014-02-12 21:26:20 +0000146#include "Windows/WindowsSupport.h"
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000147
148// On Windows, we can make use of vectored exception handling to
149// catch most crashing situations. Note that this does mean
150// we will be alerted of exceptions *before* structured exception
151// handling has the opportunity to catch it. But that isn't likely
152// to cause problems because nowhere in the project is SEH being
153// used.
154//
155// Vectored exception handling is built on top of SEH, and so it
156// works on a per-thread basis.
157//
158// The vectored exception handler functionality was added in Windows
159// XP, so if support for older versions of Windows is required,
160// it will have to be added.
161//
162// If we want to support as far back as Win2k, we could use the
163// SetUnhandledExceptionFilter API, but there's a risk of that
164// being entirely overwritten (it's not a chain).
165
166static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
167{
168 // Lookup the current thread local recovery object.
Filip Pizlof2189bf2013-09-12 17:46:57 +0000169 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000170
171 if (!CRCI) {
172 // Something has gone horribly wrong, so let's just tell everyone
173 // to keep searching
174 CrashRecoveryContext::Disable();
175 return EXCEPTION_CONTINUE_SEARCH;
176 }
177
178 // TODO: We can capture the stack backtrace here and store it on the
179 // implementation if we so choose.
180
181 // Handle the crash
182 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
183
184 // Note that we don't actually get here because HandleCrash calls
185 // longjmp, which means the HandleCrash function never returns.
186 llvm_unreachable("Handled the crash, should have longjmp'ed out of here");
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000187}
188
189// Because the Enable and Disable calls are static, it means that
190// there may not actually be an Impl available, or even a current
191// CrashRecoveryContext at all. So we make use of a thread-local
192// exception table. The handles contained in here will either be
193// non-NULL, valid VEH handles, or NULL.
194static sys::ThreadLocal<const void> sCurrentExceptionHandle;
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000195
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000196void CrashRecoveryContext::Enable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000197 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000198
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000199 if (gCrashRecoveryEnabled)
200 return;
201
202 gCrashRecoveryEnabled = true;
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000203
204 // We can set up vectored exception handling now. We will install our
205 // handler as the front of the list, though there's no assurances that
206 // it will remain at the front (another call could install itself before
207 // our handler). This 1) isn't likely, and 2) shouldn't cause problems.
208 PVOID handle = ::AddVectoredExceptionHandler(1, ExceptionHandler);
209 sCurrentExceptionHandle.set(handle);
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000210}
211
212void CrashRecoveryContext::Disable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000213 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000214
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000215 if (!gCrashRecoveryEnabled)
216 return;
217
218 gCrashRecoveryEnabled = false;
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000219
220 PVOID currentHandle = const_cast<PVOID>(sCurrentExceptionHandle.get());
221 if (currentHandle) {
222 // Now we can remove the vectored exception handler from the chain
223 ::RemoveVectoredExceptionHandler(currentHandle);
224
225 // Reset the handle in our thread-local set.
226 sCurrentExceptionHandle.set(NULL);
227 }
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000228}
229
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000230#else
231
232// Generic POSIX implementation.
233//
234// This implementation relies on synchronous signals being delivered to the
235// current thread. We use a thread local object to keep track of the active
236// crash recovery context, and install signal handlers to invoke HandleCrash on
237// the active object.
238//
239// This implementation does not to attempt to chain signal handlers in any
240// reliable fashion -- if we get a signal outside of a crash recovery context we
241// simply disable crash recovery and raise the signal again.
242
243#include <signal.h>
244
Zachary Turnera40ccf62014-06-10 18:03:04 +0000245static const int Signals[] =
246 { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP };
Daniel Dunbarc90e82a2010-07-30 17:49:04 +0000247static const unsigned NumSignals = sizeof(Signals) / sizeof(Signals[0]);
248static struct sigaction PrevActions[NumSignals];
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000249
250static void CrashRecoverySignalHandler(int Signal) {
251 // Lookup the current thread local recovery object.
Filip Pizlof2189bf2013-09-12 17:46:57 +0000252 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000253
254 if (!CRCI) {
255 // We didn't find a crash recovery context -- this means either we got a
256 // signal on a thread we didn't expect it on, the application got a signal
257 // outside of a crash recovery context, or something else went horribly
258 // wrong.
259 //
260 // Disable crash recovery and raise the signal again. The assumption here is
261 // that the enclosing application will terminate soon, and we won't want to
262 // attempt crash recovery again.
263 //
264 // This call of Disable isn't thread safe, but it doesn't actually matter.
265 CrashRecoveryContext::Disable();
266 raise(Signal);
Daniel Dunbar418e7042010-10-18 21:55:18 +0000267
268 // The signal will be thrown once the signal mask is restored.
269 return;
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000270 }
271
272 // Unblock the signal we received.
273 sigset_t SigMask;
274 sigemptyset(&SigMask);
275 sigaddset(&SigMask, Signal);
Craig Topperc10719f2014-04-07 04:17:22 +0000276 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000277
278 if (CRCI)
279 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
280}
281
282void CrashRecoveryContext::Enable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000283 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000284
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000285 if (gCrashRecoveryEnabled)
286 return;
287
288 gCrashRecoveryEnabled = true;
289
290 // Setup the signal handler.
291 struct sigaction Handler;
292 Handler.sa_handler = CrashRecoverySignalHandler;
293 Handler.sa_flags = 0;
294 sigemptyset(&Handler.sa_mask);
295
296 for (unsigned i = 0; i != NumSignals; ++i) {
Daniel Dunbarc90e82a2010-07-30 17:49:04 +0000297 sigaction(Signals[i], &Handler, &PrevActions[i]);
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000298 }
299}
300
301void CrashRecoveryContext::Disable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000302 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000303
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000304 if (!gCrashRecoveryEnabled)
305 return;
306
307 gCrashRecoveryEnabled = false;
308
309 // Restore the previous signal handlers.
310 for (unsigned i = 0; i != NumSignals; ++i)
Craig Topperc10719f2014-04-07 04:17:22 +0000311 sigaction(Signals[i], &PrevActions[i], nullptr);
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000312}
313
314#endif
315
Richard Smithc167d652014-05-06 01:44:26 +0000316bool CrashRecoveryContext::RunSafely(function_ref<void()> Fn) {
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000317 // If crash recovery is disabled, do nothing.
318 if (gCrashRecoveryEnabled) {
319 assert(!Impl && "Crash recovery context already initialized!");
Daniel Dunbarb30266e2010-08-17 22:32:37 +0000320 CrashRecoveryContextImpl *CRCI = new CrashRecoveryContextImpl(this);
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000321 Impl = CRCI;
322
323 if (setjmp(CRCI->JumpBuffer) != 0) {
324 return false;
325 }
326 }
327
Richard Smithc167d652014-05-06 01:44:26 +0000328 Fn();
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000329 return true;
330}
331
332void CrashRecoveryContext::HandleCrash() {
333 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
334 assert(CRCI && "Crash recovery context never initialized!");
335 CRCI->HandleCrash();
336}
337
338const std::string &CrashRecoveryContext::getBacktrace() const {
339 CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *) Impl;
340 assert(CRC && "Crash recovery context never initialized!");
341 assert(CRC->Failed && "No crash was detected!");
342 return CRC->Backtrace;
343}
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000344
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000345// FIXME: Portability.
346static void setThreadBackgroundPriority() {
347#ifdef __APPLE__
348 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
349#endif
350}
351
352static bool hasThreadBackgroundPriority() {
353#ifdef __APPLE__
354 return getpriority(PRIO_DARWIN_THREAD, 0) == 1;
355#else
356 return false;
357#endif
358}
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000359
360namespace {
361struct RunSafelyOnThreadInfo {
Richard Smithc167d652014-05-06 01:44:26 +0000362 function_ref<void()> Fn;
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000363 CrashRecoveryContext *CRC;
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000364 bool UseBackgroundPriority;
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000365 bool Result;
366};
367}
368
369static void RunSafelyOnThread_Dispatch(void *UserData) {
370 RunSafelyOnThreadInfo *Info =
371 reinterpret_cast<RunSafelyOnThreadInfo*>(UserData);
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000372
373 if (Info->UseBackgroundPriority)
374 setThreadBackgroundPriority();
375
Richard Smithc167d652014-05-06 01:44:26 +0000376 Info->Result = Info->CRC->RunSafely(Info->Fn);
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000377}
Richard Smithc167d652014-05-06 01:44:26 +0000378bool CrashRecoveryContext::RunSafelyOnThread(function_ref<void()> Fn,
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000379 unsigned RequestedStackSize) {
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000380 bool UseBackgroundPriority = hasThreadBackgroundPriority();
381 RunSafelyOnThreadInfo Info = { Fn, this, UseBackgroundPriority, false };
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000382 llvm_execute_on_thread(RunSafelyOnThread_Dispatch, &Info, RequestedStackSize);
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +0000383 if (CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *)Impl)
384 CRC->setSwitchedThread();
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000385 return Info.Result;
386}