diff options
-rw-r--r-- | absl/base/exception_safety_testing_test.cc | 120 | ||||
-rw-r--r-- | absl/base/internal/exception_safety_testing.h | 82 | ||||
-rw-r--r-- | absl/debugging/BUILD.bazel | 32 | ||||
-rw-r--r-- | absl/debugging/CMakeLists.txt | 28 | ||||
-rw-r--r-- | absl/debugging/failure_signal_handler.cc | 351 | ||||
-rw-r--r-- | absl/debugging/failure_signal_handler.h | 103 | ||||
-rw-r--r-- | absl/debugging/failure_signal_handler_test.cc | 146 | ||||
-rw-r--r-- | absl/types/any_exception_safety_test.cc | 35 |
8 files changed, 792 insertions, 105 deletions
diff --git a/absl/base/exception_safety_testing_test.cc b/absl/base/exception_safety_testing_test.cc index 94a7e4f7..ab029e1f 100644 --- a/absl/base/exception_safety_testing_test.cc +++ b/absl/base/exception_safety_testing_test.cc @@ -41,15 +41,7 @@ void ExpectNoThrow(const F& f) { } } -class ThrowingValueTest : public ::testing::Test { - protected: - void SetUp() override { UnsetCountdown(); } - - private: - ConstructorTracker clouseau_; -}; - -TEST_F(ThrowingValueTest, Throws) { +TEST(ThrowingValueTest, Throws) { SetCountdown(); EXPECT_THROW(ThrowingValue<> bomb, TestException); @@ -60,6 +52,8 @@ TEST_F(ThrowingValueTest, Throws) { ExpectNoThrow([]() { ThrowingValue<> bomb; }); ExpectNoThrow([]() { ThrowingValue<> bomb; }); EXPECT_THROW(ThrowingValue<> bomb, TestException); + + UnsetCountdown(); } // Tests that an operation throws when the countdown is at 0, doesn't throw when @@ -67,7 +61,6 @@ TEST_F(ThrowingValueTest, Throws) { // ThrowingValue if it throws template <typename F> void TestOp(const F& f) { - UnsetCountdown(); ExpectNoThrow(f); SetCountdown(); @@ -75,7 +68,7 @@ void TestOp(const F& f) { UnsetCountdown(); } -TEST_F(ThrowingValueTest, ThrowingCtors) { +TEST(ThrowingValueTest, ThrowingCtors) { ThrowingValue<> bomb; TestOp([]() { ThrowingValue<> bomb(1); }); @@ -83,14 +76,14 @@ TEST_F(ThrowingValueTest, ThrowingCtors) { TestOp([&]() { ThrowingValue<> bomb1 = std::move(bomb); }); } -TEST_F(ThrowingValueTest, ThrowingAssignment) { +TEST(ThrowingValueTest, ThrowingAssignment) { ThrowingValue<> bomb, bomb1; TestOp([&]() { bomb = bomb1; }); TestOp([&]() { bomb = std::move(bomb1); }); } -TEST_F(ThrowingValueTest, ThrowingComparisons) { +TEST(ThrowingValueTest, ThrowingComparisons) { ThrowingValue<> bomb1, bomb2; TestOp([&]() { return bomb1 == bomb2; }); TestOp([&]() { return bomb1 != bomb2; }); @@ -100,7 +93,7 @@ TEST_F(ThrowingValueTest, ThrowingComparisons) { TestOp([&]() { return bomb1 >= bomb2; }); } -TEST_F(ThrowingValueTest, ThrowingArithmeticOps) { +TEST(ThrowingValueTest, ThrowingArithmeticOps) { ThrowingValue<> bomb1(1), bomb2(2); TestOp([&bomb1]() { +bomb1; }); @@ -118,7 +111,7 @@ TEST_F(ThrowingValueTest, ThrowingArithmeticOps) { TestOp([&]() { bomb1 >> 1; }); } -TEST_F(ThrowingValueTest, ThrowingLogicalOps) { +TEST(ThrowingValueTest, ThrowingLogicalOps) { ThrowingValue<> bomb1, bomb2; TestOp([&bomb1]() { !bomb1; }); @@ -126,7 +119,7 @@ TEST_F(ThrowingValueTest, ThrowingLogicalOps) { TestOp([&]() { bomb1 || bomb2; }); } -TEST_F(ThrowingValueTest, ThrowingBitwiseOps) { +TEST(ThrowingValueTest, ThrowingBitwiseOps) { ThrowingValue<> bomb1, bomb2; TestOp([&bomb1]() { ~bomb1; }); @@ -135,7 +128,7 @@ TEST_F(ThrowingValueTest, ThrowingBitwiseOps) { TestOp([&]() { bomb1 ^ bomb2; }); } -TEST_F(ThrowingValueTest, ThrowingCompoundAssignmentOps) { +TEST(ThrowingValueTest, ThrowingCompoundAssignmentOps) { ThrowingValue<> bomb1(1), bomb2(2); TestOp([&]() { bomb1 += bomb2; }); @@ -149,7 +142,7 @@ TEST_F(ThrowingValueTest, ThrowingCompoundAssignmentOps) { TestOp([&]() { bomb1 *= bomb2; }); } -TEST_F(ThrowingValueTest, ThrowingStreamOps) { +TEST(ThrowingValueTest, ThrowingStreamOps) { ThrowingValue<> bomb; TestOp([&]() { std::cin >> bomb; }); @@ -158,7 +151,6 @@ TEST_F(ThrowingValueTest, ThrowingStreamOps) { template <typename F> void TestAllocatingOp(const F& f) { - UnsetCountdown(); ExpectNoThrow(f); SetCountdown(); @@ -166,32 +158,34 @@ void TestAllocatingOp(const F& f) { UnsetCountdown(); } -TEST_F(ThrowingValueTest, ThrowingAllocatingOps) { +TEST(ThrowingValueTest, ThrowingAllocatingOps) { // make_unique calls unqualified operator new, so these exercise the // ThrowingValue overloads. TestAllocatingOp([]() { return absl::make_unique<ThrowingValue<>>(1); }); TestAllocatingOp([]() { return absl::make_unique<ThrowingValue<>[]>(2); }); } -TEST_F(ThrowingValueTest, NonThrowingMoveCtor) { +TEST(ThrowingValueTest, NonThrowingMoveCtor) { ThrowingValue<NoThrow::kMoveCtor> nothrow_ctor; SetCountdown(); ExpectNoThrow([¬hrow_ctor]() { ThrowingValue<NoThrow::kMoveCtor> nothrow1 = std::move(nothrow_ctor); }); + UnsetCountdown(); } -TEST_F(ThrowingValueTest, NonThrowingMoveAssign) { +TEST(ThrowingValueTest, NonThrowingMoveAssign) { ThrowingValue<NoThrow::kMoveAssign> nothrow_assign1, nothrow_assign2; SetCountdown(); ExpectNoThrow([¬hrow_assign1, ¬hrow_assign2]() { nothrow_assign1 = std::move(nothrow_assign2); }); + UnsetCountdown(); } -TEST_F(ThrowingValueTest, ThrowingSwap) { +TEST(ThrowingValueTest, ThrowingSwap) { ThrowingValue<> bomb1, bomb2; TestOp([&]() { std::swap(bomb1, bomb2); }); @@ -202,12 +196,12 @@ TEST_F(ThrowingValueTest, ThrowingSwap) { TestOp([&]() { std::swap(bomb5, bomb6); }); } -TEST_F(ThrowingValueTest, NonThrowingSwap) { +TEST(ThrowingValueTest, NonThrowingSwap) { ThrowingValue<NoThrow::kMoveAssign | NoThrow::kMoveCtor> bomb1, bomb2; ExpectNoThrow([&]() { std::swap(bomb1, bomb2); }); } -TEST_F(ThrowingValueTest, NonThrowingAllocation) { +TEST(ThrowingValueTest, NonThrowingAllocation) { ThrowingValue<NoThrow::kAllocation>* allocated; ThrowingValue<NoThrow::kAllocation>* array; @@ -221,7 +215,7 @@ TEST_F(ThrowingValueTest, NonThrowingAllocation) { }); } -TEST_F(ThrowingValueTest, NonThrowingDelete) { +TEST(ThrowingValueTest, NonThrowingDelete) { auto* allocated = new ThrowingValue<>(1); auto* array = new ThrowingValue<>[2]; @@ -229,12 +223,14 @@ TEST_F(ThrowingValueTest, NonThrowingDelete) { ExpectNoThrow([allocated]() { delete allocated; }); SetCountdown(); ExpectNoThrow([array]() { delete[] array; }); + + UnsetCountdown(); } using Storage = absl::aligned_storage_t<sizeof(ThrowingValue<>), alignof(ThrowingValue<>)>; -TEST_F(ThrowingValueTest, NonThrowingPlacementDelete) { +TEST(ThrowingValueTest, NonThrowingPlacementDelete) { constexpr int kArrayLen = 2; // We intentionally create extra space to store the tag allocated by placement // new[]. @@ -256,16 +252,19 @@ TEST_F(ThrowingValueTest, NonThrowingPlacementDelete) { for (int i = 0; i < kArrayLen; ++i) placed_array[i].~ThrowingValue<>(); ThrowingValue<>::operator delete[](placed_array, &array_buf); }); + + UnsetCountdown(); } -TEST_F(ThrowingValueTest, NonThrowingDestructor) { +TEST(ThrowingValueTest, NonThrowingDestructor) { auto* allocated = new ThrowingValue<>(); + SetCountdown(); ExpectNoThrow([allocated]() { delete allocated; }); + UnsetCountdown(); } TEST(ThrowingBoolTest, ThrowingBool) { - UnsetCountdown(); ThrowingBool t = true; // Test that it's contextually convertible to bool @@ -276,15 +275,7 @@ TEST(ThrowingBoolTest, ThrowingBool) { TestOp([&]() { (void)!t; }); } -class ThrowingAllocatorTest : public ::testing::Test { - protected: - void SetUp() override { UnsetCountdown(); } - - private: - ConstructorTracker borlu_; -}; - -TEST_F(ThrowingAllocatorTest, MemoryManagement) { +TEST(ThrowingAllocatorTest, MemoryManagement) { // Just exercise the memory management capabilities under LSan to make sure we // don't leak. ThrowingAllocator<int> int_alloc; @@ -300,7 +291,7 @@ TEST_F(ThrowingAllocatorTest, MemoryManagement) { ef_alloc.deallocate(ef_array, 2); } -TEST_F(ThrowingAllocatorTest, CallsGlobalNew) { +TEST(ThrowingAllocatorTest, CallsGlobalNew) { ThrowingAllocator<ThrowingValue<>, NoThrow::kNoThrow> nothrow_alloc; ThrowingValue<>* ptr; @@ -308,9 +299,11 @@ TEST_F(ThrowingAllocatorTest, CallsGlobalNew) { // This will only throw if ThrowingValue::new is called. ExpectNoThrow([&]() { ptr = nothrow_alloc.allocate(1); }); nothrow_alloc.deallocate(ptr, 1); + + UnsetCountdown(); } -TEST_F(ThrowingAllocatorTest, ThrowingConstructors) { +TEST(ThrowingAllocatorTest, ThrowingConstructors) { ThrowingAllocator<int> int_alloc; int* ip = nullptr; @@ -323,22 +316,27 @@ TEST_F(ThrowingAllocatorTest, ThrowingConstructors) { EXPECT_THROW(int_alloc.construct(ip, 2), TestException); EXPECT_EQ(*ip, 1); int_alloc.deallocate(ip, 1); + + UnsetCountdown(); } -TEST_F(ThrowingAllocatorTest, NonThrowingConstruction) { +TEST(ThrowingAllocatorTest, NonThrowingConstruction) { { ThrowingAllocator<int, NoThrow::kNoThrow> int_alloc; int* ip = nullptr; SetCountdown(); ExpectNoThrow([&]() { ip = int_alloc.allocate(1); }); + SetCountdown(); ExpectNoThrow([&]() { int_alloc.construct(ip, 2); }); + EXPECT_EQ(*ip, 2); int_alloc.deallocate(ip, 1); + + UnsetCountdown(); } - UnsetCountdown(); { ThrowingAllocator<int> int_alloc; int* ip = nullptr; @@ -348,37 +346,44 @@ TEST_F(ThrowingAllocatorTest, NonThrowingConstruction) { int_alloc.deallocate(ip, 1); } - UnsetCountdown(); { ThrowingAllocator<ThrowingValue<NoThrow::kIntCtor>, NoThrow::kNoThrow> ef_alloc; ThrowingValue<NoThrow::kIntCtor>* efp; + SetCountdown(); ExpectNoThrow([&]() { efp = ef_alloc.allocate(1); }); + SetCountdown(); ExpectNoThrow([&]() { ef_alloc.construct(efp, 2); }); + EXPECT_EQ(efp->Get(), 2); ef_alloc.destroy(efp); ef_alloc.deallocate(efp, 1); + + UnsetCountdown(); } - UnsetCountdown(); { ThrowingAllocator<int> a; + SetCountdown(); ExpectNoThrow([&]() { ThrowingAllocator<double> a1 = a; }); + SetCountdown(); ExpectNoThrow([&]() { ThrowingAllocator<double> a1 = std::move(a); }); + + UnsetCountdown(); } } -TEST_F(ThrowingAllocatorTest, ThrowingAllocatorConstruction) { +TEST(ThrowingAllocatorTest, ThrowingAllocatorConstruction) { ThrowingAllocator<int> a; TestOp([]() { ThrowingAllocator<int> a; }); TestOp([&]() { a.select_on_container_copy_construction(); }); } -TEST_F(ThrowingAllocatorTest, State) { +TEST(ThrowingAllocatorTest, State) { ThrowingAllocator<int> a1, a2; EXPECT_NE(a1, a2); @@ -390,13 +395,13 @@ TEST_F(ThrowingAllocatorTest, State) { EXPECT_EQ(a3, a1); } -TEST_F(ThrowingAllocatorTest, InVector) { +TEST(ThrowingAllocatorTest, InVector) { std::vector<ThrowingValue<>, ThrowingAllocator<ThrowingValue<>>> v; for (int i = 0; i < 20; ++i) v.push_back({}); for (int i = 0; i < 20; ++i) v.pop_back(); } -TEST_F(ThrowingAllocatorTest, InList) { +TEST(ThrowingAllocatorTest, InList) { std::list<ThrowingValue<>, ThrowingAllocator<ThrowingValue<>>> l; for (int i = 0; i < 20; ++i) l.push_back({}); for (int i = 0; i < 20; ++i) l.pop_back(); @@ -772,19 +777,28 @@ struct Tracked : private exceptions_internal::TrackedObject { Tracked() : TrackedObject(ABSL_PRETTY_FUNCTION) {} }; -TEST(ConstructorTrackerTest, Pass) { - ConstructorTracker javert; - Tracked t; +TEST(ConstructorTrackerTest, CreatedBefore) { + Tracked a, b, c; + exceptions_internal::ConstructorTracker ct(exceptions_internal::countdown); +} + +TEST(ConstructorTrackerTest, CreatedAfter) { + exceptions_internal::ConstructorTracker ct(exceptions_internal::countdown); + Tracked a, b, c; } -TEST(ConstructorTrackerTest, NotDestroyed) { +TEST(ConstructorTrackerTest, NotDestroyedAfter) { absl::aligned_storage_t<sizeof(Tracked), alignof(Tracked)> storage; EXPECT_NONFATAL_FAILURE( { - ConstructorTracker gadget; + exceptions_internal::ConstructorTracker ct( + exceptions_internal::countdown); new (&storage) Tracked; }, "not destroyed"); + + // Manual destruction of the Tracked instance is not required because + // ~ConstructorTracker() handles that automatically when a leak is found } TEST(ConstructorTrackerTest, DestroyedTwice) { diff --git a/absl/base/internal/exception_safety_testing.h b/absl/base/internal/exception_safety_testing.h index 48a292b3..c014fb30 100644 --- a/absl/base/internal/exception_safety_testing.h +++ b/absl/base/internal/exception_safety_testing.h @@ -37,8 +37,6 @@ namespace absl { -struct ConstructorTracker; - // A configuration enum for Throwing*. Operations whose flags are set will // throw, everything else won't. This isn't meant to be exhaustive, more flags // can always be made in the future. @@ -105,6 +103,8 @@ void MaybeThrow(absl::string_view msg, bool throw_bad_alloc = false); testing::AssertionResult FailureMessage(const TestException& e, int countdown) noexcept; +class ConstructorTracker; + class TrackedObject { public: TrackedObject(const TrackedObject&) = delete; @@ -112,26 +112,56 @@ class TrackedObject { protected: explicit TrackedObject(const char* child_ctor) { - if (!GetAllocs().emplace(this, child_ctor).second) { + if (!GetInstanceMap().emplace(this, child_ctor).second) { ADD_FAILURE() << "Object at address " << static_cast<void*>(this) << " re-constructed in ctor " << child_ctor; } } - static std::unordered_map<TrackedObject*, absl::string_view>& GetAllocs() { - static auto* m = - new std::unordered_map<TrackedObject*, absl::string_view>(); - return *m; - } - ~TrackedObject() noexcept { - if (GetAllocs().erase(this) == 0) { + if (GetInstanceMap().erase(this) == 0) { ADD_FAILURE() << "Object at address " << static_cast<void*>(this) << " destroyed improperly"; } } - friend struct ::absl::ConstructorTracker; + private: + using InstanceMap = std::unordered_map<TrackedObject*, absl::string_view>; + static InstanceMap& GetInstanceMap() { + static auto* instance_map = new InstanceMap(); + return *instance_map; + } + + friend class ConstructorTracker; +}; + +// Inspects the constructions and destructions of anything inheriting from +// TrackedObject. This allows us to safely "leak" TrackedObjects, as +// ConstructorTracker will destroy everything left over in its destructor. +class ConstructorTracker { + public: + explicit ConstructorTracker(int c) + : init_count_(c), init_instances_(TrackedObject::GetInstanceMap()) {} + ~ConstructorTracker() { + auto& cur_instances = TrackedObject::GetInstanceMap(); + for (auto it = cur_instances.begin(); it != cur_instances.end();) { + if (init_instances_.count(it->first) == 0) { + ADD_FAILURE() << "Object at address " << static_cast<void*>(it->first) + << " constructed from " << it->second + << " where the exception countdown was set to " + << init_count_ << " was not destroyed"; + // Erasing an item inside an unordered_map invalidates the existing + // iterator. A new one is returned for iteration to continue. + it = cur_instances.erase(it); + } else { + ++it; + } + } + } + + private: + int init_count_; + TrackedObject::InstanceMap init_instances_; }; template <typename Factory, typename Operation, typename Invariant> @@ -707,37 +737,21 @@ class ThrowingAllocator : private exceptions_internal::TrackedObject { template <typename T, NoThrow Throws> int ThrowingAllocator<T, Throws>::next_id_ = 0; -// Inspects the constructions and destructions of anything inheriting from -// TrackedObject. Place this as a member variable in a test fixture to ensure -// that every ThrowingValue was constructed and destroyed correctly. This also -// allows us to safely "leak" TrackedObjects, as ConstructorTracker will destroy -// everything left over in its destructor. -struct ConstructorTracker { - ConstructorTracker() = default; - ~ConstructorTracker() { - auto& allocs = exceptions_internal::TrackedObject::GetAllocs(); - for (const auto& kv : allocs) { - ADD_FAILURE() << "Object at address " << static_cast<void*>(kv.first) - << " constructed from " << kv.second << " not destroyed"; - } - allocs.clear(); - } -}; - // Tests for resource leaks by attempting to construct a T using args repeatedly // until successful, using the countdown method. Side effects can then be -// tested for resource leaks. If a ConstructorTracker is present in the test -// fixture, then this will also test that memory resources are not leaked as -// long as T allocates TrackedObjects. +// tested for resource leaks. template <typename T, typename... Args> -T TestThrowingCtor(Args&&... args) { +void TestThrowingCtor(Args&&... args) { struct Cleanup { ~Cleanup() { exceptions_internal::UnsetCountdown(); } } c; for (int count = 0;; ++count) { + exceptions_internal::ConstructorTracker ct(count); exceptions_internal::SetCountdown(count); try { - return T(std::forward<Args>(args)...); + T temp(std::forward<Args>(args)...); + static_cast<void>(temp); + break; } catch (const exceptions_internal::TestException&) { } } @@ -934,6 +948,8 @@ class ExceptionSafetyTester { // Starting from 0 and counting upwards until one of the exit conditions is // hit... for (int count = 0;; ++count) { + exceptions_internal::ConstructorTracker ct(count); + // Run the full exception safety test algorithm for the current countdown auto reduced_res = TestAllInvariantsAtCountdown(factory_, selected_operation, count, diff --git a/absl/debugging/BUILD.bazel b/absl/debugging/BUILD.bazel index 556bb383..e1e7fced 100644 --- a/absl/debugging/BUILD.bazel +++ b/absl/debugging/BUILD.bazel @@ -95,6 +95,38 @@ cc_library( ) cc_library( + name = "failure_signal_handler", + srcs = ["failure_signal_handler.cc"], + hdrs = ["failure_signal_handler.h"], + copts = ABSL_DEFAULT_COPTS, + deps = [ + ":examine_stack", + ":stacktrace", + "//absl/base", + "//absl/base:config", + "//absl/base:core_headers", + ], +) + +cc_test( + name = "failure_signal_handler_test", + srcs = ["failure_signal_handler_test.cc"], + copts = ABSL_TEST_COPTS, + linkopts = select({ + "//absl:windows": [], + "//conditions:default": ["-pthread"], + }), + deps = [ + ":failure_signal_handler", + ":stacktrace", + ":symbolize", + "//absl/base", + "//absl/strings", + "@com_google_googletest//:gtest", + ], +) + +cc_library( name = "debugging_internal", srcs = [ "internal/address_is_readable.cc", diff --git a/absl/debugging/CMakeLists.txt b/absl/debugging/CMakeLists.txt index 456d0727..03a0a617 100644 --- a/absl/debugging/CMakeLists.txt +++ b/absl/debugging/CMakeLists.txt @@ -15,6 +15,7 @@ # list(APPEND DEBUGGING_PUBLIC_HEADERS + "failure_signal_handler.h" "leak_check.h" "stacktrace.h" "symbolize.h" @@ -51,6 +52,11 @@ list(APPEND SYMBOLIZE_SRC ${DEBUGGING_INTERNAL_HEADERS} ) +list(APPEND FAILURE_SIGNAL_HANDLER_SRC + "failure_signal_handler.cc" + ${DEBUGGING_PUBLIC_HEADERS} +) + list(APPEND EXAMINE_STACK_SRC "internal/examine_stack.cc" ${DEBUGGING_PUBLIC_HEADERS} @@ -75,6 +81,17 @@ absl_library( symbolize ) +absl_library( + TARGET + absl_failure_signal_handler + SOURCES + ${FAILURE_SIGNAL_HANDLER_SRC} + PUBLIC_LIBRARIES + absl_base absl_synchronization + EXPORT_NAME + failure_signal_handler +) + # Internal-only. Projects external to Abseil should not depend # directly on this library. absl_library( @@ -163,6 +180,17 @@ absl_test( absl_symbolize absl_stack_consumption ) +list(APPEND FAILURE_SIGNAL_HANDLER_TEST_SRC "failure_signal_handler_test.cc") + +absl_test( + TARGET + failure_signal_handler_test + SOURCES + ${FAILURE_SIGNAL_HANDLER_TEST_SRC} + PUBLIC_LIBRARIES + absl_examine_stack absl_stacktrace absl_symbolize +) + # test leak_check_test list(APPEND LEAK_CHECK_TEST_SRC "leak_check_test.cc") diff --git a/absl/debugging/failure_signal_handler.cc b/absl/debugging/failure_signal_handler.cc new file mode 100644 index 00000000..597ad144 --- /dev/null +++ b/absl/debugging/failure_signal_handler.cc @@ -0,0 +1,351 @@ +// +// Copyright 2018 The Abseil Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#include "absl/debugging/failure_signal_handler.h" + +#include "absl/base/config.h" + +#ifdef _WIN32 +#include <windows.h> +#else +#include <unistd.h> +#endif + +#ifdef ABSL_HAVE_MMAP +#include <sys/mman.h> +#endif + +#include <algorithm> +#include <atomic> +#include <cerrno> +#include <csignal> +#include <cstring> +#include <ctime> + +#include "absl/base/attributes.h" +#include "absl/base/internal/raw_logging.h" +#include "absl/base/internal/sysinfo.h" +#include "absl/debugging/internal/examine_stack.h" +#include "absl/debugging/stacktrace.h" + +#ifndef _WIN32 +#define ABSL_HAVE_SIGACTION +#endif + +namespace absl { + +ABSL_CONST_INIT static FailureSignalHandlerOptions fsh_options; + +// Resets the signal handler for signo to the default action for that +// signal, then raises the signal. +static void RaiseToDefaultHandler(int signo) { + signal(signo, SIG_DFL); + raise(signo); +} + +struct FailureSignalData { + const int signo; + const char* const as_string; +#ifdef ABSL_HAVE_SIGACTION + struct sigaction previous_action; + // StructSigaction is used to silence -Wmissing-field-initializers. + using StructSigaction = struct sigaction; + #define FSD_PREVIOUS_INIT FailureSignalData::StructSigaction() +#else + void (*previous_handler)(int); + #define FSD_PREVIOUS_INIT SIG_DFL +#endif +}; + +ABSL_CONST_INIT static FailureSignalData failure_signal_data[] = { + {SIGSEGV, "SIGSEGV", FSD_PREVIOUS_INIT}, + {SIGILL, "SIGILL", FSD_PREVIOUS_INIT}, + {SIGFPE, "SIGFPE", FSD_PREVIOUS_INIT}, + {SIGABRT, "SIGABRT", FSD_PREVIOUS_INIT}, + {SIGTERM, "SIGTERM", FSD_PREVIOUS_INIT}, +#ifndef _WIN32 + {SIGBUS, "SIGBUS", FSD_PREVIOUS_INIT}, + {SIGTRAP, "SIGTRAP", FSD_PREVIOUS_INIT}, +#endif +}; + +#undef FSD_PREVIOUS_INIT + +static void RaiseToPreviousHandler(int signo) { + // Search for the previous handler. + for (const auto& it : failure_signal_data) { + if (it.signo == signo) { +#ifdef ABSL_HAVE_SIGACTION + sigaction(signo, &it.previous_action, nullptr); +#else + signal(signo, it.previous_handler); +#endif + raise(signo); + return; + } + } + + // Not found, use the default handler. + RaiseToDefaultHandler(signo); +} + +namespace debugging_internal { + +const char* FailureSignalToString(int signo) { + for (const auto& it : failure_signal_data) { + if (it.signo == signo) { + return it.as_string; + } + } + return ""; +} + +} // namespace debugging_internal + +#ifndef _WIN32 + +static bool SetupAlternateStackOnce() { + const size_t page_mask = getpagesize() - 1; + size_t stack_size = (std::max(SIGSTKSZ, 65536) + page_mask) & ~page_mask; +#if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \ + defined(THREAD_SANITIZER) + // Account for sanitizer instrumentation requiring additional stack space. + stack_size *= 5; +#endif + + stack_t sigstk; + memset(&sigstk, 0, sizeof(sigstk)); + sigstk.ss_size = stack_size; + +#ifdef ABSL_HAVE_MMAP +#ifndef MAP_STACK +#define MAP_STACK 0 +#endif + sigstk.ss_sp = mmap(nullptr, sigstk.ss_size, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0); + if (sigstk.ss_sp == MAP_FAILED) { + ABSL_RAW_LOG(FATAL, "mmap() for alternate signal stack failed"); + } +#else + sigstk.ss_sp = malloc(sigstk.ss_size); + if (sigstk.ss_sp == nullptr) { + ABSL_RAW_LOG(FATAL, "malloc() for alternate signal stack failed"); + } +#endif + + if (sigaltstack(&sigstk, nullptr) != 0) { + ABSL_RAW_LOG(FATAL, "sigaltstack() failed with errno=%d", errno); + } + return true; +} + +#endif + +// Sets up an alternate stack for signal handlers once. +// Returns the appropriate flag for sig_action.sa_flags +// if the system supports using an alternate stack. +static int MaybeSetupAlternateStack() { +#ifndef _WIN32 + ABSL_ATTRIBUTE_UNUSED static const bool kOnce = SetupAlternateStackOnce(); + return SA_ONSTACK; +#endif + return 0; +} + +#ifdef ABSL_HAVE_SIGACTION + +static void InstallOneFailureHandler(FailureSignalData* data, + void (*handler)(int, siginfo_t*, void*)) { + struct sigaction act; + memset(&act, 0, sizeof(act)); + sigemptyset(&act.sa_mask); + act.sa_flags |= SA_SIGINFO; + // SA_NODEFER is required to handle SIGABRT from + // ImmediateAbortSignalHandler(). + act.sa_flags |= SA_NODEFER; + if (fsh_options.use_alternate_stack) { + act.sa_flags |= MaybeSetupAlternateStack(); + } + act.sa_sigaction = handler; + ABSL_RAW_CHECK(sigaction(data->signo, &act, &data->previous_action) == 0, + "sigaction() failed"); +} + +#else + +static void InstallOneFailureHandler(FailureSignalData* data, + void (*handler)(int)) { + data->previous_handler = signal(data->signo, handler); + ABSL_RAW_CHECK(data->previous_handler != SIG_ERR, "signal() failed"); +} + +#endif + +static void WriteToStderr(const char* data) { + int old_errno = errno; + absl::raw_logging_internal::SafeWriteToStderr(data, strlen(data)); + errno = old_errno; +} + +static void WriteSignalMessage(int signo, void (*writerfn)(const char*)) { + char buf[64]; + const char* const signal_string = + debugging_internal::FailureSignalToString(signo); + if (signal_string != nullptr && signal_string[0] != '\0') { + snprintf(buf, sizeof(buf), "*** %s received at time=%ld ***\n", + signal_string, + static_cast<long>(time(nullptr))); // NOLINT(runtime/int) + } else { + snprintf(buf, sizeof(buf), "*** Signal %d received at time=%ld ***\n", + signo, static_cast<long>(time(nullptr))); // NOLINT(runtime/int) + } + writerfn(buf); +} + +// `void*` might not be big enough to store `void(*)(const char*)`. +struct WriterFnStruct { + void (*writerfn)(const char*); +}; + +// Many of the absl::debugging_internal::Dump* functions in +// examine_stack.h take a writer function pointer that has a void* arg +// for historical reasons. failure_signal_handler_writer only takes a +// data pointer. This function converts between these types. +static void WriterFnWrapper(const char* data, void* arg) { + static_cast<WriterFnStruct*>(arg)->writerfn(data); +} + +// Convenient wrapper around DumpPCAndFrameSizesAndStackTrace() for signal +// handlers. "noinline" so that GetStackFrames() skips the top-most stack +// frame for this function. +ABSL_ATTRIBUTE_NOINLINE static void WriteStackTrace( + void* ucontext, bool symbolize_stacktrace, + void (*writerfn)(const char*, void*), void* writerfn_arg) { + constexpr int kNumStackFrames = 32; + void* stack[kNumStackFrames]; + int frame_sizes[kNumStackFrames]; + int min_dropped_frames; + int depth = absl::GetStackFramesWithContext( + stack, frame_sizes, kNumStackFrames, + 1, // Do not include this function in stack trace. + ucontext, &min_dropped_frames); + absl::debugging_internal::DumpPCAndFrameSizesAndStackTrace( + absl::debugging_internal::GetProgramCounter(ucontext), stack, frame_sizes, + depth, min_dropped_frames, symbolize_stacktrace, writerfn, writerfn_arg); +} + +// Called by FailureSignalHandler() to write the failure info. It is +// called once with writerfn set to WriteToStderr() and then possibly +// with writerfn set to the user provided function. +static void WriteFailureInfo(int signo, void* ucontext, + void (*writerfn)(const char*)) { + WriterFnStruct writerfn_struct{writerfn}; + WriteSignalMessage(signo, writerfn); + WriteStackTrace(ucontext, fsh_options.symbolize_stacktrace, WriterFnWrapper, + &writerfn_struct); +} + +// absl::SleepFor() can't be used here since AbslInternalSleepFor() +// may be overridden to do something that isn't async-signal-safe on +// some platforms. +static void PortableSleepForSeconds(int seconds) { +#ifdef _WIN32 + Sleep(seconds * 1000); +#else + struct timespec sleep_time; + sleep_time.tv_sec = seconds; + sleep_time.tv_nsec = 0; + while (nanosleep(&sleep_time, &sleep_time) != 0 && errno == EINTR) {} +#endif +} + +#ifdef ABSL_HAVE_ALARM +// FailureSignalHandler() installs this as a signal handler for +// SIGALRM, then sets an alarm to be delivered to the program after a +// set amount of time. If FailureSignalHandler() hangs for more than +// the alarm timeout, ImmediateAbortSignalHandler() will abort the +// program. +static void ImmediateAbortSignalHandler(int) { + RaiseToDefaultHandler(SIGABRT); +} +#endif + +// absl::base_internal::GetTID() returns pid_t on most platforms, but +// returns absl::base_internal::pid_t on Windows. +using GetTidType = decltype(absl::base_internal::GetTID()); +ABSL_CONST_INIT static std::atomic<GetTidType> failed_tid(0); + +#ifndef ABSL_HAVE_SIGACTION +static void FailureSignalHandler(int signo) { + void* ucontext = nullptr; +#else +static void FailureSignalHandler(int signo, siginfo_t*, + void* ucontext) { +#endif + + const GetTidType this_tid = absl::base_internal::GetTID(); + GetTidType previous_failed_tid = 0; + if (!failed_tid.compare_exchange_strong( + previous_failed_tid, static_cast<intptr_t>(this_tid), + std::memory_order_acq_rel, std::memory_order_relaxed)) { + ABSL_RAW_LOG( + ERROR, + "Signal %d raised at PC=%p while already in FailureSignalHandler()", + signo, absl::debugging_internal::GetProgramCounter(ucontext)); + if (this_tid != previous_failed_tid) { + // Another thread is already in FailureSignalHandler(), so wait + // a bit for it to finish. If the other thread doesn't kill us, + // we do so after sleeping. + PortableSleepForSeconds(3); + RaiseToDefaultHandler(signo); + // The recursively raised signal may be blocked until we return. + return; + } + } + +#ifdef ABSL_HAVE_ALARM + // Set an alarm to abort the program in case this code hangs or deadlocks. + if (fsh_options.alarm_on_failure_secs > 0) { + alarm(0); // Cancel any existing alarms. + signal(SIGALRM, ImmediateAbortSignalHandler); + alarm(fsh_options.alarm_on_failure_secs); + } +#endif + + // First write to stderr. + WriteFailureInfo(signo, ucontext, WriteToStderr); + + // Riskier code (because it is less likely to be async-signal-safe) + // goes after this point. + if (fsh_options.writerfn != nullptr) { + WriteFailureInfo(signo, ucontext, fsh_options.writerfn); + } + + if (fsh_options.call_previous_handler) { + RaiseToPreviousHandler(signo); + } else { + RaiseToDefaultHandler(signo); + } +} + +void InstallFailureSignalHandler(const FailureSignalHandlerOptions& options) { + fsh_options = options; + for (auto& it : failure_signal_data) { + InstallOneFailureHandler(&it, FailureSignalHandler); + } +} + +} // namespace absl diff --git a/absl/debugging/failure_signal_handler.h b/absl/debugging/failure_signal_handler.h new file mode 100644 index 00000000..17522f00 --- /dev/null +++ b/absl/debugging/failure_signal_handler.h @@ -0,0 +1,103 @@ +// +// Copyright 2018 The Abseil Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +// This module allows the programmer to install a signal handler that +// dumps useful debugging information (like a stacktrace) on program +// failure. To use this functionality, call +// absl::InstallFailureSignalHandler() very early in your program, +// usually in the first few lines of main(): +// +// int main(int argc, char** argv) { +// absl::InitializeSymbolizer(argv[0]); +// absl::FailureSignalHandlerOptions options; +// absl::InstallFailureSignalHandler(options); +// DoSomethingInteresting(); +// return 0; +// } + +#ifndef ABSL_DEBUGGING_FAILURE_SIGNAL_HANDLER_H_ +#define ABSL_DEBUGGING_FAILURE_SIGNAL_HANDLER_H_ + +namespace absl { + +// Options struct for absl::InstallFailureSignalHandler(). +struct FailureSignalHandlerOptions { + // If true, try to symbolize the stacktrace emitted on failure. + bool symbolize_stacktrace = true; + + // If true, try to run signal handlers on an alternate stack (if + // supported on the given platform). This is useful in the case + // where the program crashes due to a stack overflow. By running on + // a alternate stack, the signal handler might be able to run even + // when the normal stack space has been exausted. The downside of + // using an alternate stack is that extra memory for the alternate + // stack needs to be pre-allocated. + bool use_alternate_stack = true; + + // If positive, FailureSignalHandler() sets an alarm to be delivered + // to the program after this many seconds, which will immediately + // abort the program. This is useful in the potential case where + // FailureSignalHandler() itself is hung or deadlocked. + int alarm_on_failure_secs = 3; + + // If false, after absl::FailureSignalHandler() runs, the signal is + // raised to the default handler for that signal (which normally + // terminates the program). + // + // If true, after absl::FailureSignalHandler() runs, it will call + // the previously registered signal handler for the signal that was + // received (if one was registered). This can be used to chain + // signal handlers. + // + // IMPORTANT: If true, the chained fatal signal handlers must not + // try to recover from the fatal signal. Instead, they should + // terminate the program via some mechanism, like raising the + // default handler for the signal, or by calling _exit(). + // absl::FailureSignalHandler() may put parts of the Abseil + // library into a state that cannot be recovered from. + bool call_previous_handler = false; + + // If not null, this function may be called with a std::string argument + // containing failure data. This function is used as a hook to write + // the failure data to a secondary location, for instance, to a log + // file. This function may also be called with a null data + // argument. This is a hint that this is a good time to flush any + // buffered data before the program may be terminated. Consider + // flushing any buffered data in all calls to this function. + // + // Since this function runs in a signal handler, it should be + // async-signal-safe if possible. + // See http://man7.org/linux/man-pages/man7/signal-safety.7.html + void (*writerfn)(const char*) = nullptr; +}; + +// Installs a signal handler for the common failure signals SIGSEGV, +// SIGILL, SIGFPE, SIGABRT, SIGTERM, SIGBUG, and SIGTRAP (if they +// exist on the given platform). The signal handler dumps program +// failure data in a unspecified format to stderr. The data dumped by +// the signal handler includes information that may be useful in +// debugging the failure. This may include the program counter, a +// stacktrace, and register information on some systems. Do not rely +// on the exact format of the output; it is subject to change. +void InstallFailureSignalHandler(const FailureSignalHandlerOptions& options); + +namespace debugging_internal { +const char* FailureSignalToString(int signo); +} // namespace debugging_internal + +} // namespace absl + +#endif // ABSL_DEBUGGING_FAILURE_SIGNAL_HANDLER_H_ diff --git a/absl/debugging/failure_signal_handler_test.cc b/absl/debugging/failure_signal_handler_test.cc new file mode 100644 index 00000000..33170dab --- /dev/null +++ b/absl/debugging/failure_signal_handler_test.cc @@ -0,0 +1,146 @@ +// +// Copyright 2018 The Abseil Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#include "absl/debugging/failure_signal_handler.h" + +#include <csignal> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <fstream> + +#include "gtest/gtest.h" +#include "absl/base/internal/raw_logging.h" +#include "absl/debugging/stacktrace.h" +#include "absl/debugging/symbolize.h" +#include "absl/strings/match.h" +#include "absl/strings/str_cat.h" + +namespace { + +#if GTEST_HAS_DEATH_TEST + +// For the parameterized death tests. GetParam() returns the signal number. +using FailureSignalHandlerDeathTest = ::testing::TestWithParam<int>; + +// This function runs in a fork()ed process on most systems. +void InstallHandlerAndRaise(int signo) { + absl::InstallFailureSignalHandler(absl::FailureSignalHandlerOptions()); + raise(signo); +} + +TEST_P(FailureSignalHandlerDeathTest, AbslFailureSignal) { + const int signo = GetParam(); + std::string exit_regex = absl::StrCat( + "\\*\\*\\* ", absl::debugging_internal::FailureSignalToString(signo), + " received at time="); +#ifndef _WIN32 + EXPECT_EXIT(InstallHandlerAndRaise(signo), testing::KilledBySignal(signo), + exit_regex); +#else + // Windows doesn't have testing::KilledBySignal(). + EXPECT_DEATH(InstallHandlerAndRaise(signo), exit_regex); +#endif +} + +ABSL_CONST_INIT FILE* error_file = nullptr; + +void WriteToErrorFile(const char* msg) { + if (msg != nullptr) { + ABSL_RAW_CHECK(fwrite(msg, strlen(msg), 1, error_file) == 1, + "fwrite() failed"); + } + ABSL_RAW_CHECK(fflush(error_file) == 0, "fflush() failed"); +} + +std::string GetTmpDir() { + // TEST_TMPDIR is set by Bazel. Try the others when not running under Bazel. + static const char* const kTmpEnvVars[] = {"TEST_TMPDIR", "TMPDIR", "TEMP", + "TEMPDIR", "TMP"}; + for (const char* const var : kTmpEnvVars) { + const char* tmp_dir = std::getenv(var); + if (tmp_dir != nullptr) { + return tmp_dir; + } + } + + // Try something reasonable. + return "/tmp"; +} + +// This function runs in a fork()ed process on most systems. +void InstallHandlerWithWriteToFileAndRaise(const char* file, int signo) { + error_file = fopen(file, "w"); + ABSL_RAW_CHECK(error_file != nullptr, "Failed create error_file"); + absl::FailureSignalHandlerOptions options; + options.writerfn = WriteToErrorFile; + absl::InstallFailureSignalHandler(options); + raise(signo); +} + +TEST_P(FailureSignalHandlerDeathTest, AbslFatalSignalsWithWriterFn) { + const int signo = GetParam(); + std::string tmp_dir = GetTmpDir(); + std::string file = absl::StrCat(tmp_dir, "/signo_", signo); + + std::string exit_regex = absl::StrCat( + "\\*\\*\\* ", absl::debugging_internal::FailureSignalToString(signo), + " received at time="); +#ifndef _WIN32 + EXPECT_EXIT(InstallHandlerWithWriteToFileAndRaise(file.c_str(), signo), + testing::KilledBySignal(signo), exit_regex); +#else + // Windows doesn't have testing::KilledBySignal(). + EXPECT_DEATH(InstallHandlerWithWriteToFileAndRaise(file.c_str(), signo), + exit_regex); +#endif + + // Open the file in this process and check its contents. + std::fstream error_output(file); + ASSERT_TRUE(error_output.is_open()) << file; + std::string error_line; + std::getline(error_output, error_line); + EXPECT_TRUE(absl::StartsWith( + error_line, + absl::StrCat("*** ", + absl::debugging_internal::FailureSignalToString(signo), + " received at "))); + + if (absl::debugging_internal::StackTraceWorksForTest()) { + std::getline(error_output, error_line); + EXPECT_TRUE(absl::StartsWith(error_line, "PC: ")); + } +} + +constexpr int kFailureSignals[] = { + SIGSEGV, SIGILL, SIGFPE, SIGABRT, SIGTERM, +#ifndef _WIN32 + SIGBUS, SIGTRAP, +#endif +}; + +INSTANTIATE_TEST_CASE_P(AbslDeathTest, FailureSignalHandlerDeathTest, + ::testing::ValuesIn(kFailureSignals)); + +#endif // GTEST_HAS_DEATH_TEST + +} // namespace + +int main(int argc, char** argv) { + absl::InitializeSymbolizer(argv[0]); + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/absl/types/any_exception_safety_test.cc b/absl/types/any_exception_safety_test.cc index 82c176b5..7a72e726 100644 --- a/absl/types/any_exception_safety_test.cc +++ b/absl/types/any_exception_safety_test.cc @@ -30,11 +30,6 @@ using ThrowingThrowerVec = std::vector<Thrower, ThrowingAlloc>; namespace { -class AnyExceptionSafety : public ::testing::Test { - private: - absl::ConstructorTracker inspector_; -}; - testing::AssertionResult AnyInvariants(absl::any* a) { using testing::AssertionFailure; using testing::AssertionSuccess; @@ -84,22 +79,24 @@ testing::AssertionResult AnyIsEmpty(absl::any* a) { << absl::any_cast<Thrower>(*a).Get(); } -TEST_F(AnyExceptionSafety, Ctors) { +TEST(AnyExceptionSafety, Ctors) { Thrower val(1); - auto with_val = absl::TestThrowingCtor<absl::any>(val); - auto copy = absl::TestThrowingCtor<absl::any>(with_val); - auto in_place = - absl::TestThrowingCtor<absl::any>(absl::in_place_type_t<Thrower>(), 1); - auto in_place_list = absl::TestThrowingCtor<absl::any>( - absl::in_place_type_t<ThrowerVec>(), ThrowerList{val}); - auto in_place_list_again = - absl::TestThrowingCtor<absl::any, - absl::in_place_type_t<ThrowingThrowerVec>, - ThrowerList, ThrowingAlloc>( - absl::in_place_type_t<ThrowingThrowerVec>(), {val}, ThrowingAlloc()); + absl::TestThrowingCtor<absl::any>(val); + + Thrower copy(val); + absl::TestThrowingCtor<absl::any>(copy); + + absl::TestThrowingCtor<absl::any>(absl::in_place_type_t<Thrower>(), 1); + + absl::TestThrowingCtor<absl::any>(absl::in_place_type_t<ThrowerVec>(), + ThrowerList{val}); + + absl::TestThrowingCtor<absl::any, absl::in_place_type_t<ThrowingThrowerVec>, + ThrowerList, ThrowingAlloc>( + absl::in_place_type_t<ThrowingThrowerVec>(), {val}, ThrowingAlloc()); } -TEST_F(AnyExceptionSafety, Assignment) { +TEST(AnyExceptionSafety, Assignment) { auto original = absl::any(absl::in_place_type_t<Thrower>(), 1, absl::no_throw_ctor); auto any_is_strong = [original](absl::any* ap) { @@ -139,7 +136,7 @@ TEST_F(AnyExceptionSafety, Assignment) { } // libstdc++ std::any fails this test #if !defined(ABSL_HAVE_STD_ANY) -TEST_F(AnyExceptionSafety, Emplace) { +TEST(AnyExceptionSafety, Emplace) { auto initial_val = absl::any{absl::in_place_type_t<Thrower>(), 1, absl::no_throw_ctor}; auto one_tester = absl::MakeExceptionSafetyTester() |