1 /* Copyright 2016-present Facebook, Inc.
2 * Licensed under the Apache License, Version 2.0 */
3
4 // Note that this is a port of folly/ScopeGuard.h, adjusted to compile
5 // in watchman without pulling in all of folly (a non-goal for the watchman
6 // project at the current time).
7 // It defines SCOPE_XXX symbols that will conflict with folly/ScopeGuard.h
8 // if both are in use. Therefore the convention is that only watchman .cpp
9 // files will include this. For the small handful of watchman files that
10 // pull in folly dependencies, those files will prefer to include
11 // folly/ScopeGuard.h instead. In the longer run (once gcc 5 is more easily
12 // installable for our supported linux systems) and once the homebrew build
13 // story for our various projects is in better shape, we can remove this in
14 // favor of just depending on folly.
15
16 #pragma once
17 #include <cstddef>
18 #include <exception>
19 #include <functional>
20 #include <new>
21 #include <type_traits>
22 #include <utility>
23 #include "watchman_preprocessor.h"
24
25 #if defined(__GNUG__) || defined(__clang__)
26 #define WATCHMAN_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS
27 namespace __cxxabiv1 {
28 // forward declaration (originally defined in unwind-cxx.h from from libstdc++)
29 struct __cxa_eh_globals;
30 // declared in cxxabi.h from libstdc++-v3
31 extern "C" __cxa_eh_globals* __cxa_get_globals() noexcept;
32 }
33 #elif defined(_MSC_VER) && (_MSC_VER >= 1400) && \
34 (_MSC_VER < 1900) // MSVC++ 8.0 or greater
35 #define WATCHMAN_EXCEPTION_COUNT_USE_GETPTD
36 // forward declaration (originally defined in mtdll.h from MSVCRT)
37 struct _tiddata;
38 extern "C" _tiddata* _getptd(); // declared in mtdll.h from MSVCRT
39 #elif defined(_MSC_VER) && (_MSC_VER >= 1900) // MSVC++ 2015
40 #define WATCHMAN_EXCEPTION_COUNT_USE_STD
41 #else
42 // Raise an error when trying to use this on unsupported platforms.
43 #error "Unsupported platform, don't include this header."
44 #endif
45
46 namespace watchman {
47 namespace detail {
48
49 /**
50 * Used to check if a new uncaught exception was thrown by monitoring the
51 * number of uncaught exceptions.
52 *
53 * Usage:
54 * - create a new UncaughtExceptionCounter object
55 * - call isNewUncaughtException() on the new object to check if a new
56 * uncaught exception was thrown since the object was created
57 */
58 class UncaughtExceptionCounter {
59 public:
UncaughtExceptionCounter()60 UncaughtExceptionCounter() noexcept
61 : exceptionCount_(getUncaughtExceptionCount()) {}
62
UncaughtExceptionCounter(const UncaughtExceptionCounter & other)63 UncaughtExceptionCounter(const UncaughtExceptionCounter& other) noexcept
64 : exceptionCount_(other.exceptionCount_) {}
65
isNewUncaughtException()66 bool isNewUncaughtException() noexcept {
67 return getUncaughtExceptionCount() > exceptionCount_;
68 }
69
70 private:
71 int getUncaughtExceptionCount() noexcept;
72
73 int exceptionCount_;
74 };
75
76 /**
77 * Returns the number of uncaught exceptions.
78 *
79 * This function is based on Evgeny Panasyuk's implementation from here:
80 * http://fburl.com/15190026
81 */
getUncaughtExceptionCount()82 inline int UncaughtExceptionCounter::getUncaughtExceptionCount() noexcept {
83 #if defined(WATCHMAN_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS)
84 // __cxa_get_globals returns a __cxa_eh_globals* (defined in unwind-cxx.h).
85 // The offset below returns __cxa_eh_globals::uncaughtExceptions.
86 return *(reinterpret_cast<unsigned int*>(
87 static_cast<char*>(static_cast<void*>(__cxxabiv1::__cxa_get_globals())) +
88 sizeof(void*)));
89 #elif defined(WATCHMAN_EXCEPTION_COUNT_USE_GETPTD)
90 // _getptd() returns a _tiddata* (defined in mtdll.h).
91 // The offset below returns _tiddata::_ProcessingThrow.
92 return *(reinterpret_cast<int*>(
93 static_cast<char*>(static_cast<void*>(_getptd())) + sizeof(void*) * 28 +
94 0x4 * 8));
95 #elif defined(WATCHMAN_EXCEPTION_COUNT_USE_STD)
96 return std::uncaught_exceptions();
97 #endif
98 }
99
100 } // namespace detail
101
102 /**
103 * ScopeGuard is a general implementation of the "Initialization is
104 * Resource Acquisition" idiom. Basically, it guarantees that a function
105 * is executed upon leaving the currrent scope unless otherwise told.
106 *
107 * The makeGuard() function is used to create a new ScopeGuard object.
108 * It can be instantiated with a lambda function, a std::function<void()>,
109 * a functor, or a void(*)() function pointer.
110 *
111 *
112 * Usage example: Add a friend to memory if and only if it is also added
113 * to the db.
114 *
115 * void User::addFriend(User& newFriend) {
116 * // add the friend to memory
117 * friends_.push_back(&newFriend);
118 *
119 * // If the db insertion that follows fails, we should
120 * // remove it from memory.
121 * // (You could also declare this as "auto guard = makeGuard(...)")
122 * ScopeGuard guard = makeGuard([&] { friends_.pop_back(); });
123 *
124 * // this will throw an exception upon error, which
125 * // makes the ScopeGuard execute UserCont::pop_back()
126 * // once the Guard's destructor is called.
127 * db_->addFriend(GetName(), newFriend.GetName());
128 *
129 * // an exception was not thrown, so don't execute
130 * // the Guard.
131 * guard.dismiss();
132 * }
133 *
134 * Examine ScopeGuardTest.cpp for some more sample usage.
135 *
136 * Stolen from:
137 * Andrei's and Petru Marginean's CUJ article:
138 * http://drdobbs.com/184403758
139 * and the loki library:
140 * http://loki-lib.sourceforge.net/index.php?n=Idioms.ScopeGuardPointer
141 * and triendl.kj article:
142 * http://www.codeproject.com/KB/cpp/scope_guard.aspx
143 */
144 class ScopeGuardImplBase {
145 public:
dismiss()146 void dismiss() noexcept {
147 dismissed_ = true;
148 }
149
150 protected:
ScopeGuardImplBase()151 ScopeGuardImplBase() noexcept : dismissed_(false) {}
152
makeEmptyScopeGuard()153 static ScopeGuardImplBase makeEmptyScopeGuard() noexcept {
154 return ScopeGuardImplBase{};
155 }
156
157 template <typename T>
asConst(const T & t)158 static const T& asConst(const T& t) noexcept {
159 return t;
160 }
161
162 bool dismissed_;
163 };
164
165 template <typename FunctionType>
166 class ScopeGuardImpl : public ScopeGuardImplBase {
167 public:
ScopeGuardImpl(FunctionType & fn)168 explicit ScopeGuardImpl(FunctionType& fn) noexcept(
169 std::is_nothrow_copy_constructible<FunctionType>::value)
170 : ScopeGuardImpl(
171 asConst(fn),
172 makeFailsafe(
173 std::is_nothrow_copy_constructible<FunctionType>{},
174 &fn)) {}
175
ScopeGuardImpl(const FunctionType & fn)176 explicit ScopeGuardImpl(const FunctionType& fn) noexcept(
177 std::is_nothrow_copy_constructible<FunctionType>::value)
178 : ScopeGuardImpl(
179 fn,
180 makeFailsafe(
181 std::is_nothrow_copy_constructible<FunctionType>{},
182 &fn)) {}
183
ScopeGuardImpl(FunctionType && fn)184 explicit ScopeGuardImpl(FunctionType&& fn) noexcept(
185 std::is_nothrow_move_constructible<FunctionType>::value)
186 : ScopeGuardImpl(
187 std::move_if_noexcept(fn),
188 makeFailsafe(
189 std::is_nothrow_move_constructible<FunctionType>{},
190 &fn)) {}
191
noexcept(std::is_nothrow_move_constructible<FunctionType>::value)192 ScopeGuardImpl(ScopeGuardImpl&& other) noexcept(
193 std::is_nothrow_move_constructible<FunctionType>::value)
194 : function_(std::move_if_noexcept(other.function_)) {
195 // If the above line attempts a copy and the copy throws, other is
196 // left owning the cleanup action and will execute it (or not) depending
197 // on the value of other.dismissed_. The following lines only execute
198 // if the move/copy succeeded, in which case *this assumes ownership of
199 // the cleanup action and dismisses other.
200 dismissed_ = other.dismissed_;
201 other.dismissed_ = true;
202 }
203
~ScopeGuardImpl()204 ~ScopeGuardImpl() noexcept {
205 if (!dismissed_) {
206 execute();
207 }
208 }
209
210 private:
makeFailsafe(std::true_type,const void *)211 static ScopeGuardImplBase makeFailsafe(std::true_type, const void*) noexcept {
212 return makeEmptyScopeGuard();
213 }
214
215 template <typename Fn>
216 static auto makeFailsafe(std::false_type, Fn* fn) noexcept
217 -> ScopeGuardImpl<decltype(std::ref(*fn))> {
218 return ScopeGuardImpl<decltype(std::ref(*fn))>{std::ref(*fn)};
219 }
220
221 template <typename Fn>
ScopeGuardImpl(Fn && fn,ScopeGuardImplBase && failsafe)222 explicit ScopeGuardImpl(Fn&& fn, ScopeGuardImplBase&& failsafe)
223 : ScopeGuardImplBase{}, function_(std::forward<Fn>(fn)) {
224 failsafe.dismiss();
225 }
226
227 void* operator new(std::size_t) = delete;
228
execute()229 void execute() noexcept {
230 function_();
231 }
232
233 FunctionType function_;
234 };
235
236 template <typename FunctionType>
237 ScopeGuardImpl<typename std::decay<FunctionType>::type>
makeGuard(FunctionType && fn)238 makeGuard(FunctionType&& fn) noexcept(std::is_nothrow_constructible<
239 typename std::decay<FunctionType>::type,
240 FunctionType>::value) {
241 return ScopeGuardImpl<typename std::decay<FunctionType>::type>(
242 std::forward<FunctionType>(fn));
243 }
244
245 /**
246 * This is largely unneeded if you just use auto for your guards.
247 */
248 typedef ScopeGuardImplBase&& ScopeGuard;
249
250 namespace detail {
251
252 #if defined(WATCHMAN_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS) || \
253 defined(WATCHMAN_EXCEPTION_COUNT_USE_GETPTD) || \
254 defined(WATCHMAN_EXCEPTION_COUNT_USE_STD)
255
256 /**
257 * ScopeGuard used for executing a function when leaving the current scope
258 * depending on the presence of a new uncaught exception.
259 *
260 * If the executeOnException template parameter is true, the function is
261 * executed if a new uncaught exception is present at the end of the scope.
262 * If the parameter is false, then the function is executed if no new uncaught
263 * exceptions are present at the end of the scope.
264 *
265 * Used to implement SCOPE_FAIL and SCOPE_SUCCES below.
266 */
267 template <typename FunctionType, bool executeOnException>
268 class ScopeGuardForNewException {
269 public:
ScopeGuardForNewException(const FunctionType & fn)270 explicit ScopeGuardForNewException(const FunctionType& fn) : function_(fn) {}
271
ScopeGuardForNewException(FunctionType && fn)272 explicit ScopeGuardForNewException(FunctionType&& fn)
273 : function_(std::move(fn)) {}
274
ScopeGuardForNewException(ScopeGuardForNewException && other)275 ScopeGuardForNewException(ScopeGuardForNewException&& other)
276 : function_(std::move(other.function_)),
277 exceptionCounter_(std::move(other.exceptionCounter_)) {}
278
noexcept(executeOnException)279 ~ScopeGuardForNewException() noexcept(executeOnException) {
280 if (executeOnException == exceptionCounter_.isNewUncaughtException()) {
281 function_();
282 }
283 }
284
285 private:
286 ScopeGuardForNewException(const ScopeGuardForNewException& other) = delete;
287
288 void* operator new(std::size_t) = delete;
289
290 FunctionType function_;
291 UncaughtExceptionCounter exceptionCounter_;
292 };
293
294 /**
295 * Internal use for the macro SCOPE_FAIL below
296 */
297 enum class ScopeGuardOnFail {};
298
299 template <typename FunctionType>
300 ScopeGuardForNewException<typename std::decay<FunctionType>::type, true>
301 operator+(detail::ScopeGuardOnFail, FunctionType&& fn) {
302 return ScopeGuardForNewException<
303 typename std::decay<FunctionType>::type,
304 true>(std::forward<FunctionType>(fn));
305 }
306
307 /**
308 * Internal use for the macro SCOPE_SUCCESS below
309 */
310 enum class ScopeGuardOnSuccess {};
311
312 template <typename FunctionType>
313 ScopeGuardForNewException<typename std::decay<FunctionType>::type, false>
314 operator+(ScopeGuardOnSuccess, FunctionType&& fn) {
315 return ScopeGuardForNewException<
316 typename std::decay<FunctionType>::type,
317 false>(std::forward<FunctionType>(fn));
318 }
319
320 #endif // native uncaught_exception() supported
321
322 /**
323 * Internal use for the macro SCOPE_EXIT below
324 */
325 enum class ScopeGuardOnExit {};
326
327 template <typename FunctionType>
328 ScopeGuardImpl<typename std::decay<FunctionType>::type> operator+(
329 detail::ScopeGuardOnExit,
330 FunctionType&& fn) {
331 return ScopeGuardImpl<typename std::decay<FunctionType>::type>(
332 std::forward<FunctionType>(fn));
333 }
334 } // namespace detail
335
336 #define SCOPE_EXIT \
337 auto w_gen_symbol(SCOPE_EXIT_STATE) = \
338 ::watchman::detail::ScopeGuardOnExit() + [&]() noexcept
339
340 #if defined(WATCHMAN_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS) || \
341 defined(WATCHMAN_EXCEPTION_COUNT_USE_GETPTD) || \
342 defined(WATCHMAN_EXCEPTION_COUNT_USE_STD)
343 #define SCOPE_FAIL \
344 auto w_gen_symbol(SCOPE_FAIL_STATE) = \
345 ::watchman::detail::ScopeGuardOnFail() + [&]() noexcept
346
347 #define SCOPE_SUCCESS \
348 auto w_gen_symbol(SCOPE_SUCCESS_STATE) = \
349 ::watchman::detail::ScopeGuardOnSuccess() + [&]()
350 #endif // native uncaught_exception() supported
351
352 } // namespace watchman
353