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