From e87d758b9f874575664ab019dc4354731cb98128 Mon Sep 17 00:00:00 2001 From: Andreas Steinbart Date: Fri, 9 Oct 2026 09:21:51 +0000 Subject: [PATCH 1/2] feat(cpp): rejectArgument hook, ENCODE_BOUNDS switch; static storage clamps at a UTF-8 boundary Generated serialize() now refuses a value past a bound only the schema knows (a string or blob longer than its maxlen, an array with more elements than its count). The wrapper holds no bound: - OStreamImpl::rejectArgument() latches InvalidArgument (first failure wins), so ok()/error() report the refusal and no byte of the message is returned as a success. - sofab::ENCODE_BOUNDS (SOFAB_CPP_HAVE_ENCODE_BOUNDS) is true unless SOFAB_DISABLE_ENCODE_BOUNDS is defined. Generated code writes each check as `if (sofab::ENCODE_BOUNDS && ...)`, so the switch compiles all of them out for a footprint build that guarantees its values fit. Decode bound checks are unaffected. The static storage keeps clamping at assignment, as a documented contract, with two fixes: - FixedString::assign never cuts inside a UTF-8 character (detail::utf8Prefix, one copy for every capacity). - InlineVector::push_back past N drops the new value and keeps the held ones instead of overwriting the last element; emplace_back keeps its last-slot reuse for the decode binders. Tests: test/cpp/test_encode_bounds.cpp, the push_back case in test_istream.cpp, and encode_bounds_off.cpp (compile-only object that pins the opt-out). Refs sofa-buffers/generator#656 --- src/include/sofab/sofab.hpp | 120 ++++++++++++++++++++++++----- test/cpp/CMakeLists.txt | 7 ++ test/cpp/encode_bounds_off.cpp | 17 ++++ test/cpp/test_encode_bounds.cpp | 132 ++++++++++++++++++++++++++++++++ test/cpp/test_istream.cpp | 13 +++- 5 files changed, 266 insertions(+), 23 deletions(-) create mode 100644 test/cpp/encode_bounds_off.cpp create mode 100644 test/cpp/test_encode_bounds.cpp diff --git a/src/include/sofab/sofab.hpp b/src/include/sofab/sofab.hpp index 82e2935..d936a94 100644 --- a/src/include/sofab/sofab.hpp +++ b/src/include/sofab/sofab.hpp @@ -112,12 +112,31 @@ # define SOFAB_CPP_HAVE_ARRAY 1 #endif +/*! @brief 1 if generated code refuses an over-bound value at encode, else 0. + * + * A value past a bound only the schema knows -- a string or blob longer than + * its @c maxlen, an array with more elements than its @c count -- is refused by + * the generated @c serialize() through @ref sofab::OStreamImpl::rejectArgument. + * Each such check is written @c if (sofab::ENCODE_BOUNDS && ...), so defining + * @c SOFAB_DISABLE_ENCODE_BOUNDS removes all of them from the image: a + * footprint switch for a caller that guarantees its values fit. The decode-side + * bound checks are not affected. */ +#if defined(SOFAB_DISABLE_ENCODE_BOUNDS) +# define SOFAB_CPP_HAVE_ENCODE_BOUNDS 0 +#else +# define SOFAB_CPP_HAVE_ENCODE_BOUNDS 1 +#endif + /* types **********************************************************************/ namespace sofab { /*! @brief SofaBuffers C++ API version (mirrors @ref SOFAB_API_VERSION). */ inline constexpr int API_VERSION = 1; + /*! @brief Whether generated encode refuses an over-bound value + * (@ref SOFAB_CPP_HAVE_ENCODE_BOUNDS; off with @c SOFAB_DISABLE_ENCODE_BOUNDS). */ + inline constexpr bool ENCODE_BOUNDS = SOFAB_CPP_HAVE_ENCODE_BOUNDS != 0; + /*! @brief Always-false trait used to trigger a dependent static_assert in a * discarded @c if @c constexpr branch (so it only fires when instantiated). */ template @@ -234,12 +253,36 @@ namespace sofab /*** FixedString ***/ /*******************/ + namespace detail + { + /*! + * @brief Length of the longest prefix of @p sv that is at most @p n bytes + * and does not end inside a UTF-8 character; @p sv is longer + * than @p n. + * + * The over-long half of @ref FixedString's assignment-time clamp, one + * copy for every capacity: the cut moves back while the first byte left + * out is a continuation byte (10xxxxxx), so a valid UTF-8 @p sv keeps a + * valid UTF-8 prefix. The common case -- the value fits -- stays inline + * in @ref FixedString::assign, where a literal's length folds away. + */ + inline std::size_t utf8Prefix(std::string_view sv, std::size_t n) noexcept + { + while (n > 0 && (static_cast(sv[n]) & 0xC0u) == 0x80u) + { + --n; + } + return n; + } + } // namespace detail + /*! * @brief Fixed-capacity, heap-free string of up to @p N characters. * * A drop-in, embedded-friendly stand-in for @c std::string on both the encode * and decode paths. The characters live in an inline @c std::array, so an - * instance allocates nothing, never throws (overflow clamps to @p N), and + * instance allocates nothing, never throws (an over-long value is clamped to + * @p N bytes at a UTF-8 character boundary, see @ref assign), and * compiles cleanly under @c -fno-exceptions / @c -fno-rtti. Because the buffer * never moves, an instance is a valid address-stable decode target for the * deferred @ref IStreamImpl decoder (bytes bound now, filled by a later @@ -278,7 +321,7 @@ namespace sofab FixedString() noexcept = default; /*! - * @brief Construct from a NUL-terminated C string (truncated to @p N). + * @brief Construct from a NUL-terminated C string (clamped to @p N, see @ref assign). * @param s Source string, or @c nullptr for an empty string. */ FixedString(const char *s) noexcept @@ -287,7 +330,7 @@ namespace sofab } /*! - * @brief Construct from a string view (truncated to @p N). + * @brief Construct from a string view (clamped to @p N, see @ref assign). * @param sv Source characters (may contain embedded NULs). */ FixedString(std::string_view sv) noexcept @@ -297,7 +340,7 @@ namespace sofab #if SOFAB_CPP_HAVE_HOSTED /*! - * @brief Construct from a @c std::string (the easy on-ramp; truncated to @p N). + * @brief Construct from a @c std::string (the easy on-ramp; clamped to @p N, see @ref assign). * @param s Source string. * * Hosted only; freestanding builds take the @c std::string_view overload @@ -309,14 +352,14 @@ namespace sofab } #endif - /*! @brief Assign from a NUL-terminated C string (truncated to @p N). */ + /*! @brief Assign from a NUL-terminated C string (clamped to @p N, see @ref assign). */ FixedString &operator=(const char *s) noexcept { assign(s ? std::string_view{s} : std::string_view{}); return *this; } - /*! @brief Assign from a string view (truncated to @p N). */ + /*! @brief Assign from a string view (clamped to @p N, see @ref assign). */ FixedString &operator=(std::string_view sv) noexcept { assign(sv); @@ -324,7 +367,7 @@ namespace sofab } #if SOFAB_CPP_HAVE_HOSTED - /*! @brief Assign from a @c std::string (truncated to @p N). Hosted only. */ + /*! @brief Assign from a @c std::string (clamped to @p N, see @ref assign). Hosted only. */ FixedString &operator=(const std::string &s) noexcept { assign(std::string_view{s}); @@ -333,13 +376,21 @@ namespace sofab #endif /*! - * @brief Replace the contents with @p sv, truncated to @p N characters. + * @brief Replace the contents with @p sv, clamped to @p N bytes. + * + * The assignment-time clamp is a documented contract of the static + * storage (the generator's `allow_dynamic: false`): a value longer than + * @p N is cut, not refused, before any encoder sees it. The cut never + * lands inside a UTF-8 character -- it moves back to the start of the + * character that would not fit whole, so the kept prefix is valid UTF-8 + * whenever @p sv is. + * * @param sv Source characters (may contain embedded NULs). * @return Reference to @c *this. */ FixedString &assign(std::string_view sv) noexcept { - len_ = sv.size() > N ? N : sv.size(); + len_ = sv.size() <= N ? sv.size() : detail::utf8Prefix(sv, N); for (std::size_t i = 0; i < len_; ++i) { buf_[i] = sv[i]; @@ -501,7 +552,7 @@ namespace sofab FixedBytes() noexcept = default; /*! - * @brief Construct from a brace-enclosed list of bytes (truncated to @p N). + * @brief Construct from a brace-enclosed list of bytes (clamped to @p N; extra bytes are dropped). * * Providing this constructor makes @c FixedBytes a non-aggregate, so a * brace-init such as @c b = {1, 2, 3} routes through here and sets @@ -515,13 +566,13 @@ namespace sofab assign(init); } - /*! @brief Replace the contents from a brace-enclosed list (truncated to @p N). */ + /*! @brief Replace the contents from a brace-enclosed list (clamped to @p N; extra bytes are dropped). */ FixedBytes &operator=(std::initializer_list init) noexcept { return assign(init); } - /*! @brief Replace the contents from a brace-enclosed list (truncated to @p N). */ + /*! @brief Replace the contents from a brace-enclosed list (clamped to @p N; extra bytes are dropped). */ FixedBytes &assign(std::initializer_list init) noexcept { len_ = 0; @@ -663,7 +714,7 @@ namespace sofab InlineVector() noexcept = default; /*! - * @brief Construct from a brace-enclosed list of elements (truncated to @p N). + * @brief Construct from a brace-enclosed list of elements (clamped to @p N; extra elements are dropped). * * The presence of this constructor makes @c InlineVector a non-aggregate: * @c v = {a, b, c} routes here and sets @ref size, instead of aggregate @@ -676,13 +727,13 @@ namespace sofab assign(init); } - /*! @brief Replace the contents from a brace-enclosed list (truncated to @p N). */ + /*! @brief Replace the contents from a brace-enclosed list (clamped to @p N; extra elements are dropped). */ InlineVector &operator=(std::initializer_list init) noexcept { return assign(init); } - /*! @brief Replace the contents from a brace-enclosed list (truncated to @p N). */ + /*! @brief Replace the contents from a brace-enclosed list (clamped to @p N; extra elements are dropped). */ InlineVector &assign(std::initializer_list init) noexcept { len_ = 0; @@ -764,10 +815,17 @@ namespace sofab return buf_[i]; } - /*! @brief Append a copy of @p v (no-op growth once at capacity @p N). */ - void push_back(const T &v) noexcept { emplace_back() = v; } - /*! @brief Append @p v by move (no-op growth once at capacity @p N). */ - void push_back(T &&v) noexcept { emplace_back() = static_cast(v); } + /*! + * @brief Append a copy of @p v; once at capacity @p N, @p v is dropped. + * + * The assignment-time clamp of the static storage: elements past @p N + * are left out and the ones already held are kept, so a filled container + * holds the first @p N values it was given. (@ref emplace_back, the + * decode-side binder, reuses the last slot instead.) + */ + void push_back(const T &v) noexcept { if (len_ < N) buf_[len_++] = v; } + /*! @brief Append @p v by move; dropped once at capacity @p N (see above). */ + void push_back(T &&v) noexcept { if (len_ < N) buf_[len_++] = static_cast(v); } /*! @brief Reference to the last element. */ T &back() noexcept { return buf_[len_ - 1]; } @@ -1527,6 +1585,30 @@ namespace sofab return static_cast(failed_); } + /*! + * @brief Refuse the value being encoded: latch @ref Error::InvalidArgument. + * + * The hook a generated @c serialize() calls when a field's value is past + * a bound only the schema knows -- a string or blob longer than its + * @c maxlen, an array with more elements than its @c count. The corelib + * holds no schema bound; it records the refusal (first failure wins), so + * that @ref ok and @ref error report it like any other failed write and + * no byte of the message is returned as a success. Writes nothing + * itself. Generated code tests @ref ENCODE_BOUNDS first, so + * @c SOFAB_DISABLE_ENCODE_BOUNDS compiles every such check away. + * + * Cold and out of line: every guard in a generated serialize() then + * shares one call instead of its own inlined latch (measured on + * ARMv6-m: 202 B instead of 300 B of .text for the 18 guards of the + * bench schema), and the rare path stays out of the hot one. + * + * @return A Result carrying @ref Error::InvalidArgument. + */ + [[gnu::cold, gnu::noinline]] Result rejectArgument() noexcept + { + return result(SOFAB_RET_E_ARGUMENT); + } + protected: }; diff --git a/test/cpp/CMakeLists.txt b/test/cpp/CMakeLists.txt index 59e89f2..213deb8 100644 --- a/test/cpp/CMakeLists.txt +++ b/test/cpp/CMakeLists.txt @@ -32,6 +32,7 @@ add_executable(sofabpptest test_receiver_limits.cpp test_allocation.cpp test_vector_blocks.cpp + test_encode_bounds.cpp ../shared/sofab_test_json.c ) @@ -53,6 +54,12 @@ target_link_libraries(sofabpptest # --- ctest registration --- add_test(NAME test_cpp COMMAND sofabpptest) +# SOFAB_DISABLE_ENCODE_BOUNDS: compile-only (static_asserts), an object of its +# own so the two values of sofab::ENCODE_BOUNDS never meet in one program. +add_library(sofab_encode_bounds_off OBJECT encode_bounds_off.cpp) +target_compile_options(sofab_encode_bounds_off PRIVATE -Wall -Wextra -Wpedantic -Werror) +target_link_libraries(sofab_encode_bounds_off PRIVATE sofabuffers) + # The README's generator example, compiled and run. The stand-in lives here as a # real translation unit; the test also checks that README.md still shows calls it # implements, so a documented example cannot drift from one that compiles. Kept diff --git a/test/cpp/encode_bounds_off.cpp b/test/cpp/encode_bounds_off.cpp new file mode 100644 index 0000000..7e5c6eb --- /dev/null +++ b/test/cpp/encode_bounds_off.cpp @@ -0,0 +1,17 @@ +/*! + * @file encode_bounds_off.cpp + * @brief Compile-only: SOFAB_DISABLE_ENCODE_BOUNDS turns sofab::ENCODE_BOUNDS off. + * + * Built as an object of its own (never linked into a test binary, so the two + * values of the constant never meet in one program). Generated code writes + * each encode bound check as `if (sofab::ENCODE_BOUNDS && ...)`, so this is + * the switch that compiles all of them away. + * + * SPDX-License-Identifier: MIT + */ + +#define SOFAB_DISABLE_ENCODE_BOUNDS +#include "sofab/sofab.hpp" + +static_assert(SOFAB_CPP_HAVE_ENCODE_BOUNDS == 0, "the opt-out macro is honoured"); +static_assert(!sofab::ENCODE_BOUNDS, "the opt-out turns the generated encode bound checks off"); diff --git a/test/cpp/test_encode_bounds.cpp b/test/cpp/test_encode_bounds.cpp new file mode 100644 index 0000000..77a86c4 --- /dev/null +++ b/test/cpp/test_encode_bounds.cpp @@ -0,0 +1,132 @@ +/*! + * @file test_encode_bounds.cpp + * @brief The encode-side bound refusal hook and the static storage's clamp. + * + * A value past a bound only the schema knows (a string's maxlen, an array's + * count) is refused at encode by the GENERATED code, which calls + * OStreamImpl::rejectArgument: the corelib holds no bound, it only latches + * InvalidArgument so the stream verdict reports it. The static storage + * (FixedString / FixedBytes / InlineVector) clamps at ASSIGNMENT instead, by + * contract: the first N bytes or elements are kept, the rest is dropped, and a + * string is never cut inside a UTF-8 character. + * + * SPDX-License-Identifier: MIT + */ + +#include "sofab/sofab.hpp" + +#include +#include +#include +#include +#include + +static_assert(sofab::ENCODE_BOUNDS, "encode bound checks are ON unless SOFAB_DISABLE_ENCODE_BOUNDS"); + +namespace +{ + /* A message whose serialize() refuses its value the way generated code does. */ + struct RefusingMsg : sofab::OStreamMessage + { + std::string_view s; + sofab::OStreamImpl::Result serialize(sofab::OStreamImpl &os) const noexcept override + { + (void)os.write(0, uint32_t{1}); + if (sofab::ENCODE_BOUNDS && s.size() > 4) { return os.rejectArgument(); } + return os.write(1, s); + } + sofab::OStreamImpl::Result run(sofab::OStreamImpl &os) const noexcept { return serialize(os); } + }; +} + +TEST_CASE("rejectArgument: the Result and the stream verdict carry InvalidArgument") +{ + std::array buf{}; + sofab::OStreamView os{buf.data(), buf.size()}; + (void)os.write(1, uint32_t{1}); + const size_t before = os.bytesUsed(); + auto r = os.rejectArgument(); + CHECK(!r.ok()); + CHECK(r == sofab::Error::InvalidArgument); + CHECK(!os.ok()); + CHECK(os.error() == sofab::Error::InvalidArgument); + CHECK(os.bytesUsed() == before); + (void)os.write(2, uint32_t{2}); + CHECK(os.error() == sofab::Error::InvalidArgument); +} + +TEST_CASE("rejectArgument: the first latched failure is kept") +{ + std::array buf{}; + sofab::OStreamView os{buf.data(), buf.size()}; + (void)os.write(1, std::string_view{"too long for two bytes"}); + REQUIRE(os.error() == sofab::Error::BufferFull); + auto r = os.rejectArgument(); + CHECK(r == sofab::Error::InvalidArgument); + CHECK(os.error() == sofab::Error::BufferFull); +} + +TEST_CASE("rejectArgument: a refusing serialize() fails the encode, a value at its bound encodes") +{ + RefusingMsg m; + m.s = "abcde"; + std::array buf{}; + sofab::OStreamView bad{buf.data(), buf.size()}; + CHECK(!m.run(bad).ok()); + CHECK(bad.error() == sofab::Error::InvalidArgument); + + m.s = "abcd"; + sofab::OStreamView good{buf.data(), buf.size()}; + CHECK(m.run(good).ok()); + CHECK(good.ok()); + CHECK(good.bytesUsed() == 8); +} + +TEST_CASE("FixedString: an over-long value is clamped at a UTF-8 character boundary") +{ + CHECK(sofab::FixedString<4>{"xxxxx"}.view() == "xxxx"); + + sofab::FixedString<4> two{"xxx\xC3\xA9"}; /* xxx + U+00E9 */ + CHECK(two.view() == "xxx"); + CHECK(two.c_str()[3] == '\0'); + + CHECK(sofab::FixedString<4>{std::string_view{"\xC3\xA9\xC3\xA9\xC3\xA9"}}.view() == "\xC3\xA9\xC3\xA9"); + + sofab::FixedString<4> four; + four = std::string_view{"a\xF0\x9F\x98\x80"}; /* a + U+1F600 */ + CHECK(four.view() == "a"); + + CHECK(sofab::FixedString<5>{"a\xF0\x9F\x98\x80"}.size() == 5); + CHECK(sofab::FixedString<3>{"\xF0\x9F\x98\x80"}.empty()); + CHECK(sofab::FixedString<2>{"a\xE2\x82\xAC"}.view() == "a"); /* a + U+20AC */ + + sofab::FixedString<4> edge; + edge = "\xC3\xA9xyz"; + CHECK(edge.view() == "\xC3\xA9xy"); +} + +TEST_CASE("InlineVector / FixedBytes: past N the value is dropped, the held ones stay") +{ + sofab::InlineVector v; + for (uint32_t x : {1u, 2u, 3u, 4u, 5u}) v.push_back(x); + REQUIRE(v.size() == 3); + CHECK(v[0] == 1); + CHECK(v[1] == 2); + CHECK(v[2] == 3); + + sofab::InlineVector, 3> t; + for (const char *x : {"a", "b", "c", "d"}) t.push_back(sofab::FixedString<4>{x}); + const sofab::FixedString<4> keep{"zz"}; + t.push_back(keep); + REQUIRE(t.size() == 3); + CHECK(t[2].view() == "c"); + + sofab::InlineVector w{7, 8, 9}; + CHECK(w.size() == 2); + CHECK(w[1] == 8); + + sofab::FixedBytes<4> b{1, 2, 3, 4, 5}; + for (int i = 0; i < 3; ++i) b.push_back(9); + CHECK(b.size() == 4); + CHECK(b.data()[3] == 4); +} diff --git a/test/cpp/test_istream.cpp b/test/cpp/test_istream.cpp index 91e723c..4d524ae 100644 --- a/test/cpp/test_istream.cpp +++ b/test/cpp/test_istream.cpp @@ -1635,12 +1635,17 @@ TEST_CASE("InlineVector: push_back, emplace_back, iteration and capacity") w = {10, 20}; REQUIRE(v != w); - // At capacity the length never grows: emplace_back reuses the last slot - // (an OOB-safe clamp for a malformed over-length wire) rather than writing - // past N. The logical length stays N. + // At capacity the length never grows. push_back is the assignment-time + // clamp of the static storage: the value is dropped and the held ones stay. v.push_back(40); REQUIRE(v.size() == 3); - REQUIRE(v.back() == 40); + REQUIRE(v.back() == 30); + // emplace_back, the decode-side binder, reuses the last slot instead (an + // OOB-safe clamp for a malformed over-length wire) rather than writing past + // N. The logical length stays N. + v.emplace_back() = 50; + REQUIRE(v.size() == 3); + REQUIRE(v.back() == 50); } TEST_CASE("InlineVector: resize is the length, and readArray finds it") From 3636e52679c4beaccb6c93a2d46b7028a880f2f5 Mon Sep 17 00:00:00 2001 From: Andreas Steinbart Date: Fri, 9 Oct 2026 16:04:53 +0000 Subject: [PATCH 2/2] feat(c): refuse an over-maxlen string at encode; SOFAB_DISABLE_ENCODE_BOUNDS sofab_object_encode read a STRING member with strlen, so a char[maxlen + 1] filled without a terminator was read past the member and emitted whatever followed it. The member is now read bounded by its own storage (field->size, data the descriptor already carries; the corelib knows no schema bound), and a value that fills it without a terminator -- longer than maxlen -- is refused with SOFAB_RET_E_ARGUMENT before any byte of it is written. The length is a plain byte loop instead of strlen: no libc call. SOFAB_DISABLE_ENCODE_BOUNDS (CMake option, applied PUBLIC; the C++ wrapper reads the same macro as sofab::ENCODE_BOUNDS) removes the refusal for a caller that guarantees its values fit; the read stays bounded and such a value is emitted as the whole buffer. A sized blob's length and a sized array's or wrapper holder's count past the capacity keep being clamped to it: that is the documented clamp contract, now pinned by tests. Tests (test/c/test_object.c): a string at its bound, an unterminated one (both builds), an unterminated array element, and the blob/array/holder clamp. CI: a no-encode-bounds leg runs the unit suite and the vectors with the switch. Coverage (gcovr, the CI filter): lines 87.9% (903/1027) -> 88.0% (908/1032), branches 59.1% (528/894) -> 59.6% (536/900). Refs sofa-buffers/generator#656 --- .github/workflows/ci.yml | 10 +++ README.md | 1 + src/CMakeLists.txt | 11 +++ src/include/sofab/sofab.h | 17 ++++ src/object.c | 21 ++++- test/c/test_object.c | 182 ++++++++++++++++++++++++++++++++++++++ 6 files changed, 241 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 12069d4..6e8070f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -574,6 +574,16 @@ jobs: $RUN ./build/no-lazy-seq/test/c/sofab_vectortest $RUN ./build/no-lazy-seq/test/c/sofabtest + # The encode-side bound refusal compiled out (a footprint opt-out that removes a + # check, not a wire construct): the full unit suite runs, and the encode-bound + # tests take their #if-guarded opt-out branch -- the string read stays bounded. + - name: no-encode-bounds + run: | + cmake -S . -B build/no-encode-bounds $CM_ARGS -DCMAKE_C_FLAGS="-DSOFAB_DISABLE_ENCODE_BOUNDS" + cmake --build build/no-encode-bounds --target sofab_vectortest sofabtest --parallel $(nproc) + $RUN ./build/no-encode-bounds/test/c/sofab_vectortest + $RUN ./build/no-encode-bounds/test/c/sofabtest + # The hold-back window is a documented, tunable bound (SOFAB_LAZY_SEQ_DEPTH, # CORELIB_PLAN §6), so a build that moves it must still pass the suite: the # bound costs canonicity past its depth, never validity. diff --git a/README.md b/README.md index 6f8971e..180926b 100644 --- a/README.md +++ b/README.md @@ -304,6 +304,7 @@ disagree is a silent ABI mismatch, not a warning. Passing the macro through | `SOFAB_DISABLE_FP64_SUPPORT` | CMake option | off | Drop 64-bit float (`fp64`); auto-defined where `double` is not 8 bytes | | `SOFAB_DISABLE_INT64_SUPPORT` | CMake option | off | Narrow scalar varints from 64-bit to 32-bit (drops the `u64`/`i64` helpers) | | `SOFAB_DISABLE_INTEGER_OVERFLOW_CHECK` | CMake option | off | Skip integer overflow checks when decoding (smaller/faster, less safe) | +| `SOFAB_DISABLE_ENCODE_BOUNDS` | CMake option | off | Remove the encode-side refusal of an over-bound value: `sofab_object_encode()` no longer returns `SOFAB_RET_E_ARGUMENT` for a string member that fills its `char[maxlen + 1]` without a terminator (the read stays bounded), and the C++ wrapper's `sofab::ENCODE_BOUNDS` is `false`. Sized blob lengths and array counts are clamped to the capacity either way | | `SOFAB_DISABLE_OBJECT_API` | CMake option | off | Exclude the descriptor-driven object API (`object.c`) and leave the bare stream corelib | > **A switch that removes a wire construct makes the decoder *reject* messages diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 699d586..8e24a79 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -75,6 +75,17 @@ if(SOFAB_DISABLE_LAZY_SEQ_SUPPORT) target_compile_definitions(sofabuffers PUBLIC SOFAB_DISABLE_LAZY_SEQ_SUPPORT) endif() +# The encode-side bound refusal (sofab_object_encode refuses a string member that +# fills its char[maxlen + 1] storage without a terminator; the C++ wrapper reads +# the same macro as sofab::ENCODE_BOUNDS). A footprint switch for a caller that +# guarantees its values fit: it removes a check, not a wire construct. PUBLIC so +# the C++ wrapper's generated checks and object.c agree. +option(SOFAB_DISABLE_ENCODE_BOUNDS + "Remove the encode-side refusal of an over-bound value" OFF) +if(SOFAB_DISABLE_ENCODE_BOUNDS) + target_compile_definitions(sofabuffers PUBLIC SOFAB_DISABLE_ENCODE_BOUNDS) +endif() + # The object descriptor width profile is configured the same way, and for the # same reason applied PUBLIC: SOFAB_OBJECT_DESCR_PROFILE selects the integer # widths of sofab_object_descr_field_t in the *public* header, so the library and diff --git a/src/include/sofab/sofab.h b/src/include/sofab/sofab.h index 74de216..aaf7692 100644 --- a/src/include/sofab/sofab.h +++ b/src/include/sofab/sofab.h @@ -295,6 +295,23 @@ typedef int32_t sofab_signed_t; /*! @brief Disable integer overflow checks when reading integer values. */ // #define SOFAB_DISABLE_INTEGER_OVERFLOW_CHECK +/*! + * @brief Disable the encode-side bound refusal. + * + * By default @ref sofab_object_encode reads a @c STRING field bounded by its + * own storage (@c char[maxlen + 1]) and refuses, with + * @ref SOFAB_RET_E_ARGUMENT, a value that fills that storage without a + * terminator: it is longer than the field's @c maxlen. Defining this switch + * removes the refusal (a compare and a branch per string field) for a caller + * that guarantees its strings are terminated within their bound; the read stays + * bounded, so such a value is emitted as the whole buffer instead of read past + * it. The C++ wrapper reads the same switch as @c sofab::ENCODE_BOUNDS. A + * sized blob's length and a sized array's or wrapper holder's element count are + * clamped to the capacity in either build (the documented clamp contract), and + * decode-side bound checks are not affected. + */ +// #define SOFAB_DISABLE_ENCODE_BOUNDS + /*! * @brief Strict UTF-8 validation of @c string fields (default OFF — opt-in). * diff --git a/src/object.c b/src/object.c index 9ac922e..4dd9591 100644 --- a/src/object.c +++ b/src/object.c @@ -909,8 +909,27 @@ extern sofab_ret_t sofab_object_encode ( #endif /* !defined(SOFAB_DISABLE_FP64_SUPPORT) */ case SOFAB_OBJECT_FIELDTYPE_STRING: - ret = sofab_ostream_write_string(ctx, field->id, CAST_TO(char *, src, field->offset)); + { + /* A string member is char[maxlen + 1], so its length is read + * bounded by field->size and never past the member. A value that + * fills the member without a terminator is longer than maxlen: + * refused before a byte of it is written (SOFAB_DISABLE_ENCODE_BOUNDS + * removes the refusal; the read stays bounded). A plain byte loop + * rather than strlen/memchr: no libc call, and the loop is smaller + * than the call sequence on the footprint targets. */ + const char *s = CAST_TO(const char *, src, field->offset); + size_t len = 0; + while (len < field->size && s[len] != '\0') len++; +#if !defined(SOFAB_DISABLE_ENCODE_BOUNDS) + if (len == field->size) + { + return SOFAB_RET_E_ARGUMENT; + } +#endif + ret = sofab_ostream_write_fixlen(ctx, field->id, s, (int32_t)len, + SOFAB_FIXLENTYPE_STRING); break; + } case SOFAB_OBJECT_FIELDTYPE_BLOB: { diff --git a/test/c/test_object.c b/test/c/test_object.c index d393dda..9f3ded5 100644 --- a/test/c/test_object.c +++ b/test/c/test_object.c @@ -4097,6 +4097,179 @@ static void test_object_union_switched_to_leaf_carries_no_earlier_option (void) #endif /* sequence && fixlen && array support */ +// +// Encode bounds (generator#656). A STRING member is char[maxlen + 1]: the encoder +// reads it bounded by that storage and refuses a value that fills it without a +// terminator (longer than maxlen) with SOFAB_RET_E_ARGUMENT, unless the build +// defines SOFAB_DISABLE_ENCODE_BOUNDS, where the read stays bounded and the whole +// buffer is emitted. A sized blob's length and a sized array's or holder's count +// past the capacity are CLAMPED to it -- the documented clamp contract, the same in +// both builds. +// + +typedef struct +{ + char s[5]; /* maxlen 4 */ + char guard[4]; /* must never reach the wire */ +} _eb_str_t; + +static const sofab_object_descr_field_t _eb_str_fields[] = +{ + SOFAB_OBJECT_FIELD(0, _eb_str_t, s, SOFAB_OBJECT_FIELDTYPE_STRING), +}; + +static const sofab_object_descr_t _eb_str = + SOFAB_OBJECT_DESCR(_eb_str_fields, 1, NULL, 0); + +static sofab_ret_t _eb_encode (const sofab_object_descr_t *info, const void *in, + uint8_t *buf, size_t buflen, size_t *used) +{ + sofab_ostream_t octx; + sofab_ret_t ret; + sofab_ostream_init(&octx, buf, buflen, 0, NULL, NULL); + ret = sofab_object_encode(&octx, info, in); + *used = sofab_ostream_flush(&octx); + return ret; +} + +static void test_object_encode_string_at_bound (void) +{ + uint8_t buf[16]; + size_t used = 0; + _eb_str_t in; + memset(&in, 0, sizeof(in)); + memcpy(in.s, "abcd", 5); + memcpy(in.guard, "zzz", 4); + + TEST_ASSERT_EQUAL(SOFAB_RET_OK, _eb_encode(&_eb_str, &in, buf, sizeof(buf), &used)); + /* id 0 | FIXLEN = 0x02 ; (4 << 3) | STRING = 0x22 */ + const uint8_t expected[] = { 0x02, 0x22, 'a', 'b', 'c', 'd' }; + TEST_ASSERT_EQUAL_size_t(sizeof(expected), used); + TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, buf, used); +} + +static void test_object_encode_string_unterminated (void) +{ + uint8_t buf[16]; + size_t used = 0; + _eb_str_t in; + memset(&in, 0, sizeof(in)); + memcpy(in.s, "abcde", 5); /* fills char[5]: no terminator, 5 > maxlen 4 */ + memcpy(in.guard, "zzz", 4); + + sofab_ret_t ret = _eb_encode(&_eb_str, &in, buf, sizeof(buf), &used); +#if !defined(SOFAB_DISABLE_ENCODE_BOUNDS) + TEST_ASSERT_EQUAL_MESSAGE(SOFAB_RET_E_ARGUMENT, ret, + "a string that fills its storage without a terminator is over maxlen"); + TEST_ASSERT_EQUAL_size_t_MESSAGE(0, used, "nothing of the refused field is written"); +#else + /* The opt-out keeps the read bounded: the five bytes, never the guard. */ + TEST_ASSERT_EQUAL(SOFAB_RET_OK, ret); + const uint8_t expected[] = { 0x02, 0x2A, 'a', 'b', 'c', 'd', 'e' }; + TEST_ASSERT_EQUAL_size_t(sizeof(expected), used); + TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, buf, used); +#endif +} + +#if !defined(SOFAB_DISABLE_SEQUENCE_SUPPORT) +/* The same rule for an element of an array (a sized wrapper holder). */ +typedef struct { + uint8_t len; + char s[3][5]; +} _eb_strs_holder_t; +static const sofab_object_descr_field_t _eb_strs_fields[] = { + SOFAB_OBJECT_FIELD(0, _eb_strs_holder_t, s[0], SOFAB_OBJECT_FIELDTYPE_STRING), + SOFAB_OBJECT_FIELD(1, _eb_strs_holder_t, s[1], SOFAB_OBJECT_FIELDTYPE_STRING), + SOFAB_OBJECT_FIELD(2, _eb_strs_holder_t, s[2], SOFAB_OBJECT_FIELDTYPE_STRING), +}; +static const sofab_object_descr_t _eb_strs_holder = + SOFAB_OBJECT_DESCR_SEQ_SIZED(_eb_strs_fields, 3, NULL, 0, _eb_strs_holder_t, len); + +typedef struct { _eb_strs_holder_t arr; } _eb_strs_msg_t; +static const sofab_object_descr_field_t _eb_strs_msg_fields[] = { + SOFAB_OBJECT_FIELD_SEQUENCE(5, _eb_strs_msg_t, arr, SOFAB_OBJECT_FIELDTYPE_SEQUENCE, 0), +}; +static const sofab_object_descr_t *const _eb_strs_nested[] = { &_eb_strs_holder }; +static const sofab_object_descr_t _eb_strs_msg = + SOFAB_OBJECT_DESCR(_eb_strs_msg_fields, 1, _eb_strs_nested, 1); + +static void test_object_encode_string_element_unterminated (void) +{ + uint8_t buf[32]; + size_t used = 0; + _eb_strs_msg_t in; + memset(&in, 0, sizeof(in)); + in.arr.len = 2; + memcpy(in.arr.s[0], "ab", 3); + memcpy(in.arr.s[1], "xxxxx", 5); /* unterminated: over maxlen 4 */ + + sofab_ret_t ret = _eb_encode(&_eb_strs_msg, &in, buf, sizeof(buf), &used); +#if !defined(SOFAB_DISABLE_ENCODE_BOUNDS) + TEST_ASSERT_EQUAL_MESSAGE(SOFAB_RET_E_ARGUMENT, ret, + "an over-maxlen element of an array is refused"); +#else + TEST_ASSERT_EQUAL(SOFAB_RET_OK, ret); + (void)used; +#endif + + /* the control: the same element at its bound encodes */ + memcpy(in.arr.s[1], "xxxx", 5); + TEST_ASSERT_EQUAL(SOFAB_RET_OK, _eb_encode(&_eb_strs_msg, &in, buf, sizeof(buf), &used)); + TEST_ASSERT_TRUE(used > 0); +} + +static void test_object_encode_holder_count_clamped (void) +{ + uint8_t buf[32]; + size_t used = 0; + _eb_strs_msg_t in; + memset(&in, 0, sizeof(in)); + in.arr.len = 9; /* past the 3 slots */ + memcpy(in.arr.s[0], "a", 2); + memcpy(in.arr.s[1], "b", 2); + memcpy(in.arr.s[2], "c", 2); + + TEST_ASSERT_EQUAL(SOFAB_RET_OK, _eb_encode(&_eb_strs_msg, &in, buf, sizeof(buf), &used)); + /* seq 5 open = 0x2E; ids 0..2 one-byte strings; close 0x07 */ + const uint8_t expected[] = { 0x2E, 0x02, 0x0A, 'a', 0x0A, 0x0A, 'b', 0x12, 0x0A, 'c', 0x07 }; + TEST_ASSERT_EQUAL_size_t_MESSAGE(sizeof(expected), used, + "a holder count past the capacity is clamped to it"); + TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, buf, used); +} +#endif /* !defined(SOFAB_DISABLE_SEQUENCE_SUPPORT) */ + +static void test_object_encode_blob_len_clamped (void) +{ + uint8_t buf[32]; + size_t used = 0; + blobsized_t in; + memset(&in, 0, sizeof(in)); + for (uint8_t i = 0; i < 8; i++) in.data[i] = (uint8_t)(0xA0 + i); + in.used_len = 200; /* past the 8-byte capacity */ + + TEST_ASSERT_EQUAL(SOFAB_RET_OK, _eb_encode(&_info_blobsized, &in, buf, sizeof(buf), &used)); + const uint8_t expected[] = { 0x02, 0x43, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7 }; + TEST_ASSERT_EQUAL_size_t_MESSAGE(sizeof(expected), used, + "a blob length past the capacity is clamped to it"); + TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, buf, used); +} + +static void test_object_encode_array_len_clamped (void) +{ + uint8_t buf[32]; + size_t used = 0; + arrsized_t in; + sofab_object_init(&_info_arrsized, &in); + for (uint32_t i = 0; i < 5; i++) in.vals[i] = i + 1; + in.len = 99; /* past the 5-element capacity */ + + TEST_ASSERT_EQUAL(SOFAB_RET_OK, _eb_encode(&_info_arrsized, &in, buf, sizeof(buf), &used)); + const uint8_t expected[] = { 0x03, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05 }; + TEST_ASSERT_EQUAL_size_t_MESSAGE(sizeof(expected), used, + "an array count past the capacity is clamped to it"); + TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, buf, used); +} + int test_object_main (void) { UNITY_BEGIN(); @@ -4202,5 +4375,14 @@ int test_object_main (void) RUN_TEST(test_object_sized_wrapper_init_clears_length); + RUN_TEST(test_object_encode_string_at_bound); + RUN_TEST(test_object_encode_string_unterminated); +#if !defined(SOFAB_DISABLE_SEQUENCE_SUPPORT) + RUN_TEST(test_object_encode_string_element_unterminated); + RUN_TEST(test_object_encode_holder_count_clamped); +#endif + RUN_TEST(test_object_encode_blob_len_clamped); + RUN_TEST(test_object_encode_array_len_clamped); + return UNITY_END(); }