135d2c4c185a6a426cc6c8966421d93a59f24401
[folly.git] / folly / ScopeGuard.h
1 /*
2  * Copyright 2011-present Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #pragma once
18
19 #include <cstddef>
20 #include <functional>
21 #include <new>
22 #include <type_traits>
23 #include <utility>
24
25 #include <folly/Portability.h>
26 #include <folly/Preprocessor.h>
27 #include <folly/UncaughtExceptions.h>
28
29 namespace folly {
30
31 namespace detail {
32
33 class ScopeGuardImplBase {
34  public:
35   void dismiss() noexcept {
36     dismissed_ = true;
37   }
38
39   template <typename T>
40   FOLLY_ALWAYS_INLINE static void runAndWarnAboutToCrashOnException(
41       T& function) noexcept {
42     try {
43       function();
44     } catch (...) {
45       warnAboutToCrash();
46       std::terminate();
47     }
48   }
49
50  protected:
51   ScopeGuardImplBase() noexcept : dismissed_(false) {}
52
53   static ScopeGuardImplBase makeEmptyScopeGuard() noexcept {
54     return ScopeGuardImplBase{};
55   }
56
57   template <typename T>
58   static const T& asConst(const T& t) noexcept {
59     return t;
60   }
61
62   bool dismissed_;
63
64  private:
65   static void warnAboutToCrash() noexcept;
66 };
67
68 template <typename FunctionType>
69 class ScopeGuardImpl : public ScopeGuardImplBase {
70  public:
71   explicit ScopeGuardImpl(FunctionType& fn) noexcept(
72       std::is_nothrow_copy_constructible<FunctionType>::value)
73       : ScopeGuardImpl(
74             asConst(fn),
75             makeFailsafe(std::is_nothrow_copy_constructible<FunctionType>{},
76                          &fn)) {}
77
78   explicit ScopeGuardImpl(const FunctionType& fn) noexcept(
79       std::is_nothrow_copy_constructible<FunctionType>::value)
80       : ScopeGuardImpl(
81             fn,
82             makeFailsafe(std::is_nothrow_copy_constructible<FunctionType>{},
83                          &fn)) {}
84
85   explicit ScopeGuardImpl(FunctionType&& fn) noexcept(
86       std::is_nothrow_move_constructible<FunctionType>::value)
87       : ScopeGuardImpl(
88             std::move_if_noexcept(fn),
89             makeFailsafe(std::is_nothrow_move_constructible<FunctionType>{},
90                          &fn)) {}
91
92   ScopeGuardImpl(ScopeGuardImpl&& other) noexcept(
93       std::is_nothrow_move_constructible<FunctionType>::value)
94       : function_(std::move_if_noexcept(other.function_)) {
95     // If the above line attempts a copy and the copy throws, other is
96     // left owning the cleanup action and will execute it (or not) depending
97     // on the value of other.dismissed_. The following lines only execute
98     // if the move/copy succeeded, in which case *this assumes ownership of
99     // the cleanup action and dismisses other.
100     dismissed_ = other.dismissed_;
101     other.dismissed_ = true;
102   }
103
104   ~ScopeGuardImpl() noexcept {
105     if (!dismissed_) {
106       execute();
107     }
108   }
109
110  private:
111   static ScopeGuardImplBase makeFailsafe(std::true_type, const void*) noexcept {
112     return makeEmptyScopeGuard();
113   }
114
115   template <typename Fn>
116   static auto makeFailsafe(std::false_type, Fn* fn) noexcept
117       -> ScopeGuardImpl<decltype(std::ref(*fn))> {
118     return ScopeGuardImpl<decltype(std::ref(*fn))>{std::ref(*fn)};
119   }
120
121   template <typename Fn>
122   explicit ScopeGuardImpl(Fn&& fn, ScopeGuardImplBase&& failsafe)
123       : ScopeGuardImplBase{}, function_(std::forward<Fn>(fn)) {
124     failsafe.dismiss();
125   }
126
127   void* operator new(std::size_t) = delete;
128
129   void execute() noexcept {
130     runAndWarnAboutToCrashOnException(function_);
131   }
132
133   FunctionType function_;
134 };
135
136 template <typename F>
137 using ScopeGuardImplDecay = ScopeGuardImpl<typename std::decay<F>::type>;
138
139 } // namespace detail
140
141 /**
142  * ScopeGuard is a general implementation of the "Initialization is
143  * Resource Acquisition" idiom.  Basically, it guarantees that a function
144  * is executed upon leaving the currrent scope unless otherwise told.
145  *
146  * The makeGuard() function is used to create a new ScopeGuard object.
147  * It can be instantiated with a lambda function, a std::function<void()>,
148  * a functor, or a void(*)() function pointer.
149  *
150  *
151  * Usage example: Add a friend to memory if and only if it is also added
152  * to the db.
153  *
154  * void User::addFriend(User& newFriend) {
155  *   // add the friend to memory
156  *   friends_.push_back(&newFriend);
157  *
158  *   // If the db insertion that follows fails, we should
159  *   // remove it from memory.
160  *   auto guard = makeGuard([&] { friends_.pop_back(); });
161  *
162  *   // this will throw an exception upon error, which
163  *   // makes the ScopeGuard execute UserCont::pop_back()
164  *   // once the Guard's destructor is called.
165  *   db_->addFriend(GetName(), newFriend.GetName());
166  *
167  *   // an exception was not thrown, so don't execute
168  *   // the Guard.
169  *   guard.dismiss();
170  * }
171  *
172  * Examine ScopeGuardTest.cpp for some more sample usage.
173  *
174  * Stolen from:
175  *   Andrei's and Petru Marginean's CUJ article:
176  *     http://drdobbs.com/184403758
177  *   and the loki library:
178  *     http://loki-lib.sourceforge.net/index.php?n=Idioms.ScopeGuardPointer
179  *   and triendl.kj article:
180  *     http://www.codeproject.com/KB/cpp/scope_guard.aspx
181  */
182 template <typename F>
183 detail::ScopeGuardImplDecay<F> makeGuard(F&& f) noexcept(
184     noexcept(detail::ScopeGuardImplDecay<F>(static_cast<F&&>(f)))) {
185   return detail::ScopeGuardImplDecay<F>(static_cast<F&&>(f));
186 }
187
188 /**
189  * This is largely unneeded if you just use auto for your guards.
190  */
191 typedef detail::ScopeGuardImplBase&& ScopeGuard;
192
193 namespace detail {
194
195 #if defined(FOLLY_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS) || \
196     defined(FOLLY_EXCEPTION_COUNT_USE_GETPTD) ||          \
197     defined(FOLLY_EXCEPTION_COUNT_USE_STD)
198
199 /**
200  * ScopeGuard used for executing a function when leaving the current scope
201  * depending on the presence of a new uncaught exception.
202  *
203  * If the executeOnException template parameter is true, the function is
204  * executed if a new uncaught exception is present at the end of the scope.
205  * If the parameter is false, then the function is executed if no new uncaught
206  * exceptions are present at the end of the scope.
207  *
208  * Used to implement SCOPE_FAIL and SCOPE_SUCCESS below.
209  */
210 template <typename FunctionType, bool ExecuteOnException>
211 class ScopeGuardForNewException {
212  public:
213   explicit ScopeGuardForNewException(const FunctionType& fn) : function_(fn) {}
214
215   explicit ScopeGuardForNewException(FunctionType&& fn)
216       : function_(std::move(fn)) {}
217
218   ScopeGuardForNewException(ScopeGuardForNewException&& other) = default;
219
220   ~ScopeGuardForNewException() noexcept(ExecuteOnException) {
221     if (ExecuteOnException == (exceptionCounter_ < uncaught_exceptions())) {
222       if (ExecuteOnException) {
223         ScopeGuardImplBase::runAndWarnAboutToCrashOnException(function_);
224       } else {
225         function_();
226       }
227     }
228   }
229
230  private:
231   ScopeGuardForNewException(const ScopeGuardForNewException& other) = delete;
232
233   void* operator new(std::size_t) = delete;
234
235   FunctionType function_;
236   int exceptionCounter_{uncaught_exceptions()};
237 };
238
239 /**
240  * Internal use for the macro SCOPE_FAIL below
241  */
242 enum class ScopeGuardOnFail {};
243
244 template <typename FunctionType>
245 ScopeGuardForNewException<typename std::decay<FunctionType>::type, true>
246 operator+(detail::ScopeGuardOnFail, FunctionType&& fn) {
247   return
248       ScopeGuardForNewException<typename std::decay<FunctionType>::type, true>(
249       std::forward<FunctionType>(fn));
250 }
251
252 /**
253  * Internal use for the macro SCOPE_SUCCESS below
254  */
255 enum class ScopeGuardOnSuccess {};
256
257 template <typename FunctionType>
258 ScopeGuardForNewException<typename std::decay<FunctionType>::type, false>
259 operator+(ScopeGuardOnSuccess, FunctionType&& fn) {
260   return
261       ScopeGuardForNewException<typename std::decay<FunctionType>::type, false>(
262       std::forward<FunctionType>(fn));
263 }
264
265 #endif // native uncaught_exception() supported
266
267 /**
268  * Internal use for the macro SCOPE_EXIT below
269  */
270 enum class ScopeGuardOnExit {};
271
272 template <typename FunctionType>
273 ScopeGuardImpl<typename std::decay<FunctionType>::type>
274 operator+(detail::ScopeGuardOnExit, FunctionType&& fn) {
275   return ScopeGuardImpl<typename std::decay<FunctionType>::type>(
276       std::forward<FunctionType>(fn));
277 }
278 } // namespace detail
279
280 } // namespace folly
281
282 #define SCOPE_EXIT \
283   auto FB_ANONYMOUS_VARIABLE(SCOPE_EXIT_STATE) \
284   = ::folly::detail::ScopeGuardOnExit() + [&]() noexcept
285
286 #if defined(FOLLY_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS) || \
287     defined(FOLLY_EXCEPTION_COUNT_USE_GETPTD) ||          \
288     defined(FOLLY_EXCEPTION_COUNT_USE_STD)
289 #define SCOPE_FAIL \
290   auto FB_ANONYMOUS_VARIABLE(SCOPE_FAIL_STATE) \
291   = ::folly::detail::ScopeGuardOnFail() + [&]() noexcept
292
293 #define SCOPE_SUCCESS \
294   auto FB_ANONYMOUS_VARIABLE(SCOPE_SUCCESS_STATE) \
295   = ::folly::detail::ScopeGuardOnSuccess() + [&]()
296 #endif // native uncaught_exception() supported