CrashRecoveryContext.h revision 212904
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
15namespace llvm {
16class StringRef;
17
18/// \brief 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///    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///
42/// Crash recovery contexts may not be nested.
43class CrashRecoveryContext {
44  void *Impl;
45
46public:
47  CrashRecoveryContext() : Impl(0) {}
48  ~CrashRecoveryContext();
49
50  /// \brief Enable crash recovery.
51  static void Enable();
52
53  /// \brief Disable crash recovery.
54  static void Disable();
55
56  /// \brief Return the active context, if the code is currently executing in a
57  /// thread which is in a protected context.
58  static CrashRecoveryContext *GetCurrent();
59
60  /// \brief Execute the provide callback function (with the given arguments) in
61  /// a protected context.
62  ///
63  /// \return True if the function completed successfully, and false if the
64  /// function crashed (or HandleCrash was called explicitly). Clients should
65  /// make as little assumptions as possible about the program state when
66  /// RunSafely has returned false. Clients can use getBacktrace() to retrieve
67  /// the backtrace of the crash on failures.
68  bool RunSafely(void (*Fn)(void*), void *UserData);
69
70  /// \brief Explicitly trigger a crash recovery in the current process, and
71  /// return failure from RunSafely(). This function does not return.
72  void HandleCrash();
73
74  /// \brief Return a string containing the backtrace where the crash was
75  /// detected; or empty if the backtrace wasn't recovered.
76  ///
77  /// This function is only valid when a crash has been detected (i.e.,
78  /// RunSafely() has returned false.
79  const std::string &getBacktrace() const;
80};
81
82}
83
84#endif
85