LLVM 22.0.0git
CrashRecoveryContext.h
Go to the documentation of this file.
1//===--- CrashRecoveryContext.h - Crash Recovery ----------------*- C++ -*-===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLVM_SUPPORT_CRASHRECOVERYCONTEXT_H
10#define LLVM_SUPPORT_CRASHRECOVERYCONTEXT_H
11
14
15namespace llvm {
17
18/// Crash recovery helper object.
19///
20/// This class implements support for running operations in a safe context so
21/// that crashes (memory errors, stack overflow, assertion violations) can be
22/// detected and control restored to the crashing thread. Crash detection is
23/// purely "best effort", the exact set of failures which can be recovered from
24/// is platform dependent.
25///
26/// Clients make use of this code by first calling
27/// CrashRecoveryContext::Enable(), and then executing unsafe operations via a
28/// CrashRecoveryContext object. For example:
29///
30/// \code
31/// void actual_work(void *);
32///
33/// void foo() {
34/// CrashRecoveryContext CRC;
35///
36/// if (!CRC.RunSafely(actual_work, 0)) {
37/// ... a crash was detected, report error to user ...
38/// }
39///
40/// ... no crash was detected ...
41/// }
42/// \endcode
43///
44/// To assist recovery the class allows specifying set of actions that will be
45/// executed in any case, whether crash occurs or not. These actions may be used
46/// to reclaim resources in the case of crash.
48 void *Impl = nullptr;
49 CrashRecoveryContextCleanup *head = nullptr;
50
51public:
54
55 /// Register cleanup handler, which is used when the recovery context is
56 /// finished.
57 /// The recovery context owns the handler.
59
61
62 /// Enable crash recovery.
63 LLVM_ABI static void Enable();
64
65 /// Disable crash recovery.
66 LLVM_ABI static void Disable();
67
68 /// Return the active context, if the code is currently executing in a
69 /// thread which is in a protected context.
71
72 /// Return true if the current thread is recovering from a crash.
73 LLVM_ABI static bool isRecoveringFromCrash();
74
75 /// Execute the provided callback function (with the given arguments) in
76 /// a protected context.
77 ///
78 /// \return True if the function completed successfully, and false if the
79 /// function crashed (or HandleCrash was called explicitly). Clients should
80 /// make as little assumptions as possible about the program state when
81 /// RunSafely has returned false.
82 LLVM_ABI bool RunSafely(function_ref<void()> Fn);
83
84 /// Execute the provide callback function (with the given arguments) in
85 /// a protected context which is run in another thread (optionally with a
86 /// requested stack size).
87 ///
88 /// See RunSafely().
89 ///
90 /// On Darwin, if PRIO_DARWIN_BG is set on the calling thread, it will be
91 /// propagated to the new thread as well.
93 unsigned RequestedStackSize = 0);
94
96 unsigned RequestedStackSize = 0);
97
98 /// Explicitly trigger a crash recovery in the current process, and
99 /// return failure from RunSafely(). This function does not return.
100 [[noreturn]] LLVM_ABI void HandleExit(int RetCode);
101
102 /// Return true if RetCode indicates that a signal or an exception occurred.
103 LLVM_ABI static bool isCrash(int RetCode);
104
105 /// Throw again a signal or an exception, after it was catched once by a
106 /// CrashRecoveryContext.
107 LLVM_ABI 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.
116};
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.
126protected:
130
131public:
132 bool cleanupFired = false;
133
135 virtual void recoverResources() = 0;
136
138 return context;
139 }
140
141private:
143 CrashRecoveryContextCleanup *prev = nullptr, *next = nullptr;
144};
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>
159protected:
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) {
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>
192
193/// Cleanup handler that reclaims resource by calling 'delete' on it.
194template <typename T>
204
205/// Cleanup handler that reclaims resource by calling its method 'Release'.
206template <typename T>
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> >
252
253public:
255 : cleanup(Cleanup::create(x)) {
256 if (cleanup)
257 cleanup->getContext()->registerCleanup(cleanup);
258 }
259
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
static void cleanup(BlockFrequencyInfoImplBase &BFI)
Clear all memory not needed downstream.
#define LLVM_ABI
Definition Compiler.h:213
static const HTTPClientCleanup Cleanup
#define T
CrashRecoveryContextCleanupBase(CrashRecoveryContext *context, T *resource)
static Derived * create(T *x)
Creates cleanup handler.
Abstract base class of cleanup handlers.
CrashRecoveryContextCleanup(CrashRecoveryContext *context)
CrashRecoveryContext * getContext() const
CrashRecoveryContextDeleteCleanup(CrashRecoveryContext *context, T *resource)
CrashRecoveryContextDestructorCleanup(CrashRecoveryContext *context, T *resource)
CrashRecoveryContextReleaseRefCleanup(CrashRecoveryContext *context, T *resource)
Crash recovery helper object.
static LLVM_ABI bool isCrash(int RetCode)
Return true if RetCode indicates that a signal or an exception occurred.
static LLVM_ABI CrashRecoveryContext * GetCurrent()
Return the active context, if the code is currently executing in a thread which is in a protected con...
LLVM_ABI void HandleExit(int RetCode)
Explicitly trigger a crash recovery in the current process, and return failure from RunSafely().
static LLVM_ABI void Enable()
Enable crash recovery.
LLVM_ABI bool RunSafelyOnNewStack(function_ref< void()>, unsigned RequestedStackSize=0)
bool DumpStackAndCleanupOnFailure
Selects whether handling of failures should be done in the same way as for regular crashes.
LLVM_ABI void unregisterCleanup(CrashRecoveryContextCleanup *cleanup)
LLVM_ABI bool RunSafely(function_ref< void()> Fn)
Execute the provided callback function (with the given arguments) in a protected context.
static LLVM_ABI void Disable()
Disable crash recovery.
int RetCode
In case of a crash, this is the crash identifier.
static LLVM_ABI bool isRecoveringFromCrash()
Return true if the current thread is recovering from a crash.
static LLVM_ABI bool throwIfCrash(int RetCode)
Throw again a signal or an exception, after it was catched once by a CrashRecoveryContext.
LLVM_ABI void registerCleanup(CrashRecoveryContextCleanup *cleanup)
Register cleanup handler, which is used when the recovery context is finished.
LLVM_ABI bool RunSafelyOnThread(function_ref< void()>, unsigned RequestedStackSize=0)
Execute the provide callback function (with the given arguments) in a protected context which is run ...
An efficient, type-erasing, non-owning reference to a callable.
This is an optimization pass for GlobalISel generic memory operations.