xref: /llvm-project/llvm/lib/Support/CrashRecoveryContext.cpp (revision 13e87f43d9ed41554c16d086f077cfb8e02cced4)
1 //===--- CrashRecoveryContext.cpp - Crash Recovery ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
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"
16 #include <setjmp.h>
17 using namespace llvm;
18 
19 namespace {
20 
21 struct CrashRecoveryContextImpl;
22 
23 static ManagedStatic<
24     sys::ThreadLocal<const CrashRecoveryContextImpl> > CurrentContext;
25 
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;
32 
33   CrashRecoveryContext *CRC;
34   ::jmp_buf JumpBuffer;
35   volatile unsigned Failed : 1;
36   unsigned SwitchedThread : 1;
37 
38 public:
39   CrashRecoveryContextImpl(CrashRecoveryContext *CRC) : CRC(CRC),
40                                                         Failed(false),
41                                                         SwitchedThread(false) {
42     Next = CurrentContext->get();
43     CurrentContext->set(this);
44   }
45   ~CrashRecoveryContextImpl() {
46     if (!SwitchedThread)
47       CurrentContext->set(Next);
48   }
49 
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;
55 #endif
56   }
57 
58   void HandleCrash() {
59     // Eliminate the current context entry, to avoid re-entering in case the
60     // cleanup code crashes.
61     CurrentContext->set(Next);
62 
63     assert(!Failed && "Crash recovery context already failed!");
64     Failed = true;
65 
66     // FIXME: Stash the backtrace.
67 
68     // Jump back to the RunSafely we were called under.
69     longjmp(JumpBuffer, 1);
70   }
71 };
72 
73 }
74 
75 static ManagedStatic<sys::Mutex> gCrashRecoveryContextMutex;
76 static bool gCrashRecoveryEnabled = false;
77 
78 static ManagedStatic<sys::ThreadLocal<const CrashRecoveryContext>>
79        tlIsRecoveringFromCrash;
80 
81 CrashRecoveryContextCleanup::~CrashRecoveryContextCleanup() {}
82 
83 CrashRecoveryContext::~CrashRecoveryContext() {
84   // Reclaim registered resources.
85   CrashRecoveryContextCleanup *i = head;
86   const CrashRecoveryContext *PC = tlIsRecoveringFromCrash->get();
87   tlIsRecoveringFromCrash->set(this);
88   while (i) {
89     CrashRecoveryContextCleanup *tmp = i;
90     i = tmp->next;
91     tmp->cleanupFired = true;
92     tmp->recoverResources();
93     delete tmp;
94   }
95   tlIsRecoveringFromCrash->set(PC);
96 
97   CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
98   delete CRCI;
99 }
100 
101 bool CrashRecoveryContext::isRecoveringFromCrash() {
102   return tlIsRecoveringFromCrash->get() != nullptr;
103 }
104 
105 CrashRecoveryContext *CrashRecoveryContext::GetCurrent() {
106   if (!gCrashRecoveryEnabled)
107     return nullptr;
108 
109   const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
110   if (!CRCI)
111     return nullptr;
112 
113   return CRCI->CRC;
114 }
115 
116 void CrashRecoveryContext::registerCleanup(CrashRecoveryContextCleanup *cleanup)
117 {
118   if (!cleanup)
119     return;
120   if (head)
121     head->prev = cleanup;
122   cleanup->next = head;
123   head = cleanup;
124 }
125 
126 void
127 CrashRecoveryContext::unregisterCleanup(CrashRecoveryContextCleanup *cleanup) {
128   if (!cleanup)
129     return;
130   if (cleanup == head) {
131     head = cleanup->next;
132     if (head)
133       head->prev = nullptr;
134   }
135   else {
136     cleanup->prev->next = cleanup->next;
137     if (cleanup->next)
138       cleanup->next->prev = cleanup->prev;
139   }
140   delete cleanup;
141 }
142 
143 #ifdef LLVM_ON_WIN32
144 
145 #include "Windows/WindowsSupport.h"
146 
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
152 // used.
153 //
154 // Vectored exception handling is built on top of SEH, and so it
155 // works on a per-thread basis.
156 //
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.
160 //
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).
164 
165 static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
166 {
167   switch (ExceptionInfo->ExceptionRecord->ExceptionCode)
168   {
169   case DBG_PRINTEXCEPTION_C:
170   case DBG_PRINTEXCEPTION_WIDE_C:
171   case 0x406D1388:  // set debugger thread name
172     return EXCEPTION_CONTINUE_EXECUTION;
173   }
174 
175   // Lookup the current thread local recovery object.
176   const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
177 
178   if (!CRCI) {
179     // Something has gone horribly wrong, so let's just tell everyone
180     // to keep searching
181     CrashRecoveryContext::Disable();
182     return EXCEPTION_CONTINUE_SEARCH;
183   }
184 
185   // TODO: We can capture the stack backtrace here and store it on the
186   // implementation if we so choose.
187 
188   // Handle the crash
189   const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
190 
191   // Note that we don't actually get here because HandleCrash calls
192   // longjmp, which means the HandleCrash function never returns.
193   llvm_unreachable("Handled the crash, should have longjmp'ed out of here");
194 }
195 
196 // Because the Enable and Disable calls are static, it means that
197 // there may not actually be an Impl available, or even a current
198 // CrashRecoveryContext at all.  So we make use of a thread-local
199 // exception table.  The handles contained in here will either be
200 // non-NULL, valid VEH handles, or NULL.
201 static sys::ThreadLocal<const void> sCurrentExceptionHandle;
202 
203 void CrashRecoveryContext::Enable() {
204   sys::ScopedLock L(*gCrashRecoveryContextMutex);
205 
206   if (gCrashRecoveryEnabled)
207     return;
208 
209   gCrashRecoveryEnabled = true;
210 
211   // We can set up vectored exception handling now.  We will install our
212   // handler as the front of the list, though there's no assurances that
213   // it will remain at the front (another call could install itself before
214   // our handler).  This 1) isn't likely, and 2) shouldn't cause problems.
215   PVOID handle = ::AddVectoredExceptionHandler(1, ExceptionHandler);
216   sCurrentExceptionHandle.set(handle);
217 }
218 
219 void CrashRecoveryContext::Disable() {
220   sys::ScopedLock L(*gCrashRecoveryContextMutex);
221 
222   if (!gCrashRecoveryEnabled)
223     return;
224 
225   gCrashRecoveryEnabled = false;
226 
227   PVOID currentHandle = const_cast<PVOID>(sCurrentExceptionHandle.get());
228   if (currentHandle) {
229     // Now we can remove the vectored exception handler from the chain
230     ::RemoveVectoredExceptionHandler(currentHandle);
231 
232     // Reset the handle in our thread-local set.
233     sCurrentExceptionHandle.set(NULL);
234   }
235 }
236 
237 #else
238 
239 // Generic POSIX implementation.
240 //
241 // This implementation relies on synchronous signals being delivered to the
242 // current thread. We use a thread local object to keep track of the active
243 // crash recovery context, and install signal handlers to invoke HandleCrash on
244 // the active object.
245 //
246 // This implementation does not to attempt to chain signal handlers in any
247 // reliable fashion -- if we get a signal outside of a crash recovery context we
248 // simply disable crash recovery and raise the signal again.
249 
250 #include <signal.h>
251 
252 static const int Signals[] =
253     { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP };
254 static const unsigned NumSignals = array_lengthof(Signals);
255 static struct sigaction PrevActions[NumSignals];
256 
257 static void CrashRecoverySignalHandler(int Signal) {
258   // Lookup the current thread local recovery object.
259   const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
260 
261   if (!CRCI) {
262     // We didn't find a crash recovery context -- this means either we got a
263     // signal on a thread we didn't expect it on, the application got a signal
264     // outside of a crash recovery context, or something else went horribly
265     // wrong.
266     //
267     // Disable crash recovery and raise the signal again. The assumption here is
268     // that the enclosing application will terminate soon, and we won't want to
269     // attempt crash recovery again.
270     //
271     // This call of Disable isn't thread safe, but it doesn't actually matter.
272     CrashRecoveryContext::Disable();
273     raise(Signal);
274 
275     // The signal will be thrown once the signal mask is restored.
276     return;
277   }
278 
279   // Unblock the signal we received.
280   sigset_t SigMask;
281   sigemptyset(&SigMask);
282   sigaddset(&SigMask, Signal);
283   sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
284 
285   if (CRCI)
286     const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
287 }
288 
289 void CrashRecoveryContext::Enable() {
290   sys::ScopedLock L(*gCrashRecoveryContextMutex);
291 
292   if (gCrashRecoveryEnabled)
293     return;
294 
295   gCrashRecoveryEnabled = true;
296 
297   // Setup the signal handler.
298   struct sigaction Handler;
299   Handler.sa_handler = CrashRecoverySignalHandler;
300   Handler.sa_flags = 0;
301   sigemptyset(&Handler.sa_mask);
302 
303   for (unsigned i = 0; i != NumSignals; ++i) {
304     sigaction(Signals[i], &Handler, &PrevActions[i]);
305   }
306 }
307 
308 void CrashRecoveryContext::Disable() {
309   sys::ScopedLock L(*gCrashRecoveryContextMutex);
310 
311   if (!gCrashRecoveryEnabled)
312     return;
313 
314   gCrashRecoveryEnabled = false;
315 
316   // Restore the previous signal handlers.
317   for (unsigned i = 0; i != NumSignals; ++i)
318     sigaction(Signals[i], &PrevActions[i], nullptr);
319 }
320 
321 #endif
322 
323 bool CrashRecoveryContext::RunSafely(function_ref<void()> Fn) {
324   // If crash recovery is disabled, do nothing.
325   if (gCrashRecoveryEnabled) {
326     assert(!Impl && "Crash recovery context already initialized!");
327     CrashRecoveryContextImpl *CRCI = new CrashRecoveryContextImpl(this);
328     Impl = CRCI;
329 
330     if (setjmp(CRCI->JumpBuffer) != 0) {
331       return false;
332     }
333   }
334 
335   Fn();
336   return true;
337 }
338 
339 void CrashRecoveryContext::HandleCrash() {
340   CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
341   assert(CRCI && "Crash recovery context never initialized!");
342   CRCI->HandleCrash();
343 }
344 
345 // FIXME: Portability.
346 static void setThreadBackgroundPriority() {
347 #ifdef __APPLE__
348   setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
349 #endif
350 }
351 
352 static bool hasThreadBackgroundPriority() {
353 #ifdef __APPLE__
354   return getpriority(PRIO_DARWIN_THREAD, 0) == 1;
355 #else
356   return false;
357 #endif
358 }
359 
360 namespace {
361 struct RunSafelyOnThreadInfo {
362   function_ref<void()> Fn;
363   CrashRecoveryContext *CRC;
364   bool UseBackgroundPriority;
365   bool Result;
366 };
367 }
368 
369 static void RunSafelyOnThread_Dispatch(void *UserData) {
370   RunSafelyOnThreadInfo *Info =
371     reinterpret_cast<RunSafelyOnThreadInfo*>(UserData);
372 
373   if (Info->UseBackgroundPriority)
374     setThreadBackgroundPriority();
375 
376   Info->Result = Info->CRC->RunSafely(Info->Fn);
377 }
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();
385   return Info.Result;
386 }
387