1 //===--- CrashRecoveryContext.cpp - Crash Recovery ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Support/CrashRecoveryContext.h"
11 #include "llvm/Config/config.h"
12 #include "llvm/Support/ErrorHandling.h"
13 #include "llvm/Support/ManagedStatic.h"
14 #include "llvm/Support/Mutex.h"
15 #include "llvm/Support/ThreadLocal.h"
21 struct CrashRecoveryContextImpl;
24 sys::ThreadLocal<const CrashRecoveryContextImpl> > CurrentContext;
26 struct CrashRecoveryContextImpl {
27 CrashRecoveryContext *CRC;
28 std::string Backtrace;
30 volatile unsigned Failed : 1;
31 unsigned SwitchedThread : 1;
34 CrashRecoveryContextImpl(CrashRecoveryContext *CRC) : CRC(CRC),
36 SwitchedThread(false) {
37 CurrentContext->set(this);
39 ~CrashRecoveryContextImpl() {
41 CurrentContext->erase();
44 /// \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; }
49 // Eliminate the current context entry, to avoid re-entering in case the
50 // cleanup code crashes.
51 CurrentContext->erase();
53 assert(!Failed && "Crash recovery context already failed!");
56 // FIXME: Stash the backtrace.
58 // Jump back to the RunSafely we were called under.
59 longjmp(JumpBuffer, 1);
65 static ManagedStatic<sys::Mutex> gCrashRecoveryContextMutex;
66 static bool gCrashRecoveryEnabled = false;
68 static ManagedStatic<sys::ThreadLocal<const CrashRecoveryContextCleanup> >
69 tlIsRecoveringFromCrash;
71 CrashRecoveryContextCleanup::~CrashRecoveryContextCleanup() {}
73 CrashRecoveryContext::~CrashRecoveryContext() {
74 // Reclaim registered resources.
75 CrashRecoveryContextCleanup *i = head;
76 tlIsRecoveringFromCrash->set(head);
78 CrashRecoveryContextCleanup *tmp = i;
80 tmp->cleanupFired = true;
81 tmp->recoverResources();
84 tlIsRecoveringFromCrash->erase();
86 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
90 bool CrashRecoveryContext::isRecoveringFromCrash() {
91 return tlIsRecoveringFromCrash->get() != nullptr;
94 CrashRecoveryContext *CrashRecoveryContext::GetCurrent() {
95 if (!gCrashRecoveryEnabled)
98 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
105 void CrashRecoveryContext::registerCleanup(CrashRecoveryContextCleanup *cleanup)
110 head->prev = cleanup;
111 cleanup->next = head;
116 CrashRecoveryContext::unregisterCleanup(CrashRecoveryContextCleanup *cleanup) {
119 if (cleanup == head) {
120 head = cleanup->next;
122 head->prev = nullptr;
125 cleanup->prev->next = cleanup->next;
127 cleanup->next->prev = cleanup->prev;
134 #include "Windows/WindowsSupport.h"
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
143 // Vectored exception handling is built on top of SEH, and so it
144 // works on a per-thread basis.
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.
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).
154 static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
156 // Lookup the current thread local recovery object.
157 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
160 // Something has gone horribly wrong, so let's just tell everyone
162 CrashRecoveryContext::Disable();
163 return EXCEPTION_CONTINUE_SEARCH;
166 // TODO: We can capture the stack backtrace here and store it on the
167 // implementation if we so choose.
170 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
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");
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.
182 static sys::ThreadLocal<const void> sCurrentExceptionHandle;
184 void CrashRecoveryContext::Enable() {
185 sys::ScopedLock L(*gCrashRecoveryContextMutex);
187 if (gCrashRecoveryEnabled)
190 gCrashRecoveryEnabled = true;
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);
200 void CrashRecoveryContext::Disable() {
201 sys::ScopedLock L(*gCrashRecoveryContextMutex);
203 if (!gCrashRecoveryEnabled)
206 gCrashRecoveryEnabled = false;
208 PVOID currentHandle = const_cast<PVOID>(sCurrentExceptionHandle.get());
210 // Now we can remove the vectored exception handler from the chain
211 ::RemoveVectoredExceptionHandler(currentHandle);
213 // Reset the handle in our thread-local set.
214 sCurrentExceptionHandle.set(NULL);
220 // Generic POSIX implementation.
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.
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.
233 static const int Signals[] =
234 { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP };
235 static const unsigned NumSignals = sizeof(Signals) / sizeof(Signals[0]);
236 static struct sigaction PrevActions[NumSignals];
238 static void CrashRecoverySignalHandler(int Signal) {
239 // Lookup the current thread local recovery object.
240 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
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
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.
252 // This call of Disable isn't thread safe, but it doesn't actually matter.
253 CrashRecoveryContext::Disable();
256 // The signal will be thrown once the signal mask is restored.
260 // Unblock the signal we received.
262 sigemptyset(&SigMask);
263 sigaddset(&SigMask, Signal);
264 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
267 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
270 void CrashRecoveryContext::Enable() {
271 sys::ScopedLock L(*gCrashRecoveryContextMutex);
273 if (gCrashRecoveryEnabled)
276 gCrashRecoveryEnabled = true;
278 // Setup the signal handler.
279 struct sigaction Handler;
280 Handler.sa_handler = CrashRecoverySignalHandler;
281 Handler.sa_flags = 0;
282 sigemptyset(&Handler.sa_mask);
284 for (unsigned i = 0; i != NumSignals; ++i) {
285 sigaction(Signals[i], &Handler, &PrevActions[i]);
289 void CrashRecoveryContext::Disable() {
290 sys::ScopedLock L(*gCrashRecoveryContextMutex);
292 if (!gCrashRecoveryEnabled)
295 gCrashRecoveryEnabled = false;
297 // Restore the previous signal handlers.
298 for (unsigned i = 0; i != NumSignals; ++i)
299 sigaction(Signals[i], &PrevActions[i], nullptr);
304 bool CrashRecoveryContext::RunSafely(function_ref<void()> Fn) {
305 // If crash recovery is disabled, do nothing.
306 if (gCrashRecoveryEnabled) {
307 assert(!Impl && "Crash recovery context already initialized!");
308 CrashRecoveryContextImpl *CRCI = new CrashRecoveryContextImpl(this);
311 if (setjmp(CRCI->JumpBuffer) != 0) {
320 void CrashRecoveryContext::HandleCrash() {
321 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
322 assert(CRCI && "Crash recovery context never initialized!");
326 const 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;
333 // FIXME: Portability.
334 static void setThreadBackgroundPriority() {
336 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
340 static bool hasThreadBackgroundPriority() {
342 return getpriority(PRIO_DARWIN_THREAD, 0) == 1;
349 struct RunSafelyOnThreadInfo {
350 function_ref<void()> Fn;
351 CrashRecoveryContext *CRC;
352 bool UseBackgroundPriority;
357 static void RunSafelyOnThread_Dispatch(void *UserData) {
358 RunSafelyOnThreadInfo *Info =
359 reinterpret_cast<RunSafelyOnThreadInfo*>(UserData);
361 if (Info->UseBackgroundPriority)
362 setThreadBackgroundPriority();
364 Info->Result = Info->CRC->RunSafely(Info->Fn);
366 bool CrashRecoveryContext::RunSafelyOnThread(function_ref<void()> Fn,
367 unsigned RequestedStackSize) {
368 bool UseBackgroundPriority = hasThreadBackgroundPriority();
369 RunSafelyOnThreadInfo Info = { Fn, this, UseBackgroundPriority, false };
370 llvm_execute_on_thread(RunSafelyOnThread_Dispatch, &Info, RequestedStackSize);
371 if (CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *)Impl)
372 CRC->setSwitchedThread();