blob: 29f73fc539cd93e3a9bc249ae9848c089a6a6fc3 [file] [log] [blame]
Daniel Dunbar19a3b372010-07-28 15:40:20 +00001//===--- 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/ADT/SmallString.h"
Daniel Dunbar9789f812010-07-29 01:52:04 +000012#include "llvm/Config/config.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000013#include "llvm/Support/ErrorHandling.h"
Filip Pizlof2189bf2013-09-12 17:46:57 +000014#include "llvm/Support/ManagedStatic.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000015#include "llvm/Support/Mutex.h"
16#include "llvm/Support/ThreadLocal.h"
Daniel Dunbaraf77e222010-07-29 01:21:47 +000017#include <cstdio>
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include <setjmp.h>
Daniel Dunbar19a3b372010-07-28 15:40:20 +000019using namespace llvm;
20
21namespace {
22
23struct CrashRecoveryContextImpl;
24
Filip Pizlof2189bf2013-09-12 17:46:57 +000025static ManagedStatic<sys::ThreadLocal<const CrashRecoveryContextImpl> > CurrentContext;
Daniel Dunbaraf77e222010-07-29 01:21:47 +000026
Daniel Dunbar19a3b372010-07-28 15:40:20 +000027struct CrashRecoveryContextImpl {
Daniel Dunbarb30266e2010-08-17 22:32:37 +000028 CrashRecoveryContext *CRC;
Daniel Dunbar19a3b372010-07-28 15:40:20 +000029 std::string Backtrace;
30 ::jmp_buf JumpBuffer;
31 volatile unsigned Failed : 1;
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000032 unsigned SwitchedThread : 1;
Daniel Dunbar19a3b372010-07-28 15:40:20 +000033
34public:
Daniel Dunbarb30266e2010-08-17 22:32:37 +000035 CrashRecoveryContextImpl(CrashRecoveryContext *CRC) : CRC(CRC),
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000036 Failed(false),
37 SwitchedThread(false) {
Filip Pizlof2189bf2013-09-12 17:46:57 +000038 CurrentContext->set(this);
Daniel Dunbaraf77e222010-07-29 01:21:47 +000039 }
40 ~CrashRecoveryContextImpl() {
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000041 if (!SwitchedThread)
Filip Pizlof2189bf2013-09-12 17:46:57 +000042 CurrentContext->erase();
Daniel Dunbaraf77e222010-07-29 01:21:47 +000043 }
Daniel Dunbar19a3b372010-07-28 15:40:20 +000044
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +000045 /// \brief Called when the separate crash-recovery thread was finished, to
46 /// indicate that we don't need to clear the thread-local CurrentContext.
47 void setSwitchedThread() { SwitchedThread = true; }
48
Daniel Dunbar19a3b372010-07-28 15:40:20 +000049 void HandleCrash() {
Daniel Dunbar09b0c782010-08-17 22:32:39 +000050 // Eliminate the current context entry, to avoid re-entering in case the
51 // cleanup code crashes.
Filip Pizlof2189bf2013-09-12 17:46:57 +000052 CurrentContext->erase();
Daniel Dunbar09b0c782010-08-17 22:32:39 +000053
Daniel Dunbar19a3b372010-07-28 15:40:20 +000054 assert(!Failed && "Crash recovery context already failed!");
55 Failed = true;
56
57 // FIXME: Stash the backtrace.
58
59 // Jump back to the RunSafely we were called under.
60 longjmp(JumpBuffer, 1);
61 }
62};
63
64}
65
Filip Pizlof2189bf2013-09-12 17:46:57 +000066static ManagedStatic<sys::Mutex> gCrashRecoveryContextMutex;
Daniel Dunbar19a3b372010-07-28 15:40:20 +000067static bool gCrashRecoveryEnabled = false;
68
Filip Pizlof2189bf2013-09-12 17:46:57 +000069static ManagedStatic<sys::ThreadLocal<const CrashRecoveryContextCleanup> >
Ted Kremenekab1a2422011-03-21 18:38:03 +000070 tlIsRecoveringFromCrash;
71
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000072CrashRecoveryContextCleanup::~CrashRecoveryContextCleanup() {}
73
Daniel Dunbar19a3b372010-07-28 15:40:20 +000074CrashRecoveryContext::~CrashRecoveryContext() {
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000075 // Reclaim registered resources.
76 CrashRecoveryContextCleanup *i = head;
Filip Pizlof2189bf2013-09-12 17:46:57 +000077 tlIsRecoveringFromCrash->set(head);
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000078 while (i) {
79 CrashRecoveryContextCleanup *tmp = i;
80 i = tmp->next;
Ted Kremenek32aea2e2011-03-19 00:59:37 +000081 tmp->cleanupFired = true;
Ted Kremenek857e5352011-03-22 04:33:13 +000082 tmp->recoverResources();
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000083 delete tmp;
84 }
Filip Pizlof2189bf2013-09-12 17:46:57 +000085 tlIsRecoveringFromCrash->erase();
Ted Kremenekc44d3cf2011-03-18 02:05:11 +000086
Daniel Dunbar19a3b372010-07-28 15:40:20 +000087 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
88 delete CRCI;
89}
90
Ted Kremenekab1a2422011-03-21 18:38:03 +000091bool CrashRecoveryContext::isRecoveringFromCrash() {
Filip Pizlof2189bf2013-09-12 17:46:57 +000092 return tlIsRecoveringFromCrash->get() != 0;
Ted Kremenekab1a2422011-03-21 18:38:03 +000093}
94
Daniel Dunbarb30266e2010-08-17 22:32:37 +000095CrashRecoveryContext *CrashRecoveryContext::GetCurrent() {
Ted Kremenek794a0712011-03-19 00:59:33 +000096 if (!gCrashRecoveryEnabled)
97 return 0;
98
Filip Pizlof2189bf2013-09-12 17:46:57 +000099 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
Daniel Dunbarb30266e2010-08-17 22:32:37 +0000100 if (!CRCI)
101 return 0;
102
103 return CRCI->CRC;
104}
105
Ted Kremenekc44d3cf2011-03-18 02:05:11 +0000106void CrashRecoveryContext::registerCleanup(CrashRecoveryContextCleanup *cleanup)
107{
108 if (!cleanup)
109 return;
110 if (head)
111 head->prev = cleanup;
112 cleanup->next = head;
113 head = cleanup;
114}
115
116void
117CrashRecoveryContext::unregisterCleanup(CrashRecoveryContextCleanup *cleanup) {
118 if (!cleanup)
119 return;
120 if (cleanup == head) {
121 head = cleanup->next;
122 if (head)
123 head->prev = 0;
124 }
125 else {
126 cleanup->prev->next = cleanup->next;
127 if (cleanup->next)
128 cleanup->next->prev = cleanup->prev;
129 }
130 delete cleanup;
131}
132
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000133#ifdef LLVM_ON_WIN32
134
Reid Klecknerd59e2fa2014-02-12 21:26:20 +0000135#include "Windows/WindowsSupport.h"
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000136
137// On Windows, we can make use of vectored exception handling to
138// catch most crashing situations. Note that this does mean
139// we will be alerted of exceptions *before* structured exception
140// handling has the opportunity to catch it. But that isn't likely
141// to cause problems because nowhere in the project is SEH being
142// used.
143//
144// Vectored exception handling is built on top of SEH, and so it
145// works on a per-thread basis.
146//
147// The vectored exception handler functionality was added in Windows
148// XP, so if support for older versions of Windows is required,
149// it will have to be added.
150//
151// If we want to support as far back as Win2k, we could use the
152// SetUnhandledExceptionFilter API, but there's a risk of that
153// being entirely overwritten (it's not a chain).
154
155static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
156{
157 // Lookup the current thread local recovery object.
Filip Pizlof2189bf2013-09-12 17:46:57 +0000158 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000159
160 if (!CRCI) {
161 // Something has gone horribly wrong, so let's just tell everyone
162 // to keep searching
163 CrashRecoveryContext::Disable();
164 return EXCEPTION_CONTINUE_SEARCH;
165 }
166
167 // TODO: We can capture the stack backtrace here and store it on the
168 // implementation if we so choose.
169
170 // Handle the crash
171 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
172
173 // Note that we don't actually get here because HandleCrash calls
174 // longjmp, which means the HandleCrash function never returns.
175 llvm_unreachable("Handled the crash, should have longjmp'ed out of here");
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000176}
177
178// Because the Enable and Disable calls are static, it means that
179// there may not actually be an Impl available, or even a current
180// CrashRecoveryContext at all. So we make use of a thread-local
181// exception table. The handles contained in here will either be
182// non-NULL, valid VEH handles, or NULL.
183static sys::ThreadLocal<const void> sCurrentExceptionHandle;
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000184
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000185void CrashRecoveryContext::Enable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000186 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000187
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000188 if (gCrashRecoveryEnabled)
189 return;
190
191 gCrashRecoveryEnabled = true;
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000192
193 // We can set up vectored exception handling now. We will install our
194 // handler as the front of the list, though there's no assurances that
195 // it will remain at the front (another call could install itself before
196 // our handler). This 1) isn't likely, and 2) shouldn't cause problems.
197 PVOID handle = ::AddVectoredExceptionHandler(1, ExceptionHandler);
198 sCurrentExceptionHandle.set(handle);
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000199}
200
201void CrashRecoveryContext::Disable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000202 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000203
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000204 if (!gCrashRecoveryEnabled)
205 return;
206
207 gCrashRecoveryEnabled = false;
NAKAMURA Takumi1eae12c2011-08-20 06:35:36 +0000208
209 PVOID currentHandle = const_cast<PVOID>(sCurrentExceptionHandle.get());
210 if (currentHandle) {
211 // Now we can remove the vectored exception handler from the chain
212 ::RemoveVectoredExceptionHandler(currentHandle);
213
214 // Reset the handle in our thread-local set.
215 sCurrentExceptionHandle.set(NULL);
216 }
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000217}
218
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000219#else
220
221// Generic POSIX implementation.
222//
223// This implementation relies on synchronous signals being delivered to the
224// current thread. We use a thread local object to keep track of the active
225// crash recovery context, and install signal handlers to invoke HandleCrash on
226// the active object.
227//
228// This implementation does not to attempt to chain signal handlers in any
229// reliable fashion -- if we get a signal outside of a crash recovery context we
230// simply disable crash recovery and raise the signal again.
231
232#include <signal.h>
233
Nuno Lopese568efb2012-04-21 14:45:37 +0000234static const int Signals[] = { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP };
Daniel Dunbarc90e82a2010-07-30 17:49:04 +0000235static const unsigned NumSignals = sizeof(Signals) / sizeof(Signals[0]);
236static struct sigaction PrevActions[NumSignals];
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000237
238static void CrashRecoverySignalHandler(int Signal) {
239 // Lookup the current thread local recovery object.
Filip Pizlof2189bf2013-09-12 17:46:57 +0000240 const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000241
242 if (!CRCI) {
243 // We didn't find a crash recovery context -- this means either we got a
244 // signal on a thread we didn't expect it on, the application got a signal
245 // outside of a crash recovery context, or something else went horribly
246 // wrong.
247 //
248 // Disable crash recovery and raise the signal again. The assumption here is
249 // that the enclosing application will terminate soon, and we won't want to
250 // attempt crash recovery again.
251 //
252 // This call of Disable isn't thread safe, but it doesn't actually matter.
253 CrashRecoveryContext::Disable();
254 raise(Signal);
Daniel Dunbar418e7042010-10-18 21:55:18 +0000255
256 // The signal will be thrown once the signal mask is restored.
257 return;
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000258 }
259
260 // Unblock the signal we received.
261 sigset_t SigMask;
262 sigemptyset(&SigMask);
263 sigaddset(&SigMask, Signal);
264 sigprocmask(SIG_UNBLOCK, &SigMask, 0);
265
266 if (CRCI)
267 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
268}
269
270void CrashRecoveryContext::Enable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000271 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000272
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000273 if (gCrashRecoveryEnabled)
274 return;
275
276 gCrashRecoveryEnabled = true;
277
278 // Setup the signal handler.
279 struct sigaction Handler;
280 Handler.sa_handler = CrashRecoverySignalHandler;
281 Handler.sa_flags = 0;
282 sigemptyset(&Handler.sa_mask);
283
284 for (unsigned i = 0; i != NumSignals; ++i) {
Daniel Dunbarc90e82a2010-07-30 17:49:04 +0000285 sigaction(Signals[i], &Handler, &PrevActions[i]);
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000286 }
287}
288
289void CrashRecoveryContext::Disable() {
Filip Pizlof2189bf2013-09-12 17:46:57 +0000290 sys::ScopedLock L(*gCrashRecoveryContextMutex);
Daniel Dunbarff329942010-08-17 22:32:34 +0000291
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000292 if (!gCrashRecoveryEnabled)
293 return;
294
295 gCrashRecoveryEnabled = false;
296
297 // Restore the previous signal handlers.
298 for (unsigned i = 0; i != NumSignals; ++i)
Daniel Dunbarc90e82a2010-07-30 17:49:04 +0000299 sigaction(Signals[i], &PrevActions[i], 0);
Daniel Dunbaraf77e222010-07-29 01:21:47 +0000300}
301
302#endif
303
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000304bool CrashRecoveryContext::RunSafely(void (*Fn)(void*), void *UserData) {
305 // If crash recovery is disabled, do nothing.
306 if (gCrashRecoveryEnabled) {
307 assert(!Impl && "Crash recovery context already initialized!");
Daniel Dunbarb30266e2010-08-17 22:32:37 +0000308 CrashRecoveryContextImpl *CRCI = new CrashRecoveryContextImpl(this);
Daniel Dunbar19a3b372010-07-28 15:40:20 +0000309 Impl = CRCI;
310
311 if (setjmp(CRCI->JumpBuffer) != 0) {
312 return false;
313 }
314 }
315
316 Fn(UserData);
317 return true;
318}
319
320void CrashRecoveryContext::HandleCrash() {
321 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
322 assert(CRCI && "Crash recovery context never initialized!");
323 CRCI->HandleCrash();
324}
325
326const std::string &CrashRecoveryContext::getBacktrace() const {
327 CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *) Impl;
328 assert(CRC && "Crash recovery context never initialized!");
329 assert(CRC->Failed && "No crash was detected!");
330 return CRC->Backtrace;
331}
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000332
333//
334
335namespace {
336struct RunSafelyOnThreadInfo {
337 void (*UserFn)(void*);
338 void *UserData;
339 CrashRecoveryContext *CRC;
340 bool Result;
341};
342}
343
344static void RunSafelyOnThread_Dispatch(void *UserData) {
345 RunSafelyOnThreadInfo *Info =
346 reinterpret_cast<RunSafelyOnThreadInfo*>(UserData);
347 Info->Result = Info->CRC->RunSafely(Info->UserFn, Info->UserData);
348}
349bool CrashRecoveryContext::RunSafelyOnThread(void (*Fn)(void*), void *UserData,
350 unsigned RequestedStackSize) {
351 RunSafelyOnThreadInfo Info = { Fn, UserData, this, false };
352 llvm_execute_on_thread(RunSafelyOnThread_Dispatch, &Info, RequestedStackSize);
Argyrios Kyrtzidisf1d8f522013-06-19 22:53:45 +0000353 if (CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *)Impl)
354 CRC->setSwitchedThread();
Daniel Dunbarf4d90ba2010-11-05 07:19:09 +0000355 return Info.Result;
356}