blob: b9829e1192a13f2f276b10c717c4c4b0064f8ab4 [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 Weber28dc4172015-08-06 19:21:25 +000027 const CrashRecoveryContextImpl *Next;
28
Daniel Dunbarb30266e2010-08-17 22:32:37 +000029 CrashRecoveryContext *CRC;
Daniel Dunbar19a3b372010-07-28 15:40:20 +000030 std::string Backtrace;
31 ::jmp_buf JumpBuffer;
32 volatile unsigned Failed : 1;
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000033 unsigned SwitchedThread : 1;
Daniel Dunbar19a3b372010-07-28 15:40:20 +000034
35public:
Daniel Dunbarb30266e2010-08-17 22:32:37 +000036 CrashRecoveryContextImpl(CrashRecoveryContext *CRC) : CRC(CRC),
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000037 Failed(false),
38 SwitchedThread(false) {
Nico Weber28dc4172015-08-06 19:21:25 +000039 Next = CurrentContext->get();
Filip Pizlof2189bf2013-09-12 17:46:57 +000040 CurrentContext->set(this);
Daniel Dunbaraf77e222010-07-29 01:21:47 +000041 }
42 ~CrashRecoveryContextImpl() {
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000043 if (!SwitchedThread)
Nico Weber28dc4172015-08-06 19:21:25 +000044 CurrentContext->set(Next);
Daniel Dunbaraf77e222010-07-29 01:21:47 +000045 }
Daniel Dunbar19a3b372010-07-28 15:40:20 +000046
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000047 /// \brief Called when the separate crash-recovery thread was finished, to
48 /// indicate that we don't need to clear the thread-local CurrentContext.
Nico Weber28dc4172015-08-06 19:21:25 +000049 void setSwitchedThread() {
50#if defined(LLVM_ENABLE_THREADS) && LLVM_ENABLE_THREADS != 0
51 SwitchedThread = true;
52#endif
53 }
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000054
Daniel Dunbar19a3b372010-07-28 15:40:20 +000055 void HandleCrash() {
Daniel Dunbar09b0c782010-08-17 22:32:39 +000056 // Eliminate the current context entry, to avoid re-entering in case the
57 // cleanup code crashes.
Nico Weber28dc4172015-08-06 19:21:25 +000058 CurrentContext->set(Next);
Daniel Dunbar09b0c782010-08-17 22:32:39 +000059
Daniel Dunbar19a3b372010-07-28 15:40:20 +000060 assert(!Failed && "Crash recovery context already failed!");
61 Failed = true;
62
63 // FIXME: Stash the backtrace.
64
65 // Jump back to the RunSafely we were called under.
66 longjmp(JumpBuffer, 1);
67 }
68};
69
Alexander Kornienkof00654e2015-06-23 09:49:53 +000070}
Daniel Dunbar19a3b372010-07-28 15:40:20 +000071
Filip Pizlof2189bf2013-09-12 17:46:57 +000072static ManagedStatic<sys::Mutex> gCrashRecoveryContextMutex;
Daniel Dunbar19a3b372010-07-28 15:40:20 +000073static bool gCrashRecoveryEnabled = false;
74
Nico Weber28dc4172015-08-06 19:21:25 +000075static ManagedStatic<sys::ThreadLocal<const CrashRecoveryContext>>
Ted Kremenekab1a2422011-03-21 18:38:03 +000076 tlIsRecoveringFromCrash;
77
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000078CrashRecoveryContextCleanup::~CrashRecoveryContextCleanup() {}
79
Daniel Dunbar19a3b372010-07-28 15:40:20 +000080CrashRecoveryContext::~CrashRecoveryContext() {
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000081 // Reclaim registered resources.
82 CrashRecoveryContextCleanup *i = head;
Nico Weber28dc4172015-08-06 19:21:25 +000083 const CrashRecoveryContext *PC = tlIsRecoveringFromCrash->get();
84 tlIsRecoveringFromCrash->set(this);
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000085 while (i) {
86 CrashRecoveryContextCleanup *tmp = i;
87 i = tmp->next;
Ted Kremenek32aea2e2011-03-19 00:59:37 +000088 tmp->cleanupFired = true;
Ted Kremenek857e5352011-03-22 04:33:13 +000089 tmp->recoverResources();
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000090 delete tmp;
91 }
Nico Weber28dc4172015-08-06 19:21:25 +000092 tlIsRecoveringFromCrash->set(PC);
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000093
Daniel Dunbar19a3b372010-07-28 15:40:20 +000094 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
95 delete CRCI;
96}
97
Ted Kremenekab1a2422011-03-21 18:38:03 +000098bool CrashRecoveryContext::isRecoveringFromCrash() {
Craig Topperc10719f2014-04-07 04:17:22 +000099 return tlIsRecoveringFromCrash->get() != nullptr;
Ted Kremenekab1a2422011-03-21 18:38:03 +0000100}
101
Daniel Dunbarb30266e2010-08-17 22:32:37 +0000102CrashRecoveryContext *CrashRecoveryContext::GetCurrent() {
Ted Kremenek794a0712011-03-19 00:59:33 +0000103 if (!gCrashRecoveryEnabled)
Craig Topperc10719f2014-04-07 04:17:22 +0000104 return nullptr;
Ted Kremenek794a0712011-03-19 00:59:33 +0000105
Filip Pizlof2189bf2013-09-12 17:46:57 +0000106 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
Daniel Dunbarb30266e2010-08-17 22:32:37 +0000107 if (!CRCI)
Craig Topperc10719f2014-04-07 04:17:22 +0000108 return nullptr;
Daniel Dunbarb30266e2010-08-17 22:32:37 +0000109
110 return CRCI->CRC;
111}
112
Ted Kremenekc44d3cf2011-03-18 02:05:11 +0000113void CrashRecoveryContext::registerCleanup(CrashRecoveryContextCleanup *cleanup)
114{
115 if (!cleanup)
116 return;
117 if (head)
118 head->prev = cleanup;
119 cleanup->next = head;
120 head = cleanup;
121}
122
123void
124CrashRecoveryContext::unregisterCleanup(CrashRecoveryContextCleanup *cleanup) {
125 if (!cleanup)
126 return;
127 if (cleanup == head) {
128 head = cleanup->next;
129 if (head)
Craig Topperc10719f2014-04-07 04:17:22 +0000130 head->prev = nullptr;
Ted Kremenekc44d3cf2011-03-18 02:05:11 +0000131 }
132 else {
133 cleanup->prev->next = cleanup->next;
134 if (cleanup->next)
135 cleanup->next->prev = cleanup->prev;
136 }
137 delete cleanup;
138}
139
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000140#ifdef LLVM_ON_WIN32
141
Reid Klecknerd59e2fa2014-02-12 21:26:20 +0000142#include "Windows/WindowsSupport.h"
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000143
144// On Windows, we can make use of vectored exception handling to
145// catch most crashing situations. Note that this does mean
146// we will be alerted of exceptions *before* structured exception
147// handling has the opportunity to catch it. But that isn't likely
148// to cause problems because nowhere in the project is SEH being
149// used.
150//
151// Vectored exception handling is built on top of SEH, and so it
152// works on a per-thread basis.
153//
154// The vectored exception handler functionality was added in Windows
155// XP, so if support for older versions of Windows is required,
156// it will have to be added.
157//
158// If we want to support as far back as Win2k, we could use the
159// SetUnhandledExceptionFilter API, but there's a risk of that
160// being entirely overwritten (it's not a chain).
161
162static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
163{
164 // Lookup the current thread local recovery object.
Filip Pizlof2189bf2013-09-12 17:46:57 +0000165 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000166
167 if (!CRCI) {
168 // Something has gone horribly wrong, so let's just tell everyone
169 // to keep searching
170 CrashRecoveryContext::Disable();
171 return EXCEPTION_CONTINUE_SEARCH;
172 }
173
174 // TODO: We can capture the stack backtrace here and store it on the
175 // implementation if we so choose.
176
177 // Handle the crash
178 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
179
180 // Note that we don't actually get here because HandleCrash calls
181 // longjmp, which means the HandleCrash function never returns.
182 llvm_unreachable("Handled the crash, should have longjmp'ed out of here");
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000183}
184
185// Because the Enable and Disable calls are static, it means that
186// there may not actually be an Impl available, or even a current
187// CrashRecoveryContext at all. So we make use of a thread-local
188// exception table. The handles contained in here will either be
189// non-NULL, valid VEH handles, or NULL.
190static sys::ThreadLocal<const void> sCurrentExceptionHandle;
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000191
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000192void CrashRecoveryContext::Enable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000193 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000194
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000195 if (gCrashRecoveryEnabled)
196 return;
197
198 gCrashRecoveryEnabled = true;
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000199
200 // We can set up vectored exception handling now. We will install our
201 // handler as the front of the list, though there's no assurances that
202 // it will remain at the front (another call could install itself before
203 // our handler). This 1) isn't likely, and 2) shouldn't cause problems.
204 PVOID handle = ::AddVectoredExceptionHandler(1, ExceptionHandler);
205 sCurrentExceptionHandle.set(handle);
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000206}
207
208void CrashRecoveryContext::Disable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000209 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000210
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000211 if (!gCrashRecoveryEnabled)
212 return;
213
214 gCrashRecoveryEnabled = false;
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000215
216 PVOID currentHandle = const_cast<PVOID>(sCurrentExceptionHandle.get());
217 if (currentHandle) {
218 // Now we can remove the vectored exception handler from the chain
219 ::RemoveVectoredExceptionHandler(currentHandle);
220
221 // Reset the handle in our thread-local set.
222 sCurrentExceptionHandle.set(NULL);
223 }
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000224}
225
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000226#else
227
228// Generic POSIX implementation.
229//
230// This implementation relies on synchronous signals being delivered to the
231// current thread. We use a thread local object to keep track of the active
232// crash recovery context, and install signal handlers to invoke HandleCrash on
233// the active object.
234//
235// This implementation does not to attempt to chain signal handlers in any
236// reliable fashion -- if we get a signal outside of a crash recovery context we
237// simply disable crash recovery and raise the signal again.
238
239#include <signal.h>
240
Zachary Turnera40ccf62014-06-10 18:03:04 +0000241static const int Signals[] =
242 { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP };
Daniel Dunbarc90e82a2010-07-30 17:49:04 +0000243static const unsigned NumSignals = sizeof(Signals) / sizeof(Signals[0]);
244static struct sigaction PrevActions[NumSignals];
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000245
246static void CrashRecoverySignalHandler(int Signal) {
247 // Lookup the current thread local recovery object.
Filip Pizlof2189bf2013-09-12 17:46:57 +0000248 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000249
250 if (!CRCI) {
251 // We didn't find a crash recovery context -- this means either we got a
252 // signal on a thread we didn't expect it on, the application got a signal
253 // outside of a crash recovery context, or something else went horribly
254 // wrong.
255 //
256 // Disable crash recovery and raise the signal again. The assumption here is
257 // that the enclosing application will terminate soon, and we won't want to
258 // attempt crash recovery again.
259 //
260 // This call of Disable isn't thread safe, but it doesn't actually matter.
261 CrashRecoveryContext::Disable();
262 raise(Signal);
Daniel Dunbar418e7042010-10-18 21:55:18 +0000263
264 // The signal will be thrown once the signal mask is restored.
265 return;
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000266 }
267
268 // Unblock the signal we received.
269 sigset_t SigMask;
270 sigemptyset(&SigMask);
271 sigaddset(&SigMask, Signal);
Craig Topperc10719f2014-04-07 04:17:22 +0000272 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000273
274 if (CRCI)
275 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
276}
277
278void CrashRecoveryContext::Enable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000279 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000280
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000281 if (gCrashRecoveryEnabled)
282 return;
283
284 gCrashRecoveryEnabled = true;
285
286 // Setup the signal handler.
287 struct sigaction Handler;
288 Handler.sa_handler = CrashRecoverySignalHandler;
289 Handler.sa_flags = 0;
290 sigemptyset(&Handler.sa_mask);
291
292 for (unsigned i = 0; i != NumSignals; ++i) {
Daniel Dunbarc90e82a2010-07-30 17:49:04 +0000293 sigaction(Signals[i], &Handler, &PrevActions[i]);
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000294 }
295}
296
297void CrashRecoveryContext::Disable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000298 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000299
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000300 if (!gCrashRecoveryEnabled)
301 return;
302
303 gCrashRecoveryEnabled = false;
304
305 // Restore the previous signal handlers.
306 for (unsigned i = 0; i != NumSignals; ++i)
Craig Topperc10719f2014-04-07 04:17:22 +0000307 sigaction(Signals[i], &PrevActions[i], nullptr);
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000308}
309
310#endif
311
Richard Smithc167d652014-05-06 01:44:26 +0000312bool CrashRecoveryContext::RunSafely(function_ref<void()> Fn) {
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000313 // If crash recovery is disabled, do nothing.
314 if (gCrashRecoveryEnabled) {
315 assert(!Impl && "Crash recovery context already initialized!");
Daniel Dunbarb30266e2010-08-17 22:32:37 +0000316 CrashRecoveryContextImpl *CRCI = new CrashRecoveryContextImpl(this);
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000317 Impl = CRCI;
318
319 if (setjmp(CRCI->JumpBuffer) != 0) {
320 return false;
321 }
322 }
323
Richard Smithc167d652014-05-06 01:44:26 +0000324 Fn();
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000325 return true;
326}
327
328void CrashRecoveryContext::HandleCrash() {
329 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
330 assert(CRCI && "Crash recovery context never initialized!");
331 CRCI->HandleCrash();
332}
333
334const std::string &CrashRecoveryContext::getBacktrace() const {
335 CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *) Impl;
336 assert(CRC && "Crash recovery context never initialized!");
337 assert(CRC->Failed && "No crash was detected!");
338 return CRC->Backtrace;
339}
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000340
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000341// FIXME: Portability.
342static void setThreadBackgroundPriority() {
343#ifdef __APPLE__
344 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
345#endif
346}
347
348static bool hasThreadBackgroundPriority() {
349#ifdef __APPLE__
350 return getpriority(PRIO_DARWIN_THREAD, 0) == 1;
351#else
352 return false;
353#endif
354}
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000355
356namespace {
357struct RunSafelyOnThreadInfo {
Richard Smithc167d652014-05-06 01:44:26 +0000358 function_ref<void()> Fn;
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000359 CrashRecoveryContext *CRC;
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000360 bool UseBackgroundPriority;
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000361 bool Result;
362};
363}
364
365static void RunSafelyOnThread_Dispatch(void *UserData) {
366 RunSafelyOnThreadInfo *Info =
367 reinterpret_cast<RunSafelyOnThreadInfo*>(UserData);
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000368
369 if (Info->UseBackgroundPriority)
370 setThreadBackgroundPriority();
371
Richard Smithc167d652014-05-06 01:44:26 +0000372 Info->Result = Info->CRC->RunSafely(Info->Fn);
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000373}
Richard Smithc167d652014-05-06 01:44:26 +0000374bool CrashRecoveryContext::RunSafelyOnThread(function_ref<void()> Fn,
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000375 unsigned RequestedStackSize) {
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000376 bool UseBackgroundPriority = hasThreadBackgroundPriority();
377 RunSafelyOnThreadInfo Info = { Fn, this, UseBackgroundPriority, false };
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000378 llvm_execute_on_thread(RunSafelyOnThread_Dispatch, &Info, RequestedStackSize);
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +0000379 if (CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *)Impl)
380 CRC->setSwitchedThread();
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000381 return Info.Result;
382}