From 15538f7e3f8fdafb13b99554a8726850caeef937 Mon Sep 17 00:00:00 2001 From: Doyle Date: Tue, 19 May 2020 18:45:32 +1000 Subject: ByteSlice: Fix persisting ptr to std::moved SSO buffer The Bug: 1. Construct `byte_slice.portion_` with `epee::span(buffer)` which copies a pointer to the SSO buffer to `byte_slice.portion_` 2. It constructs `byte_slice.storage_` with `std::move(buffer)` (normally this swap pointers, but SSO means a memcpy and clear on the original SSO buffer) 3. `slice.data()` returns a pointer from `slice.portion_` that points to the original SSO cleared buffer, `slice.storage_` has the actual string. --- tests/unit_tests/epee_utils.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'tests/unit_tests/epee_utils.cpp') diff --git a/tests/unit_tests/epee_utils.cpp b/tests/unit_tests/epee_utils.cpp index 2e93f9e67..8af8f360b 100644 --- a/tests/unit_tests/epee_utils.cpp +++ b/tests/unit_tests/epee_utils.cpp @@ -387,6 +387,29 @@ TEST(ByteSlice, Construction) EXPECT_FALSE(std::is_copy_assignable()); } +TEST(ByteSlice, DataReturnedMatches) +{ + for (int i = 64; i > 0; i--) + { + std::string sso_string(i, 'a'); + std::string original = sso_string; + epee::byte_slice slice{std::move(sso_string)}; + + EXPECT_EQ(slice.size(), original.size()); + EXPECT_EQ(memcmp(slice.data(), original.data(), original.size()), 0); + } + + for (int i = 64; i > 0; i--) + { + std::vector sso_vector(i, 'a'); + std::vector original = sso_vector; + epee::byte_slice slice{std::move(sso_vector)}; + + EXPECT_EQ(slice.size(), original.size()); + EXPECT_EQ(memcmp(slice.data(), original.data(), original.size()), 0); + } +} + TEST(ByteSlice, NoExcept) { EXPECT_TRUE(std::is_nothrow_default_constructible()); -- cgit v1.2.3