From 8f11927aaee44dd12d4db0a26ee026c8665c14b2 Mon Sep 17 00:00:00 2001 From: Mathias Agopian Date: Mon, 30 Mar 2026 21:14:23 -0700 Subject: [PATCH] utils: Truncate oversized CString allocations rather than overflowing internal length logic --- libs/utils/include/utils/CString.h | 4 ++++ libs/utils/src/CString.cpp | 22 ++++++++++++---------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/libs/utils/include/utils/CString.h b/libs/utils/include/utils/CString.h index 935845f2fa..c48d9c8b55 100644 --- a/libs/utils/include/utils/CString.h +++ b/libs/utils/include/utils/CString.h @@ -66,11 +66,15 @@ public: // Allocates memory and appends a null. This constructor can be used to hold arbitrary data // inside the string (i.e. it can contain nulls or non-ASCII encodings). + // Note: If length exceeds the 32-bit maximum capacity of CString, it will be safely + // truncated to std::numeric_limits::max(). CString(const char* cstr, size_t length); // Allocates memory for a string of size length plus space for the null terminating character. // Also initializes the memory to 0. This constructor can be used to hold arbitrary data // inside the string. + // Note: If length exceeds the 32-bit maximum capacity of CString, it will be safely + // truncated to std::numeric_limits::max(). explicit CString(size_t length); // Conversion from std::string_view diff --git a/libs/utils/src/CString.cpp b/libs/utils/src/CString.cpp index ae88ee7114..c562dc1e8a 100644 --- a/libs/utils/src/CString.cpp +++ b/libs/utils/src/CString.cpp @@ -61,24 +61,26 @@ void CString::do_tracking(bool ctor) { UTILS_NOINLINE CString::CString(const char* cstr, size_t const length) { track(true); - if (length && cstr) { - Data* const p = static_cast(std::malloc(sizeof(Data) + length + 1)); - p->length = size_type(length); + size_t const len = std::min(length, (size_t)std::numeric_limits::max()); + if (len && cstr) { + Data* const p = static_cast(std::malloc(sizeof(Data) + len + 1)); + p->length = size_type(len); mCStr = reinterpret_cast(p + 1); // we don't use memcpy here to avoid a call to libc, the generated code is pretty good. - std::uninitialized_copy_n(cstr, length, mCStr); - mCStr[length] = '\0'; + std::uninitialized_copy_n(cstr, len, mCStr); + mCStr[len] = '\0'; } } CString::CString(size_t const length) { track(true); - if (length) { - Data* const p = static_cast(std::malloc(sizeof(Data) + length + 1)); - p->length = size_type(length); + size_t const len = std::min(length, (size_t)std::numeric_limits::max()); + if (len) { + Data* const p = static_cast(std::malloc(sizeof(Data) + len + 1)); + p->length = size_type(len); mCStr = reinterpret_cast(p + 1); - std::fill_n(mCStr, length, 0); - mCStr[length] = '\0'; + std::fill_n(mCStr, len, 0); + mCStr[len] = '\0'; } }