From 376b956214b87fbf6f5c71a8ebf6c4b1f1f10bf3 Mon Sep 17 00:00:00 2001 From: Daniel Bertalan Date: Wed, 5 Jun 2024 23:52:33 +0200 Subject: [PATCH] Tests: Stop invoking UB in `AK::NeverDestroyed`'s tests Instead of attempting a stack use-after-free by reading an out-of-scope object's data member, let's keep a flag that checks if the destructor had been called in the outer scope. Fixes #64 --- Tests/AK/TestNeverDestroyed.cpp | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/Tests/AK/TestNeverDestroyed.cpp b/Tests/AK/TestNeverDestroyed.cpp index 43ea3e65f63..d212ccaf7fd 100644 --- a/Tests/AK/TestNeverDestroyed.cpp +++ b/Tests/AK/TestNeverDestroyed.cpp @@ -44,20 +44,27 @@ TEST_CASE(should_construct_by_move) EXPECT_EQ(1, n->num_moves); } -NO_SANITIZE_ADDRESS static void should_not_destroy() -{ - Counter* c = nullptr; +struct DestructorChecker { + DestructorChecker(bool& destroyed) + : m_destroyed(destroyed) { - AK::NeverDestroyed n {}; - // note: explicit stack-use-after-scope - c = &n.get(); } - EXPECT_EQ(0, c->num_destroys); -} + + ~DestructorChecker() + { + m_destroyed = true; + } + + bool& m_destroyed; +}; TEST_CASE(should_not_destroy) { - should_not_destroy(); + bool destroyed = false; + { + AK::NeverDestroyed n(destroyed); + } + EXPECT(!destroyed); } TEST_CASE(should_provide_dereference_operator)