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/ADT/SmallString.h"
12 #include "llvm/Config/config.h"
13 #include "llvm/Support/Mutex.h"
14 #include "llvm/Support/ThreadLocal.h"
15 #include "llvm/Support/ErrorHandling.h"
22 struct CrashRecoveryContextImpl;
24 static sys::ThreadLocal<const CrashRecoveryContextImpl> CurrentContext;
26 struct CrashRecoveryContextImpl {
27 CrashRecoveryContext *CRC;
28 std::string Backtrace;
30 volatile unsigned Failed : 1;
33 CrashRecoveryContextImpl(CrashRecoveryContext *CRC) : CRC(CRC),
35 CurrentContext.set(this);
37 ~CrashRecoveryContextImpl() {
38 CurrentContext.erase();
42 // Eliminate the current context entry, to avoid re-entering in case the
43 // cleanup code crashes.
44 CurrentContext.erase();
46 assert(!Failed && "Crash recovery context already failed!");
49 // FIXME: Stash the backtrace.
51 // Jump back to the RunSafely we were called under.
52 longjmp(JumpBuffer, 1);
58 static sys::Mutex gCrashRecoveryContexMutex;
59 static bool gCrashRecoveryEnabled = false;
61 static sys::ThreadLocal<const CrashRecoveryContextCleanup>
62 tlIsRecoveringFromCrash;
64 CrashRecoveryContextCleanup::~CrashRecoveryContextCleanup() {}
66 CrashRecoveryContext::~CrashRecoveryContext() {
67 // Reclaim registered resources.
68 CrashRecoveryContextCleanup *i = head;
69 tlIsRecoveringFromCrash.set(head);
71 CrashRecoveryContextCleanup *tmp = i;
73 tmp->cleanupFired = true;
74 tmp->recoverResources();
77 tlIsRecoveringFromCrash.erase();
79 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
83 bool CrashRecoveryContext::isRecoveringFromCrash() {
84 return tlIsRecoveringFromCrash.get() != 0;
87 CrashRecoveryContext *CrashRecoveryContext::GetCurrent() {
88 if (!gCrashRecoveryEnabled)
91 const CrashRecoveryContextImpl *CRCI = CurrentContext.get();
98 void CrashRecoveryContext::registerCleanup(CrashRecoveryContextCleanup *cleanup)
103 head->prev = cleanup;
104 cleanup->next = head;
109 CrashRecoveryContext::unregisterCleanup(CrashRecoveryContextCleanup *cleanup) {
112 if (cleanup == head) {
113 head = cleanup->next;
118 cleanup->prev->next = cleanup->next;
120 cleanup->next->prev = cleanup->prev;
127 #include "Windows/Windows.h"
129 // On Windows, we can make use of vectored exception handling to
130 // catch most crashing situations. Note that this does mean
131 // we will be alerted of exceptions *before* structured exception
132 // handling has the opportunity to catch it. But that isn't likely
133 // to cause problems because nowhere in the project is SEH being
136 // Vectored exception handling is built on top of SEH, and so it
137 // works on a per-thread basis.
139 // The vectored exception handler functionality was added in Windows
140 // XP, so if support for older versions of Windows is required,
141 // it will have to be added.
143 // If we want to support as far back as Win2k, we could use the
144 // SetUnhandledExceptionFilter API, but there's a risk of that
145 // being entirely overwritten (it's not a chain).
147 static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
149 // Lookup the current thread local recovery object.
150 const CrashRecoveryContextImpl *CRCI = CurrentContext.get();
153 // Something has gone horribly wrong, so let's just tell everyone
155 CrashRecoveryContext::Disable();
156 return EXCEPTION_CONTINUE_SEARCH;
159 // TODO: We can capture the stack backtrace here and store it on the
160 // implementation if we so choose.
163 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
165 // Note that we don't actually get here because HandleCrash calls
166 // longjmp, which means the HandleCrash function never returns.
167 llvm_unreachable("Handled the crash, should have longjmp'ed out of here");
168 return EXCEPTION_CONTINUE_SEARCH;
171 // Because the Enable and Disable calls are static, it means that
172 // there may not actually be an Impl available, or even a current
173 // CrashRecoveryContext at all. So we make use of a thread-local
174 // exception table. The handles contained in here will either be
175 // non-NULL, valid VEH handles, or NULL.
176 static sys::ThreadLocal<const void> sCurrentExceptionHandle;
178 void CrashRecoveryContext::Enable() {
179 sys::ScopedLock L(gCrashRecoveryContexMutex);
181 if (gCrashRecoveryEnabled)
184 gCrashRecoveryEnabled = true;
186 // We can set up vectored exception handling now. We will install our
187 // handler as the front of the list, though there's no assurances that
188 // it will remain at the front (another call could install itself before
189 // our handler). This 1) isn't likely, and 2) shouldn't cause problems.
190 PVOID handle = ::AddVectoredExceptionHandler(1, ExceptionHandler);
191 sCurrentExceptionHandle.set(handle);
194 void CrashRecoveryContext::Disable() {
195 sys::ScopedLock L(gCrashRecoveryContexMutex);
197 if (!gCrashRecoveryEnabled)
200 gCrashRecoveryEnabled = false;
202 PVOID currentHandle = const_cast<PVOID>(sCurrentExceptionHandle.get());
204 // Now we can remove the vectored exception handler from the chain
205 ::RemoveVectoredExceptionHandler(currentHandle);
207 // Reset the handle in our thread-local set.
208 sCurrentExceptionHandle.set(NULL);
214 // Generic POSIX implementation.
216 // This implementation relies on synchronous signals being delivered to the
217 // current thread. We use a thread local object to keep track of the active
218 // crash recovery context, and install signal handlers to invoke HandleCrash on
219 // the active object.
221 // This implementation does not to attempt to chain signal handlers in any
222 // reliable fashion -- if we get a signal outside of a crash recovery context we
223 // simply disable crash recovery and raise the signal again.
227 static int Signals[] = { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP };
228 static const unsigned NumSignals = sizeof(Signals) / sizeof(Signals[0]);
229 static struct sigaction PrevActions[NumSignals];
231 static void CrashRecoverySignalHandler(int Signal) {
232 // Lookup the current thread local recovery object.
233 const CrashRecoveryContextImpl *CRCI = CurrentContext.get();
236 // We didn't find a crash recovery context -- this means either we got a
237 // signal on a thread we didn't expect it on, the application got a signal
238 // outside of a crash recovery context, or something else went horribly
241 // Disable crash recovery and raise the signal again. The assumption here is
242 // that the enclosing application will terminate soon, and we won't want to
243 // attempt crash recovery again.
245 // This call of Disable isn't thread safe, but it doesn't actually matter.
246 CrashRecoveryContext::Disable();
249 // The signal will be thrown once the signal mask is restored.
253 // Unblock the signal we received.
255 sigemptyset(&SigMask);
256 sigaddset(&SigMask, Signal);
257 sigprocmask(SIG_UNBLOCK, &SigMask, 0);
260 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
263 void CrashRecoveryContext::Enable() {
264 sys::ScopedLock L(gCrashRecoveryContexMutex);
266 if (gCrashRecoveryEnabled)
269 gCrashRecoveryEnabled = true;
271 // Setup the signal handler.
272 struct sigaction Handler;
273 Handler.sa_handler = CrashRecoverySignalHandler;
274 Handler.sa_flags = 0;
275 sigemptyset(&Handler.sa_mask);
277 for (unsigned i = 0; i != NumSignals; ++i) {
278 sigaction(Signals[i], &Handler, &PrevActions[i]);
282 void CrashRecoveryContext::Disable() {
283 sys::ScopedLock L(gCrashRecoveryContexMutex);
285 if (!gCrashRecoveryEnabled)
288 gCrashRecoveryEnabled = false;
290 // Restore the previous signal handlers.
291 for (unsigned i = 0; i != NumSignals; ++i)
292 sigaction(Signals[i], &PrevActions[i], 0);
297 bool CrashRecoveryContext::RunSafely(void (*Fn)(void*), void *UserData) {
298 // If crash recovery is disabled, do nothing.
299 if (gCrashRecoveryEnabled) {
300 assert(!Impl && "Crash recovery context already initialized!");
301 CrashRecoveryContextImpl *CRCI = new CrashRecoveryContextImpl(this);
304 if (setjmp(CRCI->JumpBuffer) != 0) {
313 void CrashRecoveryContext::HandleCrash() {
314 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
315 assert(CRCI && "Crash recovery context never initialized!");
319 const std::string &CrashRecoveryContext::getBacktrace() const {
320 CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *) Impl;
321 assert(CRC && "Crash recovery context never initialized!");
322 assert(CRC->Failed && "No crash was detected!");
323 return CRC->Backtrace;
329 struct RunSafelyOnThreadInfo {
330 void (*UserFn)(void*);
332 CrashRecoveryContext *CRC;
337 static void RunSafelyOnThread_Dispatch(void *UserData) {
338 RunSafelyOnThreadInfo *Info =
339 reinterpret_cast<RunSafelyOnThreadInfo*>(UserData);
340 Info->Result = Info->CRC->RunSafely(Info->UserFn, Info->UserData);
342 bool CrashRecoveryContext::RunSafelyOnThread(void (*Fn)(void*), void *UserData,
343 unsigned RequestedStackSize) {
344 RunSafelyOnThreadInfo Info = { Fn, UserData, this, false };
345 llvm_execute_on_thread(RunSafelyOnThread_Dispatch, &Info, RequestedStackSize);