From d0e92601011b65e7562d5d9ba464e2a2f848172e Mon Sep 17 00:00:00 2001 From: Dan Wang Date: Fri, 6 Sep 2024 11:04:54 +0800 Subject: [PATCH] fix(blob): allow `blob` object to be initialized with null-pointer char array whose length must be zero (#2110) Fix https://github.com/apache/incubator-pegasus/issues/2109. Null-pointer char array with zero length is allowed to be used to initialize `blob` object. Use `DCHECK` instead to check if the pointer is valid while initializing `blob` object. --- src/utils/blob.h | 4 +++- src/utils/test/blob_test.cpp | 21 ++++++++++++++++++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/utils/blob.h b/src/utils/blob.h index 62bc0a8a51..07675e9431 100644 --- a/src/utils/blob.h +++ b/src/utils/blob.h @@ -109,7 +109,9 @@ class blob /// NOTE: this operation is not efficient since it involves a memory copy. [[nodiscard]] static blob create_from_bytes(const char *s, size_t len) { - CHECK_NOTNULL(s, "null source pointer would lead to undefined behaviour"); + DCHECK(s != nullptr || len == 0, + "null source pointer with non-zero length would lead to " + "undefined behaviour"); std::shared_ptr s_arr(new char[len], std::default_delete()); memcpy(s_arr.get(), s, len); diff --git a/src/utils/test/blob_test.cpp b/src/utils/test/blob_test.cpp index 8ae2c8b7f6..586a7d68d9 100644 --- a/src/utils/test/blob_test.cpp +++ b/src/utils/test/blob_test.cpp @@ -24,6 +24,25 @@ namespace dsn { +TEST(BlobTest, CreateFromZeroLengthNullptr) +{ + const auto &obj = blob::create_from_bytes(nullptr, 0); + + EXPECT_EQ(0, obj.length()); + EXPECT_EQ(0, obj.size()); +} + +#ifndef NDEBUG + +TEST(BlobTest, CreateFromNonZeroLengthNullptr) +{ + ASSERT_DEATH({ const auto &obj = blob::create_from_bytes(nullptr, 1); }, + "null source pointer with non-zero length would lead to " + "undefined behaviour"); +} + +#endif + struct blob_base_case { std::string expected_str; @@ -32,7 +51,7 @@ struct blob_base_case class BlobBaseTest : public testing::TestWithParam { public: - void SetUp() override + BlobBaseTest() { const auto &test_case = GetParam(); _expected_str = test_case.expected_str;