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 12 #include "llvm/ADT/STLFunctionalExtras.h" 13 #include "llvm/Support/Compiler.h" 14 15 namespace llvm { 16 class CrashRecoveryContextCleanup; 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. 47 class CrashRecoveryContext { 48 void *Impl = nullptr; 49 CrashRecoveryContextCleanup *head = nullptr; 50 51 public: 52 LLVM_ABI CrashRecoveryContext(); 53 LLVM_ABI ~CrashRecoveryContext(); 54 55 /// Register cleanup handler, which is used when the recovery context is 56 /// finished. 57 /// The recovery context owns the handler. 58 LLVM_ABI void registerCleanup(CrashRecoveryContextCleanup *cleanup); 59 60 LLVM_ABI void unregisterCleanup(CrashRecoveryContextCleanup *cleanup); 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. 70 LLVM_ABI static CrashRecoveryContext *GetCurrent(); 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); RunSafely(void (* Fn)(void *),void * UserData)83 bool RunSafely(void (*Fn)(void*), void *UserData) { 84 return RunSafely([&]() { Fn(UserData); }); 85 } 86 87 /// Execute the provide callback function (with the given arguments) in 88 /// a protected context which is run in another thread (optionally with a 89 /// requested stack size). 90 /// 91 /// See RunSafely(). 92 /// 93 /// On Darwin, if PRIO_DARWIN_BG is set on the calling thread, it will be 94 /// propagated to the new thread as well. 95 LLVM_ABI bool RunSafelyOnThread(function_ref<void()>, 96 unsigned RequestedStackSize = 0); 97 bool RunSafelyOnThread(void (*Fn)(void*), void *UserData, 98 unsigned RequestedStackSize = 0) { 99 return RunSafelyOnThread([&]() { Fn(UserData); }, RequestedStackSize); 100 } 101 102 LLVM_ABI bool RunSafelyOnNewStack(function_ref<void()>, 103 unsigned RequestedStackSize = 0); 104 105 /// Explicitly trigger a crash recovery in the current process, and 106 /// return failure from RunSafely(). This function does not return. 107 [[noreturn]] LLVM_ABI void HandleExit(int RetCode); 108 109 /// Return true if RetCode indicates that a signal or an exception occurred. 110 LLVM_ABI static bool isCrash(int RetCode); 111 112 /// Throw again a signal or an exception, after it was catched once by a 113 /// CrashRecoveryContext. 114 LLVM_ABI static bool throwIfCrash(int RetCode); 115 116 /// In case of a crash, this is the crash identifier. 117 int RetCode = 0; 118 119 /// Selects whether handling of failures should be done in the same way as 120 /// for regular crashes. When this is active, a crash would print the 121 /// callstack, clean-up any temporary files and create a coredump/minidump. 122 bool DumpStackAndCleanupOnFailure = false; 123 }; 124 125 /// Abstract base class of cleanup handlers. 126 /// 127 /// Derived classes override method recoverResources, which makes actual work on 128 /// resource recovery. 129 /// 130 /// Cleanup handlers are stored in a double list, which is owned and managed by 131 /// a crash recovery context. 132 class LLVM_ABI CrashRecoveryContextCleanup { 133 protected: 134 CrashRecoveryContext *context = nullptr; CrashRecoveryContextCleanup(CrashRecoveryContext * context)135 CrashRecoveryContextCleanup(CrashRecoveryContext *context) 136 : context(context) {} 137 138 public: 139 bool cleanupFired = false; 140 141 virtual ~CrashRecoveryContextCleanup(); 142 virtual void recoverResources() = 0; 143 getContext()144 CrashRecoveryContext *getContext() const { 145 return context; 146 } 147 148 private: 149 friend class CrashRecoveryContext; 150 CrashRecoveryContextCleanup *prev = nullptr, *next = nullptr; 151 }; 152 153 /// Base class of cleanup handler that controls recovery of resources of the 154 /// given type. 155 /// 156 /// \tparam Derived Class that uses this class as a base. 157 /// \tparam T Type of controlled resource. 158 /// 159 /// This class serves as a base for its template parameter as implied by 160 /// Curiously Recurring Template Pattern. 161 /// 162 /// This class factors out creation of a cleanup handler. The latter requires 163 /// knowledge of the current recovery context, which is provided by this class. 164 template<typename Derived, typename T> 165 class CrashRecoveryContextCleanupBase : public CrashRecoveryContextCleanup { 166 protected: 167 T *resource; CrashRecoveryContextCleanupBase(CrashRecoveryContext * context,T * resource)168 CrashRecoveryContextCleanupBase(CrashRecoveryContext *context, T *resource) 169 : CrashRecoveryContextCleanup(context), resource(resource) {} 170 171 public: 172 /// Creates cleanup handler. 173 /// \param x Pointer to the resource recovered by this handler. 174 /// \return New handler or null if the method was called outside a recovery 175 /// context. create(T * x)176 static Derived *create(T *x) { 177 if (x) { 178 if (CrashRecoveryContext *context = CrashRecoveryContext::GetCurrent()) 179 return new Derived(context, x); 180 } 181 return nullptr; 182 } 183 }; 184 185 /// Cleanup handler that reclaims resource by calling destructor on it. 186 template <typename T> 187 class CrashRecoveryContextDestructorCleanup : public 188 CrashRecoveryContextCleanupBase<CrashRecoveryContextDestructorCleanup<T>, T> { 189 public: CrashRecoveryContextDestructorCleanup(CrashRecoveryContext * context,T * resource)190 CrashRecoveryContextDestructorCleanup(CrashRecoveryContext *context, 191 T *resource) 192 : CrashRecoveryContextCleanupBase< 193 CrashRecoveryContextDestructorCleanup<T>, T>(context, resource) {} 194 recoverResources()195 void recoverResources() override { 196 this->resource->~T(); 197 } 198 }; 199 200 /// Cleanup handler that reclaims resource by calling 'delete' on it. 201 template <typename T> 202 class CrashRecoveryContextDeleteCleanup : public 203 CrashRecoveryContextCleanupBase<CrashRecoveryContextDeleteCleanup<T>, T> { 204 public: CrashRecoveryContextDeleteCleanup(CrashRecoveryContext * context,T * resource)205 CrashRecoveryContextDeleteCleanup(CrashRecoveryContext *context, T *resource) 206 : CrashRecoveryContextCleanupBase< 207 CrashRecoveryContextDeleteCleanup<T>, T>(context, resource) {} 208 recoverResources()209 void recoverResources() override { delete this->resource; } 210 }; 211 212 /// Cleanup handler that reclaims resource by calling its method 'Release'. 213 template <typename T> 214 class CrashRecoveryContextReleaseRefCleanup : public 215 CrashRecoveryContextCleanupBase<CrashRecoveryContextReleaseRefCleanup<T>, T> { 216 public: CrashRecoveryContextReleaseRefCleanup(CrashRecoveryContext * context,T * resource)217 CrashRecoveryContextReleaseRefCleanup(CrashRecoveryContext *context, 218 T *resource) 219 : CrashRecoveryContextCleanupBase<CrashRecoveryContextReleaseRefCleanup<T>, 220 T>(context, resource) {} 221 recoverResources()222 void recoverResources() override { this->resource->Release(); } 223 }; 224 225 /// Helper class for managing resource cleanups. 226 /// 227 /// \tparam T Type of resource been reclaimed. 228 /// \tparam Cleanup Class that defines how the resource is reclaimed. 229 /// 230 /// Clients create objects of this type in the code executed in a crash recovery 231 /// context to ensure that the resource will be reclaimed even in the case of 232 /// crash. For example: 233 /// 234 /// \code 235 /// void actual_work(void *) { 236 /// ... 237 /// std::unique_ptr<Resource> R(new Resource()); 238 /// CrashRecoveryContextCleanupRegistrar D(R.get()); 239 /// ... 240 /// } 241 /// 242 /// void foo() { 243 /// CrashRecoveryContext CRC; 244 /// 245 /// if (!CRC.RunSafely(actual_work, 0)) { 246 /// ... a crash was detected, report error to user ... 247 /// } 248 /// \endcode 249 /// 250 /// If the code of `actual_work` in the example above does not crash, the 251 /// destructor of CrashRecoveryContextCleanupRegistrar removes cleanup code from 252 /// the current CrashRecoveryContext and the resource is reclaimed by the 253 /// destructor of std::unique_ptr. If crash happens, destructors are not called 254 /// and the resource is reclaimed by cleanup object registered in the recovery 255 /// context by the constructor of CrashRecoveryContextCleanupRegistrar. 256 template <typename T, typename Cleanup = CrashRecoveryContextDeleteCleanup<T> > 257 class CrashRecoveryContextCleanupRegistrar { 258 CrashRecoveryContextCleanup *cleanup; 259 260 public: CrashRecoveryContextCleanupRegistrar(T * x)261 CrashRecoveryContextCleanupRegistrar(T *x) 262 : cleanup(Cleanup::create(x)) { 263 if (cleanup) 264 cleanup->getContext()->registerCleanup(cleanup); 265 } 266 ~CrashRecoveryContextCleanupRegistrar()267 ~CrashRecoveryContextCleanupRegistrar() { unregister(); } 268 unregister()269 void unregister() { 270 if (cleanup && !cleanup->cleanupFired) 271 cleanup->getContext()->unregisterCleanup(cleanup); 272 cleanup = nullptr; 273 } 274 }; 275 } // end namespace llvm 276 277 #endif // LLVM_SUPPORT_CRASHRECOVERYCONTEXT_H 278