about summary refs log tree commit diff
path: root/absl/base
diff options
context:
space:
mode:
Diffstat (limited to 'absl/base')
-rw-r--r--absl/base/BUILD.bazel1
-rw-r--r--absl/base/CMakeLists.txt19
-rw-r--r--absl/base/exception_safety_testing_test.cc25
-rw-r--r--absl/base/internal/exception_safety_testing.cc7
-rw-r--r--absl/base/internal/exception_safety_testing.h61
5 files changed, 85 insertions, 28 deletions
diff --git a/absl/base/BUILD.bazel b/absl/base/BUILD.bazel
index f6d6c3d24caf..609d78ad6287 100644
--- a/absl/base/BUILD.bazel
+++ b/absl/base/BUILD.bazel
@@ -235,6 +235,7 @@ cc_library(
     hdrs = ["internal/exception_safety_testing.h"],
     copts = ABSL_TEST_COPTS + ABSL_EXCEPTIONS_FLAG,
     deps = [
+        ":base",
         ":config",
         ":pretty_function",
         "//absl/memory",
diff --git a/absl/base/CMakeLists.txt b/absl/base/CMakeLists.txt
index 1b24fd1bb60b..cb0daa69ffdc 100644
--- a/absl/base/CMakeLists.txt
+++ b/absl/base/CMakeLists.txt
@@ -33,6 +33,7 @@ list(APPEND BASE_INTERNAL_HEADERS
   "internal/cycleclock.h"
   "internal/endian.h"
   "internal/exception_testing.h"
+  "internal/exception_safety_testing.h"
   "internal/identity.h"
   "internal/invoke.h"
   "internal/log_severity.h"
@@ -43,6 +44,7 @@ list(APPEND BASE_INTERNAL_HEADERS
   "internal/malloc_hook.h"
   "internal/malloc_hook_invoke.h"
   "internal/per_thread_tls.h"
+  "internal/pretty_function.h"
   "internal/raw_logging.h"
   "internal/scheduling_mode.h"
   "internal/spinlock.h"
@@ -57,8 +59,9 @@ list(APPEND BASE_INTERNAL_HEADERS
 
 
 # absl_base main library
-list(APPEND BASE_SRC 
+list(APPEND BASE_SRC
   "internal/cycleclock.cc"
+  "internal/exception_safety_testing.cc"
   "internal/raw_logging.cc"
   "internal/spinlock.cc"
   "internal/sysinfo.cc"
@@ -318,6 +321,20 @@ absl_test(
     ${THREAD_IDENTITY_TEST_PUBLIC_LIBRARIES}
 )
 
+#test exceptions_safety_testing_test
+set(EXCEPTION_SAFETY_TESTING_TEST_SRC "exception_safety_testing_test.cc")
+set(EXCEPTION_SAFETY_TESTING_TEST_PUBLIC_LIBRARIES absl::base absl::memory absl::meta absl::strings absl::optional)
+
+absl_test(
+  TARGET
+    absl_exception_safety_testing_test
+  SOURCES
+    ${EXCEPTION_SAFETY_TESTING_TEST_SRC}
+  PUBLIC_LIBRARIES
+    ${EXCEPTION_SAFETY_TESTING_TEST_PUBLIC_LIBRARIES}
+  PRIVATE_COMPILE_FLAGS
+    ${ABSL_EXCEPTIONS_FLAG}
+)
 
 # test absl_malloc_extension_system_malloc_test
 set(MALLOC_EXTENSION_SYSTEM_MALLOC_TEST_SRC "internal/malloc_extension_test.cc")
diff --git a/absl/base/exception_safety_testing_test.cc b/absl/base/exception_safety_testing_test.cc
index 1fc03861784e..5477b40a5bed 100644
--- a/absl/base/exception_safety_testing_test.cc
+++ b/absl/base/exception_safety_testing_test.cc
@@ -63,7 +63,7 @@ TEST_F(ThrowingValueTest, Throws) {
 // the countdown doesn't hit 0, and doesn't modify the state of the
 // ThrowingValue if it throws
 template <typename F>
-void TestOp(F&& f) {
+void TestOp(const F& f) {
   UnsetCountdown();
   ExpectNoThrow(f);
 
@@ -153,11 +153,21 @@ TEST_F(ThrowingValueTest, ThrowingStreamOps) {
   TestOp([&]() { std::cout << bomb; });
 }
 
+template <typename F>
+void TestAllocatingOp(const F& f) {
+  UnsetCountdown();
+  ExpectNoThrow(f);
+
+  SetCountdown();
+  EXPECT_THROW(f(), exceptions_internal::TestBadAllocException);
+  UnsetCountdown();
+}
+
 TEST_F(ThrowingValueTest, ThrowingAllocatingOps) {
   // make_unique calls unqualified operator new, so these exercise the
   // ThrowingValue overloads.
-  TestOp([]() { return absl::make_unique<ThrowingValue<>>(1); });
-  TestOp([]() { return absl::make_unique<ThrowingValue<>[]>(2); });
+  TestAllocatingOp([]() { return absl::make_unique<ThrowingValue<>>(1); });
+  TestAllocatingOp([]() { return absl::make_unique<ThrowingValue<>[]>(2); });
 }
 
 TEST_F(ThrowingValueTest, NonThrowingMoveCtor) {
@@ -399,7 +409,8 @@ struct CallOperator {
 };
 
 struct NonNegative {
-  friend testing::AssertionResult AbslCheckInvariants(NonNegative* g) {
+  friend testing::AssertionResult AbslCheckInvariants(
+      NonNegative* g, absl::InternalAbslNamespaceFinder) {
     if (g->i >= 0) return testing::AssertionSuccess();
     return testing::AssertionFailure()
            << "i should be non-negative but is " << g->i;
@@ -503,7 +514,8 @@ struct HasReset : public NonNegative {
 
   void reset() { i = 0; }
 
-  friend bool AbslCheckInvariants(HasReset* h) {
+  friend bool AbslCheckInvariants(HasReset* h,
+                                  absl::InternalAbslNamespaceFinder) {
     h->reset();
     return h->i == 0;
   }
@@ -591,7 +603,8 @@ struct ExhaustivenessTester {
     return true;
   }
 
-  friend testing::AssertionResult AbslCheckInvariants(ExhaustivenessTester*) {
+  friend testing::AssertionResult AbslCheckInvariants(
+      ExhaustivenessTester*, absl::InternalAbslNamespaceFinder) {
     return testing::AssertionSuccess();
   }
 
diff --git a/absl/base/internal/exception_safety_testing.cc b/absl/base/internal/exception_safety_testing.cc
index ab8d6c9fb4d0..821438ecc28c 100644
--- a/absl/base/internal/exception_safety_testing.cc
+++ b/absl/base/internal/exception_safety_testing.cc
@@ -23,8 +23,11 @@ namespace exceptions_internal {
 
 int countdown = -1;
 
-void MaybeThrow(absl::string_view msg) {
-  if (countdown-- == 0) throw TestException(msg);
+void MaybeThrow(absl::string_view msg, bool throw_bad_alloc) {
+  if (countdown-- == 0) {
+    if (throw_bad_alloc) throw TestBadAllocException(msg);
+    throw TestException(msg);
+  }
 }
 
 testing::AssertionResult FailureMessage(const TestException& e,
diff --git a/absl/base/internal/exception_safety_testing.h b/absl/base/internal/exception_safety_testing.h
index a0127a8819fa..8eac2264884f 100644
--- a/absl/base/internal/exception_safety_testing.h
+++ b/absl/base/internal/exception_safety_testing.h
@@ -35,6 +35,8 @@
 #include "absl/types/optional.h"
 
 namespace absl {
+struct InternalAbslNamespaceFinder {};
+
 struct AllocInspector;
 
 // A configuration enum for Throwing*.  Operations whose flags are set will
@@ -71,31 +73,45 @@ constexpr bool ThrowingAllowed(NoThrow flags, NoThrow flag) {
 class TestException {
  public:
   explicit TestException(absl::string_view msg) : msg_(msg) {}
-  absl::string_view what() const { return msg_; }
+  virtual ~TestException() {}
+  virtual const char* what() const noexcept { return msg_.c_str(); }
 
  private:
   std::string msg_;
 };
 
+// TestBadAllocException exists because allocation functions must throw an
+// exception which can be caught by a handler of std::bad_alloc.  We use a child
+// class of std::bad_alloc so we can customise the error message, and also
+// derive from TestException so we don't accidentally end up catching an actual
+// bad_alloc exception in TestExceptionSafety.
+class TestBadAllocException : public std::bad_alloc, public TestException {
+ public:
+  explicit TestBadAllocException(absl::string_view msg)
+      : TestException(msg) {}
+  using TestException::what;
+};
+
 extern int countdown;
 
-void MaybeThrow(absl::string_view msg);
+void MaybeThrow(absl::string_view msg, bool throw_bad_alloc = false);
 
 testing::AssertionResult FailureMessage(const TestException& e,
                                         int countdown) noexcept;
 
 class TrackedObject {
+ public:
+  TrackedObject(const TrackedObject&) = delete;
+  TrackedObject(TrackedObject&&) = delete;
+
  protected:
-  explicit TrackedObject(absl::string_view child_ctor) {
+  explicit TrackedObject(const char* child_ctor) {
     if (!GetAllocs().emplace(this, child_ctor).second) {
       ADD_FAILURE() << "Object at address " << static_cast<void*>(this)
                     << " re-constructed in ctor " << child_ctor;
     }
   }
 
-  TrackedObject(const TrackedObject&) = delete;
-  TrackedObject(TrackedObject&&) = delete;
-
   static std::unordered_map<TrackedObject*, absl::string_view>& GetAllocs() {
     static auto* m =
         new std::unordered_map<TrackedObject*, absl::string_view>();
@@ -120,10 +136,10 @@ using FactoryType = typename absl::result_of_t<Factory()>::element_type;
 template <typename Factory, typename Op, typename Checker>
 absl::optional<testing::AssertionResult> TestCheckerAtCountdown(
     Factory factory, const Op& op, int count, const Checker& check) {
-  exceptions_internal::countdown = count;
   auto t_ptr = factory();
   absl::optional<testing::AssertionResult> out;
   try {
+    exceptions_internal::countdown = count;
     op(t_ptr.get());
   } catch (const exceptions_internal::TestException& e) {
     out.emplace(check(t_ptr.get()));
@@ -141,6 +157,10 @@ int UpdateOut(Factory factory, const Op& op, int count, const Checker& checker,
   return 0;
 }
 
+// Declare AbslCheckInvariants so that it can be found eventually via ADL.
+// Taking `...` gives it the lowest possible precedence.
+void AbslCheckInvariants(...);
+
 // Returns an optional with the result of the check if op fails, or an empty
 // optional if op passes
 template <typename Factory, typename Op, typename... Checkers>
@@ -148,8 +168,9 @@ absl::optional<testing::AssertionResult> TestAtCountdown(
     Factory factory, const Op& op, int count, const Checkers&... checkers) {
   // Don't bother with the checkers if the class invariants are already broken.
   auto out = TestCheckerAtCountdown(
-      factory, op, count,
-      [](FactoryType<Factory>* t_ptr) { return AbslCheckInvariants(t_ptr); });
+      factory, op, count, [](FactoryType<Factory>* t_ptr) {
+        return AbslCheckInvariants(t_ptr, InternalAbslNamespaceFinder());
+      });
   if (!out.has_value()) return out;
 
   // Run each checker, short circuiting after the first failure
@@ -483,7 +504,7 @@ class ThrowingValue : private exceptions_internal::TrackedObject {
   static void* operator new(size_t s, Args&&... args) noexcept(
       !exceptions_internal::ThrowingAllowed(Flags, NoThrow::kAllocation)) {
     if (exceptions_internal::ThrowingAllowed(Flags, NoThrow::kAllocation)) {
-      exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
+      exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION, true);
     }
     return ::operator new(s, std::forward<Args>(args)...);
   }
@@ -492,7 +513,7 @@ class ThrowingValue : private exceptions_internal::TrackedObject {
   static void* operator new[](size_t s, Args&&... args) noexcept(
       !exceptions_internal::ThrowingAllowed(Flags, NoThrow::kAllocation)) {
     if (exceptions_internal::ThrowingAllowed(Flags, NoThrow::kAllocation)) {
-      exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
+      exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION, true);
     }
     return ::operator new[](s, std::forward<Args>(args)...);
   }
@@ -630,10 +651,7 @@ class ThrowingAllocator : private exceptions_internal::TrackedObject {
     p->~U();
   }
 
-  size_type max_size() const
-      noexcept(!exceptions_internal::ThrowingAllowed(Flags,
-                                                     NoThrow::kNoThrow)) {
-    ReadStateAndMaybeThrow(ABSL_PRETTY_FUNCTION);
+  size_type max_size() const noexcept {
     return std::numeric_limits<difference_type>::max() / sizeof(value_type);
   }
 
@@ -720,9 +738,12 @@ T TestThrowingCtor(Args&&... args) {
 
 // Tests that performing operation Op on a T follows exception safety
 // guarantees.  By default only tests the basic guarantee. There must be a
-// function, AbslCheckInvariants(T*) which returns
-// anything convertible to bool and which makes sure the invariants of the type
-// are upheld.  This is called before any of the checkers.
+// function, AbslCheckInvariants(T*, absl::InternalAbslNamespaceFinder) which
+// returns anything convertible to bool and which makes sure the invariants of
+// the type are upheld.  This is called before any of the checkers.  The
+// InternalAbslNamespaceFinder is unused, and just helps find
+// AbslCheckInvariants for absl types which become aliases to std::types in
+// C++17.
 //
 // Parameters:
 //   * TFactory: operator() returns a unique_ptr to the type under test (T).  It
@@ -740,11 +761,13 @@ template <typename TFactory, typename FunctionFromTPtrToVoid,
 testing::AssertionResult TestExceptionSafety(TFactory factory,
                                              FunctionFromTPtrToVoid&& op,
                                              const Checkers&... checkers) {
+  struct Cleanup {
+    ~Cleanup() { UnsetCountdown(); }
+  } c;
   for (int countdown = 0;; ++countdown) {
     auto out = exceptions_internal::TestAtCountdown(factory, op, countdown,
                                                     checkers...);
     if (!out.has_value()) {
-      UnsetCountdown();
       return testing::AssertionSuccess();
     }
     if (!*out) return *out;