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 // 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.
31 const CrashRecoveryContextImpl *Next;
33 CrashRecoveryContext *CRC;
35 volatile unsigned Failed : 1;
36 unsigned SwitchedThread : 1;
39 CrashRecoveryContextImpl(CrashRecoveryContext *CRC) : CRC(CRC),
41 SwitchedThread(false) {
42 Next = CurrentContext->get();
43 CurrentContext->set(this);
45 ~CrashRecoveryContextImpl() {
47 CurrentContext->set(Next);
50 /// \brief Called when the separate crash-recovery thread was finished, to
51 /// indicate that we don't need to clear the thread-local CurrentContext.
52 void setSwitchedThread() {
53 #if defined(LLVM_ENABLE_THREADS) && LLVM_ENABLE_THREADS != 0
54 SwitchedThread = true;
59 // Eliminate the current context entry, to avoid re-entering in case the
60 // cleanup code crashes.
61 CurrentContext->set(Next);
63 assert(!Failed && "Crash recovery context already failed!");
66 // FIXME: Stash the backtrace.
68 // Jump back to the RunSafely we were called under.
69 longjmp(JumpBuffer, 1);
75 static ManagedStatic<sys::Mutex> gCrashRecoveryContextMutex;
76 static bool gCrashRecoveryEnabled = false;
78 static ManagedStatic<sys::ThreadLocal<const CrashRecoveryContext>>
79 tlIsRecoveringFromCrash;
81 CrashRecoveryContextCleanup::~CrashRecoveryContextCleanup() {}
83 CrashRecoveryContext::~CrashRecoveryContext() {
84 // Reclaim registered resources.
85 CrashRecoveryContextCleanup *i = head;
86 const CrashRecoveryContext *PC = tlIsRecoveringFromCrash->get();
87 tlIsRecoveringFromCrash->set(this);
89 CrashRecoveryContextCleanup *tmp = i;
91 tmp->cleanupFired = true;
92 tmp->recoverResources();
95 tlIsRecoveringFromCrash->set(PC);
97 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
101 bool CrashRecoveryContext::isRecoveringFromCrash() {
102 return tlIsRecoveringFromCrash->get() != nullptr;
105 CrashRecoveryContext *CrashRecoveryContext::GetCurrent() {
106 if (!gCrashRecoveryEnabled)
109 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
116 void CrashRecoveryContext::registerCleanup(CrashRecoveryContextCleanup *cleanup)
121 head->prev = cleanup;
122 cleanup->next = head;
127 CrashRecoveryContext::unregisterCleanup(CrashRecoveryContextCleanup *cleanup) {
130 if (cleanup == head) {
131 head = cleanup->next;
133 head->prev = nullptr;
136 cleanup->prev->next = cleanup->next;
138 cleanup->next->prev = cleanup->prev;
145 #include "Windows/WindowsSupport.h"
147 // On Windows, we can make use of vectored exception handling to
148 // catch most crashing situations. Note that this does mean
149 // we will be alerted of exceptions *before* structured exception
150 // handling has the opportunity to catch it. But that isn't likely
151 // to cause problems because nowhere in the project is SEH being
154 // Vectored exception handling is built on top of SEH, and so it
155 // works on a per-thread basis.
157 // The vectored exception handler functionality was added in Windows
158 // XP, so if support for older versions of Windows is required,
159 // it will have to be added.
161 // If we want to support as far back as Win2k, we could use the
162 // SetUnhandledExceptionFilter API, but there's a risk of that
163 // being entirely overwritten (it's not a chain).
165 static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
167 // DBG_PRINTEXCEPTION_WIDE_C is not properly defined on all supported
168 // compilers and platforms, so we define it manually.
169 constexpr ULONG DbgPrintExceptionWideC = 0x4001000AL;
170 switch (ExceptionInfo->ExceptionRecord->ExceptionCode)
172 case DBG_PRINTEXCEPTION_C:
173 case DbgPrintExceptionWideC:
174 case 0x406D1388: // set debugger thread name
175 return EXCEPTION_CONTINUE_EXECUTION;
178 // Lookup the current thread local recovery object.
179 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
182 // Something has gone horribly wrong, so let's just tell everyone
184 CrashRecoveryContext::Disable();
185 return EXCEPTION_CONTINUE_SEARCH;
188 // TODO: We can capture the stack backtrace here and store it on the
189 // implementation if we so choose.
192 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
194 // Note that we don't actually get here because HandleCrash calls
195 // longjmp, which means the HandleCrash function never returns.
196 llvm_unreachable("Handled the crash, should have longjmp'ed out of here");
199 // Because the Enable and Disable calls are static, it means that
200 // there may not actually be an Impl available, or even a current
201 // CrashRecoveryContext at all. So we make use of a thread-local
202 // exception table. The handles contained in here will either be
203 // non-NULL, valid VEH handles, or NULL.
204 static sys::ThreadLocal<const void> sCurrentExceptionHandle;
206 void CrashRecoveryContext::Enable() {
207 sys::ScopedLock L(*gCrashRecoveryContextMutex);
209 if (gCrashRecoveryEnabled)
212 gCrashRecoveryEnabled = true;
214 // We can set up vectored exception handling now. We will install our
215 // handler as the front of the list, though there's no assurances that
216 // it will remain at the front (another call could install itself before
217 // our handler). This 1) isn't likely, and 2) shouldn't cause problems.
218 PVOID handle = ::AddVectoredExceptionHandler(1, ExceptionHandler);
219 sCurrentExceptionHandle.set(handle);
222 void CrashRecoveryContext::Disable() {
223 sys::ScopedLock L(*gCrashRecoveryContextMutex);
225 if (!gCrashRecoveryEnabled)
228 gCrashRecoveryEnabled = false;
230 PVOID currentHandle = const_cast<PVOID>(sCurrentExceptionHandle.get());
232 // Now we can remove the vectored exception handler from the chain
233 ::RemoveVectoredExceptionHandler(currentHandle);
235 // Reset the handle in our thread-local set.
236 sCurrentExceptionHandle.set(NULL);
242 // Generic POSIX implementation.
244 // This implementation relies on synchronous signals being delivered to the
245 // current thread. We use a thread local object to keep track of the active
246 // crash recovery context, and install signal handlers to invoke HandleCrash on
247 // the active object.
249 // This implementation does not to attempt to chain signal handlers in any
250 // reliable fashion -- if we get a signal outside of a crash recovery context we
251 // simply disable crash recovery and raise the signal again.
255 static const int Signals[] =
256 { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP };
257 static const unsigned NumSignals = array_lengthof(Signals);
258 static struct sigaction PrevActions[NumSignals];
260 static void CrashRecoverySignalHandler(int Signal) {
261 // Lookup the current thread local recovery object.
262 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
265 // We didn't find a crash recovery context -- this means either we got a
266 // signal on a thread we didn't expect it on, the application got a signal
267 // outside of a crash recovery context, or something else went horribly
270 // Disable crash recovery and raise the signal again. The assumption here is
271 // that the enclosing application will terminate soon, and we won't want to
272 // attempt crash recovery again.
274 // This call of Disable isn't thread safe, but it doesn't actually matter.
275 CrashRecoveryContext::Disable();
278 // The signal will be thrown once the signal mask is restored.
282 // Unblock the signal we received.
284 sigemptyset(&SigMask);
285 sigaddset(&SigMask, Signal);
286 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
289 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
292 void CrashRecoveryContext::Enable() {
293 sys::ScopedLock L(*gCrashRecoveryContextMutex);
295 if (gCrashRecoveryEnabled)
298 gCrashRecoveryEnabled = true;
300 // Setup the signal handler.
301 struct sigaction Handler;
302 Handler.sa_handler = CrashRecoverySignalHandler;
303 Handler.sa_flags = 0;
304 sigemptyset(&Handler.sa_mask);
306 for (unsigned i = 0; i != NumSignals; ++i) {
307 sigaction(Signals[i], &Handler, &PrevActions[i]);
311 void CrashRecoveryContext::Disable() {
312 sys::ScopedLock L(*gCrashRecoveryContextMutex);
314 if (!gCrashRecoveryEnabled)
317 gCrashRecoveryEnabled = false;
319 // Restore the previous signal handlers.
320 for (unsigned i = 0; i != NumSignals; ++i)
321 sigaction(Signals[i], &PrevActions[i], nullptr);
326 bool CrashRecoveryContext::RunSafely(function_ref<void()> Fn) {
327 // If crash recovery is disabled, do nothing.
328 if (gCrashRecoveryEnabled) {
329 assert(!Impl && "Crash recovery context already initialized!");
330 CrashRecoveryContextImpl *CRCI = new CrashRecoveryContextImpl(this);
333 if (setjmp(CRCI->JumpBuffer) != 0) {
342 void CrashRecoveryContext::HandleCrash() {
343 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
344 assert(CRCI && "Crash recovery context never initialized!");
348 // FIXME: Portability.
349 static void setThreadBackgroundPriority() {
351 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
355 static bool hasThreadBackgroundPriority() {
357 return getpriority(PRIO_DARWIN_THREAD, 0) == 1;
364 struct RunSafelyOnThreadInfo {
365 function_ref<void()> Fn;
366 CrashRecoveryContext *CRC;
367 bool UseBackgroundPriority;
372 static void RunSafelyOnThread_Dispatch(void *UserData) {
373 RunSafelyOnThreadInfo *Info =
374 reinterpret_cast<RunSafelyOnThreadInfo*>(UserData);
376 if (Info->UseBackgroundPriority)
377 setThreadBackgroundPriority();
379 Info->Result = Info->CRC->RunSafely(Info->Fn);
381 bool CrashRecoveryContext::RunSafelyOnThread(function_ref<void()> Fn,
382 unsigned RequestedStackSize) {
383 bool UseBackgroundPriority = hasThreadBackgroundPriority();
384 RunSafelyOnThreadInfo Info = { Fn, this, UseBackgroundPriority, false };
385 llvm_execute_on_thread(RunSafelyOnThread_Dispatch, &Info, RequestedStackSize);
386 if (CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *)Impl)
387 CRC->setSwitchedThread();