1 //===--- CrashRecoveryContext.h - Crash Recovery ----------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_SUPPORT_CRASHRECOVERYCONTEXT_H
10 #define LLVM_SUPPORT_CRASHRECOVERYCONTEXT_H
12 #include "llvm/ADT/STLExtras.h"
15 class CrashRecoveryContextCleanup
;
17 /// Crash recovery helper object.
19 /// This class implements support for running operations in a safe context so
20 /// that crashes (memory errors, stack overflow, assertion violations) can be
21 /// detected and control restored to the crashing thread. Crash detection is
22 /// purely "best effort", the exact set of failures which can be recovered from
23 /// is platform dependent.
25 /// Clients make use of this code by first calling
26 /// CrashRecoveryContext::Enable(), and then executing unsafe operations via a
27 /// CrashRecoveryContext object. For example:
30 /// void actual_work(void *);
33 /// CrashRecoveryContext CRC;
35 /// if (!CRC.RunSafely(actual_work, 0)) {
36 /// ... a crash was detected, report error to user ...
39 /// ... no crash was detected ...
43 /// To assist recovery the class allows specifying set of actions that will be
44 /// executed in any case, whether crash occurs or not. These actions may be used
45 /// to reclaim resources in the case of crash.
46 class CrashRecoveryContext
{
48 CrashRecoveryContextCleanup
*head
;
51 CrashRecoveryContext() : Impl(nullptr), head(nullptr) {}
52 ~CrashRecoveryContext();
54 /// Register cleanup handler, which is used when the recovery context is
56 /// The recovery context owns the handler.
57 void registerCleanup(CrashRecoveryContextCleanup
*cleanup
);
59 void unregisterCleanup(CrashRecoveryContextCleanup
*cleanup
);
61 /// Enable crash recovery.
64 /// Disable crash recovery.
65 static void Disable();
67 /// Return the active context, if the code is currently executing in a
68 /// thread which is in a protected context.
69 static CrashRecoveryContext
*GetCurrent();
71 /// Return true if the current thread is recovering from a crash.
72 static bool isRecoveringFromCrash();
74 /// Execute the provided callback function (with the given arguments) in
75 /// a protected context.
77 /// \return True if the function completed successfully, and false if the
78 /// function crashed (or HandleCrash was called explicitly). Clients should
79 /// make as little assumptions as possible about the program state when
80 /// RunSafely has returned false.
81 bool RunSafely(function_ref
<void()> Fn
);
82 bool RunSafely(void (*Fn
)(void*), void *UserData
) {
83 return RunSafely([&]() { Fn(UserData
); });
86 /// Execute the provide callback function (with the given arguments) in
87 /// a protected context which is run in another thread (optionally with a
88 /// requested stack size).
90 /// See RunSafely() and llvm_execute_on_thread().
92 /// On Darwin, if PRIO_DARWIN_BG is set on the calling thread, it will be
93 /// propagated to the new thread as well.
94 bool RunSafelyOnThread(function_ref
<void()>, unsigned RequestedStackSize
= 0);
95 bool RunSafelyOnThread(void (*Fn
)(void*), void *UserData
,
96 unsigned RequestedStackSize
= 0) {
97 return RunSafelyOnThread([&]() { Fn(UserData
); }, RequestedStackSize
);
100 /// Explicitly trigger a crash recovery in the current process, and
101 /// return failure from RunSafely(). This function does not return.
105 /// Abstract base class of cleanup handlers.
107 /// Derived classes override method recoverResources, which makes actual work on
108 /// resource recovery.
110 /// Cleanup handlers are stored in a double list, which is owned and managed by
111 /// a crash recovery context.
112 class CrashRecoveryContextCleanup
{
114 CrashRecoveryContext
*context
;
115 CrashRecoveryContextCleanup(CrashRecoveryContext
*context
)
116 : context(context
), cleanupFired(false) {}
121 virtual ~CrashRecoveryContextCleanup();
122 virtual void recoverResources() = 0;
124 CrashRecoveryContext
*getContext() const {
129 friend class CrashRecoveryContext
;
130 CrashRecoveryContextCleanup
*prev
, *next
;
133 /// Base class of cleanup handler that controls recovery of resources of the
136 /// \tparam Derived Class that uses this class as a base.
137 /// \tparam T Type of controlled resource.
139 /// This class serves as a base for its template parameter as implied by
140 /// Curiously Recurring Template Pattern.
142 /// This class factors out creation of a cleanup handler. The latter requires
143 /// knowledge of the current recovery context, which is provided by this class.
144 template<typename Derived
, typename T
>
145 class CrashRecoveryContextCleanupBase
: public CrashRecoveryContextCleanup
{
148 CrashRecoveryContextCleanupBase(CrashRecoveryContext
*context
, T
*resource
)
149 : CrashRecoveryContextCleanup(context
), resource(resource
) {}
152 /// Creates cleanup handler.
153 /// \param x Pointer to the resource recovered by this handler.
154 /// \return New handler or null if the method was called outside a recovery
156 static Derived
*create(T
*x
) {
158 if (CrashRecoveryContext
*context
= CrashRecoveryContext::GetCurrent())
159 return new Derived(context
, x
);
165 /// Cleanup handler that reclaims resource by calling destructor on it.
166 template <typename T
>
167 class CrashRecoveryContextDestructorCleanup
: public
168 CrashRecoveryContextCleanupBase
<CrashRecoveryContextDestructorCleanup
<T
>, T
> {
170 CrashRecoveryContextDestructorCleanup(CrashRecoveryContext
*context
,
172 : CrashRecoveryContextCleanupBase
<
173 CrashRecoveryContextDestructorCleanup
<T
>, T
>(context
, resource
) {}
175 virtual void recoverResources() {
176 this->resource
->~T();
180 /// Cleanup handler that reclaims resource by calling 'delete' on it.
181 template <typename T
>
182 class CrashRecoveryContextDeleteCleanup
: public
183 CrashRecoveryContextCleanupBase
<CrashRecoveryContextDeleteCleanup
<T
>, T
> {
185 CrashRecoveryContextDeleteCleanup(CrashRecoveryContext
*context
, T
*resource
)
186 : CrashRecoveryContextCleanupBase
<
187 CrashRecoveryContextDeleteCleanup
<T
>, T
>(context
, resource
) {}
189 void recoverResources() override
{ delete this->resource
; }
192 /// Cleanup handler that reclaims resource by calling its method 'Release'.
193 template <typename T
>
194 class CrashRecoveryContextReleaseRefCleanup
: public
195 CrashRecoveryContextCleanupBase
<CrashRecoveryContextReleaseRefCleanup
<T
>, T
> {
197 CrashRecoveryContextReleaseRefCleanup(CrashRecoveryContext
*context
,
199 : CrashRecoveryContextCleanupBase
<CrashRecoveryContextReleaseRefCleanup
<T
>,
200 T
>(context
, resource
) {}
202 void recoverResources() override
{ this->resource
->Release(); }
205 /// Helper class for managing resource cleanups.
207 /// \tparam T Type of resource been reclaimed.
208 /// \tparam Cleanup Class that defines how the resource is reclaimed.
210 /// Clients create objects of this type in the code executed in a crash recovery
211 /// context to ensure that the resource will be reclaimed even in the case of
212 /// crash. For example:
215 /// void actual_work(void *) {
217 /// std::unique_ptr<Resource> R(new Resource());
218 /// CrashRecoveryContextCleanupRegistrar D(R.get());
223 /// CrashRecoveryContext CRC;
225 /// if (!CRC.RunSafely(actual_work, 0)) {
226 /// ... a crash was detected, report error to user ...
230 /// If the code of `actual_work` in the example above does not crash, the
231 /// destructor of CrashRecoveryContextCleanupRegistrar removes cleanup code from
232 /// the current CrashRecoveryContext and the resource is reclaimed by the
233 /// destructor of std::unique_ptr. If crash happens, destructors are not called
234 /// and the resource is reclaimed by cleanup object registered in the recovery
235 /// context by the constructor of CrashRecoveryContextCleanupRegistrar.
236 template <typename T
, typename Cleanup
= CrashRecoveryContextDeleteCleanup
<T
> >
237 class CrashRecoveryContextCleanupRegistrar
{
238 CrashRecoveryContextCleanup
*cleanup
;
241 CrashRecoveryContextCleanupRegistrar(T
*x
)
242 : cleanup(Cleanup::create(x
)) {
244 cleanup
->getContext()->registerCleanup(cleanup
);
247 ~CrashRecoveryContextCleanupRegistrar() { unregister(); }
250 if (cleanup
&& !cleanup
->cleanupFired
)
251 cleanup
->getContext()->unregisterCleanup(cleanup
);
255 } // end namespace llvm
257 #endif // LLVM_SUPPORT_CRASHRECOVERYCONTEXT_H