blob: 263114c06f986a3e3594aeec9a805551d6e8c434 [file] [log] [blame]
Daniel Dunbara309dac2010-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 Dunbardade28e2010-07-29 01:52:04 +000012#include "llvm/Config/config.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000013#include "llvm/Support/Mutex.h"
14#include "llvm/Support/ThreadLocal.h"
NAKAMURA Takumi77c10822011-08-20 06:35:36 +000015#include "llvm/Support/ErrorHandling.h"
Daniel Dunbara309dac2010-07-28 15:40:20 +000016#include <setjmp.h>
Daniel Dunbard9082df2010-07-29 01:21:47 +000017#include <cstdio>
Daniel Dunbara309dac2010-07-28 15:40:20 +000018using namespace llvm;
19
20namespace {
21
22struct CrashRecoveryContextImpl;
23
Daniel Dunbard9082df2010-07-29 01:21:47 +000024static sys::ThreadLocal<const CrashRecoveryContextImpl> CurrentContext;
25
Daniel Dunbara309dac2010-07-28 15:40:20 +000026struct CrashRecoveryContextImpl {
Daniel Dunbara8fa7982010-08-17 22:32:37 +000027 CrashRecoveryContext *CRC;
Daniel Dunbara309dac2010-07-28 15:40:20 +000028 std::string Backtrace;
29 ::jmp_buf JumpBuffer;
30 volatile unsigned Failed : 1;
31
32public:
Daniel Dunbara8fa7982010-08-17 22:32:37 +000033 CrashRecoveryContextImpl(CrashRecoveryContext *CRC) : CRC(CRC),
34 Failed(false) {
Daniel Dunbard9082df2010-07-29 01:21:47 +000035 CurrentContext.set(this);
36 }
37 ~CrashRecoveryContextImpl() {
Daniel Dunbara6855822010-07-29 15:24:21 +000038 CurrentContext.erase();
Daniel Dunbard9082df2010-07-29 01:21:47 +000039 }
Daniel Dunbara309dac2010-07-28 15:40:20 +000040
41 void HandleCrash() {
Daniel Dunbarebe7eb82010-08-17 22:32:39 +000042 // Eliminate the current context entry, to avoid re-entering in case the
43 // cleanup code crashes.
44 CurrentContext.erase();
45
Daniel Dunbara309dac2010-07-28 15:40:20 +000046 assert(!Failed && "Crash recovery context already failed!");
47 Failed = true;
48
49 // FIXME: Stash the backtrace.
50
51 // Jump back to the RunSafely we were called under.
52 longjmp(JumpBuffer, 1);
53 }
54};
55
56}
57
Daniel Dunbarc0c815e2010-08-17 22:32:34 +000058static sys::Mutex gCrashRecoveryContexMutex;
Daniel Dunbara309dac2010-07-28 15:40:20 +000059static bool gCrashRecoveryEnabled = false;
60
Ted Kremenekb52fde42011-03-21 18:38:03 +000061static sys::ThreadLocal<const CrashRecoveryContextCleanup>
62 tlIsRecoveringFromCrash;
63
Ted Kremeneka4f98392011-03-18 02:05:11 +000064CrashRecoveryContextCleanup::~CrashRecoveryContextCleanup() {}
65
Daniel Dunbara309dac2010-07-28 15:40:20 +000066CrashRecoveryContext::~CrashRecoveryContext() {
Ted Kremeneka4f98392011-03-18 02:05:11 +000067 // Reclaim registered resources.
68 CrashRecoveryContextCleanup *i = head;
Ted Kremenekb52fde42011-03-21 18:38:03 +000069 tlIsRecoveringFromCrash.set(head);
Ted Kremeneka4f98392011-03-18 02:05:11 +000070 while (i) {
71 CrashRecoveryContextCleanup *tmp = i;
72 i = tmp->next;
Ted Kremenek1a06d572011-03-19 00:59:37 +000073 tmp->cleanupFired = true;
Ted Kremenek3311d952011-03-22 04:33:13 +000074 tmp->recoverResources();
Ted Kremeneka4f98392011-03-18 02:05:11 +000075 delete tmp;
76 }
Ted Kremenekb52fde42011-03-21 18:38:03 +000077 tlIsRecoveringFromCrash.erase();
Ted Kremeneka4f98392011-03-18 02:05:11 +000078
Daniel Dunbara309dac2010-07-28 15:40:20 +000079 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
80 delete CRCI;
81}
82
Ted Kremenekb52fde42011-03-21 18:38:03 +000083bool CrashRecoveryContext::isRecoveringFromCrash() {
84 return tlIsRecoveringFromCrash.get() != 0;
85}
86
Daniel Dunbara8fa7982010-08-17 22:32:37 +000087CrashRecoveryContext *CrashRecoveryContext::GetCurrent() {
Ted Kremenekfb200e32011-03-19 00:59:33 +000088 if (!gCrashRecoveryEnabled)
89 return 0;
90
Daniel Dunbara8fa7982010-08-17 22:32:37 +000091 const CrashRecoveryContextImpl *CRCI = CurrentContext.get();
92 if (!CRCI)
93 return 0;
94
95 return CRCI->CRC;
96}
97
Ted Kremeneka4f98392011-03-18 02:05:11 +000098void CrashRecoveryContext::registerCleanup(CrashRecoveryContextCleanup *cleanup)
99{
100 if (!cleanup)
101 return;
102 if (head)
103 head->prev = cleanup;
104 cleanup->next = head;
105 head = cleanup;
106}
107
108void
109CrashRecoveryContext::unregisterCleanup(CrashRecoveryContextCleanup *cleanup) {
110 if (!cleanup)
111 return;
112 if (cleanup == head) {
113 head = cleanup->next;
114 if (head)
115 head->prev = 0;
116 }
117 else {
118 cleanup->prev->next = cleanup->next;
119 if (cleanup->next)
120 cleanup->next->prev = cleanup->prev;
121 }
122 delete cleanup;
123}
124
Daniel Dunbard9082df2010-07-29 01:21:47 +0000125#ifdef LLVM_ON_WIN32
126
NAKAMURA Takumi77c10822011-08-20 06:35:36 +0000127#include "Windows/Windows.h"
128
129// On Windows, we can make use of vectored exception handling to
130// catch most crashing situations. Note that this does mean
131// we will be alerted of exceptions *before* structured exception
132// handling has the opportunity to catch it. But that isn't likely
133// to cause problems because nowhere in the project is SEH being
134// used.
135//
136// Vectored exception handling is built on top of SEH, and so it
137// works on a per-thread basis.
138//
139// The vectored exception handler functionality was added in Windows
140// XP, so if support for older versions of Windows is required,
141// it will have to be added.
142//
143// If we want to support as far back as Win2k, we could use the
144// SetUnhandledExceptionFilter API, but there's a risk of that
145// being entirely overwritten (it's not a chain).
146
147static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
148{
149 // Lookup the current thread local recovery object.
150 const CrashRecoveryContextImpl *CRCI = CurrentContext.get();
151
152 if (!CRCI) {
153 // Something has gone horribly wrong, so let's just tell everyone
154 // to keep searching
155 CrashRecoveryContext::Disable();
156 return EXCEPTION_CONTINUE_SEARCH;
157 }
158
159 // TODO: We can capture the stack backtrace here and store it on the
160 // implementation if we so choose.
161
162 // Handle the crash
163 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
164
165 // Note that we don't actually get here because HandleCrash calls
166 // longjmp, which means the HandleCrash function never returns.
167 llvm_unreachable("Handled the crash, should have longjmp'ed out of here");
168 return EXCEPTION_CONTINUE_SEARCH;
169}
170
171// Because the Enable and Disable calls are static, it means that
172// there may not actually be an Impl available, or even a current
173// CrashRecoveryContext at all. So we make use of a thread-local
174// exception table. The handles contained in here will either be
175// non-NULL, valid VEH handles, or NULL.
176static sys::ThreadLocal<const void> sCurrentExceptionHandle;
Daniel Dunbard9082df2010-07-29 01:21:47 +0000177
Daniel Dunbara309dac2010-07-28 15:40:20 +0000178void CrashRecoveryContext::Enable() {
Daniel Dunbarc0c815e2010-08-17 22:32:34 +0000179 sys::ScopedLock L(gCrashRecoveryContexMutex);
180
Daniel Dunbara309dac2010-07-28 15:40:20 +0000181 if (gCrashRecoveryEnabled)
182 return;
183
184 gCrashRecoveryEnabled = true;
NAKAMURA Takumi77c10822011-08-20 06:35:36 +0000185
186 // We can set up vectored exception handling now. We will install our
187 // handler as the front of the list, though there's no assurances that
188 // it will remain at the front (another call could install itself before
189 // our handler). This 1) isn't likely, and 2) shouldn't cause problems.
190 PVOID handle = ::AddVectoredExceptionHandler(1, ExceptionHandler);
191 sCurrentExceptionHandle.set(handle);
Daniel Dunbara309dac2010-07-28 15:40:20 +0000192}
193
194void CrashRecoveryContext::Disable() {
Daniel Dunbarc0c815e2010-08-17 22:32:34 +0000195 sys::ScopedLock L(gCrashRecoveryContexMutex);
196
Daniel Dunbara309dac2010-07-28 15:40:20 +0000197 if (!gCrashRecoveryEnabled)
198 return;
199
200 gCrashRecoveryEnabled = false;
NAKAMURA Takumi77c10822011-08-20 06:35:36 +0000201
202 PVOID currentHandle = const_cast<PVOID>(sCurrentExceptionHandle.get());
203 if (currentHandle) {
204 // Now we can remove the vectored exception handler from the chain
205 ::RemoveVectoredExceptionHandler(currentHandle);
206
207 // Reset the handle in our thread-local set.
208 sCurrentExceptionHandle.set(NULL);
209 }
Daniel Dunbara309dac2010-07-28 15:40:20 +0000210}
211
Daniel Dunbard9082df2010-07-29 01:21:47 +0000212#else
213
214// Generic POSIX implementation.
215//
216// This implementation relies on synchronous signals being delivered to the
217// current thread. We use a thread local object to keep track of the active
218// crash recovery context, and install signal handlers to invoke HandleCrash on
219// the active object.
220//
221// This implementation does not to attempt to chain signal handlers in any
222// reliable fashion -- if we get a signal outside of a crash recovery context we
223// simply disable crash recovery and raise the signal again.
224
225#include <signal.h>
226
Daniel Dunbar63cc2e12010-07-30 17:49:04 +0000227static int Signals[] = { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP };
228static const unsigned NumSignals = sizeof(Signals) / sizeof(Signals[0]);
229static struct sigaction PrevActions[NumSignals];
Daniel Dunbard9082df2010-07-29 01:21:47 +0000230
231static void CrashRecoverySignalHandler(int Signal) {
232 // Lookup the current thread local recovery object.
233 const CrashRecoveryContextImpl *CRCI = CurrentContext.get();
234
235 if (!CRCI) {
236 // We didn't find a crash recovery context -- this means either we got a
237 // signal on a thread we didn't expect it on, the application got a signal
238 // outside of a crash recovery context, or something else went horribly
239 // wrong.
240 //
241 // Disable crash recovery and raise the signal again. The assumption here is
242 // that the enclosing application will terminate soon, and we won't want to
243 // attempt crash recovery again.
244 //
245 // This call of Disable isn't thread safe, but it doesn't actually matter.
246 CrashRecoveryContext::Disable();
247 raise(Signal);
Daniel Dunbard49e2aa2010-10-18 21:55:18 +0000248
249 // The signal will be thrown once the signal mask is restored.
250 return;
Daniel Dunbard9082df2010-07-29 01:21:47 +0000251 }
252
253 // Unblock the signal we received.
254 sigset_t SigMask;
255 sigemptyset(&SigMask);
256 sigaddset(&SigMask, Signal);
257 sigprocmask(SIG_UNBLOCK, &SigMask, 0);
258
259 if (CRCI)
260 const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
261}
262
263void CrashRecoveryContext::Enable() {
Daniel Dunbarc0c815e2010-08-17 22:32:34 +0000264 sys::ScopedLock L(gCrashRecoveryContexMutex);
265
Daniel Dunbard9082df2010-07-29 01:21:47 +0000266 if (gCrashRecoveryEnabled)
267 return;
268
269 gCrashRecoveryEnabled = true;
270
271 // Setup the signal handler.
272 struct sigaction Handler;
273 Handler.sa_handler = CrashRecoverySignalHandler;
274 Handler.sa_flags = 0;
275 sigemptyset(&Handler.sa_mask);
276
277 for (unsigned i = 0; i != NumSignals; ++i) {
Daniel Dunbar63cc2e12010-07-30 17:49:04 +0000278 sigaction(Signals[i], &Handler, &PrevActions[i]);
Daniel Dunbard9082df2010-07-29 01:21:47 +0000279 }
280}
281
282void CrashRecoveryContext::Disable() {
Daniel Dunbarc0c815e2010-08-17 22:32:34 +0000283 sys::ScopedLock L(gCrashRecoveryContexMutex);
284
Daniel Dunbard9082df2010-07-29 01:21:47 +0000285 if (!gCrashRecoveryEnabled)
286 return;
287
288 gCrashRecoveryEnabled = false;
289
290 // Restore the previous signal handlers.
291 for (unsigned i = 0; i != NumSignals; ++i)
Daniel Dunbar63cc2e12010-07-30 17:49:04 +0000292 sigaction(Signals[i], &PrevActions[i], 0);
Daniel Dunbard9082df2010-07-29 01:21:47 +0000293}
294
295#endif
296
Daniel Dunbara309dac2010-07-28 15:40:20 +0000297bool CrashRecoveryContext::RunSafely(void (*Fn)(void*), void *UserData) {
298 // If crash recovery is disabled, do nothing.
299 if (gCrashRecoveryEnabled) {
300 assert(!Impl && "Crash recovery context already initialized!");
Daniel Dunbara8fa7982010-08-17 22:32:37 +0000301 CrashRecoveryContextImpl *CRCI = new CrashRecoveryContextImpl(this);
Daniel Dunbara309dac2010-07-28 15:40:20 +0000302 Impl = CRCI;
303
304 if (setjmp(CRCI->JumpBuffer) != 0) {
305 return false;
306 }
307 }
308
309 Fn(UserData);
310 return true;
311}
312
313void CrashRecoveryContext::HandleCrash() {
314 CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
315 assert(CRCI && "Crash recovery context never initialized!");
316 CRCI->HandleCrash();
317}
318
319const std::string &CrashRecoveryContext::getBacktrace() const {
320 CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *) Impl;
321 assert(CRC && "Crash recovery context never initialized!");
322 assert(CRC->Failed && "No crash was detected!");
323 return CRC->Backtrace;
324}
Daniel Dunbarf8254d642010-11-05 07:19:09 +0000325
326//
327
328namespace {
329struct RunSafelyOnThreadInfo {
330 void (*UserFn)(void*);
331 void *UserData;
332 CrashRecoveryContext *CRC;
333 bool Result;
334};
335}
336
337static void RunSafelyOnThread_Dispatch(void *UserData) {
338 RunSafelyOnThreadInfo *Info =
339 reinterpret_cast<RunSafelyOnThreadInfo*>(UserData);
340 Info->Result = Info->CRC->RunSafely(Info->UserFn, Info->UserData);
341}
342bool CrashRecoveryContext::RunSafelyOnThread(void (*Fn)(void*), void *UserData,
343 unsigned RequestedStackSize) {
344 RunSafelyOnThreadInfo Info = { Fn, UserData, this, false };
345 llvm_execute_on_thread(RunSafelyOnThread_Dispatch, &Info, RequestedStackSize);
346 return Info.Result;
347}