From c79ad7b634afb36f7513ef6b370b6ee8e2e2b29f Mon Sep 17 00:00:00 2001 From: Aaron Date: Tue, 8 Sep 2026 12:39:26 +0100 Subject: [PATCH] feat: support payloads up to 65,528 bits Flash parameter records need to grow beyond CAN-FD frame capacity. Keep transport limits in callers while retaining descriptor layout, field conversions, wire bytes and the 64-bit default buffer. Use a shared maximum and overflow-safe field validation. Check every legal field geometry against an independent model and compare legacy pack/unpack results with the pinned 2.4.0 implementation in CI. Validation: native and simulated-MAU sanitizers, 100% line/branch coverage, zero misch findings or new deviations, and TI C2000 22.6.2/25.11.1 release compilation at default and maximum buffer sizes. Target execution remains a consumer integration check. Closes #6 --- .github/workflows/ci.yml | 38 ++- CHANGELOG.md | 30 ++ CONTRIBUTING.md | 12 +- README.md | 50 ++- docs/large-payload-verification.md | 172 ++++++++++ include/ppack.h | 53 ++-- include/ppack_platform.h | 19 +- meson.build | 21 +- src/ppack.c | 9 +- tests/compatibility/meson.build | 33 ++ tests/compatibility/meson_options.txt | 6 + tests/compatibility/test_legacy_compat.c | 147 +++++++++ tests/meson.build | 6 +- tests/test_large_payload.c | 387 +++++++++++++++++++++++ tests/test_payload_size.c | 21 +- tests/test_ppack_main.c | 4 +- 16 files changed, 944 insertions(+), 64 deletions(-) create mode 100644 docs/large-payload-verification.md create mode 100644 tests/compatibility/meson.build create mode 100644 tests/compatibility/meson_options.txt create mode 100644 tests/compatibility/test_legacy_compat.c create mode 100644 tests/test_large_payload.c diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 77ef2bc..df876e7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,24 +56,44 @@ jobs: - name: Test run: meson test -C build --verbose + - name: Compare with the unmodified 2.4.0 codec + run: | + # Pin the pre-extension source. Never replace it with the PR head. + legacy_commit=fecf8778423c353a54b7387aa0954887a75fbe49 + git fetch --no-tags --depth=1 origin "$legacy_commit" + mkdir -p "$RUNNER_TEMP/ppack-legacy" + git archive "$legacy_commit" include src | tar -x -C "$RUNNER_TEMP/ppack-legacy" + meson setup build_compat tests/compatibility \ + --buildtype=debug \ + "-Dlegacy_root=$RUNNER_TEMP/ppack-legacy" \ + -Db_sanitize=address,undefined \ + -Dc_args=-fsanitize=float-cast-overflow \ + -Dc_link_args=-fsanitize=float-cast-overflow + meson test -C build_compat --verbose + - name: Upload test log if: failure() uses: actions/upload-artifact@v4 with: name: testlog-${{ matrix.os }} - path: build/meson-logs/testlog.txt + path: | + build/meson-logs/testlog.txt + build_compat/meson-logs/testlog.txt # --------------------------------------------------------------------------- - # Exercise the PPACK_PAYLOAD_BITS override path. The library and tests - # must build and pass at the documented 512-bit ceiling (CAN-FD frame - # data field). Locks in that no future change accidentally hard-codes - # an assumption tying the convenience-macro buffer size to 64 bits. + # Exercise the buffer-size override at CAN-FD size and at the codec's + # maximum. Runtime sizes must remain independent of this default. # --------------------------------------------------------------------------- override-test: - name: "Override test (PPACK_PAYLOAD_BITS=512)" + name: "Override test (PPACK_PAYLOAD_BITS=${{ matrix.bits }})" runs-on: ubuntu-latest needs: test + strategy: + fail-fast: false + matrix: + bits: [512, 65528] + steps: - uses: actions/checkout@v4 @@ -87,13 +107,13 @@ jobs: - name: Install meson run: pip install meson - - name: Configure (debug + sanitizers + 512-bit override) + - name: Configure (debug + sanitizers + buffer-size override) run: > meson setup build --buildtype=debug -Dbuild_tests=true -Db_sanitize=address,undefined - "-Dc_args=-DPPACK_PAYLOAD_BITS=512 -fsanitize=float-cast-overflow" + "-Dc_args=-DPPACK_PAYLOAD_BITS=${{ matrix.bits }} -fsanitize=float-cast-overflow" -Dc_link_args=-fsanitize=float-cast-overflow - name: Build @@ -106,7 +126,7 @@ jobs: if: failure() uses: actions/upload-artifact@v4 with: - name: testlog-override + name: testlog-override-${{ matrix.bits }} path: build/meson-logs/testlog.txt # --------------------------------------------------------------------------- diff --git a/CHANGELOG.md b/CHANGELOG.md index f979ccf..e9a8a7c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,36 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +## [2.5.0] - 2026-09-08 + +### Changed + +- Raised the payload limit from 512 to 65,528 bits, or 8,191 logical octets. + The public `PPACK_MAX_PAYLOAD_BITS` constant defines the runtime and + compile-time maximum. The default buffer size remains 64 bits. +- Retained function signatures, field-descriptor layout, 32-bit field widths, + and the packed representation of existing fields. + +Callers must provide enough payload storage and enforce transport-specific +limits. Valid sizes above 512 bits no longer fail before buffer access. +The codec still permits partial output on errors. CRC, record publication, +and format-version policy remain the consumer's responsibility. + +### Fixed + +- Changed field-range validation to ordered subtraction. This prevents + malformed high offsets from wrapping the check on 16-bit `size_t` targets. + +### Added + +- Independent bit-at-a-time reference tests for every legal start/width pair, + every payload size, high-offset mixed types, and boundary value patterns. +- Guard, clearing, input-preservation, and malformed-geometry tests for both + native and simulated 16-bit-MAU storage. +- Compile-time configuration checks and a maximum-size CI override build. +- A [verification record](docs/large-payload-verification.md) with the range + argument, compatibility checks, and target-compilation scope. + ## [2.4.0] - 2026-07-03 ### Fixed diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7ee24c9..c8fd2e2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -15,7 +15,7 @@ meson setup build --buildtype=debug -Dbuild_tests=true \ meson compile -C build meson test -C build --verbose -# Coverage (CI gate is 80% line + 70% branch) +# Coverage (CI gate is 100% line + 100% branch) meson setup build_cov --buildtype=debug -Dbuild_tests=true \ -Db_coverage=true meson compile -C build_cov && meson test -C build_cov @@ -58,11 +58,15 @@ The library is analysed with `misch` (cppcheck-backed MISRA C:2023 analysis), co - Add a test for every new feature. - All tests must pass on both build configurations: 8-bit native and 16-bit MAU simulated (`-DPPACK_SIMULATE_16BIT_MAU`). -- CI enforces an 80% line / 70% branch coverage gate. New code without +- CI enforces a 100% line / 100% branch coverage gate. New code without tests will fail the coverage gate. - Tests live in `tests/test_*.c`. -- Fuzz seeds are fixed (`0xBEEF000N`) so failures are reproducible from - the test name alone. Do not introduce non-deterministic tests. +- Fuzz seeds are fixed and recorded in each test. Failures must be + reproducible from the test name alone. Do not use non-deterministic tests. + +For payload-size changes, also run the independent geometry sweep and the +legacy comparison. See [large-payload verification](docs/large-payload-verification.md) +for commands and the limits of these checks. ## Wire format and API stability diff --git a/README.md b/README.md index e68e908..2b7b72a 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ A generic payload serialisation library for bit-aligned data fields in C. ## Features - **Bit-aligned fields** - Fields can start at any bit position and span arbitrary bit ranges -- **Variable payload size** - Caller supplies the payload size in bits (multiple of 8, up to 512); supports CAN classic (64) and CAN-FD (up to 512) +- **Variable payload size** - Caller supplies a multiple of 8 bits, up to 65,528 bits. CAN classic and CAN-FD sizes remain supported. - **No dynamic memory** - Fixed-size operations, no `malloc` / `free` - **Deterministic WCET** - All operations have bounded execution time - **Scaled fields** - Linear scale/offset transformations for physical-unit encoding @@ -170,6 +170,37 @@ Or, if every payload in your project is 512 bits, set `ppack_byte_t payload[PPACK_PAYLOAD_UNITS]`. The runtime API still takes the size explicitly. +### Larger stored records + +Stored records can use up to `PPACK_MAX_PAYLOAD_BITS`, which is 65,528 bits +or 8,191 logical octets. Individual fields remain limited to 32 bits. +For example, a 1,024-bit record needs 128 payload storage units: + +```c +ppack_byte_t record[1024u / PPACK_ADDR_UNIT_BITS]; +int ret = ppack_pack(¶meters, record, 1024u, + parameter_fields, parameter_field_count); +``` + +Increasing `payload_bits` does not resize a buffer. Allocate at least +`payload_bits / 8` elements of `ppack_byte_t` before calling the codec. +Each logical octet occupies one 16-bit storage unit on a 16-bit MAU target. +The default `PPACK_PAYLOAD_BITS` remains 64. Do not allocate the maximum +on a small stack unless that space is available. + +The codec no longer rejects valid sizes above 512 bits. Callers must enforce +CAN-FD and other transport limits before calling it. Audit callers that relied +on the old rejection to protect a smaller buffer. + +The packed representation of existing fields does not change. The codec does +not provide CRC, schema versioning, or atomic record updates. Decode into a +temporary structure and publish it only after a successful return. On failure, +pack and unpack can leave partial output. Record-format changes still require +the consumer's version and recovery policy. + +See [large-payload verification](docs/large-payload-verification.md) for the +range argument, test coverage, and remaining caller obligations. + ## Building ```sh @@ -212,7 +243,10 @@ int ppack_unpack(void *base_ptr, const void *payload, size_t payload_bits, const struct ppack_field *fields, size_t field_count); ``` -`payload_bits` is the payload size in bits. Must be a positive multiple of `PPACK_ADDR_UNIT_BITS` (always 8) and no greater than 512 (CAN-FD frame data field). Common values: `64` for CAN classic, `512` for full CAN-FD frames. +`payload_bits` is the payload size in bits. It must be a positive multiple +of `PPACK_ADDR_UNIT_BITS`, which is always 8. The maximum is +`PPACK_MAX_PAYLOAD_BITS`, or 65,528. Common values are `64` for CAN classic +and `512` for full CAN-FD frames. The caller must enforce transport limits. ### Field Descriptor @@ -247,7 +281,7 @@ For `PPACK_BEHAVIOUR_SCALED` fields the struct member must always be `float`, re | Code | Value | Meaning | | -------------------- | ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `PPACK_SUCCESS` | 0 | Operation succeeded | -| `PPACK_ERR_INVALARG` | 1 | Invalid argument (NULL fields, zero field count, `bit_length` out of range, `payload_bits` zero or not a multiple of `PPACK_ADDR_UNIT_BITS` or > 512, scaling requested for `PPACK_TYPE_UINT8`) | +| `PPACK_ERR_INVALARG` | 1 | Invalid argument (NULL fields, zero field count, `bit_length` out of range, `payload_bits` zero or not a multiple of `PPACK_ADDR_UNIT_BITS` or > `PPACK_MAX_PAYLOAD_BITS`, scaling requested for `PPACK_TYPE_UINT8`) | | `PPACK_ERR_NOTFOUND` | 3 | Unknown field type | | `PPACK_ERR_NULLPTR` | 4 | NULL pointer passed for `base_ptr` or `payload` | | `PPACK_ERR_OVERFLOW` | 5 | `start_bit + bit_length > payload_bits`, or `scale == 0` on a `SCALED` field | @@ -256,7 +290,9 @@ Functions return the negated error code on failure (e.g. `-PPACK_ERR_NULLPTR`). ## Wire Format -The payload is `payload_bits` bits long (a multiple of 8, between 8 and 512), addressed as `payload_bits / 8` logical bytes numbered 0 to `payload_bits / 8 - 1`. +The payload contains `payload_bits` bits, a multiple of 8 between 8 and 65,528. +Its `payload_bits / 8` logical bytes are numbered from 0 to +`payload_bits / 8 - 1`. - **Bit numbering**: payload bit `N` lives in logical byte `N / 8`, at position `N mod 8` within that byte. - **Within a byte**: bit 0 is the least significant bit. @@ -338,7 +374,7 @@ All public APIs validate arguments at the function boundary. - Passing `NULL` for any pointer returns `-PPACK_ERR_NULLPTR`. - Passing `NULL` or an empty `fields` array returns `-PPACK_ERR_INVALARG`. -- A `payload_bits` argument that is zero, not a multiple of `PPACK_ADDR_UNIT_BITS`, or greater than 512 returns `-PPACK_ERR_INVALARG`. +- A `payload_bits` argument that is zero, not a multiple of 8, or greater than `PPACK_MAX_PAYLOAD_BITS` returns `-PPACK_ERR_INVALARG`. - A field with `bit_length == 0` or `bit_length > 32` returns `-PPACK_ERR_INVALARG`. - A field where `start_bit + bit_length > payload_bits` returns `-PPACK_ERR_OVERFLOW`. - A `PPACK_BEHAVIOUR_SCALED` field with `scale == 0.0` returns `-PPACK_ERR_OVERFLOW`. @@ -360,7 +396,7 @@ ppack is a serialisation primitive only. The following are explicitly out of sco - **No integrity checks**: no CRC, checksum, or framing. Caller (or the transport, e.g. the CAN frame CRC) is responsible for detecting bit errors. - **No schema versioning**: the field-descriptor layout is the schema. Maintain it in shared headers across nodes. -- **Payload size capped at 512 bits**: matches a full CAN-FD frame data field. Larger payloads require multiple ppack calls on chunks. +- **Payload size capped at 65,528 bits**: the bound retains 16-bit bit indices and supports targets with 16-bit `size_t`. - **No multi-buffer / streaming API**: a single payload is processed in one call. - **No runtime endianness adaptation**: the wire format is little-endian. Big-endian hosts would need explicit byte swapping at the boundary (no such host is currently a target). @@ -370,7 +406,7 @@ ppack is a serialisation primitive only. The following are explicitly out of sco | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Memory** | All operations use stack memory; no dynamic allocation | | **MISRA C:2023** | Audited with `misch` (cppcheck-backed MISRA C:2023 analysis; configuration in `misra.toml`); the audit reports zero findings. Deviations are justified at point of use with `cppcheck-suppress ... @deviation` comments, or project-wide in `misra-deviations.txt`. The only required-rule deviations are three Rule 21.15 sites: the type-erased struct-member copies centralised in two internal helpers, and the deliberate F32 `float`/`uint32_t` pun. Design follows MISRA principles throughout: no dynamic allocation, no UB shifts, explicit error codes, `memcpy`-based type punning. | -| **Payload size** | Caller-supplied via `payload_bits` (multiple of 8, between 8 and 512). 64 matches CAN classic; 512 matches full CAN-FD. | +| **Payload size** | Caller-supplied via `payload_bits`, a multiple of 8 between 8 and 65,528. The default buffer size remains 64 bits. | | **Bit ordering** | LSB-first within each byte; multi-byte fields little-endian; fields may span byte boundaries | | **Field size** | 1-32 bits per field | | **Thread safety** | Not thread-safe; caller must provide mutual exclusion when `base_ptr` or `payload` is shared across threads or ISRs | diff --git a/docs/large-payload-verification.md b/docs/large-payload-verification.md new file mode 100644 index 0000000..6f1f291 --- /dev/null +++ b/docs/large-payload-verification.md @@ -0,0 +1,172 @@ +# Large-payload verification + +Version 2.5.0 raises the payload limit from 512 to 65,528 bits. +The change addresses [ppack #6](https://github.com/aajll/ppack/issues/6). +The consumer request is +[pebb-firmware #178](https://github.com/Next-Gen-MP/pebb-firmware/issues/178). + +## Scope + +The function signatures and `struct ppack_field` layout do not change. +The default buffer size remains 64 bits. Fields remain 1 to 32 bits wide. +The bit-copy loops, integer conversions, floating-point conversions, and +field ordering do not change. + +The implementation uses one public maximum for runtime and compile-time +validation. Field validation checks the start before subtracting it from +the payload size. This prevents an overflowing start-plus-length sum on +targets with 16-bit `size_t`. + +Valid sizes above 512 bits now reach buffer access. This intentionally changes +the old oversized-input rejection behavior. Callers must allocate sufficient +storage and enforce their own transport limits. + +## Range argument + +These bounds apply after successful payload and field validation: + +1. The payload size is a multiple of eight in the range 8 to 65,528. +2. The field width is in the range 1 to 32. +3. The start is no greater than the payload size. +4. The field width is no greater than the payload size minus the start. + +The subtraction cannot underflow because condition 3 is checked first. +It remains valid when `size_t` has only 16 bits. + +Together, the conditions imply that every accessed bit is between 0 and +65,527. The `uint16_t` bit-index additions cannot wrap for accepted fields. +The largest logical-octet index is 8,190. + +Each loop iteration processes between one and eight bits. A 32-bit field +requires at most five iterations. Value shifts remain below 32, regardless +of the absolute field position. The larger payload does not widen a field +or change its packed representation. + +Packing clears at most 8,191 payload storage units. On a real 16-bit-MAU +target, each logical octet occupies one 16-bit C addressable unit. +The host simulation uses two 8-bit C addressable units per logical octet. +Even that clearing count fits within a 16-bit `size_t`. + +This is a code-level range argument, not a machine-checked formal proof. +It assumes valid caller-owned buffers, accessible descriptors, and correct +structure offsets and member types. + +## Persistent tests + +`tests/test_large_payload.c` contains an independent bit-at-a-time model. +It does not use ppack's bit-index or bit-copy helpers. Pack results are +compared with reference bytes. Unpack consumes separately constructed +reference bytes, including nonzero bits outside the selected field. + +Each native or simulated-storage run checks: + +- All 2,096,400 legal start-position and field-width pairs, with deterministic + pseudorandom values and the smallest payload that contains each field. +- All 8,191 legal payload sizes, with a field ending at the payload boundary. +- Every source-bit position, zero, ones, and alternating patterns at every + alignment near the old limit, high offsets, and the new limit. +- Every supported raw and scaled type in large, unaligned multi-field layouts. +- Buffer guards, complete clearing from nonzero contents, unpack input + preservation, and untouched destination neighbors. +- Invalid sizes and widths, exact-end overflow, starts beyond the payload, + and malformed descriptors near `UINT16_MAX`. +- Preservation of a 496-bit prefix when fields are appended beyond bit 512. + +The existing golden-byte fixtures remain unchanged. Meson also checks valid +and invalid `PPACK_PAYLOAD_BITS` definitions during test configuration. +CI runs the default buffer size and overrides of 512 and 65,528 bits. + +### Legacy comparison + +`tests/compatibility` builds the current and unmodified 2.4.0 implementations +into one test process under separate function names. It compares exact pack +bytes and unpacked member representations from independent input payloads. + +The test covers every legacy payload size, legal start and width, seven raw +types, and four scaled types. Each storage model checks 5,512,760 cases. +Values use a fixed pseudorandom seed. This is not exhaustive over all values +or multi-field descriptor combinations. + +CI pins the old source to `fecf8778423c353a54b7387aa0954887a75fbe49`. +It runs both storage models on Linux and macOS with sanitizers. +To reproduce from the repository root: + +```sh +legacy_dir=$(mktemp -d) +git archive fecf8778423c353a54b7387aa0954887a75fbe49 include src | + tar -x -C "$legacy_dir" +meson setup build_compat tests/compatibility \ + --buildtype=debug "-Dlegacy_root=$legacy_dir" \ + -Db_sanitize=address,undefined \ + -Dc_args=-fsanitize=float-cast-overflow \ + -Dc_link_args=-fsanitize=float-cast-overflow +meson test -C build_compat --verbose +``` + +Keep the extracted legacy source until the build directory is no longer +needed. A shallow checkout must fetch the pinned commit first. + +## Local verification record + +The following checks passed during development on 2026-09-08: + +| Check | Result | +| --- | --- | +| GCC 14.2, ASan, UBSan, float-cast-overflow | Native and simulated-storage suites pass | +| Maximum default-buffer override | Both storage models pass at 65,528 bits | +| Exact comparison with 2.4.0 | 5,512,760 cases pass per storage model | +| GCC coverage | 229/229 lines and 108/108 branches | +| `misch run`, version 0.4.0 | Zero findings, no new deviations | +| `misch deviations` | All deviations justified and valid | +| TI C2000 22.6.2.LTS and 25.11.1.LTS | Release library compilation passes with default and maximum buffer definitions | +| GCC release library | Builds successfully | + +The TI builds used C11, C28x large/unified memory, EABI, and FPU32. +They did not enable relaxed floating-point mode. The cross-file settings were: + +```ini +[binaries] +c = '/path/to/ti-cgt-c2000/bin/cl2000' +ar = '/path/to/ti-cgt-c2000/bin/ar2000' + +[host_machine] +system = 'none' +cpu_family = 'c2000' +cpu = 'c28x' +endian = 'little' + +[properties] +needs_exe_wrapper = true + +[built-in options] +c_args = ['--c11', '-v28', '-ml', '-mt', '--float_support=fpu32', + '--abi=eabi', '--diag_warning=225', '--display_error_number', + '--diag_wrap=off', '-I/path/to/ti-cgt-c2000/include'] +``` + +Use absolute toolchain paths. Add `-DPPACK_PAYLOAD_BITS=65528` to `c_args` +for the maximum-buffer check. Build each configuration with Meson: + +```sh +meson setup build_target --cross-file /path/to/cross.ini \ + --buildtype=release -Dbuild_tests=false +meson compile -C build_target +``` + +No target hardware or instruction-set simulator was available for execution. +Target compilation does not establish target runtime correctness. Host MAU +simulation does not reproduce target integer promotions or `size_t` width. +The range argument covers the intended 16-bit arithmetic constraints, but +consumer testing on the actual target remains necessary. + +## Consumer obligations + +The codec cannot validate the allocation size behind a pointer. The caller +must supply at least `payload_bits / 8` elements of `ppack_byte_t` and valid +structure offsets. Increasing the runtime size does not resize a buffer. + +Pack and unpack can leave partial output after an error. A record manager +must decode into temporary storage and publish only after success. It must +also retain whole-record CRC, redundant-copy selection, and atomic commits. +New stored fields still need the consumer's format-version and recovery +policy. Extending ppack alone does not verify those firmware behaviors. diff --git a/include/ppack.h b/include/ppack.h index 14fbe15..8977c42 100644 --- a/include/ppack.h +++ b/include/ppack.h @@ -51,11 +51,11 @@ extern "C" { * * @details * The ppack library serialises and deserialises C structures into a - * variable-size payload (any multiple of 8 bits, up to 512 bits) + * variable-size payload (any multiple of 8 bits, up to 65528 bits) * using arbitrary bit-aligned field descriptors. It supports * @c uint8_t, @c uint16_t, @c int16_t, @c uint32_t, @c int32_t, - * IEEE-754 @c float, and raw bitfields up to 32 bits wide. The - * 512-bit ceiling matches the maximum CAN-FD frame data field. + * IEEE-754 @c float, and raw bitfields up to 32 bits wide. + * Transport-specific limits must be checked by the caller. * * The payload size is supplied at the call site via the * @c payload_bits argument; classic 8-byte CAN payloads use @@ -88,11 +88,12 @@ extern "C" { * explicit byte swapping in user code. * * Declare the payload buffer as @c ppack_byte_t - * payload[PPACK_PAYLOAD_UNITS]. This model works on all MAU sizes. The @c - * PPACK_PAYLOAD_UNITS macro declares a 64-bit payload by default (8 bytes or - * four 16-bit words). Override @c PPACK_PAYLOAD_BITS at the toolchain level for - * other sizes (for example, @c -DPPACK_PAYLOAD_BITS=512). The runtime API takes - * the size as an explicit argument. + * payload[PPACK_PAYLOAD_UNITS]. This model works on all MAU sizes. + * The macro declares a 64-bit payload by default: eight storage units + * on both 8-bit and 16-bit MAU targets. Override @c PPACK_PAYLOAD_BITS + * for other sizes, or declare @c ppack_byte_t payload[N / 8u] and pass + * N as the runtime size. Increasing the runtime size does not resize + * the buffer. The caller must provide sufficient storage. * * ## Scaled-field semantics * @@ -212,6 +213,15 @@ enum ppack_behaviour { /** * @brief Describes a field within a payload. * + * @details + * - ::ppack_field::type Data type of the field. + * - ::ppack_field::start_bit Starting bit position (0..payload_bits-1). + * - ::ppack_field::bit_length Number of bits (1-32). + * - ::ppack_field::ptr_offset Offset from offsetof() into the base structure. + * - ::ppack_field::scale Scaling factor, ignored for F32 and BITS. + * - ::ppack_field::offset Offset after scaling, ignored for F32 and BITS. + * - ::ppack_field::behaviour Raw or scaled mode, see ppack_behaviour. + * * @note Set @c bit_length to match the natural width of @c type. * The library accepts larger values (it enforces * @c bit_length <= 32 and @@ -228,13 +238,12 @@ enum ppack_behaviour { * native C type implied by @c type (see @c ppack_type). */ struct ppack_field { - enum ppack_type type; /**< Data type of the field */ - uint16_t start_bit; /**< Starting bit position (0..payload_bits-1) */ - uint16_t bit_length; /**< Number of bits (1-32) */ - size_t ptr_offset; /**< Offset returned by offsetof() into base */ - float scale; /**< Scaling factor (ignored for F32 / BITS) */ - float offset; /**< Offset after scaling (ignored for F32 / BITS) */ - /** Raw or scaled (see @c ppack_behaviour) */ + enum ppack_type type; + uint16_t start_bit; + uint16_t bit_length; + size_t ptr_offset; + float scale; + float offset; enum ppack_behaviour behaviour; }; @@ -263,7 +272,7 @@ struct ppack_field { * for non-default sizes. * @param[in] payload_bits Payload size in bits. Must be a positive * multiple of @c PPACK_ADDR_UNIT_BITS and no - * greater than 512 (CAN-FD frame data field). + * greater than @c PPACK_MAX_PAYLOAD_BITS. * @param[in] fields Array of field descriptors * @param[in] field_count Number of fields * @@ -273,8 +282,9 @@ struct ppack_field { * @c field_count is 0, @c fields is NULL, * @c payload_bits is 0, @c payload_bits is not * a multiple of @c PPACK_ADDR_UNIT_BITS, - * @c payload_bits exceeds 512, @c bit_length is 0 - * or greater than 32, scaling is set for + * @c payload_bits exceeds the maximum, + * @c bit_length is 0 or greater than 32, + * scaling is set for * @c PPACK_TYPE_UINT8, or a SCALED field * produces a NaN result. * @return -PPACK_ERR_OVERFLOW when @c start_bit plus bit_length exceeds @@ -315,7 +325,7 @@ int ppack_pack(const void *base_ptr, void *payload, size_t payload_bits, * for non-default sizes. * @param[in] payload_bits Payload size in bits. Must be a positive * multiple of @c PPACK_ADDR_UNIT_BITS and no - * greater than 512. + * greater than @c PPACK_MAX_PAYLOAD_BITS. * @param[in] fields Array of field descriptors * @param[in] field_count Number of fields * @@ -325,8 +335,9 @@ int ppack_pack(const void *base_ptr, void *payload, size_t payload_bits, * @c field_count is 0, @c fields is NULL, * @c payload_bits is 0, @c payload_bits is not * a multiple of @c PPACK_ADDR_UNIT_BITS, - * @c payload_bits exceeds 512, @c bit_length is 0 - * or greater than 32, or scaling is set for + * @c payload_bits exceeds the maximum, + * @c bit_length is 0 or greater than 32, + * or scaling is set for * @c PPACK_TYPE_UINT8. * @return -PPACK_ERR_OVERFLOW if @c start_bit + bit_length exceeds * @c payload_bits diff --git a/include/ppack_platform.h b/include/ppack_platform.h index f2c23be..f3d22af 100644 --- a/include/ppack_platform.h +++ b/include/ppack_platform.h @@ -27,7 +27,7 @@ * * The library's wire format is identical across both addressing * models: a sequence of N bits (where N is the @c payload_bits - * argument, a multiple of 8 between 8 and 512), with bit 0 + * argument, a multiple of 8 between 8 and 65528), with bit 0 * corresponding to the least significant bit of the first logical * 8-bit byte. See the "Wire format" section in the README for the * full contract. @@ -83,6 +83,16 @@ typedef uint8_t ppack_byte_t; */ typedef ppack_byte_t ppack_u8_t; +/** + * @brief Maximum payload size in bits: 8191 logical octets. + * + * This is the largest multiple of 8 representable in uint16_t. + * It keeps payload sizes representable with 16-bit size_t and valid + * bit positions within the uint16_t indices used by the codec. + * This limit does not set the default buffer size or a transport limit. + */ +#define PPACK_MAX_PAYLOAD_BITS 65528u + /** * @brief Default payload size in bits for @c PPACK_PAYLOAD_UNITS * (defined in @c ppack.h). @@ -90,7 +100,7 @@ typedef ppack_byte_t ppack_u8_t; * Override at the toolchain level (for example, @c -DPPACK_PAYLOAD_BITS=128) * to declare stack buffers of a different size. * The value must be a positive multiple of @c PPACK_ADDR_UNIT_BITS - * and no greater than 512. + * and no greater than @c PPACK_MAX_PAYLOAD_BITS. * * The runtime API takes the payload size as an explicit argument. */ @@ -132,9 +142,8 @@ _Static_assert((PPACK_PAYLOAD_BITS > 0u) "PPACK_PAYLOAD_BITS must be a positive multiple of " "PPACK_ADDR_UNIT_BITS"); -_Static_assert(PPACK_PAYLOAD_BITS <= 512u, - "PPACK_PAYLOAD_BITS must be at most 512 " - "(CAN-FD frame data field ceiling)"); +_Static_assert(PPACK_PAYLOAD_BITS <= PPACK_MAX_PAYLOAD_BITS, + "PPACK_PAYLOAD_BITS must be at most 65528"); _Static_assert(sizeof(float) == sizeof(uint32_t), "ppack requires a 32-bit float " diff --git a/meson.build b/meson.build index 028afd1..efc8692 100644 --- a/meson.build +++ b/meson.build @@ -1,7 +1,7 @@ project( 'ppack', 'c', - version: '2.4.0', + version: '2.5.0', default_options: [ 'c_std=c11', 'warning_level=3', @@ -60,6 +60,25 @@ ppack_dep = declare_dependency( # === Host unit tests ========================================================== if get_option('build_tests') + # Check header configuration separately from the runtime size checks. + cc = meson.get_compiler('c') + foreach bits : ['8', '512', '65528'] + assert(cc.compiles( + '#include "ppack.h"', + include_directories: public_headers, + args: ['-UPPACK_PAYLOAD_BITS', '-DPPACK_PAYLOAD_BITS=' + bits], + name: 'valid default payload size ' + bits, + ), 'Valid PPACK_PAYLOAD_BITS rejected: ' + bits) + endforeach + foreach bits : ['0', '7', '65529', '65536'] + assert(not cc.compiles( + '#include "ppack.h"', + include_directories: public_headers, + args: ['-UPPACK_PAYLOAD_BITS', '-DPPACK_PAYLOAD_BITS=' + bits], + name: 'invalid default payload size ' + bits, + ), 'Invalid PPACK_PAYLOAD_BITS accepted: ' + bits) + endforeach + # Second build of the library with the 16-bit MAU simulation flag, so the # test binary linking against it actually exercises the word-addressable # code path end-to-end (including ppack_u8_t sizing inside the library). diff --git a/src/ppack.c b/src/ppack.c index abdbf5a..840a5be 100644 --- a/src/ppack.c +++ b/src/ppack.c @@ -31,9 +31,6 @@ /* ================ DEFINES ================================================= */ -/** Maximum supported payload size in bits (CAN-FD frame data field). */ -#define PPACK_MAX_PAYLOAD_BITS 512u - /** Maximum supported field width in bits. */ #define PPACK_MAX_FIELD_BITS 32u @@ -249,7 +246,11 @@ validate_field(const struct ppack_field *f, size_t payload_bits) if ((f->bit_length == 0u) || (f->bit_length > PPACK_MAX_FIELD_BITS)) { return -PPACK_ERR_INVALARG; } - if ((size_t)f->start_bit + (size_t)f->bit_length > payload_bits) { + /* Check the start before subtracting. Adding start and length can + * wrap when size_t is 16 bits, even for a small payload. */ + if (((size_t)f->start_bit > payload_bits) + || ((size_t)f->bit_length + > (payload_bits - (size_t)f->start_bit))) { return -PPACK_ERR_OVERFLOW; } return PPACK_SUCCESS; diff --git a/tests/compatibility/meson.build b/tests/compatibility/meson.build new file mode 100644 index 0000000..2c65a0a --- /dev/null +++ b/tests/compatibility/meson.build @@ -0,0 +1,33 @@ +# Optional side-by-side comparison. Supply an unmodified legacy checkout. +project('ppack-legacy-comparison', 'c', default_options: ['c_std=c11']) + +legacy_root = get_option('legacy_root') +assert(legacy_root != '', 'Set -Dlegacy_root to an absolute legacy source path') +current_root = '../..' +current_headers = include_directories(current_root / 'include') +legacy_headers = include_directories(legacy_root / 'include') + +foreach simulate : [false, true] + suffix = simulate ? '-sim' : '-native' + flags = simulate ? ['-DPPACK_SIMULATE_16BIT_MAU'] : [] + legacy = static_library( + 'legacy' + suffix, + legacy_root / 'src' / 'ppack.c', + include_directories: legacy_headers, + c_args: flags + ['-Dppack_pack=legacy_pack', '-Dppack_unpack=legacy_unpack'], + ) + current = static_library( + 'current' + suffix, + current_root / 'src' / 'ppack.c', + include_directories: current_headers, + c_args: flags, + ) + exe = executable( + 'compare' + suffix, + 'test_legacy_compat.c', + include_directories: [current_headers, include_directories('..')], + c_args: flags, + link_with: [legacy, current], + ) + test('legacy comparison' + suffix, exe, timeout: 120) +endforeach diff --git a/tests/compatibility/meson_options.txt b/tests/compatibility/meson_options.txt new file mode 100644 index 0000000..5d72347 --- /dev/null +++ b/tests/compatibility/meson_options.txt @@ -0,0 +1,6 @@ +option( + 'legacy_root', + type: 'string', + value: '', + description: 'Absolute path to an unmodified legacy ppack source tree', +) diff --git a/tests/compatibility/test_legacy_compat.c b/tests/compatibility/test_legacy_compat.c new file mode 100644 index 0000000..98a2211 --- /dev/null +++ b/tests/compatibility/test_legacy_compat.c @@ -0,0 +1,147 @@ +/* + * @file: test_legacy_compat.c + * @brief Compare valid legacy geometry against an unmodified old codec. + * + * This checks exact pack bytes and independently generated input to unpack. + * Every legal legacy size, start and width is exercised for all seven raw + * types and four scaled types. Values use a fixed xorshift32 seed. + */ + +#include "ppack.h" +#include "test_harness.h" +#include +#include + +int legacy_pack(const void *, void *, size_t, const struct ppack_field *, + size_t); +int legacy_unpack(void *, const void *, size_t, const struct ppack_field *, + size_t); + +union value { + ppack_u8_t u8; + uint16_t u16; + int16_t s16; + uint32_t u32; + int32_t s32; + float f32; +}; + +static uint32_t state = 0xBEEF2001u; +static uint32_t +next(void) +{ + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + return state; +} + +int +main(void) +{ + size_t cases = 0; + for (size_t bits = 8; bits <= 512; bits += 8) { + for (uint16_t width = 1; width <= 32 && width <= bits; + ++width) { + for (uint16_t start = 0; (size_t)start + width <= bits; + ++start) { + for (uint32_t mode = 0; mode < 11; ++mode) { + struct ppack_field field = { + .start_bit = start, + .bit_length = width, + .ptr_offset = 0, + .scale = 0.5f, + .offset = 1.0f, + .behaviour = PPACK_BEHAVIOUR_RAW, + }; + uint32_t r = next(); + union value src = {0}; + size_t member_size; + switch (mode) { + case 0: + field.type = PPACK_TYPE_UINT8; + src.u8 = (ppack_u8_t)r; + member_size = sizeof(src.u8); + break; + case 1: + field.type = PPACK_TYPE_UINT16; + src.u16 = (uint16_t)r; + member_size = sizeof(src.u16); + break; + case 2: + field.type = PPACK_TYPE_INT16; + src.s16 = (int16_t)r; + member_size = sizeof(src.s16); + break; + case 3: + field.type = PPACK_TYPE_UINT32; + src.u32 = r; + member_size = sizeof(src.u32); + break; + case 4: + field.type = PPACK_TYPE_INT32; + src.s32 = (int32_t)r; + member_size = sizeof(src.s32); + break; + case 5: + field.type = PPACK_TYPE_F32; + memcpy(&src.f32, &r, sizeof(r)); + member_size = sizeof(src.f32); + break; + case 6: + field.type = PPACK_TYPE_BITS; + src.u32 = r; + member_size = sizeof(src.u32); + break; + default: + field.type = + (mode == 7) + ? PPACK_TYPE_UINT16 + : (mode == 8) + ? PPACK_TYPE_INT16 + : (mode == 9) + ? PPACK_TYPE_UINT32 + : PPACK_TYPE_INT32; + field.behaviour = + PPACK_BEHAVIOUR_SCALED; + src.f32 = + (float)(int32_t)r / 32.0f; + member_size = sizeof(src.f32); + break; + } + ppack_byte_t old[64], current[64], + input[64]; + TEST_ASSERT(legacy_pack(&src, old, bits, + &field, 1) + == 0); + TEST_ASSERT(ppack_pack(&src, current, + bits, &field, 1) + == 0); + TEST_ASSERT( + memcmp(old, current, + bits / 8 * sizeof(old[0])) + == 0); + for (size_t i = 0; i < bits / 8; ++i) { + input[i] = (ppack_byte_t)next(); + } + union value a, b; + memset(&a, 0xA5, sizeof(a)); + memset(&b, 0xA5, sizeof(b)); + TEST_ASSERT(legacy_unpack(&a, input, + bits, &field, + 1) + == 0); + TEST_ASSERT(ppack_unpack(&b, input, + bits, &field, + 1) + == 0); + TEST_ASSERT(memcmp(&a, &b, member_size) + == 0); + ++cases; + } + } + } + } + printf("Exact legacy comparison: %zu pack/unpack cases passed\n", + cases); +} diff --git a/tests/meson.build b/tests/meson.build index 8c8d69d..25cc478 100644 --- a/tests/meson.build +++ b/tests/meson.build @@ -19,6 +19,7 @@ test_sources = [ 'test_partial_coverage.c', 'test_payload_size.c', 'test_mau_layout.c', + 'test_large_payload.c', ] test_exe = executable( @@ -28,7 +29,8 @@ test_exe = executable( include_directories: public_headers, ) -test('ppack 8-bit native', test_exe) +# The geometry sweep covers over two million start/width pairs per model. +test('ppack 8-bit native', test_exe, timeout: 120) test_16bit_exe = executable( 'test_ppack_16bit', @@ -37,4 +39,4 @@ test_16bit_exe = executable( include_directories: public_headers, ) -test('ppack 16-bit simulated', test_16bit_exe) +test('ppack 16-bit simulated', test_16bit_exe, timeout: 120) diff --git a/tests/test_large_payload.c b/tests/test_large_payload.c new file mode 100644 index 0000000..47275a8 --- /dev/null +++ b/tests/test_large_payload.c @@ -0,0 +1,387 @@ +/* + * @file: test_large_payload.c + * @brief Large-payload checks against an independent bit-at-a-time model. + * + * The reference code uses logical octets directly. It must not call the + * codec's index, mask, read or write helpers. Pack and unpack are checked + * separately so matching codec errors cannot hide behind a round trip. + */ + +#include "ppack.h" +#include "test_fuzz.h" +#include "test_harness.h" +#include +#include +#include + +#define MAX_UNITS (PPACK_MAX_PAYLOAD_BITS / 8u) +#define GUARD ((ppack_byte_t)0xA5u) + +static void +reference_write(ppack_byte_t *wire, uint32_t start, uint16_t width, + uint32_t value) +{ + for (uint32_t bit = 0; bit < width; ++bit) { + uint32_t position = start + bit; + ppack_byte_t mask = (ppack_byte_t)(1u << (position % 8u)); + if (((value >> bit) & 1u) != 0u) { + wire[position / 8u] |= mask; + } else { + wire[position / 8u] &= (ppack_byte_t)~mask; + } + } +} + +static uint32_t +reference_read(const ppack_byte_t *wire, uint32_t start, uint16_t width) +{ + uint32_t value = 0; + for (uint32_t bit = 0; bit < width; ++bit) { + uint32_t position = start + bit; + if ((wire[position / 8u] & (1u << (position % 8u))) != 0u) { + value |= UINT32_C(1) << bit; + } + } + return value; +} + +static void +check_raw(size_t bits, uint16_t start, uint16_t width, uint32_t value) +{ + /* Static host-test storage avoids large per-call stack frames. */ + static ppack_byte_t guarded[MAX_UNITS + 2u]; + static ppack_byte_t expected[MAX_UNITS]; + size_t units = bits / 8u; + size_t bytes = units * sizeof(ppack_byte_t); + ppack_byte_t *payload = &guarded[1]; + struct ppack_field field = { + .type = PPACK_TYPE_BITS, + .start_bit = start, + .bit_length = width, + .ptr_offset = 0, + .behaviour = PPACK_BEHAVIOUR_RAW, + }; + + memset(payload, 0xFF, bytes); + guarded[0] = GUARD; + guarded[units + 1u] = GUARD; + memset(expected, 0, bytes); + reference_write(expected, start, width, value); + TEST_ASSERT(ppack_pack(&value, payload, bits, &field, 1) + == PPACK_SUCCESS); + TEST_ASSERT(memcmp(payload, expected, bytes) == 0); + TEST_ASSERT(guarded[0] == GUARD); + TEST_ASSERT(guarded[units + 1u] == GUARD); + + /* Decode reference bytes with nonzero gaps, not the packed result. + * The high storage bits also start nonzero in the MAU simulation. */ + memset(expected, 0xFF, bytes); + reference_write(expected, start, width, value); + memcpy(payload, expected, bytes); + uint32_t out[3] = {UINT32_C(0x12345678), 0, UINT32_C(0x87654321)}; + TEST_ASSERT(ppack_unpack(&out[1], payload, bits, &field, 1) + == PPACK_SUCCESS); + TEST_ASSERT(out[1] == reference_read(expected, start, width)); + TEST_ASSERT(out[0] == UINT32_C(0x12345678)); + TEST_ASSERT(out[2] == UINT32_C(0x87654321)); + TEST_ASSERT(memcmp(payload, expected, bytes) == 0); + TEST_ASSERT(guarded[0] == GUARD); + TEST_ASSERT(guarded[units + 1u] == GUARD); +} + +TEST_CASE(test_large_every_field_geometry) +{ + /* Every legal start/width pair, including all eight alignments. + * Each uses the smallest legal payload that contains the field. + * Wider loop counters cannot wrap at the uint16_t limit. */ + fuzz_seed(0xBEEF1001u); + for (uint32_t start = 0; start < PPACK_MAX_PAYLOAD_BITS; ++start) { + for (uint16_t width = 1; width <= 32u; ++width) { + uint32_t end = start + width; + if (end <= PPACK_MAX_PAYLOAD_BITS) { + size_t bits = (size_t)((end + 7u) & ~7u); + check_raw(bits, (uint16_t)start, width, + fuzz_next()); + } + } + } +} + +TEST_CASE(test_large_basis_patterns) +{ + /* Values are independent of geometry in the codec. Exercise every + * source bit at each alignment near old and new size boundaries. */ + static const uint16_t bases[] = {0, 504, 1016, 32760, 65488}; + for (size_t i = 0; i < sizeof(bases) / sizeof(bases[0]); ++i) { + for (uint16_t alignment = 0; alignment < 8u; ++alignment) { + uint16_t start = bases[i] + alignment; + for (uint16_t width = 1; width <= 32u; ++width) { + check_raw(PPACK_MAX_PAYLOAD_BITS, start, width, + 0); + check_raw(PPACK_MAX_PAYLOAD_BITS, start, width, + UINT32_MAX); + check_raw(PPACK_MAX_PAYLOAD_BITS, start, width, + UINT32_C(0xAAAAAAAA)); + check_raw(PPACK_MAX_PAYLOAD_BITS, start, width, + UINT32_C(0x55555555)); + for (uint16_t bit = 0; bit < width; ++bit) { + uint32_t value = UINT32_C(1) << bit; + check_raw(PPACK_MAX_PAYLOAD_BITS, start, + width, value); + check_raw(PPACK_MAX_PAYLOAD_BITS, start, + width, ~value); + } + } + } + } +} + +TEST_CASE(test_large_each_payload_size) +{ + /* Test every legal size with an exact-end field. Adjacent guard + * units detect too much clearing. Nonzero fill detects too little. */ + for (uint32_t bits = 8; bits <= PPACK_MAX_PAYLOAD_BITS; bits += 8u) { + uint16_t width = (bits < 32u) ? (uint16_t)bits : 32u; + uint16_t start = (uint16_t)(bits - width); + check_raw((size_t)bits, start, width, UINT32_C(0xDEADBEEF)); + } +} + +TEST_CASE(test_large_invalid_sizes_and_geometry) +{ + static ppack_byte_t payload[MAX_UNITS + 1u]; + uint32_t value = UINT32_C(0xDEADBEEF); + struct ppack_field field = { + .type = PPACK_TYPE_BITS, + .start_bit = 0, + .bit_length = 1, + .ptr_offset = 0, + .behaviour = PPACK_BEHAVIOUR_RAW, + }; + const size_t invalid_sizes[] = { + 0, + 1, + 7, + 513, + PPACK_MAX_PAYLOAD_BITS - 1u, + (size_t)PPACK_MAX_PAYLOAD_BITS + 1u, + (size_t)PPACK_MAX_PAYLOAD_BITS + 8u, + SIZE_MAX, + }; + for (size_t i = 0; i < sizeof(invalid_sizes) / sizeof(invalid_sizes[0]); + ++i) { + /* Tiny actual storage proves size rejection comes first. */ + ppack_byte_t tiny = GUARD; + uint32_t out = value; + TEST_ASSERT( + ppack_pack(&value, &tiny, invalid_sizes[i], &field, 1) + == -PPACK_ERR_INVALARG); + TEST_ASSERT(tiny == GUARD); + TEST_ASSERT( + ppack_unpack(&out, &tiny, invalid_sizes[i], &field, 1) + == -PPACK_ERR_INVALARG); + TEST_ASSERT(out == value); + TEST_ASSERT(tiny == GUARD); + } + + const uint16_t invalid_widths[] = {0, 33, UINT16_MAX}; + for (size_t i = 0; + i < sizeof(invalid_widths) / sizeof(invalid_widths[0]); ++i) { + field.bit_length = invalid_widths[i]; + uint32_t out = value; + TEST_ASSERT(ppack_pack(&value, payload, PPACK_MAX_PAYLOAD_BITS, + &field, 1) + == -PPACK_ERR_INVALARG); + TEST_ASSERT(ppack_unpack(&out, payload, PPACK_MAX_PAYLOAD_BITS, + &field, 1) + == -PPACK_ERR_INVALARG); + TEST_ASSERT(out == value); + } + + const size_t sizes[] = {8, 64, 512, 520, 1024, PPACK_MAX_PAYLOAD_BITS}; + for (size_t i = 0; i < sizeof(sizes) / sizeof(sizes[0]); ++i) { + const uint16_t starts[] = { + (uint16_t)(sizes[i] - 1u), + (uint16_t)sizes[i], + (uint16_t)(sizes[i] + 1u), + UINT16_MAX - 15u, + UINT16_MAX, + }; + for (size_t j = 0; j < sizeof(starts) / sizeof(starts[0]); + ++j) { + field.start_bit = starts[j]; + field.bit_length = 32; + uint32_t out = value; + payload[sizes[i] / 8u] = GUARD; + TEST_ASSERT( + ppack_pack(&value, payload, sizes[i], &field, 1) + == -PPACK_ERR_OVERFLOW); + TEST_ASSERT( + ppack_unpack(&out, payload, sizes[i], &field, 1) + == -PPACK_ERR_OVERFLOW); + TEST_ASSERT(out == value); + TEST_ASSERT(payload[sizes[i] / 8u] == GUARD); + } + } +} + +TEST_CASE(test_large_mixed_types) +{ + struct sample { + ppack_u8_t u8; + uint16_t u16; + int16_t s16; + uint32_t u32; + int32_t s32; + float f32; + uint32_t bits; + float scaled_u16; + float scaled_s16; + float scaled_u32; + float scaled_s32; + }; + const struct sample source = { + .u8 = 0x5A, + .u16 = 0x1234, + .s16 = -1234, + .u32 = UINT32_C(0x12345678), + .s32 = -1234567, + .f32 = 1.0f, + .bits = UINT32_C(0xDEADBEEF), + .scaled_u16 = 42.5f, + .scaled_s16 = -10.5f, + .scaled_u32 = 42.5f, + .scaled_s32 = -10.5f, + }; + struct ppack_field fields[] = { + {PPACK_TYPE_UINT8, 0, 7, offsetof(struct sample, u8), 0, 0, + PPACK_BEHAVIOUR_RAW}, + {PPACK_TYPE_UINT16, 0, 13, offsetof(struct sample, u16), 0, 0, + PPACK_BEHAVIOUR_RAW}, + {PPACK_TYPE_INT16, 0, 15, offsetof(struct sample, s16), 0, 0, + PPACK_BEHAVIOUR_RAW}, + {PPACK_TYPE_UINT32, 0, 29, offsetof(struct sample, u32), 0, 0, + PPACK_BEHAVIOUR_RAW}, + {PPACK_TYPE_INT32, 0, 31, offsetof(struct sample, s32), 0, 0, + PPACK_BEHAVIOUR_RAW}, + {PPACK_TYPE_F32, 0, 32, offsetof(struct sample, f32), 0, 0, + PPACK_BEHAVIOUR_RAW}, + {PPACK_TYPE_BITS, 0, 32, offsetof(struct sample, bits), 0, 0, + PPACK_BEHAVIOUR_RAW}, + {PPACK_TYPE_UINT16, 0, 16, offsetof(struct sample, scaled_u16), + 0.5f, 1.0f, PPACK_BEHAVIOUR_SCALED}, + {PPACK_TYPE_INT16, 0, 16, offsetof(struct sample, scaled_s16), 0.5f, + 1.0f, PPACK_BEHAVIOUR_SCALED}, + {PPACK_TYPE_UINT32, 0, 32, offsetof(struct sample, scaled_u32), + 0.5f, 1.0f, PPACK_BEHAVIOUR_SCALED}, + {PPACK_TYPE_INT32, 0, 32, offsetof(struct sample, scaled_s32), 0.5f, + 1.0f, PPACK_BEHAVIOUR_SCALED}, + }; + const uint32_t raw[] = { + 0x5A, + 0x1234, + (uint32_t)-1234, + UINT32_C(0x12345678), + (uint32_t)-1234567, + UINT32_C(0x3F800000), + UINT32_C(0xDEADBEEF), + 83, + (uint32_t)-23, + 83, + (uint32_t)-23, + }; + const uint16_t bases[] = {493, 1021, 65001}; + static ppack_byte_t payload[MAX_UNITS]; + static ppack_byte_t expected[MAX_UNITS]; + size_t count = sizeof(fields) / sizeof(fields[0]); + for (size_t layout = 0; layout < sizeof(bases) / sizeof(bases[0]); + ++layout) { + uint16_t start = bases[layout]; + memset(expected, 0, sizeof(expected)); + for (size_t i = 0; i < count; ++i) { + fields[i].start_bit = start; + reference_write(expected, start, fields[i].bit_length, + raw[i]); + start += fields[i].bit_length + 3u; + } + memset(payload, 0xFF, sizeof(payload)); + TEST_ASSERT(ppack_pack(&source, payload, PPACK_MAX_PAYLOAD_BITS, + fields, count) + == PPACK_SUCCESS); + TEST_ASSERT(memcmp(payload, expected, sizeof(payload)) == 0); + + struct sample out = {0}; + TEST_ASSERT(ppack_unpack(&out, expected, PPACK_MAX_PAYLOAD_BITS, + fields, count) + == PPACK_SUCCESS); + TEST_ASSERT(out.u8 == source.u8); + TEST_ASSERT(out.u16 == source.u16); + TEST_ASSERT(out.s16 == source.s16); + TEST_ASSERT(out.u32 == source.u32); + TEST_ASSERT(out.s32 == source.s32); + TEST_ASSERT(out.f32 == source.f32); + TEST_ASSERT(out.bits == source.bits); + TEST_ASSERT(out.scaled_u16 == source.scaled_u16); + TEST_ASSERT(out.scaled_s16 == source.scaled_s16); + TEST_ASSERT(out.scaled_u32 == source.scaled_u32); + TEST_ASSERT(out.scaled_s32 == source.scaled_s32); + + /* Disjoint fields are independent of descriptor order. + * sizeof the fixed array is a compile-time bound, not a VLA. + */ + struct ppack_field reversed[sizeof(fields) / sizeof(fields[0])]; + for (size_t i = 0; i < count; ++i) { + reversed[i] = fields[count - 1u - i]; + } + TEST_ASSERT(ppack_pack(&source, payload, PPACK_MAX_PAYLOAD_BITS, + reversed, count) + == PPACK_SUCCESS); + TEST_ASSERT(memcmp(payload, expected, sizeof(payload)) == 0); + } +} + +TEST_CASE(test_large_preserves_legacy_prefix) +{ + const uint32_t source[] = { + UINT32_C(0x12345678), UINT32_C(0x456789AB), UINT32_C(0xDEADBEEF), + UINT32_C(0x89ABCDEF), UINT32_C(0x0ABCDEF0), + }; + const struct ppack_field fields[] = { + {PPACK_TYPE_BITS, 0, 32, 0, 0, 0, PPACK_BEHAVIOUR_RAW}, + {PPACK_TYPE_BITS, 57, 31, sizeof(uint32_t), 0, 0, + PPACK_BEHAVIOUR_RAW}, + {PPACK_TYPE_BITS, 464, 32, 2u * sizeof(uint32_t), 0, 0, + PPACK_BEHAVIOUR_RAW}, + {PPACK_TYPE_BITS, 496, 32, 3u * sizeof(uint32_t), 0, 0, + PPACK_BEHAVIOUR_RAW}, + {PPACK_TYPE_BITS, 65500, 28, 4u * sizeof(uint32_t), 0, 0, + PPACK_BEHAVIOUR_RAW}, + }; + ppack_byte_t legacy[496u / 8u]; + static ppack_byte_t extended[MAX_UNITS]; + uint32_t out[5] = {0}; + TEST_ASSERT(ppack_pack(source, legacy, 496, fields, 3) + == PPACK_SUCCESS); + TEST_ASSERT( + ppack_pack(source, extended, PPACK_MAX_PAYLOAD_BITS, fields, 5) + == PPACK_SUCCESS); + TEST_ASSERT(memcmp(legacy, extended, sizeof(legacy)) == 0); + TEST_ASSERT( + ppack_unpack(out, extended, PPACK_MAX_PAYLOAD_BITS, fields, 5) + == PPACK_SUCCESS); + TEST_ASSERT(memcmp(source, out, sizeof(source)) == 0); +} + +void +run_large_payload_tests(void) +{ + run_test(test_large_every_field_geometry, + "test_large_every_field_geometry"); + run_test(test_large_basis_patterns, "test_large_basis_patterns"); + run_test(test_large_each_payload_size, "test_large_each_payload_size"); + run_test(test_large_invalid_sizes_and_geometry, + "test_large_invalid_sizes_and_geometry"); + run_test(test_large_mixed_types, "test_large_mixed_types"); + run_test(test_large_preserves_legacy_prefix, + "test_large_preserves_legacy_prefix"); +} diff --git a/tests/test_payload_size.c b/tests/test_payload_size.c index e88ab79..d902c42 100644 --- a/tests/test_payload_size.c +++ b/tests/test_payload_size.c @@ -92,14 +92,15 @@ TEST_CASE(test_pack_payload_bits_above_ceiling_rejected) .behaviour = PPACK_BEHAVIOUR_RAW}, }; - /* Just above the 512-bit CAN-FD ceiling. */ - TEST_ASSERT(ppack_pack(&data, payload, 520, fields, 1) + /* Oversized payloads must fail before touching this small buffer. */ + TEST_ASSERT(ppack_pack(&data, payload, + (size_t)PPACK_MAX_PAYLOAD_BITS + 8u, fields, 1) == -PPACK_ERR_INVALARG); - TEST_ASSERT(ppack_pack(&data, payload, 1024, fields, 1) + TEST_ASSERT(ppack_pack(&data, payload, SIZE_MAX, fields, 1) == -PPACK_ERR_INVALARG); } -TEST_CASE(test_pack_payload_bits_at_ceiling_passes) +TEST_CASE(test_pack_canfd_payload_passes) { /* 512-bit payload with a uint32 field at the very top. */ ppack_byte_t payload[512u / PPACK_ADDR_UNIT_BITS] = {0}; @@ -245,9 +246,9 @@ TEST_CASE(test_roundtrip_256bit_payload) TEST_ASSERT(dst.field_uint32 == src.field_uint32); } -TEST_CASE(test_roundtrip_each_legal_size) +TEST_CASE(test_roundtrip_each_legacy_size) { - /* Sweep every supported payload size and round-trip a small + /* Sweep every legacy payload size and round-trip a small * field at the bottom. Catches regressions in the memset width * and the unit-count math. */ const struct ppack_field fields[] = { @@ -462,8 +463,8 @@ run_payload_size_tests(void) "test_pack_payload_bits_not_multiple_rejected"); run_test(test_pack_payload_bits_above_ceiling_rejected, "test_pack_payload_bits_above_ceiling_rejected"); - run_test(test_pack_payload_bits_at_ceiling_passes, - "test_pack_payload_bits_at_ceiling_passes"); + run_test(test_pack_canfd_payload_passes, + "test_pack_canfd_payload_passes"); run_test(test_pack_overflow_against_payload_bits, "test_pack_overflow_against_payload_bits"); run_test(test_pack_field_above_64_bits_with_64_payload_rejected, @@ -472,8 +473,8 @@ run_payload_size_tests(void) "test_roundtrip_128bit_payload"); run_test(test_roundtrip_256bit_payload, "test_roundtrip_256bit_payload"); - run_test(test_roundtrip_each_legal_size, - "test_roundtrip_each_legal_size"); + run_test(test_roundtrip_each_legacy_size, + "test_roundtrip_each_legacy_size"); run_test(test_wire_lockdown_128bit, "test_wire_lockdown_128bit"); run_test(test_wire_lockdown_256bit, "test_wire_lockdown_256bit"); run_test(test_wire_lockdown_512bit, "test_wire_lockdown_512bit"); diff --git a/tests/test_ppack_main.c b/tests/test_ppack_main.c index 855c017..7ac5047 100644 --- a/tests/test_ppack_main.c +++ b/tests/test_ppack_main.c @@ -20,7 +20,7 @@ * on word-addressable platforms ppack_byte_t == uint16_t (2 bytes). * * PPACK_PAYLOAD_UNITS is bounded by the library's own static asserts - * in ppack_platform.h (multiple of PPACK_ADDR_UNIT_BITS, ≤ 512 bits); + * in ppack_platform.h (positive multiple of 8, at most 65528 bits); * we deliberately do not duplicate that bound here so tests build * cleanly under any legal PPACK_PAYLOAD_BITS override. */ @@ -44,6 +44,7 @@ extern void run_wire_lockdown_tests(void); extern void run_partial_coverage_tests(void); extern void run_payload_size_tests(void); extern void run_mau_layout_tests(void); +extern void run_large_payload_tests(void); int main(void) @@ -68,6 +69,7 @@ main(void) run_partial_coverage_tests(); run_payload_size_tests(); run_mau_layout_tests(); + run_large_payload_tests(); fprintf(stdout, "\n=== All tests passed ===\n\n"); return EXIT_SUCCESS;