From 156ccfdb7da35ab786530cdd956e3881b50983f7 Mon Sep 17 00:00:00 2001 From: fallenoak Date: Fri, 10 Feb 2023 14:53:11 -0600 Subject: [PATCH] fix(datastore): correctly handle null terminated strings --- common/datastore/CDataStore.cpp | 8 ++++++-- test/DataStore.cpp | 16 +++++++++++++++- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/common/datastore/CDataStore.cpp b/common/datastore/CDataStore.cpp index 6f944d4..0374c18 100644 --- a/common/datastore/CDataStore.cpp +++ b/common/datastore/CDataStore.cpp @@ -159,6 +159,10 @@ CDataStore& CDataStore::GetString(char* val, uint32_t maxChars) { STORM_ASSERT(this->IsFinal()); STORM_ASSERT(val || maxChars == 0); + if (maxChars == 0) { + return *this; + } + if (this->FetchRead(this->m_read, 1)) { auto ofs = this->m_read - this->m_base; auto ptr = &this->m_data[ofs]; @@ -168,7 +172,7 @@ CDataStore& CDataStore::GetString(char* val, uint32_t maxChars) { val[i] = *reinterpret_cast(&ptr[i]); } - this->m_read += i; + this->m_read += i == maxChars ? i : i + 1; } return *this; @@ -316,7 +320,7 @@ CDataStore& CDataStore::PutData(const void* val, uint32_t bytes) { CDataStore& CDataStore::PutString(const char* val) { auto len = SStrLen(val); - return this->PutArray(reinterpret_cast(val), len); + return this->PutArray(reinterpret_cast(val), len + 1); } void CDataStore::Reset() { diff --git a/test/DataStore.cpp b/test/DataStore.cpp index ecfa3cc..952098d 100644 --- a/test/DataStore.cpp +++ b/test/DataStore.cpp @@ -80,9 +80,10 @@ TEST_CASE("CDataStore::Get", "[datastore]") { msg.GetString(readVal, sizeof(readVal)); REQUIRE(SStrCmp(readVal, writeVal, STORM_MAX_STR) == 0); + REQUIRE(msg.IsRead()); } - SECTION("gets string honoring maxchars") { + SECTION("gets string honoring maxchars > 0") { const char* writeVal = "foobar"; char readVal[7] = "bar"; @@ -92,5 +93,18 @@ TEST_CASE("CDataStore::Get", "[datastore]") { msg.GetString(readVal, 3); REQUIRE(SStrCmp(readVal, "foo", STORM_MAX_STR) == 0); + REQUIRE(msg.m_read == 3); + } + + SECTION("gets string honoring maxchars of 0") { + const char* writeVal = "foobar"; + char readVal[7] = "bar"; + + CDataStore msg; + msg.PutString(writeVal); + msg.Finalize(); + msg.GetString(readVal, 0); + + REQUIRE(msg.m_read == 0); } }