Add llvm::function_ref (and a couple of uses of it), representing a type-erased refer...
[oota-llvm.git] / include / llvm / Support / CrashRecoveryContext.h
1 //===--- CrashRecoveryContext.h - Crash Recovery ----------------*- C++ -*-===//
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
10 #ifndef LLVM_SUPPORT_CRASHRECOVERYCONTEXT_H
11 #define LLVM_SUPPORT_CRASHRECOVERYCONTEXT_H
12
13 #include <string>
14
15 #include "llvm/ADT/STLExtras.h"
16
17 namespace llvm {
18 class StringRef;
19
20 class CrashRecoveryContextCleanup;
21
22 /// \brief Crash recovery helper object.
23 ///
24 /// This class implements support for running operations in a safe context so
25 /// that crashes (memory errors, stack overflow, assertion violations) can be
26 /// detected and control restored to the crashing thread. Crash detection is
27 /// purely "best effort", the exact set of failures which can be recovered from
28 /// is platform dependent.
29 ///
30 /// Clients make use of this code by first calling
31 /// CrashRecoveryContext::Enable(), and then executing unsafe operations via a
32 /// CrashRecoveryContext object. For example:
33 ///
34 ///    void actual_work(void *);
35 ///
36 ///    void foo() {
37 ///      CrashRecoveryContext CRC;
38 ///
39 ///      if (!CRC.RunSafely(actual_work, 0)) {
40 ///         ... a crash was detected, report error to user ...
41 ///      }
42 ///
43 ///      ... no crash was detected ...
44 ///    }
45 ///
46 /// Crash recovery contexts may not be nested.
47 class CrashRecoveryContext {
48   void *Impl;
49   CrashRecoveryContextCleanup *head;
50
51 public:
52   CrashRecoveryContext() : Impl(nullptr), head(nullptr) {}
53   ~CrashRecoveryContext();
54
55   void registerCleanup(CrashRecoveryContextCleanup *cleanup);
56   void unregisterCleanup(CrashRecoveryContextCleanup *cleanup);
57
58   /// \brief Enable crash recovery.
59   static void Enable();
60
61   /// \brief Disable crash recovery.
62   static void Disable();
63
64   /// \brief Return the active context, if the code is currently executing in a
65   /// thread which is in a protected context.
66   static CrashRecoveryContext *GetCurrent();
67
68   /// \brief Return true if the current thread is recovering from a
69   /// crash.
70   static bool isRecoveringFromCrash();
71
72   /// \brief Execute the provide callback function (with the given arguments) in
73   /// a protected context.
74   ///
75   /// \return True if the function completed successfully, and false if the
76   /// function crashed (or HandleCrash was called explicitly). Clients should
77   /// make as little assumptions as possible about the program state when
78   /// RunSafely has returned false. Clients can use getBacktrace() to retrieve
79   /// the backtrace of the crash on failures.
80   bool RunSafely(function_ref<void()> Fn);
81   bool RunSafely(void (*Fn)(void*), void *UserData) {
82     return RunSafely([&]() { Fn(UserData); });
83   }
84
85   /// \brief Execute the provide callback function (with the given arguments) in
86   /// a protected context which is run in another thread (optionally with a
87   /// requested stack size).
88   ///
89   /// See RunSafely() and llvm_execute_on_thread().
90   bool RunSafelyOnThread(function_ref<void()>, unsigned RequestedStackSize = 0);
91   bool RunSafelyOnThread(void (*Fn)(void*), void *UserData,
92                          unsigned RequestedStackSize = 0) {
93     return RunSafelyOnThread([&]() { Fn(UserData); }, RequestedStackSize);
94   }
95
96   /// \brief Explicitly trigger a crash recovery in the current process, and
97   /// return failure from RunSafely(). This function does not return.
98   void HandleCrash();
99
100   /// \brief Return a string containing the backtrace where the crash was
101   /// detected; or empty if the backtrace wasn't recovered.
102   ///
103   /// This function is only valid when a crash has been detected (i.e.,
104   /// RunSafely() has returned false.
105   const std::string &getBacktrace() const;
106 };
107
108 class CrashRecoveryContextCleanup {
109 protected:
110   CrashRecoveryContext *context;
111   CrashRecoveryContextCleanup(CrashRecoveryContext *context)
112     : context(context), cleanupFired(false) {}
113 public:
114   bool cleanupFired;
115   
116   virtual ~CrashRecoveryContextCleanup();
117   virtual void recoverResources() = 0;
118
119   CrashRecoveryContext *getContext() const {
120     return context;
121   }
122
123 private:
124   friend class CrashRecoveryContext;
125   CrashRecoveryContextCleanup *prev, *next;
126 };
127
128 template<typename DERIVED, typename T>
129 class CrashRecoveryContextCleanupBase : public CrashRecoveryContextCleanup {
130 protected:
131   T *resource;
132   CrashRecoveryContextCleanupBase(CrashRecoveryContext *context, T* resource)
133     : CrashRecoveryContextCleanup(context), resource(resource) {}
134 public:
135   static DERIVED *create(T *x) {
136     if (x) {
137       if (CrashRecoveryContext *context = CrashRecoveryContext::GetCurrent())
138         return new DERIVED(context, x);
139     }
140     return 0;
141   }
142 };
143
144 template <typename T>
145 class CrashRecoveryContextDestructorCleanup : public
146   CrashRecoveryContextCleanupBase<CrashRecoveryContextDestructorCleanup<T>, T> {
147 public:
148   CrashRecoveryContextDestructorCleanup(CrashRecoveryContext *context,
149                                         T *resource) 
150     : CrashRecoveryContextCleanupBase<
151         CrashRecoveryContextDestructorCleanup<T>, T>(context, resource) {}
152
153   virtual void recoverResources() {
154     this->resource->~T();
155   }
156 };
157
158 template <typename T>
159 class CrashRecoveryContextDeleteCleanup : public
160   CrashRecoveryContextCleanupBase<CrashRecoveryContextDeleteCleanup<T>, T> {
161 public:
162   CrashRecoveryContextDeleteCleanup(CrashRecoveryContext *context, T *resource)
163     : CrashRecoveryContextCleanupBase<
164         CrashRecoveryContextDeleteCleanup<T>, T>(context, resource) {}
165
166   virtual void recoverResources() {
167     delete this->resource;
168   }  
169 };
170
171 template <typename T>
172 class CrashRecoveryContextReleaseRefCleanup : public
173   CrashRecoveryContextCleanupBase<CrashRecoveryContextReleaseRefCleanup<T>, T>
174 {
175 public:
176   CrashRecoveryContextReleaseRefCleanup(CrashRecoveryContext *context, 
177                                         T *resource)
178     : CrashRecoveryContextCleanupBase<CrashRecoveryContextReleaseRefCleanup<T>,
179           T>(context, resource) {}
180
181   virtual void recoverResources() {
182     this->resource->Release();
183   }
184 };
185
186 template <typename T, typename Cleanup = CrashRecoveryContextDeleteCleanup<T> >
187 class CrashRecoveryContextCleanupRegistrar {
188   CrashRecoveryContextCleanup *cleanup;
189 public:
190   CrashRecoveryContextCleanupRegistrar(T *x)
191     : cleanup(Cleanup::create(x)) {
192     if (cleanup)
193       cleanup->getContext()->registerCleanup(cleanup);
194   }
195
196   ~CrashRecoveryContextCleanupRegistrar() {
197     unregister();
198   }
199   
200   void unregister() {
201     if (cleanup && !cleanup->cleanupFired)
202       cleanup->getContext()->unregisterCleanup(cleanup);
203     cleanup = 0;
204   }
205 };
206 }
207
208 #endif