Fix fibers gdb utils script
[folly.git] / folly / ExceptionWrapper.h
1 /*
2  * Copyright 2016 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 <exception>
20 #include <memory>
21 #include <string>
22 #include <type_traits>
23 #include <utility>
24
25 #include <folly/ExceptionString.h>
26 #include <folly/FBString.h>
27 #include <folly/detail/ExceptionWrapper.h>
28
29 namespace folly {
30
31 /*
32  * Throwing exceptions can be a convenient way to handle errors. Storing
33  * exceptions in an exception_ptr makes it easy to handle exceptions in a
34  * different thread or at a later time. exception_ptr can also be used in a very
35  * generic result/exception wrapper.
36  *
37  * However, there are some issues with throwing exceptions and
38  * std::exception_ptr. These issues revolve around throw being expensive,
39  * particularly in a multithreaded environment (see
40  * ExceptionWrapperBenchmark.cpp).
41  *
42  * Imagine we have a library that has an API which returns a result/exception
43  * wrapper. Let's consider some approaches for implementing this wrapper.
44  * First, we could store a std::exception. This approach loses the derived
45  * exception type, which can make exception handling more difficult for users
46  * that prefer rethrowing the exception. We could use a folly::dynamic for every
47  * possible type of exception. This is not very flexible - adding new types of
48  * exceptions requires a change to the result/exception wrapper. We could use an
49  * exception_ptr. However, constructing an exception_ptr as well as accessing
50  * the error requires a call to throw. That means that there will be two calls
51  * to throw in order to process the exception. For performance sensitive
52  * applications, this may be unacceptable.
53  *
54  * exception_wrapper is designed to handle exception management for both
55  * convenience and high performance use cases. make_exception_wrapper is
56  * templated on derived type, allowing us to rethrow the exception properly for
57  * users that prefer convenience. These explicitly named exception types can
58  * therefore be handled without any peformance penalty.  exception_wrapper is
59  * also flexible enough to accept any type. If a caught exception is not of an
60  * explicitly named type, then std::exception_ptr is used to preserve the
61  * exception state. For performance sensitive applications, the accessor methods
62  * can test or extract a pointer to a specific exception type with very little
63  * overhead.
64  *
65  * Example usage:
66  *
67  * exception_wrapper globalExceptionWrapper;
68  *
69  * // Thread1
70  * void doSomethingCrazy() {
71  *   int rc = doSomethingCrazyWithLameReturnCodes();
72  *   if (rc == NAILED_IT) {
73  *     globalExceptionWrapper = exception_wrapper();
74  *   } else if (rc == FACE_PLANT) {
75  *     globalExceptionWrapper = make_exception_wrapper<FacePlantException>();
76  *   } else if (rc == FAIL_WHALE) {
77  *     globalExceptionWrapper = make_exception_wrapper<FailWhaleException>();
78  *   }
79  * }
80  *
81  * // Thread2: Exceptions are ok!
82  * void processResult() {
83  *   try {
84  *     globalExceptionWrapper.throwException();
85  *   } catch (const FacePlantException& e) {
86  *     LOG(ERROR) << "FACEPLANT!";
87  *   } catch (const FailWhaleException& e) {
88  *     LOG(ERROR) << "FAILWHALE!";
89  *   }
90  * }
91  *
92  * // Thread2: Exceptions are bad!
93  * void processResult() {
94  *   globalExceptionWrapper.with_exception(
95  *       [&](FacePlantException& faceplant) {
96  *         LOG(ERROR) << "FACEPLANT";
97  *       }) ||
98  *   globalExceptionWrapper.with_exception(
99  *       [&](FailWhaleException& failwhale) {
100  *         LOG(ERROR) << "FAILWHALE!";
101  *       }) ||
102  *   LOG(FATAL) << "Unrecognized exception";
103  * }
104  *
105  */
106 class exception_wrapper {
107  protected:
108   template <typename Ex>
109   struct optimize;
110
111  public:
112   exception_wrapper() = default;
113
114   // Implicitly construct an exception_wrapper from a qualifying exception.
115   // See the optimize struct for details.
116   template <typename Ex, typename =
117     typename std::enable_if<optimize<typename std::decay<Ex>::type>::value>
118     ::type>
119   /* implicit */ exception_wrapper(Ex&& exn) {
120     typedef typename std::decay<Ex>::type DEx;
121     item_ = std::make_shared<DEx>(std::forward<Ex>(exn));
122     throwfn_ = folly::detail::Thrower<DEx>::doThrow;
123   }
124
125   // The following two constructors are meant to emulate the behavior of
126   // try_and_catch in performance sensitive code as well as to be flexible
127   // enough to wrap exceptions of unknown type. There is an overload that
128   // takes an exception reference so that the wrapper can extract and store
129   // the exception's type and what() when possible.
130   //
131   // The canonical use case is to construct an all-catching exception wrapper
132   // with minimal overhead like so:
133   //
134   //   try {
135   //     // some throwing code
136   //   } catch (const std::exception& e) {
137   //     // won't lose e's type and what()
138   //     exception_wrapper ew{std::current_exception(), e};
139   //   } catch (...) {
140   //     // everything else
141   //     exception_wrapper ew{std::current_exception()};
142   //   }
143   //
144   // try_and_catch is cleaner and preferable. Use it unless you're sure you need
145   // something like this instead.
146   template <typename Ex>
147   explicit exception_wrapper(std::exception_ptr eptr, Ex& exn) {
148     assign_eptr(eptr, exn);
149   }
150
151   explicit exception_wrapper(std::exception_ptr eptr) {
152     assign_eptr(eptr);
153   }
154
155   // If the exception_wrapper does not contain an exception, std::terminate()
156   // is invoked to assure the [[noreturn]] behaviour.
157   [[noreturn]] void throwException() const;
158
159   explicit operator bool() const {
160     return item_ || eptr_;
161   }
162
163   // This implementation is similar to std::exception_ptr's implementation
164   // where two exception_wrappers are equal when the address in the underlying
165   // reference field both point to the same exception object.  The reference
166   // field remains the same when the exception_wrapper is copied or when
167   // the exception_wrapper is "rethrown".
168   bool operator==(const exception_wrapper& a) const {
169     if (item_) {
170       return a.item_ && item_.get() == a.item_.get();
171     } else {
172       return eptr_ == a.eptr_;
173     }
174   }
175
176   bool operator!=(const exception_wrapper& a) const {
177     return !(*this == a);
178   }
179
180   // This will return a non-nullptr only if the exception is held as a
181   // copy.  It is the only interface which will distinguish between an
182   // exception held this way, and by exception_ptr.  You probably
183   // shouldn't use it at all.
184   std::exception* getCopied() { return item_.get(); }
185   const std::exception* getCopied() const { return item_.get(); }
186
187   fbstring what() const;
188   fbstring class_name() const;
189
190   template <class Ex>
191   bool is_compatible_with() const {
192     if (item_) {
193       return dynamic_cast<const Ex*>(item_.get());
194     } else if (eptr_) {
195       try {
196         std::rethrow_exception(eptr_);
197       } catch (typename std::decay<Ex>::type&) {
198         return true;
199       } catch (...) {
200         // fall through
201       }
202     }
203     return false;
204   }
205
206   template <class F>
207   bool with_exception(F&& f) {
208     using arg_type = typename functor_traits<F>::arg_type_decayed;
209     return with_exception<arg_type>(std::forward<F>(f));
210   }
211
212   template <class F>
213   bool with_exception(F&& f) const {
214     using arg_type = typename functor_traits<F>::arg_type_decayed;
215     return with_exception<const arg_type>(std::forward<F>(f));
216   }
217
218   // If this exception wrapper wraps an exception of type Ex, with_exception
219   // will call f with the wrapped exception as an argument and return true, and
220   // will otherwise return false.
221   template <class Ex, class F>
222   typename std::enable_if<
223     std::is_base_of<std::exception, typename std::decay<Ex>::type>::value,
224     bool>::type
225   with_exception(F f) {
226     return with_exception1<typename std::decay<Ex>::type>(f, this);
227   }
228
229   // Const overload
230   template <class Ex, class F>
231   typename std::enable_if<
232     std::is_base_of<std::exception, typename std::decay<Ex>::type>::value,
233     bool>::type
234   with_exception(F f) const {
235     return with_exception1<const typename std::decay<Ex>::type>(f, this);
236   }
237
238   // Overload for non-exceptions. Always rethrows.
239   template <class Ex, class F>
240   typename std::enable_if<
241     !std::is_base_of<std::exception, typename std::decay<Ex>::type>::value,
242     bool>::type
243   with_exception(F f) const {
244     try {
245       if (*this) {
246         throwException();
247       }
248     } catch (typename std::decay<Ex>::type& e) {
249       f(e);
250       return true;
251     } catch (...) {
252       // fall through
253     }
254     return false;
255   }
256
257   std::exception_ptr getExceptionPtr() const {
258     if (eptr_) {
259       return eptr_;
260     }
261
262     try {
263       if (*this) {
264         throwException();
265       }
266     } catch (...) {
267       return std::current_exception();
268     }
269     return std::exception_ptr();
270   }
271
272 protected:
273   template <typename Ex>
274   struct optimize {
275     static const bool value =
276       std::is_base_of<std::exception, Ex>::value &&
277       std::is_copy_assignable<Ex>::value &&
278       !std::is_abstract<Ex>::value;
279   };
280
281   template <typename Ex>
282   void assign_eptr(std::exception_ptr eptr, Ex& e) {
283     this->eptr_ = eptr;
284     this->estr_ = exceptionStr(e).toStdString();
285     this->ename_ = demangle(typeid(e)).toStdString();
286   }
287
288   void assign_eptr(std::exception_ptr eptr) {
289     this->eptr_ = eptr;
290   }
291
292   // Optimized case: if we know what type the exception is, we can
293   // store a copy of the concrete type, and a helper function so we
294   // can rethrow it.
295   std::shared_ptr<std::exception> item_;
296   void (*throwfn_)(std::exception*){nullptr};
297   // Fallback case: store the library wrapper, which is less efficient
298   // but gets the job done.  Also store exceptionPtr() the name of the
299   // exception type, so we can at least get those back out without
300   // having to rethrow.
301   std::exception_ptr eptr_;
302   std::string estr_;
303   std::string ename_;
304
305   template <class T, class... Args>
306   friend exception_wrapper make_exception_wrapper(Args&&... args);
307
308 private:
309   template <typename F>
310   struct functor_traits {
311     template <typename T>
312     struct impl;
313     template <typename C, typename R, typename A>
314     struct impl<R(C::*)(A)> { using arg_type = A; };
315     template <typename C, typename R, typename A>
316     struct impl<R(C::*)(A) const> { using arg_type = A; };
317     using functor_decayed = typename std::decay<F>::type;
318     using functor_op = decltype(&functor_decayed::operator());
319     using arg_type = typename impl<functor_op>::arg_type;
320     using arg_type_decayed = typename std::decay<arg_type>::type;
321   };
322
323   // What makes this useful is that T can be exception_wrapper* or
324   // const exception_wrapper*, and the compiler will use the
325   // instantiation which works with F.
326   template <class Ex, class F, class T>
327   static bool with_exception1(F f, T* that) {
328     if (that->item_) {
329       if (auto ex = dynamic_cast<Ex*>(that->item_.get())) {
330         f(*ex);
331         return true;
332       }
333     } else if (that->eptr_) {
334       try {
335         std::rethrow_exception(that->eptr_);
336       } catch (Ex& e) {
337         f(e);
338         return true;
339       } catch (...) {
340         // fall through
341       }
342     }
343     return false;
344   }
345 };
346
347 template <class T, class... Args>
348 exception_wrapper make_exception_wrapper(Args&&... args) {
349   exception_wrapper ew;
350   ew.item_ = std::make_shared<T>(std::forward<Args>(args)...);
351   ew.throwfn_ = folly::detail::Thrower<T>::doThrow;
352   return ew;
353 }
354
355 // For consistency with exceptionStr() functions in String.h
356 fbstring exceptionStr(const exception_wrapper& ew);
357
358 /*
359  * try_and_catch is a simple replacement for try {} catch(){} that allows you to
360  * specify which derived exceptions you would like to catch and store in an
361  * exception_wrapper.
362  *
363  * Because we cannot build an equivalent of std::current_exception(), we need
364  * to catch every derived exception that we are interested in catching.
365  *
366  * Exceptions should be listed in the reverse order that you would write your
367  * catch statements (that is, std::exception& should be first).
368  *
369  * NOTE: Although implemented as a derived class (for syntactic delight), don't
370  * be confused - you should not pass around try_and_catch objects!
371  *
372  * Example Usage:
373  *
374  * // This catches my runtime_error and if I call throwException() on ew, it
375  * // will throw a runtime_error
376  * auto ew = folly::try_and_catch<std::exception, std::runtime_error>([=]() {
377  *   if (badThingHappens()) {
378  *     throw std::runtime_error("ZOMG!");
379  *   }
380  * });
381  *
382  * // This will catch the exception and if I call throwException() on ew, it
383  * // will throw a std::exception
384  * auto ew = folly::try_and_catch<std::exception, std::runtime_error>([=]() {
385  *   if (badThingHappens()) {
386  *     throw std::exception();
387  *   }
388  * });
389  *
390  * // This will not catch the exception and it will be thrown.
391  * auto ew = folly::try_and_catch<std::runtime_error>([=]() {
392  *   if (badThingHappens()) {
393  *     throw std::exception();
394  *   }
395  * });
396  */
397
398 template <typename... Exceptions>
399 class try_and_catch;
400
401 template <typename LastException, typename... Exceptions>
402 class try_and_catch<LastException, Exceptions...> :
403     public try_and_catch<Exceptions...> {
404  public:
405   template <typename F>
406   explicit try_and_catch(F&& fn) : Base() {
407     call_fn(fn);
408   }
409
410  protected:
411   typedef try_and_catch<Exceptions...> Base;
412
413   try_and_catch() : Base() {}
414
415   template <typename Ex>
416   typename std::enable_if<!exception_wrapper::optimize<Ex>::value>::type
417   assign_exception(Ex& e, std::exception_ptr eptr) {
418     exception_wrapper::assign_eptr(eptr, e);
419   }
420
421   template <typename Ex>
422   typename std::enable_if<exception_wrapper::optimize<Ex>::value>::type
423   assign_exception(Ex& e, std::exception_ptr /*eptr*/) {
424     this->item_ = std::make_shared<Ex>(e);
425     this->throwfn_ = folly::detail::Thrower<Ex>::doThrow;
426   }
427
428   template <typename F>
429   void call_fn(F&& fn) {
430     try {
431       Base::call_fn(std::move(fn));
432     } catch (LastException& e) {
433       if (typeid(e) == typeid(LastException&)) {
434         assign_exception(e, std::current_exception());
435       } else {
436         exception_wrapper::assign_eptr(std::current_exception(), e);
437       }
438     }
439   }
440 };
441
442 template<>
443 class try_and_catch<> : public exception_wrapper {
444  public:
445   try_and_catch() = default;
446
447  protected:
448   template <typename F>
449   void call_fn(F&& fn) {
450     fn();
451   }
452 };
453
454 } // folly