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/ErrorHandling.h"
14 #include "llvm/Support/ManagedStatic.h"
15 #include "llvm/Support/Mutex.h"
16 #include "llvm/Support/ThreadLocal.h"
23 struct CrashRecoveryContextImpl;
26 sys::ThreadLocal<const CrashRecoveryContextImpl> > CurrentContext;
28 struct CrashRecoveryContextImpl {
29 CrashRecoveryContext *CRC;
30 std::string Backtrace;
32 volatile unsigned Failed : 1;
33 unsigned SwitchedThread : 1;
36 CrashRecoveryContextImpl(CrashRecoveryContext *CRC) : CRC(CRC),
38 SwitchedThread(false) {
39 CurrentContext->set(this);
41 ~CrashRecoveryContextImpl() {
43 CurrentContext->erase();
46 /// \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; }
51 // Eliminate the current context entry, to avoid re-entering in case the
52 // cleanup code crashes.
53 CurrentContext->erase();
55 assert(!Failed && "Crash recovery context already failed!");
58 // FIXME: Stash the backtrace.
60 // Jump back to the RunSafely we were called under.
61 longjmp(JumpBuffer, 1);
67 static ManagedStatic<sys::Mutex> gCrashRecoveryContextMutex;
68 static bool gCrashRecoveryEnabled = false;
70 static ManagedStatic<sys::ThreadLocal<const CrashRecoveryContextCleanup> >
71 tlIsRecoveringFromCrash;
73 CrashRecoveryContextCleanup::~CrashRecoveryContextCleanup() {}
75 CrashRecoveryContext::~CrashRecoveryContext() {
76 // Reclaim registered resources.
77 CrashRecoveryContextCleanup *i = head;
78 tlIsRecoveringFromCrash->set(head);
80 CrashRecoveryContextCleanup *tmp = i;
82 tmp->cleanupFired = true;
83 tmp->recoverResources();
86 tlIsRecoveringFromCrash->erase();
88 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
92 bool CrashRecoveryContext::isRecoveringFromCrash() {
93 return tlIsRecoveringFromCrash->get() != nullptr;
96 CrashRecoveryContext *CrashRecoveryContext::GetCurrent() {
97 if (!gCrashRecoveryEnabled)
100 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
107 void CrashRecoveryContext::registerCleanup(CrashRecoveryContextCleanup *cleanup)
112 head->prev = cleanup;
113 cleanup->next = head;
118 CrashRecoveryContext::unregisterCleanup(CrashRecoveryContextCleanup *cleanup) {
121 if (cleanup == head) {
122 head = cleanup->next;
124 head->prev = nullptr;
127 cleanup->prev->next = cleanup->next;
129 cleanup->next->prev = cleanup->prev;
136 #include "Windows/WindowsSupport.h"
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
145 // Vectored exception handling is built on top of SEH, and so it
146 // works on a per-thread basis.
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.
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).
156 static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
158 // Lookup the current thread local recovery object.
159 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
162 // Something has gone horribly wrong, so let's just tell everyone
164 CrashRecoveryContext::Disable();
165 return EXCEPTION_CONTINUE_SEARCH;
168 // TODO: We can capture the stack backtrace here and store it on the
169 // implementation if we so choose.
172 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
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");
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.
184 static sys::ThreadLocal<const void> sCurrentExceptionHandle;
186 void CrashRecoveryContext::Enable() {
187 sys::ScopedLock L(*gCrashRecoveryContextMutex);
189 if (gCrashRecoveryEnabled)
192 gCrashRecoveryEnabled = true;
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);
202 void CrashRecoveryContext::Disable() {
203 sys::ScopedLock L(*gCrashRecoveryContextMutex);
205 if (!gCrashRecoveryEnabled)
208 gCrashRecoveryEnabled = false;
210 PVOID currentHandle = const_cast<PVOID>(sCurrentExceptionHandle.get());
212 // Now we can remove the vectored exception handler from the chain
213 ::RemoveVectoredExceptionHandler(currentHandle);
215 // Reset the handle in our thread-local set.
216 sCurrentExceptionHandle.set(NULL);
222 // Generic POSIX implementation.
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.
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.
235 static const int Signals[] =
236 { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP };
237 static const unsigned NumSignals = sizeof(Signals) / sizeof(Signals[0]);
238 static struct sigaction PrevActions[NumSignals];
240 static void CrashRecoverySignalHandler(int Signal) {
241 // Lookup the current thread local recovery object.
242 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
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
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.
254 // This call of Disable isn't thread safe, but it doesn't actually matter.
255 CrashRecoveryContext::Disable();
258 // The signal will be thrown once the signal mask is restored.
262 // Unblock the signal we received.
264 sigemptyset(&SigMask);
265 sigaddset(&SigMask, Signal);
266 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
269 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
272 void CrashRecoveryContext::Enable() {
273 sys::ScopedLock L(*gCrashRecoveryContextMutex);
275 if (gCrashRecoveryEnabled)
278 gCrashRecoveryEnabled = true;
280 // Setup the signal handler.
281 struct sigaction Handler;
282 Handler.sa_handler = CrashRecoverySignalHandler;
283 Handler.sa_flags = 0;
284 sigemptyset(&Handler.sa_mask);
286 for (unsigned i = 0; i != NumSignals; ++i) {
287 sigaction(Signals[i], &Handler, &PrevActions[i]);
291 void CrashRecoveryContext::Disable() {
292 sys::ScopedLock L(*gCrashRecoveryContextMutex);
294 if (!gCrashRecoveryEnabled)
297 gCrashRecoveryEnabled = false;
299 // Restore the previous signal handlers.
300 for (unsigned i = 0; i != NumSignals; ++i)
301 sigaction(Signals[i], &PrevActions[i], nullptr);
306 bool CrashRecoveryContext::RunSafely(function_ref<void()> Fn) {
307 // If crash recovery is disabled, do nothing.
308 if (gCrashRecoveryEnabled) {
309 assert(!Impl && "Crash recovery context already initialized!");
310 CrashRecoveryContextImpl *CRCI = new CrashRecoveryContextImpl(this);
313 if (setjmp(CRCI->JumpBuffer) != 0) {
322 void CrashRecoveryContext::HandleCrash() {
323 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
324 assert(CRCI && "Crash recovery context never initialized!");
328 const 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;
335 // FIXME: Portability.
336 static void setThreadBackgroundPriority() {
338 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
342 static bool hasThreadBackgroundPriority() {
344 return getpriority(PRIO_DARWIN_THREAD, 0) == 1;
351 struct RunSafelyOnThreadInfo {
352 function_ref<void()> Fn;
353 CrashRecoveryContext *CRC;
354 bool UseBackgroundPriority;
359 static void RunSafelyOnThread_Dispatch(void *UserData) {
360 RunSafelyOnThreadInfo *Info =
361 reinterpret_cast<RunSafelyOnThreadInfo*>(UserData);
363 if (Info->UseBackgroundPriority)
364 setThreadBackgroundPriority();
366 Info->Result = Info->CRC->RunSafely(Info->Fn);
368 bool CrashRecoveryContext::RunSafelyOnThread(function_ref<void()> Fn,
369 unsigned RequestedStackSize) {
370 bool UseBackgroundPriority = hasThreadBackgroundPriority();
371 RunSafelyOnThreadInfo Info = { Fn, this, UseBackgroundPriority, false };
372 llvm_execute_on_thread(RunSafelyOnThread_Dispatch, &Info, RequestedStackSize);
373 if (CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *)Impl)
374 CRC->setSwitchedThread();