blob: 9b0e44339d8411dddf387fcb3afabc7141b1a315 [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"
11#include "llvm/ADT/SmallString.h"
Daniel Dunbar9789f812010-07-29 01:52:04 +000012#include "llvm/Config/config.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000013#include "llvm/Support/ErrorHandling.h"
Filip Pizlof2189bf2013-09-12 17:46:57 +000014#include "llvm/Support/ManagedStatic.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000015#include "llvm/Support/Mutex.h"
16#include "llvm/Support/ThreadLocal.h"
Daniel Dunbaraf77e222010-07-29 01:21:47 +000017#include <cstdio>
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include <setjmp.h>
Daniel Dunbar19a3b372010-07-28 15:40:20 +000019using namespace llvm;
20
21namespace {
22
23struct CrashRecoveryContextImpl;
24
Zachary Turnera40ccf62014-06-10 18:03:04 +000025static ManagedStatic<
26 sys::ThreadLocal<const CrashRecoveryContextImpl> > CurrentContext;
Daniel Dunbaraf77e222010-07-29 01:21:47 +000027
Daniel Dunbar19a3b372010-07-28 15:40:20 +000028struct CrashRecoveryContextImpl {
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) {
Filip Pizlof2189bf2013-09-12 17:46:57 +000039 CurrentContext->set(this);
Daniel Dunbaraf77e222010-07-29 01:21:47 +000040 }
41 ~CrashRecoveryContextImpl() {
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000042 if (!SwitchedThread)
Filip Pizlof2189bf2013-09-12 17:46:57 +000043 CurrentContext->erase();
Daniel Dunbaraf77e222010-07-29 01:21:47 +000044 }
Daniel Dunbar19a3b372010-07-28 15:40:20 +000045
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000046 /// \brief Called when the separate crash-recovery thread was finished, to
47 /// indicate that we don't need to clear the thread-local CurrentContext.
48 void setSwitchedThread() { SwitchedThread = true; }
49
Daniel Dunbar19a3b372010-07-28 15:40:20 +000050 void HandleCrash() {
Daniel Dunbar09b0c782010-08-17 22:32:39 +000051 // Eliminate the current context entry, to avoid re-entering in case the
52 // cleanup code crashes.
Filip Pizlof2189bf2013-09-12 17:46:57 +000053 CurrentContext->erase();
Daniel Dunbar09b0c782010-08-17 22:32:39 +000054
Daniel Dunbar19a3b372010-07-28 15:40:20 +000055 assert(!Failed && "Crash recovery context already failed!");
56 Failed = true;
57
58 // FIXME: Stash the backtrace.
59
60 // Jump back to the RunSafely we were called under.
61 longjmp(JumpBuffer, 1);
62 }
63};
64
65}
66
Filip Pizlof2189bf2013-09-12 17:46:57 +000067static ManagedStatic<sys::Mutex> gCrashRecoveryContextMutex;
Daniel Dunbar19a3b372010-07-28 15:40:20 +000068static bool gCrashRecoveryEnabled = false;
69
Filip Pizlof2189bf2013-09-12 17:46:57 +000070static ManagedStatic<sys::ThreadLocal<const CrashRecoveryContextCleanup> >
Ted Kremenekab1a2422011-03-21 18:38:03 +000071 tlIsRecoveringFromCrash;
72
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000073CrashRecoveryContextCleanup::~CrashRecoveryContextCleanup() {}
74
Daniel Dunbar19a3b372010-07-28 15:40:20 +000075CrashRecoveryContext::~CrashRecoveryContext() {
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000076 // Reclaim registered resources.
77 CrashRecoveryContextCleanup *i = head;
Filip Pizlof2189bf2013-09-12 17:46:57 +000078 tlIsRecoveringFromCrash->set(head);
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000079 while (i) {
80 CrashRecoveryContextCleanup *tmp = i;
81 i = tmp->next;
Ted Kremenek32aea2e2011-03-19 00:59:37 +000082 tmp->cleanupFired = true;
Ted Kremenek857e5352011-03-22 04:33:13 +000083 tmp->recoverResources();
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000084 delete tmp;
85 }
Filip Pizlof2189bf2013-09-12 17:46:57 +000086 tlIsRecoveringFromCrash->erase();
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000087
Daniel Dunbar19a3b372010-07-28 15:40:20 +000088 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
89 delete CRCI;
90}
91
Ted Kremenekab1a2422011-03-21 18:38:03 +000092bool CrashRecoveryContext::isRecoveringFromCrash() {
Craig Topperc10719f2014-04-07 04:17:22 +000093 return tlIsRecoveringFromCrash->get() != nullptr;
Ted Kremenekab1a2422011-03-21 18:38:03 +000094}
95
Daniel Dunbarb30266e2010-08-17 22:32:37 +000096CrashRecoveryContext *CrashRecoveryContext::GetCurrent() {
Ted Kremenek794a0712011-03-19 00:59:33 +000097 if (!gCrashRecoveryEnabled)
Craig Topperc10719f2014-04-07 04:17:22 +000098 return nullptr;
Ted Kremenek794a0712011-03-19 00:59:33 +000099
Filip Pizlof2189bf2013-09-12 17:46:57 +0000100 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
Daniel Dunbarb30266e2010-08-17 22:32:37 +0000101 if (!CRCI)
Craig Topperc10719f2014-04-07 04:17:22 +0000102 return nullptr;
Daniel Dunbarb30266e2010-08-17 22:32:37 +0000103
104 return CRCI->CRC;
105}
106
Ted Kremenekc44d3cf2011-03-18 02:05:11 +0000107void CrashRecoveryContext::registerCleanup(CrashRecoveryContextCleanup *cleanup)
108{
109 if (!cleanup)
110 return;
111 if (head)
112 head->prev = cleanup;
113 cleanup->next = head;
114 head = cleanup;
115}
116
117void
118CrashRecoveryContext::unregisterCleanup(CrashRecoveryContextCleanup *cleanup) {
119 if (!cleanup)
120 return;
121 if (cleanup == head) {
122 head = cleanup->next;
123 if (head)
Craig Topperc10719f2014-04-07 04:17:22 +0000124 head->prev = nullptr;
Ted Kremenekc44d3cf2011-03-18 02:05:11 +0000125 }
126 else {
127 cleanup->prev->next = cleanup->next;
128 if (cleanup->next)
129 cleanup->next->prev = cleanup->prev;
130 }
131 delete cleanup;
132}
133
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000134#ifdef LLVM_ON_WIN32
135
Reid Klecknerd59e2fa2014-02-12 21:26:20 +0000136#include "Windows/WindowsSupport.h"
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000137
138// On Windows, we can make use of vectored exception handling to
139// catch most crashing situations. Note that this does mean
140// we will be alerted of exceptions *before* structured exception
141// handling has the opportunity to catch it. But that isn't likely
142// to cause problems because nowhere in the project is SEH being
143// used.
144//
145// Vectored exception handling is built on top of SEH, and so it
146// works on a per-thread basis.
147//
148// The vectored exception handler functionality was added in Windows
149// XP, so if support for older versions of Windows is required,
150// it will have to be added.
151//
152// If we want to support as far back as Win2k, we could use the
153// SetUnhandledExceptionFilter API, but there's a risk of that
154// being entirely overwritten (it's not a chain).
155
156static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
157{
158 // Lookup the current thread local recovery object.
Filip Pizlof2189bf2013-09-12 17:46:57 +0000159 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000160
161 if (!CRCI) {
162 // Something has gone horribly wrong, so let's just tell everyone
163 // to keep searching
164 CrashRecoveryContext::Disable();
165 return EXCEPTION_CONTINUE_SEARCH;
166 }
167
168 // TODO: We can capture the stack backtrace here and store it on the
169 // implementation if we so choose.
170
171 // Handle the crash
172 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
173
174 // Note that we don't actually get here because HandleCrash calls
175 // longjmp, which means the HandleCrash function never returns.
176 llvm_unreachable("Handled the crash, should have longjmp'ed out of here");
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000177}
178
179// Because the Enable and Disable calls are static, it means that
180// there may not actually be an Impl available, or even a current
181// CrashRecoveryContext at all. So we make use of a thread-local
182// exception table. The handles contained in here will either be
183// non-NULL, valid VEH handles, or NULL.
184static sys::ThreadLocal<const void> sCurrentExceptionHandle;
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000185
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000186void CrashRecoveryContext::Enable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000187 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000188
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000189 if (gCrashRecoveryEnabled)
190 return;
191
192 gCrashRecoveryEnabled = true;
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000193
194 // We can set up vectored exception handling now. We will install our
195 // handler as the front of the list, though there's no assurances that
196 // it will remain at the front (another call could install itself before
197 // our handler). This 1) isn't likely, and 2) shouldn't cause problems.
198 PVOID handle = ::AddVectoredExceptionHandler(1, ExceptionHandler);
199 sCurrentExceptionHandle.set(handle);
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000200}
201
202void CrashRecoveryContext::Disable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000203 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000204
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000205 if (!gCrashRecoveryEnabled)
206 return;
207
208 gCrashRecoveryEnabled = false;
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000209
210 PVOID currentHandle = const_cast<PVOID>(sCurrentExceptionHandle.get());
211 if (currentHandle) {
212 // Now we can remove the vectored exception handler from the chain
213 ::RemoveVectoredExceptionHandler(currentHandle);
214
215 // Reset the handle in our thread-local set.
216 sCurrentExceptionHandle.set(NULL);
217 }
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000218}
219
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000220#else
221
222// Generic POSIX implementation.
223//
224// This implementation relies on synchronous signals being delivered to the
225// current thread. We use a thread local object to keep track of the active
226// crash recovery context, and install signal handlers to invoke HandleCrash on
227// the active object.
228//
229// This implementation does not to attempt to chain signal handlers in any
230// reliable fashion -- if we get a signal outside of a crash recovery context we
231// simply disable crash recovery and raise the signal again.
232
233#include <signal.h>
234
Zachary Turnera40ccf62014-06-10 18:03:04 +0000235static const int Signals[] =
236 { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP };
Daniel Dunbarc90e82a2010-07-30 17:49:04 +0000237static const unsigned NumSignals = sizeof(Signals) / sizeof(Signals[0]);
238static struct sigaction PrevActions[NumSignals];
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000239
240static void CrashRecoverySignalHandler(int Signal) {
241 // Lookup the current thread local recovery object.
Filip Pizlof2189bf2013-09-12 17:46:57 +0000242 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000243
244 if (!CRCI) {
245 // We didn't find a crash recovery context -- this means either we got a
246 // signal on a thread we didn't expect it on, the application got a signal
247 // outside of a crash recovery context, or something else went horribly
248 // wrong.
249 //
250 // Disable crash recovery and raise the signal again. The assumption here is
251 // that the enclosing application will terminate soon, and we won't want to
252 // attempt crash recovery again.
253 //
254 // This call of Disable isn't thread safe, but it doesn't actually matter.
255 CrashRecoveryContext::Disable();
256 raise(Signal);
Daniel Dunbar418e7042010-10-18 21:55:18 +0000257
258 // The signal will be thrown once the signal mask is restored.
259 return;
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000260 }
261
262 // Unblock the signal we received.
263 sigset_t SigMask;
264 sigemptyset(&SigMask);
265 sigaddset(&SigMask, Signal);
Craig Topperc10719f2014-04-07 04:17:22 +0000266 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000267
268 if (CRCI)
269 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
270}
271
272void CrashRecoveryContext::Enable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000273 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000274
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000275 if (gCrashRecoveryEnabled)
276 return;
277
278 gCrashRecoveryEnabled = true;
279
280 // Setup the signal handler.
281 struct sigaction Handler;
282 Handler.sa_handler = CrashRecoverySignalHandler;
283 Handler.sa_flags = 0;
284 sigemptyset(&Handler.sa_mask);
285
286 for (unsigned i = 0; i != NumSignals; ++i) {
Daniel Dunbarc90e82a2010-07-30 17:49:04 +0000287 sigaction(Signals[i], &Handler, &PrevActions[i]);
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000288 }
289}
290
291void CrashRecoveryContext::Disable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000292 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000293
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000294 if (!gCrashRecoveryEnabled)
295 return;
296
297 gCrashRecoveryEnabled = false;
298
299 // Restore the previous signal handlers.
300 for (unsigned i = 0; i != NumSignals; ++i)
Craig Topperc10719f2014-04-07 04:17:22 +0000301 sigaction(Signals[i], &PrevActions[i], nullptr);
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000302}
303
304#endif
305
Richard Smithc167d652014-05-06 01:44:26 +0000306bool CrashRecoveryContext::RunSafely(function_ref<void()> Fn) {
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000307 // If crash recovery is disabled, do nothing.
308 if (gCrashRecoveryEnabled) {
309 assert(!Impl && "Crash recovery context already initialized!");
Daniel Dunbarb30266e2010-08-17 22:32:37 +0000310 CrashRecoveryContextImpl *CRCI = new CrashRecoveryContextImpl(this);
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000311 Impl = CRCI;
312
313 if (setjmp(CRCI->JumpBuffer) != 0) {
314 return false;
315 }
316 }
317
Richard Smithc167d652014-05-06 01:44:26 +0000318 Fn();
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000319 return true;
320}
321
322void CrashRecoveryContext::HandleCrash() {
323 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
324 assert(CRCI && "Crash recovery context never initialized!");
325 CRCI->HandleCrash();
326}
327
328const std::string &CrashRecoveryContext::getBacktrace() const {
329 CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *) Impl;
330 assert(CRC && "Crash recovery context never initialized!");
331 assert(CRC->Failed && "No crash was detected!");
332 return CRC->Backtrace;
333}
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000334
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000335// FIXME: Portability.
336static void setThreadBackgroundPriority() {
337#ifdef __APPLE__
338 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
339#endif
340}
341
342static bool hasThreadBackgroundPriority() {
343#ifdef __APPLE__
344 return getpriority(PRIO_DARWIN_THREAD, 0) == 1;
345#else
346 return false;
347#endif
348}
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000349
350namespace {
351struct RunSafelyOnThreadInfo {
Richard Smithc167d652014-05-06 01:44:26 +0000352 function_ref<void()> Fn;
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000353 CrashRecoveryContext *CRC;
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000354 bool UseBackgroundPriority;
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000355 bool Result;
356};
357}
358
359static void RunSafelyOnThread_Dispatch(void *UserData) {
360 RunSafelyOnThreadInfo *Info =
361 reinterpret_cast<RunSafelyOnThreadInfo*>(UserData);
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000362
363 if (Info->UseBackgroundPriority)
364 setThreadBackgroundPriority();
365
Richard Smithc167d652014-05-06 01:44:26 +0000366 Info->Result = Info->CRC->RunSafely(Info->Fn);
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000367}
Richard Smithc167d652014-05-06 01:44:26 +0000368bool CrashRecoveryContext::RunSafelyOnThread(function_ref<void()> Fn,
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000369 unsigned RequestedStackSize) {
Argyrios Kyrtzidise9012b02014-06-25 23:54:50 +0000370 bool UseBackgroundPriority = hasThreadBackgroundPriority();
371 RunSafelyOnThreadInfo Info = { Fn, this, UseBackgroundPriority, false };
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000372 llvm_execute_on_thread(RunSafelyOnThread_Dispatch, &Info, RequestedStackSize);
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +0000373 if (CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *)Impl)
374 CRC->setSwitchedThread();
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000375 return Info.Result;
376}