diff --git a/absl/base/exception_safety_testing_test.cc b/absl/base/exception_safety_testing_test.cc index 94a7e4f74..ab029e1f0 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 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 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>(1); }); TestAllocatingOp([]() { return absl::make_unique[]>(2); }); } -TEST_F(ThrowingValueTest, NonThrowingMoveCtor) { +TEST(ThrowingValueTest, NonThrowingMoveCtor) { ThrowingValue nothrow_ctor; SetCountdown(); ExpectNoThrow([¬hrow_ctor]() { ThrowingValue nothrow1 = std::move(nothrow_ctor); }); + UnsetCountdown(); } -TEST_F(ThrowingValueTest, NonThrowingMoveAssign) { +TEST(ThrowingValueTest, NonThrowingMoveAssign) { ThrowingValue 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 bomb1, bomb2; ExpectNoThrow([&]() { std::swap(bomb1, bomb2); }); } -TEST_F(ThrowingValueTest, NonThrowingAllocation) { +TEST(ThrowingValueTest, NonThrowingAllocation) { ThrowingValue* allocated; ThrowingValue* 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), 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_alloc; @@ -300,7 +291,7 @@ TEST_F(ThrowingAllocatorTest, MemoryManagement) { ef_alloc.deallocate(ef_array, 2); } -TEST_F(ThrowingAllocatorTest, CallsGlobalNew) { +TEST(ThrowingAllocatorTest, CallsGlobalNew) { ThrowingAllocator, 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_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_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_alloc; int* ip = nullptr; @@ -348,37 +346,44 @@ TEST_F(ThrowingAllocatorTest, NonThrowingConstruction) { int_alloc.deallocate(ip, 1); } - UnsetCountdown(); { ThrowingAllocator, NoThrow::kNoThrow> ef_alloc; ThrowingValue* 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 a; + SetCountdown(); ExpectNoThrow([&]() { ThrowingAllocator a1 = a; }); + SetCountdown(); ExpectNoThrow([&]() { ThrowingAllocator a1 = std::move(a); }); + + UnsetCountdown(); } } -TEST_F(ThrowingAllocatorTest, ThrowingAllocatorConstruction) { +TEST(ThrowingAllocatorTest, ThrowingAllocatorConstruction) { ThrowingAllocator a; TestOp([]() { ThrowingAllocator a; }); TestOp([&]() { a.select_on_container_copy_construction(); }); } -TEST_F(ThrowingAllocatorTest, State) { +TEST(ThrowingAllocatorTest, State) { ThrowingAllocator 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, ThrowingAllocator>> 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, ThrowingAllocator>> 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, NotDestroyed) { +TEST(ConstructorTrackerTest, CreatedAfter) { + exceptions_internal::ConstructorTracker ct(exceptions_internal::countdown); + Tracked a, b, c; +} + +TEST(ConstructorTrackerTest, NotDestroyedAfter) { absl::aligned_storage_t 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 48a292b3e..c014fb30f 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(this) << " re-constructed in ctor " << child_ctor; } } - static std::unordered_map& GetAllocs() { - static auto* m = - new std::unordered_map(); - return *m; - } - ~TrackedObject() noexcept { - if (GetAllocs().erase(this) == 0) { + if (GetInstanceMap().erase(this) == 0) { ADD_FAILURE() << "Object at address " << static_cast(this) << " destroyed improperly"; } } - friend struct ::absl::ConstructorTracker; + private: + using InstanceMap = std::unordered_map; + 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(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 @@ -707,37 +737,21 @@ class ThrowingAllocator : private exceptions_internal::TrackedObject { template int ThrowingAllocator::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(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 -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)...); + T temp(std::forward(args)...); + static_cast(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 556bb3839..e1e7fced6 100644 --- a/absl/debugging/BUILD.bazel +++ b/absl/debugging/BUILD.bazel @@ -94,6 +94,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 = [ diff --git a/absl/debugging/CMakeLists.txt b/absl/debugging/CMakeLists.txt index 456d07271..03a0a617e 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 000000000..597ad1445 --- /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 +#else +#include +#endif + +#ifdef ABSL_HAVE_MMAP +#include +#endif + +#include +#include +#include +#include +#include +#include + +#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(time(nullptr))); // NOLINT(runtime/int) + } else { + snprintf(buf, sizeof(buf), "*** Signal %d received at time=%ld ***\n", + signo, static_cast(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(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 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(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 000000000..17522f00b --- /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 000000000..33170dab1 --- /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 +#include +#include +#include +#include + +#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; + +// 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 82c176b51..7a72e7263 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; 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(*a).Get(); } -TEST_F(AnyExceptionSafety, Ctors) { +TEST(AnyExceptionSafety, Ctors) { Thrower val(1); - auto with_val = absl::TestThrowingCtor(val); - auto copy = absl::TestThrowingCtor(with_val); - auto in_place = - absl::TestThrowingCtor(absl::in_place_type_t(), 1); - auto in_place_list = absl::TestThrowingCtor( - absl::in_place_type_t(), ThrowerList{val}); - auto in_place_list_again = - absl::TestThrowingCtor, - ThrowerList, ThrowingAlloc>( - absl::in_place_type_t(), {val}, ThrowingAlloc()); + absl::TestThrowingCtor(val); + + Thrower copy(val); + absl::TestThrowingCtor(copy); + + absl::TestThrowingCtor(absl::in_place_type_t(), 1); + + absl::TestThrowingCtor(absl::in_place_type_t(), + ThrowerList{val}); + + absl::TestThrowingCtor, + ThrowerList, ThrowingAlloc>( + absl::in_place_type_t(), {val}, ThrowingAlloc()); } -TEST_F(AnyExceptionSafety, Assignment) { +TEST(AnyExceptionSafety, Assignment) { auto original = absl::any(absl::in_place_type_t(), 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(), 1, absl::no_throw_ctor}; auto one_tester = absl::MakeExceptionSafetyTester()