CrashRecoveryContext.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. #include "llvm/Support/CrashRecoveryContext.h"
  10. #include "llvm/Config/config.h"
  11. #include "llvm/Support/ErrorHandling.h"
  12. #include "llvm/Support/ManagedStatic.h"
  13. #include "llvm/Support/Mutex.h"
  14. #include "llvm/Support/ThreadLocal.h"
  15. #include <setjmp.h>
  16. using namespace llvm;
  17. namespace {
  18. struct CrashRecoveryContextImpl;
  19. static ManagedStatic<
  20. sys::ThreadLocal<const CrashRecoveryContextImpl> > CurrentContext;
  21. struct CrashRecoveryContextImpl {
  22. CrashRecoveryContext *CRC;
  23. std::string Backtrace;
  24. ::jmp_buf JumpBuffer;
  25. volatile unsigned Failed : 1;
  26. unsigned SwitchedThread : 1;
  27. public:
  28. CrashRecoveryContextImpl(CrashRecoveryContext *CRC) : CRC(CRC),
  29. Failed(false),
  30. SwitchedThread(false) {
  31. CurrentContext->set(this);
  32. }
  33. ~CrashRecoveryContextImpl() {
  34. if (!SwitchedThread)
  35. CurrentContext->erase();
  36. }
  37. /// \brief Called when the separate crash-recovery thread was finished, to
  38. /// indicate that we don't need to clear the thread-local CurrentContext.
  39. void setSwitchedThread() { SwitchedThread = true; }
  40. void HandleCrash() {
  41. // Eliminate the current context entry, to avoid re-entering in case the
  42. // cleanup code crashes.
  43. CurrentContext->erase();
  44. assert(!Failed && "Crash recovery context already failed!");
  45. Failed = true;
  46. // FIXME: Stash the backtrace.
  47. // Jump back to the RunSafely we were called under.
  48. longjmp(JumpBuffer, 1);
  49. }
  50. };
  51. }
  52. static ManagedStatic<sys::Mutex> gCrashRecoveryContextMutex;
  53. static bool gCrashRecoveryEnabled = false;
  54. static ManagedStatic<sys::ThreadLocal<const CrashRecoveryContextCleanup> >
  55. tlIsRecoveringFromCrash;
  56. CrashRecoveryContextCleanup::~CrashRecoveryContextCleanup() {}
  57. CrashRecoveryContext::~CrashRecoveryContext() {
  58. // Reclaim registered resources.
  59. CrashRecoveryContextCleanup *i = head;
  60. tlIsRecoveringFromCrash->set(head);
  61. while (i) {
  62. CrashRecoveryContextCleanup *tmp = i;
  63. i = tmp->next;
  64. tmp->cleanupFired = true;
  65. tmp->recoverResources();
  66. delete tmp;
  67. }
  68. tlIsRecoveringFromCrash->erase();
  69. CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
  70. delete CRCI;
  71. }
  72. bool CrashRecoveryContext::isRecoveringFromCrash() {
  73. return tlIsRecoveringFromCrash->get() != nullptr;
  74. }
  75. CrashRecoveryContext *CrashRecoveryContext::GetCurrent() {
  76. if (!gCrashRecoveryEnabled)
  77. return nullptr;
  78. const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
  79. if (!CRCI)
  80. return nullptr;
  81. return CRCI->CRC;
  82. }
  83. void CrashRecoveryContext::registerCleanup(CrashRecoveryContextCleanup *cleanup)
  84. {
  85. if (!cleanup)
  86. return;
  87. if (head)
  88. head->prev = cleanup;
  89. cleanup->next = head;
  90. head = cleanup;
  91. }
  92. void
  93. CrashRecoveryContext::unregisterCleanup(CrashRecoveryContextCleanup *cleanup) {
  94. if (!cleanup)
  95. return;
  96. if (cleanup == head) {
  97. head = cleanup->next;
  98. if (head)
  99. head->prev = nullptr;
  100. }
  101. else {
  102. cleanup->prev->next = cleanup->next;
  103. if (cleanup->next)
  104. cleanup->next->prev = cleanup->prev;
  105. }
  106. delete cleanup;
  107. }
  108. #ifdef LLVM_ON_WIN32
  109. #include "Windows/WindowsSupport.h"
  110. // On Windows, we can make use of vectored exception handling to
  111. // catch most crashing situations. Note that this does mean
  112. // we will be alerted of exceptions *before* structured exception
  113. // handling has the opportunity to catch it. But that isn't likely
  114. // to cause problems because nowhere in the project is SEH being
  115. // used.
  116. //
  117. // Vectored exception handling is built on top of SEH, and so it
  118. // works on a per-thread basis.
  119. //
  120. // The vectored exception handler functionality was added in Windows
  121. // XP, so if support for older versions of Windows is required,
  122. // it will have to be added.
  123. //
  124. // If we want to support as far back as Win2k, we could use the
  125. // SetUnhandledExceptionFilter API, but there's a risk of that
  126. // being entirely overwritten (it's not a chain).
  127. static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
  128. {
  129. // Lookup the current thread local recovery object.
  130. const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
  131. if (!CRCI) {
  132. // Something has gone horribly wrong, so let's just tell everyone
  133. // to keep searching
  134. CrashRecoveryContext::Disable();
  135. return EXCEPTION_CONTINUE_SEARCH;
  136. }
  137. // TODO: We can capture the stack backtrace here and store it on the
  138. // implementation if we so choose.
  139. // Handle the crash
  140. const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
  141. // Note that we don't actually get here because HandleCrash calls
  142. // longjmp, which means the HandleCrash function never returns.
  143. llvm_unreachable("Handled the crash, should have longjmp'ed out of here");
  144. }
  145. // Because the Enable and Disable calls are static, it means that
  146. // there may not actually be an Impl available, or even a current
  147. // CrashRecoveryContext at all. So we make use of a thread-local
  148. // exception table. The handles contained in here will either be
  149. // non-NULL, valid VEH handles, or NULL.
  150. static sys::ThreadLocal<const void> sCurrentExceptionHandle;
  151. void CrashRecoveryContext::Enable() {
  152. sys::ScopedLock L(*gCrashRecoveryContextMutex);
  153. if (gCrashRecoveryEnabled)
  154. return;
  155. gCrashRecoveryEnabled = true;
  156. // We can set up vectored exception handling now. We will install our
  157. // handler as the front of the list, though there's no assurances that
  158. // it will remain at the front (another call could install itself before
  159. // our handler). This 1) isn't likely, and 2) shouldn't cause problems.
  160. PVOID handle = ::AddVectoredExceptionHandler(1, ExceptionHandler);
  161. sCurrentExceptionHandle.set(handle);
  162. }
  163. void CrashRecoveryContext::Disable() {
  164. sys::ScopedLock L(*gCrashRecoveryContextMutex);
  165. if (!gCrashRecoveryEnabled)
  166. return;
  167. gCrashRecoveryEnabled = false;
  168. PVOID currentHandle = const_cast<PVOID>(sCurrentExceptionHandle.get());
  169. if (currentHandle) {
  170. // Now we can remove the vectored exception handler from the chain
  171. ::RemoveVectoredExceptionHandler(currentHandle);
  172. // Reset the handle in our thread-local set.
  173. sCurrentExceptionHandle.set(NULL);
  174. }
  175. }
  176. #else
  177. // Generic POSIX implementation.
  178. //
  179. // This implementation relies on synchronous signals being delivered to the
  180. // current thread. We use a thread local object to keep track of the active
  181. // crash recovery context, and install signal handlers to invoke HandleCrash on
  182. // the active object.
  183. //
  184. // This implementation does not to attempt to chain signal handlers in any
  185. // reliable fashion -- if we get a signal outside of a crash recovery context we
  186. // simply disable crash recovery and raise the signal again.
  187. #include <signal.h>
  188. static const int Signals[] =
  189. { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP };
  190. static const unsigned NumSignals = sizeof(Signals) / sizeof(Signals[0]);
  191. static struct sigaction PrevActions[NumSignals];
  192. static void CrashRecoverySignalHandler(int Signal) {
  193. // Lookup the current thread local recovery object.
  194. const CrashRecoveryContextImpl *CRCI = CurrentContext->get();
  195. if (!CRCI) {
  196. // We didn't find a crash recovery context -- this means either we got a
  197. // signal on a thread we didn't expect it on, the application got a signal
  198. // outside of a crash recovery context, or something else went horribly
  199. // wrong.
  200. //
  201. // Disable crash recovery and raise the signal again. The assumption here is
  202. // that the enclosing application will terminate soon, and we won't want to
  203. // attempt crash recovery again.
  204. //
  205. // This call of Disable isn't thread safe, but it doesn't actually matter.
  206. CrashRecoveryContext::Disable();
  207. raise(Signal);
  208. // The signal will be thrown once the signal mask is restored.
  209. return;
  210. }
  211. // Unblock the signal we received.
  212. sigset_t SigMask;
  213. sigemptyset(&SigMask);
  214. sigaddset(&SigMask, Signal);
  215. sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
  216. if (CRCI)
  217. const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash();
  218. }
  219. void CrashRecoveryContext::Enable() {
  220. sys::ScopedLock L(*gCrashRecoveryContextMutex);
  221. if (gCrashRecoveryEnabled)
  222. return;
  223. gCrashRecoveryEnabled = true;
  224. // Setup the signal handler.
  225. struct sigaction Handler;
  226. Handler.sa_handler = CrashRecoverySignalHandler;
  227. Handler.sa_flags = 0;
  228. sigemptyset(&Handler.sa_mask);
  229. for (unsigned i = 0; i != NumSignals; ++i) {
  230. sigaction(Signals[i], &Handler, &PrevActions[i]);
  231. }
  232. }
  233. void CrashRecoveryContext::Disable() {
  234. sys::ScopedLock L(*gCrashRecoveryContextMutex);
  235. if (!gCrashRecoveryEnabled)
  236. return;
  237. gCrashRecoveryEnabled = false;
  238. // Restore the previous signal handlers.
  239. for (unsigned i = 0; i != NumSignals; ++i)
  240. sigaction(Signals[i], &PrevActions[i], nullptr);
  241. }
  242. #endif
  243. bool CrashRecoveryContext::RunSafely(function_ref<void()> Fn) {
  244. // If crash recovery is disabled, do nothing.
  245. if (gCrashRecoveryEnabled) {
  246. assert(!Impl && "Crash recovery context already initialized!");
  247. CrashRecoveryContextImpl *CRCI = new CrashRecoveryContextImpl(this);
  248. Impl = CRCI;
  249. if (setjmp(CRCI->JumpBuffer) != 0) {
  250. return false;
  251. }
  252. }
  253. Fn();
  254. return true;
  255. }
  256. void CrashRecoveryContext::HandleCrash() {
  257. CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
  258. assert(CRCI && "Crash recovery context never initialized!");
  259. CRCI->HandleCrash();
  260. }
  261. const std::string &CrashRecoveryContext::getBacktrace() const {
  262. CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *) Impl;
  263. assert(CRC && "Crash recovery context never initialized!");
  264. assert(CRC->Failed && "No crash was detected!");
  265. return CRC->Backtrace;
  266. }
  267. // FIXME: Portability.
  268. static void setThreadBackgroundPriority() {
  269. #ifdef __APPLE__
  270. setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
  271. #endif
  272. }
  273. static bool hasThreadBackgroundPriority() {
  274. #ifdef __APPLE__
  275. return getpriority(PRIO_DARWIN_THREAD, 0) == 1;
  276. #else
  277. return false;
  278. #endif
  279. }
  280. namespace {
  281. struct RunSafelyOnThreadInfo {
  282. function_ref<void()> Fn;
  283. CrashRecoveryContext *CRC;
  284. bool UseBackgroundPriority;
  285. bool Result;
  286. };
  287. }
  288. static void RunSafelyOnThread_Dispatch(void *UserData) {
  289. RunSafelyOnThreadInfo *Info =
  290. reinterpret_cast<RunSafelyOnThreadInfo*>(UserData);
  291. if (Info->UseBackgroundPriority)
  292. setThreadBackgroundPriority();
  293. Info->Result = Info->CRC->RunSafely(Info->Fn);
  294. }
  295. bool CrashRecoveryContext::RunSafelyOnThread(function_ref<void()> Fn,
  296. unsigned RequestedStackSize) {
  297. bool UseBackgroundPriority = hasThreadBackgroundPriority();
  298. RunSafelyOnThreadInfo Info = { Fn, this, UseBackgroundPriority, false };
  299. llvm_execute_on_thread(RunSafelyOnThread_Dispatch, &Info, RequestedStackSize);
  300. if (CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *)Impl)
  301. CRC->setSwitchedThread();
  302. return Info.Result;
  303. }