diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cb9fc01..77ef2bc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,6 +10,9 @@ jobs: # --------------------------------------------------------------------------- # Build the library and run the full test suite under ASan + UBSan. # Runs on both Linux and macOS to catch platform-specific issues. + # float-cast-overflow is added explicitly: GCC does not include it in + # -fsanitize=undefined (clang does), and it is the check that catches + # undefined float-to-integer conversions (e.g. NaN) in the scaled paths. # --------------------------------------------------------------------------- test: name: "Test (${{ matrix.os }})" @@ -44,6 +47,8 @@ jobs: --buildtype=debug -Dbuild_tests=true -Db_sanitize=address,undefined + -Dc_args=-fsanitize=float-cast-overflow + -Dc_link_args=-fsanitize=float-cast-overflow - name: Build run: meson compile -C build @@ -88,7 +93,8 @@ jobs: --buildtype=debug -Dbuild_tests=true -Db_sanitize=address,undefined - -Dc_args=-DPPACK_PAYLOAD_BITS=512 + "-Dc_args=-DPPACK_PAYLOAD_BITS=512 -fsanitize=float-cast-overflow" + -Dc_link_args=-fsanitize=float-cast-overflow - name: Build run: meson compile -C build @@ -137,7 +143,8 @@ jobs: # --------------------------------------------------------------------------- # Code coverage gate. Builds with gcov instrumentation, runs the full # test suite, and fails the job if line or branch coverage drops below - # the threshold. Threshold is currently 80% line / 70% branch as a pragmatic baseline. + # the threshold. The suite achieves 100% line and branch coverage; the + # gate is set there to keep it that way. # --------------------------------------------------------------------------- coverage: name: "Coverage gate" @@ -180,8 +187,8 @@ jobs: --html-details coverage-report/index.html \ --txt coverage-report/summary.txt \ --print-summary \ - --fail-under-line 80 \ - --fail-under-branch 70 + --fail-under-line 100 \ + --fail-under-branch 100 - name: Upload coverage report if: always() diff --git a/CHANGELOG.md b/CHANGELOG.md index e6115eb..f5a5c5c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,32 @@ 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.4.0] - 2026-07-03 + +### Fixed + +- Rejected NaN on scaled pack paths with `-PPACK_ERR_INVALARG`. Previously a NaN source value (or a NaN scaled result from the scale/offset arithmetic) reached a float-to-integer cast, which is undefined behaviour; ±infinity continues to saturate to the clamp bounds. Locked down with dedicated non-finite tests for every scaled type. + +### Changed + +- Resolved the required MISRA C:2023 violations for Rules 10.4, 10.7 and 10.8 through unsigned suffixes and temporary variables for composite expressions. +- Centralised the type-erased struct-member copies in internal `ppack_member_write` / `ppack_member_read` helpers; Rule 21.15 is now deviated at exactly three documented sites (the two helpers and the deliberate F32 `float`/`uint32_t` pun) rather than silenced per call site. +- Resolved advisory Rule 12.1 findings by making operator precedence explicit with parentheses. +- Moved `PPACK_PAYLOAD_UNITS` from `ppack_platform.h` to `ppack.h` to explicitly surface it as part of the public API. Include `ppack.h` (the documented entry point) rather than `ppack_platform.h` directly. +- Updated `README.md` and `CONTRIBUTING.md` to describe the tool-driven MISRA workflow. + +### Removed + +- Removed unused `PPACK_WORD_MASK` macro from `ppack_platform.h`. + +### Added + +- Adopted `misch` (cppcheck-backed MISRA C:2023 analysis) via `misra.toml`. The audit is clean; all deviations (advisory Rules 2.5, 8.7, 11.5, 15.5, 18.4 and required Rule 21.15) are justified at point of use with `cppcheck-suppress` `@deviation` comments or project-wide in `misra-deviations.txt`. +- Added a compile-time guard that `float` is exactly 32 bits (`PPACK_TYPE_F32` wire-format prerequisite). +- Added `-fsanitize=float-cast-overflow` to the CI sanitizer jobs: GCC does not include the float-to-integer conversion check in `-fsanitize=undefined`, leaving the Linux jobs blind to that UB class. +- Raised the CI coverage gate from 80% line / 70% branch to 100% / 100%, matching what the suite achieves. +- Documented error-path semantics for `ppack_pack` / `ppack_unpack` (destination contents are unspecified after a non-zero return) and clarified the 16-bit MAU `PPACK_TYPE_UINT8` storage contract (unpack zeroes the upper 8 bits of the member's storage unit). + ## [2.3.0] - 2026-06-19 ### Changed diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c3c8565..7ee24c9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -42,19 +42,15 @@ gcovr --root . --filter 'src/' --filter 'include/' --print-summary - Public functions return `int` (negated `PPACK_ERR_*` on failure). No `errno`, no exceptions. -## MISRA C:2012 +## MISRA C:2023 -The library is reviewed against MISRA C:2012. The full deviation record -lives in the file header of `src/ppack.c`. If your change introduces a -new deviation: +The library is analysed with `misch` (cppcheck-backed MISRA C:2023 analysis), configured by `misra.toml`. The audit is clean: `misch run` must report zero findings. If your change introduces a new finding: -1. Add an entry to the file-header deviation record (rule, sites, - justification, mitigation). -2. Add an inline `/* MISRA */` marker at the deviation site. -3. Justify the deviation in the PR description. +1. Prefer restructuring the code so the rule is satisfied. Deviate only when compliance would make the code genuinely worse, and never restructure purely to hide a violation from the checker; an honest deviation beats evasion. +2. Suppress at point of use with `/* cppcheck-suppress misra-c2012- ; @deviation */`, or add a justified project-wide entry to `misra-deviations.txt` for house-style rules. +3. Verify with `misch run` and `misch deviations` (every suppression must carry a rationale), and justify the deviation in the PR description. -`required` rule deviations face a higher bar than `advisory`. We -currently have zero required-rule deviations and want to keep it that way. +`required` rule deviations face a higher bar than `advisory`. We currently carry exactly three, all Rule 21.15: the type-erased struct-member copies centralised in `ppack_member_write` / `ppack_member_read`, and the deliberate F32 `float`/`uint32_t` pun. Do not add required-rule deviations without strong justification; route new member copies through the existing helpers. ## Tests and coverage diff --git a/README.md b/README.md index 56a83d5..7c9b36a 100644 --- a/README.md +++ b/README.md @@ -284,6 +284,10 @@ For `PPACK_TYPE_UINT32` and `PPACK_TYPE_INT32` scaled fields, the float clamp us For safety-critical applications where an out-of-range physical value MUST be detected, validate the input at the call site before calling `ppack_pack`. +### Non-finite values + +Pack rejects a scaled field whose scaled result is NaN (a NaN source value, or a NaN produced by the scale/offset arithmetic) with `-PPACK_ERR_INVALARG`; NaN has no defined integer representation. Positive and negative infinity are treated like any other out-of-range value and saturate to the clamp bounds above. `PPACK_TYPE_F32` fields are a raw bit-copy and carry NaN/infinity payloads unchanged. + ### Quantization The float-to-integer cast in pack truncates toward zero (C standard cast semantics). The maximum round-trip error is one LSB, equal to `scale`. For round-to-nearest behaviour, pre-add `0.5f * scale * sign(physical)` at the call site before pack. @@ -365,7 +369,7 @@ ppack is a serialisation primitive only. The following are explicitly out of sco | Topic | Note | | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Memory** | All operations use stack memory; no dynamic allocation | -| **MISRA C:2012 principles** | Designed with MISRA C:2012 principles: no dynamic allocation, no UB shifts, explicit error codes, `memcpy`-based type punning. A deviation record is maintained in the file header of `src/ppack.c` and at each deviation site (search for `MISRA`). Full tool-driven compliance requires running a certified static analyser against the source. | +| **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. | | **Bit ordering** | LSB-first within each byte; multi-byte fields little-endian; fields may span byte boundaries | | **Field size** | 1-32 bits per field | diff --git a/include/ppack.h b/include/ppack.h index 6de8491..d9faedc 100644 --- a/include/ppack.h +++ b/include/ppack.h @@ -28,6 +28,21 @@ extern "C" { * without needing a separate include. */ +/** + * @brief Number of addressable units occupied by a payload of + * @c PPACK_PAYLOAD_BITS bits. + * + * On 16-bit MAU platforms, ppack allocates one addressable unit per + * logical octet. This ensures compatibility with other primitives. + * + * Use this to declare a portable payload buffer: + * @code + * ppack_byte_t payload[PPACK_PAYLOAD_UNITS]; + * @endcode + */ +/* cppcheck-suppress misra-c2012-2.5 ; @deviation Public API macro for caller buffer sizing. */ +#define PPACK_PAYLOAD_UNITS (PPACK_PAYLOAD_BITS / PPACK_ADDR_UNIT_BITS) + /** * @defgroup ppack_api Ppack Library * @@ -108,6 +123,14 @@ extern "C" { * @c 2147483520 respectively (the next representable float * below the type's true maximum). * + * @b Non-finite values: pack rejects a SCALED field whose scaled + * result is NaN (a NaN source value, or a NaN produced by the + * scale/offset arithmetic) with @c -PPACK_ERR_INVALARG; NaN has no + * defined integer representation. Positive/negative infinity is + * treated like any other out-of-range value and saturates to the + * destination type's clamp bounds. @c PPACK_TYPE_F32 fields are a + * raw bit-copy and carry NaN/infinity payloads unchanged. + * * ## 16-bit MAU Platform Notes * * On platforms with a 16-bit minimum addressable unit (MAU) @@ -118,17 +141,19 @@ extern "C" { * ensure interoperability with other primitives. Two contract points * specific to this platform: * - * @li A @c PPACK_TYPE_UINT8 field reads and writes only the LOW 8 - * bits of its struct member's storage. On 16-bit MAU platforms - * the member's underlying 16-bit storage can technically hold 0..65535, - * but only the low 8 bits round-trip through the wire. + * @li A @c PPACK_TYPE_UINT8 field carries only the low 8 bits of its + * struct member through the wire. On pack, the upper 8 bits of + * the member's 16-bit storage are read but masked out. On + * unpack, the member's FULL storage unit is written: the low 8 + * bits receive the wire value and the upper 8 bits are zeroed. + * Do not keep sentinel data in the upper bits of a + * @c PPACK_TYPE_UINT8 member; it will not survive an unpack. * * @li The @c ptr_offset value comes from @c offsetof(), which * returns @c char-units. On 16-bit MAU platforms a @c char is 16 * bits, so the value is naturally in 16-bit units; the library * does not need to translate it. Always use @c offsetof() rather * than computing offsets by hand. - * * @{ */ @@ -251,8 +276,9 @@ struct ppack_field { * @return -PPACK_ERR_INVALARG if @c field_count is 0, @c fields is NULL, * @c payload_bits is 0, not a multiple of * @c PPACK_ADDR_UNIT_BITS, or > 512; - * @c bit_length is 0 or > 32; or scaling is - * requested for @c PPACK_TYPE_UINT8 + * @c bit_length is 0 or > 32; scaling is + * requested for @c PPACK_TYPE_UINT8; or a + * SCALED field's scaled result is NaN * @return -PPACK_ERR_OVERFLOW if @c start_bit + bit_length exceeds * @c payload_bits, or @c scale is 0.0 on a * SCALED field @@ -262,8 +288,13 @@ struct ppack_field { * across threads or ISRs must provide their own mutual exclusion. * * @note Out-of-range scaled values clamp silently to the destination - * type's representable range. See "Scaled-field semantics" in - * the file-level docs. + * type's representable range; NaN is rejected. See "Scaled-field + * semantics" in the file-level docs. + * + * @note Not atomic on failure: the payload buffer is zeroed before the + * field descriptors are validated, so on an error return its + * contents are unspecified (zeroed and possibly partially + * written). Do not transmit a payload after a non-zero return. */ int ppack_pack(const void *base_ptr, void *payload, size_t payload_bits, const struct ppack_field *fields, size_t field_count); @@ -302,6 +333,12 @@ int ppack_pack(const void *base_ptr, void *payload, size_t payload_bits, * * @note Not thread-safe. Callers sharing @c base_ptr or @c payload * across threads or ISRs must provide their own mutual exclusion. + * + * @note Not atomic on failure: fields are decoded in descriptor order, + * so on an error return the struct members of every field before + * the offending descriptor have already been overwritten. Treat + * the destination structure as unspecified after a non-zero + * return. */ int ppack_unpack(void *base_ptr, const void *payload, size_t payload_bits, const struct ppack_field *fields, size_t field_count); diff --git a/include/ppack_platform.h b/include/ppack_platform.h index 5c96d9a..8be0aed 100644 --- a/include/ppack_platform.h +++ b/include/ppack_platform.h @@ -15,12 +15,12 @@ * platforms), @c ppack_byte_t is @c uint16_t. Regardless of MAU size, * ppack treats the payload as a sequence of 8-bit logical units to * ensure interoperability with other primitives (like @c ucrc). - * * @c PPACK_PAYLOAD_BITS is a user-overridable convenience macro that - * sizes @c PPACK_PAYLOAD_UNITS for stack buffer declarations. Define - * it before including the header (e.g. @c -DPPACK_PAYLOAD_BITS=128 - * or @c -DPPACK_PAYLOAD_BITS=512) to change the default. The runtime + * sizes the @c PPACK_PAYLOAD_UNITS buffer-sizing macro (defined in + * @c ppack.h, the library's public entry point). Define it before + * including the header (e.g. @c -DPPACK_PAYLOAD_BITS=128 or + * @c -DPPACK_PAYLOAD_BITS=512) to change the default. The runtime * @c ppack_pack / @c ppack_unpack API takes the payload size as an * explicit argument and does not depend on this macro. * @@ -57,6 +57,7 @@ /** @brief Storage unit used for the payload buffer. */ typedef uint16_t ppack_byte_t; #else +/* cppcheck-suppress misra-c2012-2.5 ; @deviation Public macro for external platform detection. */ #define PPACK_IS_16BIT_MAU 0 /** @brief Logical bits per payload unit. Always 8 for interoperability. */ #define PPACK_ADDR_UNIT_BITS 8u @@ -84,7 +85,7 @@ typedef ppack_byte_t ppack_u8_t; /** * @brief Default payload size in bits for the @c PPACK_PAYLOAD_UNITS - * convenience macro. + * convenience macro (defined in @c ppack.h). * * Override at the toolchain level (e.g. @c -DPPACK_PAYLOAD_BITS=128) * to size stack buffer declarations to a non-default payload. Must @@ -98,24 +99,6 @@ typedef ppack_byte_t ppack_u8_t; #define PPACK_PAYLOAD_BITS 64u #endif -/** - * @brief Number of addressable units occupied by a payload of - * @c PPACK_PAYLOAD_BITS bits. - * - * On 16-bit MAU platforms, ppack allocates one addressable unit per - * logical octet. This ensures compatibility with other primitives. - - * - * Use this to declare a portable payload buffer: - * @code - * ppack_byte_t payload[PPACK_PAYLOAD_UNITS]; - * @endcode - */ -#define PPACK_PAYLOAD_UNITS (PPACK_PAYLOAD_BITS / PPACK_ADDR_UNIT_BITS) - -/** @brief Bitmask covering one addressable unit. */ -#define PPACK_WORD_MASK (((uint32_t)1u << PPACK_ADDR_UNIT_BITS) - 1u) - /** * @brief Convert a payload bit index to its addressable-unit index. * @@ -142,11 +125,11 @@ ppack_bit_to_shift(uint16_t bit) } /* Catch unsupported configurations at compile time. */ -_Static_assert(PPACK_ADDR_UNIT_BITS == 8 || PPACK_ADDR_UNIT_BITS == 16, +_Static_assert((PPACK_ADDR_UNIT_BITS == 8u) || (PPACK_ADDR_UNIT_BITS == 16u), "ppack only supports 8-bit or 16-bit addressable units"); -_Static_assert(PPACK_PAYLOAD_BITS > 0u - && PPACK_PAYLOAD_BITS % PPACK_ADDR_UNIT_BITS == 0u, +_Static_assert((PPACK_PAYLOAD_BITS > 0u) + && ((PPACK_PAYLOAD_BITS % PPACK_ADDR_UNIT_BITS) == 0u), "PPACK_PAYLOAD_BITS must be a positive multiple of " "PPACK_ADDR_UNIT_BITS"); @@ -154,4 +137,8 @@ _Static_assert(PPACK_PAYLOAD_BITS <= 512u, "PPACK_PAYLOAD_BITS must be at most 512 " "(CAN-FD frame data field ceiling)"); +_Static_assert(sizeof(float) == sizeof(uint32_t), + "ppack requires a 32-bit float " + "(PPACK_TYPE_F32 wire-format prerequisite)"); + #endif /* PPACK_PLATFORM_H_ */ diff --git a/meson.build b/meson.build index 9c6112a..6d17709 100644 --- a/meson.build +++ b/meson.build @@ -1,7 +1,7 @@ project( 'ppack', 'c', - version: '2.3.0', + version: '2.4.0', default_options: [ 'c_std=c11', 'warning_level=3', diff --git a/misra-deviations.txt b/misra-deviations.txt new file mode 100644 index 0000000..4ac6843 --- /dev/null +++ b/misra-deviations.txt @@ -0,0 +1,14 @@ +# Project-level MISRA deviations for ppack. Each entry is preceded by the +# rationale that misch harvests into the deviation record. A bare rule id +# deviates that rule across every in-scope file; add :file or :file:line to +# narrow the scope. + +# Rule 15.5 (a function should have a single point of exit) is deviated +# project-wide as a deliberate house style. Precondition guard clauses that +# return early on invalid input and the branch-per-outcome returns in the +# pack/unpack type-dispatch switches are clearer and less error-prone than +# threading a result variable through nested if/else. None of these +# functions acquire a resource, take a lock, or have any teardown, so there +# is no shared cleanup that a single exit point would protect. Advisory; +# deviation accepted. +misra-c2012-15.5 diff --git a/misra.toml b/misra.toml new file mode 100644 index 0000000..a1c790a --- /dev/null +++ b/misra.toml @@ -0,0 +1,42 @@ +# misch configuration. See misch/docs/DESIGN.md for the full schema. + +[project] +# Analysed source roots. Directory-style entries match everything beneath +# them; globs (e.g. "*.c") are also honoured. +# The shipped library is src/ + the public headers. tests/ is host-side +# test infrastructure, out of MISRA scope. +scope = ["include/", "src/"] +# Explicitly excluded. Every compile-DB file must match scope OR exclude; +# an unclassified file is a hard error (no silent scope creep). +exclude = ["tests/"] + +[db] +# Where compile_commands.json comes from: meson | cmake | existing | bear. +source = "meson" +# path = "build/compile_commands.json" # only for source = "existing" + +[platform] +# A cppcheck built-in (unix64, unix32, ...) or set [platform].xml to a +# custom platform description for exotic targets. +preset = "unix64" + +[toolchain] +# Extra -D defines cppcheck should see (e.g. neutralising compiler +# keywords on a cross target: "__interrupt="). +defines = [] + +[rules] +# Bring-your-own MISRA headlines (see docs/rule-texts.md). Never commit it. +# Precedence: $MISRA_RULE_TEXTS > this value. Absent => category: unknown. +texts = "${MISRA_RULE_TEXTS}" + +[report] +# Default output is the terminal. Add file outputs as needed, e.g.: +# outputs = ["terminal", {format = "json", path = "misra.json"}] +outputs = ["terminal"] + +[deviations] +# Project-level (blanket) MISRA deviations. Each entry is a cppcheck +# suppression whose preceding comment block is the mandatory justification; +# `misch deviations` harvests them into the audit record. +suppressions = "misra-deviations.txt" diff --git a/src/ppack.c b/src/ppack.c index 463f440..3a1bdbe 100644 --- a/src/ppack.c +++ b/src/ppack.c @@ -6,67 +6,28 @@ * @brief * Implementation of the ppack library - generic payload serialisation. * - * @par MISRA C:2012 Deviation Record + * @par MISRA C:2023 Compliance * - * Deviations are intentional and have been reviewed. Each site is also - * tagged in-line at point-of-use (search for "MISRA "). Tool-driven - * full compliance requires running a certified static analyser - * (e.g. PC-lint Plus, Coverity, Polyspace) against this list. - * - * Last reviewed: against MISRA C:2012 Guidelines (manual review). - * - * Rule 11.5 (advisory) - Cast from pointer-to-void to pointer-to-object - * Sites: write_bits, read_bits payload casts to ppack_byte_t*; - * ppack_pack/unpack base_ptr cast to char* for offset - * arithmetic. - * Justification: The public API takes void* / const void* per the C - * standard's convention for opaque polymorphic buffer - * types. Internal code requires unit-typed access on - * the payload (for indexed read-modify-write of bits) - * and char-typed access on the user struct (for - * offsetof()-based member addressing). - * Mitigation: Verified end-to-end on host (8-bit MAU) and via - * PPACK_SIMULATE_16BIT_MAU host build (16-bit MAU code - * path). ASan + UBSan clean across the test suite, - * including 35 000 randomised round-trip iterations - * per type. - * - * Rule 18.4 (advisory) - The +, -, += and -= operators should not be - * applied to an expression of pointer type - * Sites: ppack_pack / ppack_unpack field_ptr arithmetic - * (char* + ptr_offset). - * Justification: ptr_offset is the user-supplied offsetof() value and - * encodes the location of the struct member relative - * to base_ptr. Arithmetic addition is the natural and - * idiomatic way to apply it; alternatives (subscript, - * uintptr_t round-trip) either reduce to the same - * underlying pointer arithmetic or introduce a - * pointer-to-integer conversion (Rule 11.4) which is - * worse. - * Mitigation: ptr_offset is bounded by sizeof(user struct) and - * validated implicitly at use (memcpy with a fixed - * small size). All field tests exercise this path. - * - * Rule 15.5 (advisory) - A function should have a single point of exit - * Sites: ppack_pack, ppack_unpack, validate_field, sign_extend - * Justification: Early-return-on-error is the project's idiomatic - * control flow. Refactoring to a single-exit pattern - * would either deeply nest the validation arms (hurting - * readability) or introduce a goto-cleanup (Rule 15.1 - * deviation), trading one advisory deviation for - * another with no readability gain. - * Mitigation: All exit points return one of the documented error - * codes or PPACK_SUCCESS; covered by NULL/INVALARG/ - * OVERFLOW/NOTFOUND test cases. + * The library is analysed with misch (cppcheck-backed MISRA C:2023 + * analysis), configured by misra.toml at the project root. The audit is + * clean; every deviation is recorded at point of use as a + * `cppcheck-suppress` comment carrying an `@deviation` rationale, or + * project-wide in misra-deviations.txt (Rule 15.5, single-exit house + * style). The only required-rule deviations are three Rule 21.15 sites: + * the type-erased member copies centralised in ppack_member_write / + * ppack_member_read, and the deliberate float/uint32_t pun in F32 + * unpack. Run `misch run` to reproduce the audit and `misch deviations` + * to harvest the deviation record. */ /* ================ INCLUDES ================================================ */ +#include #include #include #include "ppack.h" -#include +#include "ppack_platform.h" /* ================ DEFINES ================================================= */ @@ -121,6 +82,34 @@ ppack_clamp_float(float val, float lo, float hi) return result; } +/** + * @brief Copy @p n bytes from a typed temporary into a struct member + * addressed as char* via its offsetof() value. + * + * Centralises the type-erased member store so the deliberate Rule 21.15 + * deviation has a single, documented site. + */ +static void +ppack_member_write(char *dst, const void *src, size_t n) +{ + /* cppcheck-suppress misra-c2012-21.15 ; @deviation Type-erased copy to a struct member addressed via offsetof(); the source temporary's type matches the member's declared type by API contract (see ppack_type). */ + (void)memcpy(dst, src, n); +} + +/** + * @brief Copy @p n bytes from a struct member addressed as const char* + * via its offsetof() value into a typed temporary. + * + * Centralises the type-erased member load so the deliberate Rule 21.15 + * deviation has a single, documented site. + */ +static void +ppack_member_read(void *dst, const char *src, size_t n) +{ + /* cppcheck-suppress misra-c2012-21.15 ; @deviation Type-erased copy from a struct member addressed via offsetof(); the destination temporary's type matches the member's declared type by API contract (see ppack_type). */ + (void)memcpy(dst, src, n); +} + /** * @brief Write a bitfield of arbitrary length into a payload buffer. * @@ -135,7 +124,7 @@ ppack_clamp_float(float val, float lo, float hi) static void write_bits(void *payload, uint16_t start_bit, uint16_t bit_len, uint32_t value) { - /* MISRA 11.5: opaque void* payload requires unit-typed access. */ + /* cppcheck-suppress misra-c2012-11.5 ; @deviation Opaque void* payload requires unit-typed access for indexed read-modify-write. */ ppack_byte_t *words = (ppack_byte_t *)payload; uint16_t bits_written = 0; @@ -178,7 +167,7 @@ write_bits(void *payload, uint16_t start_bit, uint16_t bit_len, uint32_t value) static uint32_t read_bits(const void *payload, uint16_t start_bit, uint16_t bit_len) { - /* MISRA 11.5: opaque const void* payload requires unit-typed access. */ + /* cppcheck-suppress misra-c2012-11.5 ; @deviation Opaque const void* payload requires unit-typed access for indexed reads. */ const ppack_byte_t *words = (const ppack_byte_t *)payload; uint32_t result = 0; uint16_t bits_read = 0; @@ -221,7 +210,8 @@ read_bits(const void *payload, uint16_t start_bit, uint16_t bit_len) static int32_t sign_extend(uint32_t value, uint16_t width) { - uint32_t sign_bit = (uint32_t)1u << (width - 1u); + uint16_t shift = width - 1u; + uint32_t sign_bit = (uint32_t)1u << shift; /* If sign bit is set, fill upper bits with 1s. */ if ((value & sign_bit) != 0u) { @@ -248,7 +238,7 @@ sign_extend(uint32_t value, uint16_t width) static int validate_field(const struct ppack_field *f, size_t payload_bits) { - if (f->bit_length == 0u || f->bit_length > PPACK_MAX_FIELD_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) { @@ -270,7 +260,7 @@ validate_field(const struct ppack_field *f, size_t payload_bits) static int validate_payload_bits(size_t payload_bits) { - if (payload_bits == 0u || payload_bits > PPACK_MAX_PAYLOAD_BITS) { + if ((payload_bits == 0u) || (payload_bits > PPACK_MAX_PAYLOAD_BITS)) { return -PPACK_ERR_INVALARG; } if ((payload_bits % (size_t)PPACK_ADDR_UNIT_BITS) != 0u) { @@ -282,14 +272,15 @@ validate_payload_bits(size_t payload_bits) /* ================ GLOBAL PROTOTYPES ======================================= */ int +/* cppcheck-suppress misra-c2012-8.7 ; @deviation Public API function consumed by external translation units. */ ppack_unpack(void *base_ptr, const void *payload, size_t payload_bits, const struct ppack_field *fields, size_t field_count) { - if (base_ptr == NULL || payload == NULL) { + if ((base_ptr == NULL) || (payload == NULL)) { return -PPACK_ERR_NULLPTR; } - if (field_count == 0u || fields == NULL) { + if ((field_count == 0u) || (fields == NULL)) { return -PPACK_ERR_INVALARG; } @@ -306,10 +297,10 @@ ppack_unpack(void *base_ptr, const void *payload, size_t payload_bits, return vret; } - /* MISRA 11.5: void* opaque struct requires char* for offset - * arithmetic. MISRA 18.4: ptr_offset is the user-supplied - * offsetof() value and is added to the base pointer. */ - char *field_ptr = (char *)base_ptr + f->ptr_offset; + /* cppcheck-suppress misra-c2012-11.5 ; @deviation void* opaque struct requires char* for offsetof()-based member addressing. */ + char *field_ptr = (char *)base_ptr; + /* cppcheck-suppress misra-c2012-18.4 ; @deviation ptr_offset is the user-supplied offsetof() value and is added to the base pointer. */ + field_ptr += f->ptr_offset; uint32_t raw = read_bits(payload, f->start_bit, f->bit_length); switch (f->type) { @@ -318,18 +309,20 @@ ppack_unpack(void *base_ptr, const void *payload, size_t payload_bits, return -PPACK_ERR_INVALARG; } ppack_u8_t tmp = (ppack_u8_t)(raw & 0xFFu); - (void)memcpy(field_ptr, &tmp, sizeof(tmp)); + ppack_member_write(field_ptr, &tmp, sizeof(tmp)); break; } case PPACK_TYPE_UINT16: { if (f->behaviour == PPACK_BEHAVIOUR_SCALED) { - float tmp = ((float)(uint16_t)raw) * f->scale + float tmp = (((float)(uint16_t)raw) * f->scale) + f->offset; - (void)memcpy(field_ptr, &tmp, sizeof(tmp)); + ppack_member_write(field_ptr, &tmp, + sizeof(tmp)); } else { uint16_t tmp = (uint16_t)raw; - (void)memcpy(field_ptr, &tmp, sizeof(tmp)); + ppack_member_write(field_ptr, &tmp, + sizeof(tmp)); } break; } @@ -338,22 +331,27 @@ ppack_unpack(void *base_ptr, const void *payload, size_t payload_bits, if (f->behaviour == PPACK_BEHAVIOUR_SCALED) { int32_t sval = sign_extend(raw, f->bit_length); float tmp = - ((float)sval) * f->scale + f->offset; - (void)memcpy(field_ptr, &tmp, sizeof(tmp)); + (((float)sval) * f->scale) + f->offset; + ppack_member_write(field_ptr, &tmp, + sizeof(tmp)); } else { int16_t tmp = (int16_t)sign_extend(raw, f->bit_length); - (void)memcpy(field_ptr, &tmp, sizeof(tmp)); + ppack_member_write(field_ptr, &tmp, + sizeof(tmp)); } break; } case PPACK_TYPE_UINT32: { if (f->behaviour == PPACK_BEHAVIOUR_SCALED) { - float tmp = ((float)raw) * f->scale + f->offset; - (void)memcpy(field_ptr, &tmp, sizeof(tmp)); + float tmp = + (((float)raw) * f->scale) + f->offset; + ppack_member_write(field_ptr, &tmp, + sizeof(tmp)); } else { - (void)memcpy(field_ptr, &raw, sizeof(raw)); + ppack_member_write(field_ptr, &raw, + sizeof(raw)); } break; } @@ -362,23 +360,26 @@ ppack_unpack(void *base_ptr, const void *payload, size_t payload_bits, int32_t sval = sign_extend(raw, f->bit_length); if (f->behaviour == PPACK_BEHAVIOUR_SCALED) { float tmp = - ((float)sval) * f->scale + f->offset; - (void)memcpy(field_ptr, &tmp, sizeof(tmp)); + (((float)sval) * f->scale) + f->offset; + ppack_member_write(field_ptr, &tmp, + sizeof(tmp)); } else { - (void)memcpy(field_ptr, &sval, sizeof(sval)); + ppack_member_write(field_ptr, &sval, + sizeof(sval)); } break; } case PPACK_TYPE_F32: { float tmp; + /* cppcheck-suppress misra-c2012-21.15 ; @deviation Deliberate float/uint32_t bit reinterpretation; memcpy is the well-defined idiom for type punning. */ (void)memcpy(&tmp, &raw, sizeof(tmp)); - (void)memcpy(field_ptr, &tmp, sizeof(tmp)); + ppack_member_write(field_ptr, &tmp, sizeof(tmp)); break; } case PPACK_TYPE_BITS: { - (void)memcpy(field_ptr, &raw, sizeof(raw)); + ppack_member_write(field_ptr, &raw, sizeof(raw)); break; } @@ -390,14 +391,15 @@ ppack_unpack(void *base_ptr, const void *payload, size_t payload_bits, } int +/* cppcheck-suppress misra-c2012-8.7 ; @deviation Public API function consumed by external translation units. */ ppack_pack(const void *base_ptr, void *payload, size_t payload_bits, const struct ppack_field *fields, size_t field_count) { - if (base_ptr == NULL || payload == NULL) { + if ((base_ptr == NULL) || (payload == NULL)) { return -PPACK_ERR_NULLPTR; } - if (field_count == 0u || fields == NULL) { + if ((field_count == 0u) || (fields == NULL)) { return -PPACK_ERR_INVALARG; } @@ -417,10 +419,10 @@ ppack_pack(const void *base_ptr, void *payload, size_t payload_bits, return vret; } - /* MISRA 11.5: const void* opaque struct requires const char* - * for offset arithmetic. MISRA 18.4: ptr_offset is the - * user-supplied offsetof() value. */ - const char *field_ptr = (const char *)base_ptr + f->ptr_offset; + /* cppcheck-suppress misra-c2012-11.5 ; @deviation const void* opaque struct requires const char* for offsetof()-based member addressing. */ + const char *field_ptr = (const char *)base_ptr; + /* cppcheck-suppress misra-c2012-18.4 ; @deviation ptr_offset is the user-supplied offsetof() value. */ + field_ptr += f->ptr_offset; uint32_t raw = 0u; switch (f->type) { @@ -429,8 +431,10 @@ ppack_pack(const void *base_ptr, void *payload, size_t payload_bits, return -PPACK_ERR_INVALARG; } ppack_u8_t tmp; - (void)memcpy(&tmp, field_ptr, sizeof(tmp)); - raw = (uint32_t)(tmp & 0xFFu); + ppack_member_read(&tmp, field_ptr, sizeof(tmp)); + uint32_t mask_val = (uint32_t)tmp; + mask_val &= 0xFFu; + raw = mask_val; break; } @@ -440,14 +444,17 @@ ppack_pack(const void *base_ptr, void *payload, size_t payload_bits, return -PPACK_ERR_OVERFLOW; } float val; - (void)memcpy(&val, field_ptr, sizeof(val)); + ppack_member_read(&val, field_ptr, sizeof(val)); float scaled = (val - f->offset) / f->scale; + if (isnan(scaled) != 0) { + return -PPACK_ERR_INVALARG; + } scaled = ppack_clamp_float(scaled, 0.0f, 65535.0f); raw = (uint32_t)(uint16_t)scaled; } else { uint16_t tmp; - (void)memcpy(&tmp, field_ptr, sizeof(tmp)); + ppack_member_read(&tmp, field_ptr, sizeof(tmp)); raw = (uint32_t)tmp; } break; @@ -459,14 +466,17 @@ ppack_pack(const void *base_ptr, void *payload, size_t payload_bits, return -PPACK_ERR_OVERFLOW; } float val; - (void)memcpy(&val, field_ptr, sizeof(val)); + ppack_member_read(&val, field_ptr, sizeof(val)); float scaled = (val - f->offset) / f->scale; + if (isnan(scaled) != 0) { + return -PPACK_ERR_INVALARG; + } scaled = ppack_clamp_float(scaled, -32768.0f, 32767.0f); raw = (uint32_t)(int16_t)scaled; } else { int16_t tmp; - (void)memcpy(&tmp, field_ptr, sizeof(tmp)); + ppack_member_read(&tmp, field_ptr, sizeof(tmp)); raw = (uint32_t)tmp; } break; @@ -478,13 +488,16 @@ ppack_pack(const void *base_ptr, void *payload, size_t payload_bits, return -PPACK_ERR_OVERFLOW; } float val; - (void)memcpy(&val, field_ptr, sizeof(val)); + ppack_member_read(&val, field_ptr, sizeof(val)); float scaled = (val - f->offset) / f->scale; + if (isnan(scaled) != 0) { + return -PPACK_ERR_INVALARG; + } scaled = ppack_clamp_float( scaled, 0.0f, PPACK_FLOAT_UINT32_MAX); raw = (uint32_t)scaled; } else { - (void)memcpy(&raw, field_ptr, sizeof(raw)); + ppack_member_read(&raw, field_ptr, sizeof(raw)); } break; } @@ -495,15 +508,18 @@ ppack_pack(const void *base_ptr, void *payload, size_t payload_bits, return -PPACK_ERR_OVERFLOW; } float val; - (void)memcpy(&val, field_ptr, sizeof(val)); + ppack_member_read(&val, field_ptr, sizeof(val)); float scaled = (val - f->offset) / f->scale; + if (isnan(scaled) != 0) { + return -PPACK_ERR_INVALARG; + } scaled = ppack_clamp_float( scaled, PPACK_FLOAT_INT32_MIN, PPACK_FLOAT_INT32_MAX); raw = (uint32_t)(int32_t)scaled; } else { int32_t tmp; - (void)memcpy(&tmp, field_ptr, sizeof(tmp)); + ppack_member_read(&tmp, field_ptr, sizeof(tmp)); raw = (uint32_t)tmp; } break; @@ -511,13 +527,13 @@ ppack_pack(const void *base_ptr, void *payload, size_t payload_bits, case PPACK_TYPE_F32: { uint32_t tmp; - (void)memcpy(&tmp, field_ptr, sizeof(tmp)); + ppack_member_read(&tmp, field_ptr, sizeof(tmp)); raw = tmp; break; } case PPACK_TYPE_BITS: { - (void)memcpy(&raw, field_ptr, sizeof(raw)); + ppack_member_read(&raw, field_ptr, sizeof(raw)); break; } diff --git a/tests/meson.build b/tests/meson.build index 9032258..8c8d69d 100644 --- a/tests/meson.build +++ b/tests/meson.build @@ -5,6 +5,7 @@ test_sources = [ 'test_null_args.c', 'test_validation.c', 'test_scale_zero.c', + 'test_scaled_nonfinite.c', 'test_layout.c', 'test_roundtrip_raw.c', 'test_sign_extension.c', diff --git a/tests/test_ppack_main.c b/tests/test_ppack_main.c index 23baf40..855c017 100644 --- a/tests/test_ppack_main.c +++ b/tests/test_ppack_main.c @@ -30,6 +30,7 @@ _Static_assert(sizeof(ppack_byte_t) == 1 || sizeof(ppack_byte_t) == 2, extern void run_null_arg_tests(void); extern void run_validation_tests(void); extern void run_scale_zero_tests(void); +extern void run_scaled_nonfinite_tests(void); extern void run_roundtrip_raw_tests(void); extern void run_sign_extension_tests(void); extern void run_layout_tests(void); @@ -53,6 +54,7 @@ main(void) run_null_arg_tests(); run_validation_tests(); run_scale_zero_tests(); + run_scaled_nonfinite_tests(); run_roundtrip_raw_tests(); run_sign_extension_tests(); run_layout_tests(); diff --git a/tests/test_scaled_nonfinite.c b/tests/test_scaled_nonfinite.c new file mode 100644 index 0000000..767de0d --- /dev/null +++ b/tests/test_scaled_nonfinite.c @@ -0,0 +1,177 @@ +/* + * @file: test_scaled_nonfinite.c + * @brief Non-finite inputs on SCALED fields: NaN is rejected with + * -PPACK_ERR_INVALARG (casting NaN to an integer is undefined + * behaviour); +/-infinity saturates to the destination clamp + * bounds like any other out-of-range value. + */ + +#include "ppack.h" +#include "test_fixtures.h" +#include "test_harness.h" +#include +#include +#include + +TEST_CASE(test_pack_nonfinite_uint16_scaled) +{ + ppack_byte_t payload[PPACK_PAYLOAD_UNITS] = {0}; + test_struct_scaled_t data = {.field_uint16_scaled = NAN}; + + const struct ppack_field fields[] = { + {.type = PPACK_TYPE_UINT16, + .start_bit = 0, + .bit_length = 16, + .ptr_offset = offsetof(test_struct_scaled_t, field_uint16_scaled), + .scale = 1.0f, + .offset = 0.0f, + .behaviour = PPACK_BEHAVIOUR_SCALED}, + }; + + /* NaN has no defined integer representation: rejected. */ + int ret = ppack_pack(&data, payload, 64, fields, 1); + TEST_ASSERT(ret == -PPACK_ERR_INVALARG); + + /* +Inf saturates to the destination maximum (65535). */ + data.field_uint16_scaled = INFINITY; + ret = ppack_pack(&data, payload, 64, fields, 1); + TEST_ASSERT(ret == PPACK_SUCCESS); + ASSERT_PAYLOAD_BYTES_EQ(payload, 0, 2, 0xFF, 0xFF); + + /* -Inf saturates to the destination minimum (0). */ + data.field_uint16_scaled = -INFINITY; + ret = ppack_pack(&data, payload, 64, fields, 1); + TEST_ASSERT(ret == PPACK_SUCCESS); + ASSERT_PAYLOAD_BYTES_EQ(payload, 0, 2, 0x00, 0x00); +} + +TEST_CASE(test_pack_nonfinite_int16_scaled) +{ + ppack_byte_t payload[PPACK_PAYLOAD_UNITS] = {0}; + test_struct_scaled_t data = {.field_int16_scaled = NAN}; + + const struct ppack_field fields[] = { + {.type = PPACK_TYPE_INT16, + .start_bit = 0, + .bit_length = 16, + .ptr_offset = offsetof(test_struct_scaled_t, field_int16_scaled), + .scale = 1.0f, + .offset = 0.0f, + .behaviour = PPACK_BEHAVIOUR_SCALED}, + }; + + int ret = ppack_pack(&data, payload, 64, fields, 1); + TEST_ASSERT(ret == -PPACK_ERR_INVALARG); + + /* +Inf saturates to 32767 (0x7FFF little-endian). */ + data.field_int16_scaled = INFINITY; + ret = ppack_pack(&data, payload, 64, fields, 1); + TEST_ASSERT(ret == PPACK_SUCCESS); + ASSERT_PAYLOAD_BYTES_EQ(payload, 0, 2, 0xFF, 0x7F); + + /* -Inf saturates to -32768 (0x8000 little-endian). */ + data.field_int16_scaled = -INFINITY; + ret = ppack_pack(&data, payload, 64, fields, 1); + TEST_ASSERT(ret == PPACK_SUCCESS); + ASSERT_PAYLOAD_BYTES_EQ(payload, 0, 2, 0x00, 0x80); +} + +TEST_CASE(test_pack_nonfinite_uint32_scaled) +{ + ppack_byte_t payload[PPACK_PAYLOAD_UNITS] = {0}; + test_struct_scaled_t data = {.field_uint32_scaled = NAN}; + + const struct ppack_field fields[] = { + {.type = PPACK_TYPE_UINT32, + .start_bit = 0, + .bit_length = 32, + .ptr_offset = offsetof(test_struct_scaled_t, field_uint32_scaled), + .scale = 1.0f, + .offset = 0.0f, + .behaviour = PPACK_BEHAVIOUR_SCALED}, + }; + + int ret = ppack_pack(&data, payload, 64, fields, 1); + TEST_ASSERT(ret == -PPACK_ERR_INVALARG); + + /* +Inf saturates to the float-exact clamp 4294967040 + * (0xFFFFFF00 little-endian). */ + data.field_uint32_scaled = INFINITY; + ret = ppack_pack(&data, payload, 64, fields, 1); + TEST_ASSERT(ret == PPACK_SUCCESS); + ASSERT_PAYLOAD_BYTES_EQ(payload, 0, 4, 0x00, 0xFF, 0xFF, 0xFF); + + /* -Inf saturates to 0. */ + data.field_uint32_scaled = -INFINITY; + ret = ppack_pack(&data, payload, 64, fields, 1); + TEST_ASSERT(ret == PPACK_SUCCESS); + ASSERT_PAYLOAD_BYTES_EQ(payload, 0, 4, 0x00, 0x00, 0x00, 0x00); +} + +TEST_CASE(test_pack_nonfinite_int32_scaled) +{ + ppack_byte_t payload[PPACK_PAYLOAD_UNITS] = {0}; + test_struct_scaled_t data = {.field_int32_scaled = NAN}; + + const struct ppack_field fields[] = { + {.type = PPACK_TYPE_INT32, + .start_bit = 0, + .bit_length = 32, + .ptr_offset = offsetof(test_struct_scaled_t, field_int32_scaled), + .scale = 1.0f, + .offset = 0.0f, + .behaviour = PPACK_BEHAVIOUR_SCALED}, + }; + + int ret = ppack_pack(&data, payload, 64, fields, 1); + TEST_ASSERT(ret == -PPACK_ERR_INVALARG); + + /* +Inf saturates to the float-exact clamp 2147483520 + * (0x7FFFFF80 little-endian). */ + data.field_int32_scaled = INFINITY; + ret = ppack_pack(&data, payload, 64, fields, 1); + TEST_ASSERT(ret == PPACK_SUCCESS); + ASSERT_PAYLOAD_BYTES_EQ(payload, 0, 4, 0x80, 0xFF, 0xFF, 0x7F); + + /* -Inf saturates to -2147483648 (0x80000000 little-endian). */ + data.field_int32_scaled = -INFINITY; + ret = ppack_pack(&data, payload, 64, fields, 1); + TEST_ASSERT(ret == PPACK_SUCCESS); + ASSERT_PAYLOAD_BYTES_EQ(payload, 0, 4, 0x00, 0x00, 0x00, 0x80); +} + +TEST_CASE(test_pack_nonfinite_descriptor_rejected) +{ + ppack_byte_t payload[PPACK_PAYLOAD_UNITS] = {0}; + test_struct_scaled_t data = {.field_uint16_scaled = 1.0f}; + + /* A NaN offset poisons the scaled result even for a finite + * source value: rejected the same way as a NaN input. */ + const struct ppack_field fields[] = { + {.type = PPACK_TYPE_UINT16, + .start_bit = 0, + .bit_length = 16, + .ptr_offset = offsetof(test_struct_scaled_t, field_uint16_scaled), + .scale = 1.0f, + .offset = NAN, + .behaviour = PPACK_BEHAVIOUR_SCALED}, + }; + + int ret = ppack_pack(&data, payload, 64, fields, 1); + TEST_ASSERT(ret == -PPACK_ERR_INVALARG); +} + +void +run_scaled_nonfinite_tests(void) +{ + run_test(test_pack_nonfinite_uint16_scaled, + "test_pack_nonfinite_uint16_scaled"); + run_test(test_pack_nonfinite_int16_scaled, + "test_pack_nonfinite_int16_scaled"); + run_test(test_pack_nonfinite_uint32_scaled, + "test_pack_nonfinite_uint32_scaled"); + run_test(test_pack_nonfinite_int32_scaled, + "test_pack_nonfinite_int32_scaled"); + run_test(test_pack_nonfinite_descriptor_rejected, + "test_pack_nonfinite_descriptor_rejected"); +}