From: Joel Rosdahl Date: Mon, 22 May 2023 17:58:41 +0000 (+0200) Subject: fix: Fix undefined behavior in util::read_file_part for zero count X-Git-Tag: v4.8.2~15 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=e24cedf8fba91d5e14ca2d0f1be81e42ed8fe9f6;p=thirdparty%2Fccache.git fix: Fix undefined behavior in util::read_file_part for zero count If util::read_file_part's count argument is 0 (which can currently only happen in unit tests), we'll do &result[0] where result is default-initialized std::unique_ptr. This is not allowed even though we won't actually dereference the pointer. Found by compiling with -D_GLIBCXX_ASSERTIONS. Fixes #1288. --- diff --git a/src/util/file.cpp b/src/util/file.cpp index d084f88c4..57a6b560f 100644 --- a/src/util/file.cpp +++ b/src/util/file.cpp @@ -214,6 +214,11 @@ template nonstd::expected read_file_part(const std::string& path, size_t pos, size_t count) { + T result; + if (count == 0) { + return result; + } + Fd fd(open(path.c_str(), O_RDONLY | O_BINARY)); if (!fd) { LOG("Failed to open {}: {}", path, strerror(errno)); @@ -226,7 +231,6 @@ read_file_part(const std::string& path, size_t pos, size_t count) int64_t ret = 0; size_t bytes_read = 0; - T result; result.resize(count); while (true) { diff --git a/unittest/test_util_file.cpp b/unittest/test_util_file.cpp index 77e5c0bec..4695750c2 100644 --- a/unittest/test_util_file.cpp +++ b/unittest/test_util_file.cpp @@ -147,7 +147,9 @@ TEST_CASE("util::read_file_part") SUBCASE("util::Bytes") { - CHECK(util::read_file_part("test", 0, 0) == util::to_span("")); + auto lhs = util::read_file_part("test", 0, 0); + auto rhs = util::to_span(""); + CHECK(lhs == rhs); CHECK(util::read_file_part("test", 0, 6) == util::to_span("banana")); CHECK(util::read_file_part("test", 0, 1000)