blob: f756635ee1f9021186fa2c257ac9e2ec8ed59513 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===--- CrashRecoveryContext.h - Crash Recovery ----------------*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// 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
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLVM_SUPPORT_CRASHRECOVERYCONTEXT_H
10#define LLVM_SUPPORT_CRASHRECOVERYCONTEXT_H
11
12#include "llvm/ADT/STLExtras.h"
13
14namespace llvm {
15class CrashRecoveryContextCleanup;
16
17/// Crash recovery helper object.
18///
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.
24///
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:
28///
29/// \code
30/// void actual_work(void *);
31///
32/// void foo() {
33/// CrashRecoveryContext CRC;
34///
35/// if (!CRC.RunSafely(actual_work, 0)) {
36/// ... a crash was detected, report error to user ...
37/// }
38///
39/// ... no crash was detected ...
40/// }
41/// \endcode
42///
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.
46class CrashRecoveryContext {
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020047 void *Impl = nullptr;
48 CrashRecoveryContextCleanup *head = nullptr;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010049
50public:
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020051 CrashRecoveryContext();
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010052 ~CrashRecoveryContext();
53
54 /// Register cleanup handler, which is used when the recovery context is
55 /// finished.
Andrew Scullcdfcccc2018-10-05 20:58:37 +010056 /// The recovery context owns the handler.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010057 void registerCleanup(CrashRecoveryContextCleanup *cleanup);
58
59 void unregisterCleanup(CrashRecoveryContextCleanup *cleanup);
60
61 /// Enable crash recovery.
62 static void Enable();
63
64 /// Disable crash recovery.
65 static void Disable();
66
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();
70
71 /// Return true if the current thread is recovering from a crash.
72 static bool isRecoveringFromCrash();
73
74 /// Execute the provided callback function (with the given arguments) in
75 /// a protected context.
76 ///
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); });
84 }
85
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).
89 ///
90 /// See RunSafely() and llvm_execute_on_thread().
91 ///
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);
98 }
99
100 /// Explicitly trigger a crash recovery in the current process, and
101 /// return failure from RunSafely(). This function does not return.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200102 LLVM_ATTRIBUTE_NORETURN
103 void HandleExit(int RetCode);
104
105 /// Throw again a signal or an exception, after it was catched once by a
106 /// CrashRecoveryContext.
107 static bool throwIfCrash(int RetCode);
108
109 /// In case of a crash, this is the crash identifier.
110 int RetCode = 0;
111
112 /// Selects whether handling of failures should be done in the same way as
113 /// for regular crashes. When this is active, a crash would print the
114 /// callstack, clean-up any temporary files and create a coredump/minidump.
115 bool DumpStackAndCleanupOnFailure = false;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100116};
117
118/// Abstract base class of cleanup handlers.
119///
120/// Derived classes override method recoverResources, which makes actual work on
121/// resource recovery.
122///
123/// Cleanup handlers are stored in a double list, which is owned and managed by
124/// a crash recovery context.
125class CrashRecoveryContextCleanup {
126protected:
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200127 CrashRecoveryContext *context = nullptr;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100128 CrashRecoveryContextCleanup(CrashRecoveryContext *context)
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200129 : context(context) {}
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100130
131public:
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200132 bool cleanupFired = false;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100133
134 virtual ~CrashRecoveryContextCleanup();
135 virtual void recoverResources() = 0;
136
137 CrashRecoveryContext *getContext() const {
138 return context;
139 }
140
141private:
142 friend class CrashRecoveryContext;
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200143 CrashRecoveryContextCleanup *prev = nullptr, *next = nullptr;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100144};
145
146/// Base class of cleanup handler that controls recovery of resources of the
147/// given type.
148///
149/// \tparam Derived Class that uses this class as a base.
150/// \tparam T Type of controlled resource.
151///
152/// This class serves as a base for its template parameter as implied by
153/// Curiously Recurring Template Pattern.
154///
155/// This class factors out creation of a cleanup handler. The latter requires
156/// knowledge of the current recovery context, which is provided by this class.
157template<typename Derived, typename T>
158class CrashRecoveryContextCleanupBase : public CrashRecoveryContextCleanup {
159protected:
160 T *resource;
161 CrashRecoveryContextCleanupBase(CrashRecoveryContext *context, T *resource)
162 : CrashRecoveryContextCleanup(context), resource(resource) {}
163
164public:
165 /// Creates cleanup handler.
166 /// \param x Pointer to the resource recovered by this handler.
167 /// \return New handler or null if the method was called outside a recovery
168 /// context.
169 static Derived *create(T *x) {
170 if (x) {
171 if (CrashRecoveryContext *context = CrashRecoveryContext::GetCurrent())
172 return new Derived(context, x);
173 }
174 return nullptr;
175 }
176};
177
178/// Cleanup handler that reclaims resource by calling destructor on it.
179template <typename T>
180class CrashRecoveryContextDestructorCleanup : public
181 CrashRecoveryContextCleanupBase<CrashRecoveryContextDestructorCleanup<T>, T> {
182public:
183 CrashRecoveryContextDestructorCleanup(CrashRecoveryContext *context,
184 T *resource)
185 : CrashRecoveryContextCleanupBase<
186 CrashRecoveryContextDestructorCleanup<T>, T>(context, resource) {}
187
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200188 void recoverResources() override {
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100189 this->resource->~T();
190 }
191};
192
193/// Cleanup handler that reclaims resource by calling 'delete' on it.
194template <typename T>
195class CrashRecoveryContextDeleteCleanup : public
196 CrashRecoveryContextCleanupBase<CrashRecoveryContextDeleteCleanup<T>, T> {
197public:
198 CrashRecoveryContextDeleteCleanup(CrashRecoveryContext *context, T *resource)
199 : CrashRecoveryContextCleanupBase<
200 CrashRecoveryContextDeleteCleanup<T>, T>(context, resource) {}
201
202 void recoverResources() override { delete this->resource; }
203};
204
205/// Cleanup handler that reclaims resource by calling its method 'Release'.
206template <typename T>
207class CrashRecoveryContextReleaseRefCleanup : public
208 CrashRecoveryContextCleanupBase<CrashRecoveryContextReleaseRefCleanup<T>, T> {
209public:
210 CrashRecoveryContextReleaseRefCleanup(CrashRecoveryContext *context,
211 T *resource)
212 : CrashRecoveryContextCleanupBase<CrashRecoveryContextReleaseRefCleanup<T>,
213 T>(context, resource) {}
214
215 void recoverResources() override { this->resource->Release(); }
216};
217
218/// Helper class for managing resource cleanups.
219///
220/// \tparam T Type of resource been reclaimed.
221/// \tparam Cleanup Class that defines how the resource is reclaimed.
222///
223/// Clients create objects of this type in the code executed in a crash recovery
224/// context to ensure that the resource will be reclaimed even in the case of
225/// crash. For example:
226///
227/// \code
228/// void actual_work(void *) {
229/// ...
230/// std::unique_ptr<Resource> R(new Resource());
231/// CrashRecoveryContextCleanupRegistrar D(R.get());
232/// ...
233/// }
234///
235/// void foo() {
236/// CrashRecoveryContext CRC;
237///
238/// if (!CRC.RunSafely(actual_work, 0)) {
239/// ... a crash was detected, report error to user ...
240/// }
241/// \endcode
242///
243/// If the code of `actual_work` in the example above does not crash, the
244/// destructor of CrashRecoveryContextCleanupRegistrar removes cleanup code from
245/// the current CrashRecoveryContext and the resource is reclaimed by the
246/// destructor of std::unique_ptr. If crash happens, destructors are not called
247/// and the resource is reclaimed by cleanup object registered in the recovery
248/// context by the constructor of CrashRecoveryContextCleanupRegistrar.
249template <typename T, typename Cleanup = CrashRecoveryContextDeleteCleanup<T> >
250class CrashRecoveryContextCleanupRegistrar {
251 CrashRecoveryContextCleanup *cleanup;
252
253public:
254 CrashRecoveryContextCleanupRegistrar(T *x)
255 : cleanup(Cleanup::create(x)) {
256 if (cleanup)
257 cleanup->getContext()->registerCleanup(cleanup);
258 }
259
260 ~CrashRecoveryContextCleanupRegistrar() { unregister(); }
261
262 void unregister() {
263 if (cleanup && !cleanup->cleanupFired)
264 cleanup->getContext()->unregisterCleanup(cleanup);
265 cleanup = nullptr;
266 }
267};
268} // end namespace llvm
269
270#endif // LLVM_SUPPORT_CRASHRECOVERYCONTEXT_H