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;
34 std::string Backtrace;
36 volatile unsigned Failed : 1;
37 unsigned SwitchedThread : 1;
40 CrashRecoveryContextImpl(CrashRecoveryContext *CRC) : CRC(CRC),
42 SwitchedThread(false) {
43 Next = CurrentContext->get();
44 CurrentContext->set(this);
46 ~CrashRecoveryContextImpl() {
48 CurrentContext->set(Next);
51 /// \brief Called when the separate crash-recovery thread was finished, to
52 /// indicate that we don't need to clear the thread-local CurrentContext.
53 void setSwitchedThread() {
54 #if defined(LLVM_ENABLE_THREADS) && LLVM_ENABLE_THREADS != 0
55 SwitchedThread = true;
60 // Eliminate the current context entry, to avoid re-entering in case the
61 // cleanup code crashes.
62 CurrentContext->set(Next);
64 assert(!Failed && "Crash recovery context already failed!");
67 // FIXME: Stash the backtrace.
69 // Jump back to the RunSafely we were called under.
70 longjmp(JumpBuffer, 1);
76 static ManagedStatic<sys::Mutex> gCrashRecoveryContextMutex;
77 static bool gCrashRecoveryEnabled = false;
79 static ManagedStatic<sys::ThreadLocal<const CrashRecoveryContext>>
80 tlIsRecoveringFromCrash;
82 CrashRecoveryContextCleanup::~CrashRecoveryContextCleanup() {}
84 CrashRecoveryContext::~CrashRecoveryContext() {
85 // Reclaim registered resources.
86 CrashRecoveryContextCleanup *i = head;
87 const CrashRecoveryContext *PC = tlIsRecoveringFromCrash->get();
88 tlIsRecoveringFromCrash->set(this);
90 CrashRecoveryContextCleanup *tmp = i;
92 tmp->cleanupFired = true;
93 tmp->recoverResources();
96 tlIsRecoveringFromCrash->set(PC);
98 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
102 bool CrashRecoveryContext::isRecoveringFromCrash() {
103 return tlIsRecoveringFromCrash->get() != nullptr;
106 CrashRecoveryContext *CrashRecoveryContext::GetCurrent() {
107 if (!gCrashRecoveryEnabled)
110 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
117 void CrashRecoveryContext::registerCleanup(CrashRecoveryContextCleanup *cleanup)
122 head->prev = cleanup;
123 cleanup->next = head;
128 CrashRecoveryContext::unregisterCleanup(CrashRecoveryContextCleanup *cleanup) {
131 if (cleanup == head) {
132 head = cleanup->next;
134 head->prev = nullptr;
137 cleanup->prev->next = cleanup->next;
139 cleanup->next->prev = cleanup->prev;
146 #include "Windows/WindowsSupport.h"
148 // On Windows, we can make use of vectored exception handling to
149 // catch most crashing situations. Note that this does mean
150 // we will be alerted of exceptions *before* structured exception
151 // handling has the opportunity to catch it. But that isn't likely
152 // to cause problems because nowhere in the project is SEH being
155 // Vectored exception handling is built on top of SEH, and so it
156 // works on a per-thread basis.
158 // The vectored exception handler functionality was added in Windows
159 // XP, so if support for older versions of Windows is required,
160 // it will have to be added.
162 // If we want to support as far back as Win2k, we could use the
163 // SetUnhandledExceptionFilter API, but there's a risk of that
164 // being entirely overwritten (it's not a chain).
166 static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
168 // Lookup the current thread local recovery object.
169 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
172 // Something has gone horribly wrong, so let's just tell everyone
174 CrashRecoveryContext::Disable();
175 return EXCEPTION_CONTINUE_SEARCH;
178 // TODO: We can capture the stack backtrace here and store it on the
179 // implementation if we so choose.
182 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
184 // Note that we don't actually get here because HandleCrash calls
185 // longjmp, which means the HandleCrash function never returns.
186 llvm_unreachable("Handled the crash, should have longjmp'ed out of here");
189 // Because the Enable and Disable calls are static, it means that
190 // there may not actually be an Impl available, or even a current
191 // CrashRecoveryContext at all. So we make use of a thread-local
192 // exception table. The handles contained in here will either be
193 // non-NULL, valid VEH handles, or NULL.
194 static sys::ThreadLocal<const void> sCurrentExceptionHandle;
196 void CrashRecoveryContext::Enable() {
197 sys::ScopedLock L(*gCrashRecoveryContextMutex);
199 if (gCrashRecoveryEnabled)
202 gCrashRecoveryEnabled = true;
204 // We can set up vectored exception handling now. We will install our
205 // handler as the front of the list, though there's no assurances that
206 // it will remain at the front (another call could install itself before
207 // our handler). This 1) isn't likely, and 2) shouldn't cause problems.
208 PVOID handle = ::AddVectoredExceptionHandler(1, ExceptionHandler);
209 sCurrentExceptionHandle.set(handle);
212 void CrashRecoveryContext::Disable() {
213 sys::ScopedLock L(*gCrashRecoveryContextMutex);
215 if (!gCrashRecoveryEnabled)
218 gCrashRecoveryEnabled = false;
220 PVOID currentHandle = const_cast<PVOID>(sCurrentExceptionHandle.get());
222 // Now we can remove the vectored exception handler from the chain
223 ::RemoveVectoredExceptionHandler(currentHandle);
225 // Reset the handle in our thread-local set.
226 sCurrentExceptionHandle.set(NULL);
232 // Generic POSIX implementation.
234 // This implementation relies on synchronous signals being delivered to the
235 // current thread. We use a thread local object to keep track of the active
236 // crash recovery context, and install signal handlers to invoke HandleCrash on
237 // the active object.
239 // This implementation does not to attempt to chain signal handlers in any
240 // reliable fashion -- if we get a signal outside of a crash recovery context we
241 // simply disable crash recovery and raise the signal again.
245 static const int Signals[] =
246 { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP };
247 static const unsigned NumSignals = sizeof(Signals) / sizeof(Signals[0]);
248 static struct sigaction PrevActions[NumSignals];
250 static void CrashRecoverySignalHandler(int Signal) {
251 // Lookup the current thread local recovery object.
252 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
255 // We didn't find a crash recovery context -- this means either we got a
256 // signal on a thread we didn't expect it on, the application got a signal
257 // outside of a crash recovery context, or something else went horribly
260 // Disable crash recovery and raise the signal again. The assumption here is
261 // that the enclosing application will terminate soon, and we won't want to
262 // attempt crash recovery again.
264 // This call of Disable isn't thread safe, but it doesn't actually matter.
265 CrashRecoveryContext::Disable();
268 // The signal will be thrown once the signal mask is restored.
272 // Unblock the signal we received.
274 sigemptyset(&SigMask);
275 sigaddset(&SigMask, Signal);
276 sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
279 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
282 void CrashRecoveryContext::Enable() {
283 sys::ScopedLock L(*gCrashRecoveryContextMutex);
285 if (gCrashRecoveryEnabled)
288 gCrashRecoveryEnabled = true;
290 // Setup the signal handler.
291 struct sigaction Handler;
292 Handler.sa_handler = CrashRecoverySignalHandler;
293 Handler.sa_flags = 0;
294 sigemptyset(&Handler.sa_mask);
296 for (unsigned i = 0; i != NumSignals; ++i) {
297 sigaction(Signals[i], &Handler, &PrevActions[i]);
301 void CrashRecoveryContext::Disable() {
302 sys::ScopedLock L(*gCrashRecoveryContextMutex);
304 if (!gCrashRecoveryEnabled)
307 gCrashRecoveryEnabled = false;
309 // Restore the previous signal handlers.
310 for (unsigned i = 0; i != NumSignals; ++i)
311 sigaction(Signals[i], &PrevActions[i], nullptr);
316 bool CrashRecoveryContext::RunSafely(function_ref<void()> Fn) {
317 // If crash recovery is disabled, do nothing.
318 if (gCrashRecoveryEnabled) {
319 assert(!Impl && "Crash recovery context already initialized!");
320 CrashRecoveryContextImpl *CRCI = new CrashRecoveryContextImpl(this);
323 if (setjmp(CRCI->JumpBuffer) != 0) {
332 void CrashRecoveryContext::HandleCrash() {
333 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
334 assert(CRCI && "Crash recovery context never initialized!");
338 const std::string &CrashRecoveryContext::getBacktrace() const {
339 CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *) Impl;
340 assert(CRC && "Crash recovery context never initialized!");
341 assert(CRC->Failed && "No crash was detected!");
342 return CRC->Backtrace;
345 // FIXME: Portability.
346 static void setThreadBackgroundPriority() {
348 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
352 static bool hasThreadBackgroundPriority() {
354 return getpriority(PRIO_DARWIN_THREAD, 0) == 1;
361 struct RunSafelyOnThreadInfo {
362 function_ref<void()> Fn;
363 CrashRecoveryContext *CRC;
364 bool UseBackgroundPriority;
369 static void RunSafelyOnThread_Dispatch(void *UserData) {
370 RunSafelyOnThreadInfo *Info =
371 reinterpret_cast<RunSafelyOnThreadInfo*>(UserData);
373 if (Info->UseBackgroundPriority)
374 setThreadBackgroundPriority();
376 Info->Result = Info->CRC->RunSafely(Info->Fn);
378 bool CrashRecoveryContext::RunSafelyOnThread(function_ref<void()> Fn,
379 unsigned RequestedStackSize) {
380 bool UseBackgroundPriority = hasThreadBackgroundPriority();
381 RunSafelyOnThreadInfo Info = { Fn, this, UseBackgroundPriority, false };
382 llvm_execute_on_thread(RunSafelyOnThread_Dispatch, &Info, RequestedStackSize);
383 if (CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *)Impl)
384 CRC->setSwitchedThread();