From a31459bce6f466f01c66185dda75b9b7639ee04c Mon Sep 17 00:00:00 2001 From: Ryan Blue Date: Sun, 11 Dec 2022 10:36:38 -0500 Subject: [PATCH] [wpiutil] Fix UnescapeCString overflow when inputSize < 2 (#4796) Add tests for empty, small, and string without escapes. --- .../thirdparty/llvm/cpp/llvm/StringExtras.cpp | 2 +- .../test/native/cpp/UnescapeCStringTest.cpp | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/wpiutil/src/main/native/thirdparty/llvm/cpp/llvm/StringExtras.cpp b/wpiutil/src/main/native/thirdparty/llvm/cpp/llvm/StringExtras.cpp index 0b9f7d42f0..930772488e 100644 --- a/wpiutil/src/main/native/thirdparty/llvm/cpp/llvm/StringExtras.cpp +++ b/wpiutil/src/main/native/thirdparty/llvm/cpp/llvm/StringExtras.cpp @@ -362,7 +362,7 @@ std::optional wpi::parse_float( std::pair wpi::UnescapeCString( std::string_view str, wpi::SmallVectorImpl& buf) { buf.clear(); - buf.reserve(str.size() - 2); + buf.reserve(str.size()); const char* s = str.data(); const char* end = str.data() + str.size(); for (; s != end && *s != '"'; ++s) { diff --git a/wpiutil/src/test/native/cpp/UnescapeCStringTest.cpp b/wpiutil/src/test/native/cpp/UnescapeCStringTest.cpp index d3aa63c34b..7f0ca5fcf8 100644 --- a/wpiutil/src/test/native/cpp/UnescapeCStringTest.cpp +++ b/wpiutil/src/test/native/cpp/UnescapeCStringTest.cpp @@ -52,4 +52,23 @@ TEST(UnescapeCStringTest, Octal) { EXPECT_TRUE(rem.empty()); } +TEST(UnescapeCStringTest, EmptyString) { + SmallString<64> buf; + auto [out, rem] = UnescapeCString("", buf); + EXPECT_EQ(out, ""); +} + +TEST(UnescapeCStringTest, ShortString) { + SmallString<64> buf; + auto [out, rem] = UnescapeCString("a", buf); + EXPECT_EQ(out, "a"); +} + +TEST(UnescapeCStringTest, NoEscapesString) { + SmallString<64> buf; + std::string_view input = "abcdefghijklmnopqrstuvwxyz1234567890"; + auto [out, rem] = UnescapeCString(input, buf); + EXPECT_EQ(out, input); +} + } // namespace