From b68fd0f1005657b3d82bba56af8344cbb9dbcaa3 Mon Sep 17 00:00:00 2001 From: Aaron James Long Date: Wed, 14 Oct 2026 23:14:02 +0100 Subject: [PATCH] docs: split the README into integration, API and design docs The README held the install guide, a configuration table, the API, use cases and a notes table, while the protocol, memory ordering and progress guarantees were spread across header comments and CONTRIBUTING.md. The README is now a landing page with a compiled quick start, and docs/design.md records the ordering argument, the uniprocessor backend's limits, progress, counter wrap and verification. A docs test compiles every C example, and CONTRIBUTING.md and AGENTS.md describe misch, scripts/format.sh and the current CI. The integration guide states that SEQLOCK_COUNTER_TYPE and the backend macros must match between the library and its callers, and that a replacement seqlock_conf.h earlier on the include path is never used, because seqlock.h includes it with quotes. Refs #6 --- .github/workflows/ci.yml | 7 +- AGENTS.md | 172 ++++++++++--------- CHANGELOG.md | 2 + CONTRIBUTING.md | 207 ++++++++++------------- README.md | 258 +++++----------------------- docs/api.md | 173 +++++++++++++++++++ docs/design.md | 124 ++++++++++++++ docs/integration.md | 105 ++++++++++++ tests/docs/check_snippets.py | 315 +++++++++++++++++++++++++++++++++++ tests/meson.build | 25 +++ 10 files changed, 969 insertions(+), 419 deletions(-) create mode 100644 docs/api.md create mode 100644 docs/design.md create mode 100644 docs/integration.md create mode 100755 tests/docs/check_snippets.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 234dcb0..85d2dff 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,9 +41,10 @@ jobs: run: uv tool install meson && uv tool install ninja # TSAN and ASAN are mutually exclusive, so this is a dedicated job with - # only the thread sanitizer. It exercises the concurrent torn-read test - # (design §7 #5); the library auto-selects its race-free payload copy - # under TSAN, so a clean run proves the synchronisation, not luck. + # only the thread sanitizer. It runs the concurrent torn-read tests + # described under Verification in docs/design.md. The library selects + # its race-free payload copy under TSAN, so a clean run checks the + # synchronisation itself. - name: Configure (debug + thread sanitizer) run: meson setup build-tsan --buildtype=debug -Dbuild_tests=true -Db_sanitize=thread diff --git a/AGENTS.md b/AGENTS.md index 3fc8d95..55b8a2a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,11 +1,13 @@ # AGENTS.md -## Project-specific instructions +--- + +## 1) Project-specific instructions **Project:** `seqlock` -**Primary goal:** Single-writer / multi-reader sequence lock (seqlock) for lock-free, internally consistent snapshots of a multi-word value. Readers never block the writer and never observe a torn tuple. +**Primary goal:** A C11 single-writer, multi-reader sequence lock: one producer publishes a multi-word value with a wait-free store, any number of readers take consistent copies with a lock-free load, and no reader ever accepts a mixture of two stores. No allocation, no system calls, no locks. -### Essential commands +### 1.1 Essential commands #### Configure and build (library only) @@ -17,7 +19,7 @@ meson compile -C build #### Configure, build, and run unit tests ```sh -meson setup build --wipe --buildtype=debug -Dbuild_tests=true +meson setup build --wipe --buildtype=debug -Dbuild_tests=true -Db_sanitize=address,undefined meson compile -C build meson test -C build --verbose ``` @@ -29,104 +31,110 @@ meson setup build-tsan --wipe --buildtype=debug -Dbuild_tests=true -Db_sanitize= meson test -C build-tsan --verbose ``` -Run TSAN on an x86-64 host (or a 4K-page AArch64). TSAN cannot initialise on a -16K-page AArch64 kernel (47-bit VMA); use a native or ASAN/UBSan build there. +#### MISRA C:2023, once per atomic backend (reads `build/compile_commands.json`) + +```sh +env -u MISRA_RULE_TEXTS misch run --baseline +env -u MISRA_RULE_TEXTS misch run --baseline --profile c11 +env -u MISRA_RULE_TEXTS misch run --baseline --profile no_atomics +misch deviations +``` + +#### Formatting (pinned clang-format through `uvx`) + +```sh +scripts/format.sh # check, as CI does +scripts/format.sh --fix # rewrite in place +``` + +### 1.2 Notes + +- `meson setup` generates the optional `seqlock_version.h` into the build directory; `seqlock.h` does not include it. +- The build produces only a static library. The only Meson option is `build_tests`. +- `SEQLOCK_COUNTER_TYPE` and the backend macros must be identical for the library and every caller; nothing detects a mismatch. `seqlock.h` includes `seqlock_conf.h` with quotes, so configuration is by `-D` only, never by a replacement header. +- ThreadSanitizer needs a 4 KiB-page kernel with a 48-bit address space on AArch64, and AddressSanitizer does not start on a 39-bit one; use a plain native build there. + +--- + +## 2) Non-negotiable design invariants -### CI / source of truth +- **Protocol.** Odd counter store, release fence (F1), payload copy, release store of the next even value. Reader: acquire load, copy, acquire fence, relaxed load, accept only on equality. Never remove F1 or weaken an ordering; a compiler barrier is not a substitute on weakly ordered CPUs. +- **One writer per cell.** `store` is never concurrent with another `store` on the same cell, and `init` is never concurrent with anything. +- **Type-erased core.** The protocol, fences and payload copy live once, in `src/seqlock.c`. `SEQLOCK_DEFINE` emits only `static inline` forwarders, and the cell layout `{ seqlock_hdr_t hdr; type payload; }` is part of the contract. +- **Selectable backend.** Every counter access and fence goes through the `seqlock_conf.h` macros. The two atomic backends must reject a counter that is not always lock-free at compile time. +- **Payload copy.** `memcpy` under `no_sanitize("thread")` by default, relaxed byte-wise atomics under ThreadSanitizer. A change to the copy keeps ThreadSanitizer clean and the mt and soak tests passing. +- No heap, no system calls, no blocking, no global state. + +--- + +## 3) CI / source of truth - CI definitions live in `.github/workflows/ci.yml`. -- A dedicated `tsan` job runs the thread sanitiser; ASAN and TSAN are mutually - exclusive, so it is separate from the ASAN/UBSan matrix. -- Prefer running the same commands locally as CI runs. -- If `pre-commit` is configured later, run it before committing. +- Prefer running the same commands locally as CI runs (see §1.1 above). +- Install Python tools (Meson, Ninja, gcovr, misch) with `uv tool install`, never `pip`; CI does the same through `astral-sh/setup-uv`. CI installs `cppcheck` from Homebrew because Ubuntu's 2.13 reports different findings. +- `misch run --baseline` must pass for the base configuration and both profiles; each has its own baseline in `analysis/baseline/`. Never regenerate a baseline to admit a new finding. Run it with `MISRA_RULE_TEXTS` unset, as CI does. +- The CI jobs are: tests under ASan/UBSan, the same tests under ThreadSanitizer, a release build, a 100 percent line and branch coverage gate merged across backends, a TI C2000 library build (CGT 22.6.2 and 25.11.1, COFF and EABI, warnings as errors), `clang-format`, and `misch` for each backend. + +--- + +## 4) Docs / commit conventions + +### Documentation layout + +- `README.md` is a short landing page (about 85 lines). Put detail in `docs/`, never in the README; link to the owning file instead. +- `docs/integration.md` owns requirements, install methods, configuration consistency, building, sanitiser host limits, and cross builds. +- `docs/api.md` owns the API reference, the configuration macros and recipes. Change it together with the headers; keep signatures in fenced `c` blocks and describe them in prose, not function tables. Check every value an example states against a build. +- `docs/design.md` is the single authoritative design record: protocol, memory ordering, backends and their limits, payload copy, progress, counter wrap, failure behaviour, MISRA position, and verification. +- `CONTRIBUTING.md` documents the contributor workflow; `CHANGELOG.md` holds release history (Keep a Changelog); `.github/SECURITY.md` covers vulnerability reporting. +- Code blocks in `README.md`, `CONTRIBUTING.md`, and `docs/` are compiled by the `seqlock docs examples` test (`tests/docs/check_snippets.py`). Each document is compiled as one source file: a `c` fence is file-level code, `` wraps statements, and `` excludes pseudo-code. Do not use `skip` to silence a broken example. +- Prose uses British spelling. Do not hard-wrap Markdown: write one line per paragraph. The 80-column limit applies to C source, not Markdown. -## Docs / commit conventions +### Commits -- Use Conventional Commits when asked to commit. -- Keep commits focused and explain why the change exists. -- **Never** commit unless the user explicitly asks. +- Use **Conventional Commits** format when asked to commit. +- Keep commits focused; explain *why* in the message body. -## C style expectations +--- -### Build and configuration +## 5) C style expectations -- Use the Meson build system; do not introduce another build system. -- Update `meson.build` when adding or removing source files or public headers. -- `seqlock_conf.h` is a public configuration header; install it alongside - `seqlock.h`. -- The library is `both_libraries('seqlock', 'src/seqlock.c', ...)`: the compiled - core is a real translation unit, not an empty stub. +### Build & configuration + +- Use the Meson build system. Do not introduce CMake, Make, or other systems. +- Update `meson.build` and `tests/meson.build` when adding or removing files. +- `seqlock_conf.h` is public and installed beside `seqlock.h`. Every option in it stays behind an `#ifndef` guard. ### Formatting -- `.clang-format` is present and should be used on modified `.c` and `.h` files. +- `.clang-format` is present and **mandatory**. Run `scripts/format.sh --fix` before committing. It runs the clang-format release pinned in the script through `uvx`. Do not use a system `clang-format`: another release can format the same code differently. - Do not reformat unrelated code. - Key settings: 8-space indent, `BreakBeforeBraces: Linux`, column limit 80. -- Avoid em dashes in comments, doc-comments, and prose. - -### Style and correctness - -- Match the conventions in the existing files. -- All public identifiers use the `seqlock_` / `SEQLOCK_` prefix. -- Keep public headers minimal and stable; do not expose internal helpers. -- Prefer explicit fixed-width integer types when ABI or serialisation matters. -- No dynamic memory, no syscalls, no blocking anywhere in the library. -- Compile-time validation via `_Static_assert` (lock-free counter, non-empty and - non-over-aligned payload); the primitive must fail to compile rather than - degrade silently. -- Public symbols carry Doxygen annotations with full contract information - (preconditions, concurrency, return semantics). -- Use `seqlock_conf.h` for compile-time configuration options. It is included - automatically by `seqlock.h` and every option is `#ifndef`-guarded so a - consumer can override it (e.g. via a project `config/seqlock_conf.h`). -- **Do not** preserve backwards compatibility unless the user explicitly asks. - -### Architecture / API design - -- Hybrid layout: a type-erased core (`seqlock_core_*` in `src/seqlock.c`) holds - all correctness-critical logic, and `SEQLOCK_DEFINE(name, type)` emits thin - `static inline` typed shims that forward to it. Keep the protocol, fences, and - TSAN handling in the core, in one place; the shims only add type safety. -- The generated cell layout is fixed and part of the contract: - `{ seqlock_hdr_t hdr; type payload; }`, `hdr` first. -- Single-producer: at most one thread calls `store()` per cell; concurrent - writers are undefined behaviour. -- `load()` / `try_load()` are safe for any number of readers concurrent with the - writer. The payload must be trivially copyable POD, stored by value. -- `init()` is setup-only and must not run concurrently with `store()`/`load()`. -- `try_load()` returns `false` on bound exhaustion; `*out` is then unspecified - (no scratch buffer is allocated). Callers branch on the return value. - -### Concurrency correctness (read before touching the protocol) - -- The writer's release fence after the odd increment (F1) is **mandatory** on - weakly-ordered CPUs; a plain compiler barrier is NOT sufficient. Do not - "simplify" it away. -- The even increment publishes via a release store; the reader's first load is - acquire and its second load is preceded by an acquire fence. Do not weaken - these orderings. -- Payload-copy race handling uses a benign `no_sanitize("thread")` `memcpy` - normally, and a race-free relaxed-atomic copy under TSAN (auto-selected via - `SEQLOCK_ATOMIC_PAYLOAD_COPY`). If you change the copy, the TSAN test must - stay clean and the deterministic torn-read test must still pass. -- All atomics and fences go through the `seqlock_conf.h` macros so the backend - (`__atomic`, C11, or uniprocessor fallback) stays swappable. +- Keep each file's existing `/* ==== NAME ==== */` section banners. + +### Style & correctness + +- Match conventions in the existing files (indentation, braces, naming). +- Every public identifier uses the `seqlock_` or `SEQLOCK_` prefix. Keep public headers minimal; do not expose internal helpers. +- Validate pointer arguments at every public API boundary. Public functions return `void` or `bool`; no `errno`. +- Use fixed-width types from ``; never plain `int` for a fixed-width quantity. +- Reject an unusable configuration with `_Static_assert` or `#error` rather than degrading at run time. +- Public symbols carry Doxygen with the full contract: preconditions, concurrency, and return semantics. + +### MISRA deviations + +- Prefer compliant code; never restructure only to hide a finding. Deviate at the point of use with `/* cppcheck-suppress misra-c2012- ; @deviation */`, or project-wide in `analysis/deviations/misra-deviations.txt` for a house-style rule. ### Comment placement (Doxygen) - Inline trailing annotations (`/**< ... */`) on `enum`/`struct` members are allowed only when the resulting line fits the 80-column limit. - If any member's annotation would overrun, move **all** of that aggregate's member docs into a single structured Doxygen block above the type, as an `@details` list of `- ::SYMBOL description` entries. - Never mix inline and block forms within one aggregate, and never leave a trailing comment that clang-format would wrap onto a second line. -- After editing, verify with a `clang-format --style=file` no-reformat diff and an 80-column scan. +- After editing, run `scripts/format.sh` and an 80-column scan. ### Testing -- Run `meson test -C build` after changes; also run the TSAN build for any - change to the protocol or the payload copy. -- Tests live in `tests/test_*.c` using the built-in harness in - `tests/seqlock_test.h` (`TEST_CASE` / `TEST_ASSERT` / `run_test`). Do not add - Unity or other external test dependencies. -- The multi-threaded torn-read test (`tests/test_seqlock_mt.c`) doubles as the - TSAN gate; its payload carries a self-checking invariant so any torn read is - detected at runtime, independent of the sanitiser. +- Run `meson test -C build` after every change, and the ThreadSanitizer build for any change to the protocol, a backend or the payload copy. +- Tests use the harness in `tests/seqlock_test.h` (`TEST_CASE`, `TEST_ASSERT`, `run_test`). Do not add Unity or another external framework. +- Concurrency tests assert an invariant, never a timing. Reach new branches deterministically in a single thread, as `tests/test_seqlock_retry.c` does. - Add a test case for each bug fix and each new feature. +- Keep `src/` and `include/` at the coverage gate (100 percent line and branch). diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b54f68..674ffca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - `scripts/format.sh`, which pins the clang-format release and runs it with `uvx`. CI checks formatting through it. - CI runs the MISRA C:2023 analysis with `misch` for each atomic backend, fails on any finding outside that backend's recorded baseline, and prints the deviation record. - CI compiles the library with warnings as errors using two releases of a vendor C11 compiler for a 16-bit-MAU DSP target, under both of its object formats. That compiler selects the uniprocessor backend. +- `docs/integration.md`, `docs/api.md` and `docs/design.md`. The design record covers the protocol and its memory-ordering argument, the limits of the uniprocessor backend, progress guarantees, counter wrap, and verification. The README is now a landing page. +- A `seqlock docs examples` test that compiles every C example in the documentation against the public headers. ### Changed diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7eadaa8..9e3d193 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,143 +1,113 @@ # Contributing to seqlock -seqlock is a small C library providing a single-writer / multi-reader -sequence lock: a lock-free way to publish a multi-word value as an -internally consistent snapshot. It is designed to be safe to drop into -embedded firmware and audited, safety-adjacent environments. +`seqlock` is a small C11 sequence lock: one writer publishes a multi-word value and any number of readers take consistent copies of it without locks. Its correctness lives in a few memory-ordering choices that no single-threaded test can see, so read [design.md](docs/design.md) before you change the protocol, the fences, or the payload copy. ## Getting started -The same commands CI runs, locally: +Install a C11 compiler and install the Python tools with [uv](https://docs.astral.sh/uv/), as CI does. The MISRA analysis also needs a current `cppcheck`; CI installs it from Homebrew because the 2.13 release in Ubuntu 24.04 reports different findings. The same commands CI runs, locally: ```sh -# Configure with tests + sanitisers (CI default) -meson setup build --buildtype=debug -Dbuild_tests=true \ - -Db_sanitize=address,undefined +# Python tools +uv tool install meson +uv tool install ninja +uv tool install gcovr +uv tool install misch + +# Configure with tests and sanitisers (CI default) +meson setup build --buildtype=debug -Dbuild_tests=true -Db_sanitize=address,undefined meson compile -C build meson test -C build --verbose -# ThreadSanitizer (separate from ASan; CI runs a dedicated job) -meson setup build-tsan --buildtype=debug -Dbuild_tests=true \ - -Db_sanitize=thread +# ThreadSanitizer, which cannot share a build with AddressSanitizer +meson setup build-tsan --buildtype=debug -Dbuild_tests=true -Db_sanitize=thread meson compile -C build-tsan meson test -C build-tsan --verbose -# Coverage (CI gates on 100% line and branch coverage of src/ + include/) -meson setup build-cov --buildtype=debug -Dbuild_tests=true -Db_coverage=true \ - -Dc_args=-fprofile-update=atomic +# Release build (the configuration a downstream consumer uses) +meson setup build-rel --buildtype=release -Dbuild_tests=false +meson compile -C build-rel + +# Coverage (CI gate is 100% line and branch for src/ and include/) +meson setup build-cov --buildtype=debug -Dbuild_tests=true -Db_coverage=true -Dc_args=-fprofile-update=atomic meson compile -C build-cov && meson test -C build-cov -gcovr --root . --filter 'src/' --filter 'include/' \ - --fail-under-line 100 --fail-under-branch 100 --print-summary +gcovr --root . --filter 'src/' --filter 'include/' --fail-under-line 100 --fail-under-branch 100 --print-summary + +# MISRA C:2023, once per atomic backend (reads build/compile_commands.json) +env -u MISRA_RULE_TEXTS misch run --baseline +env -u MISRA_RULE_TEXTS misch run --baseline --profile c11 +env -u MISRA_RULE_TEXTS misch run --baseline --profile no_atomics +misch deviations + +# Formatting (pinned clang-format through uvx) +scripts/format.sh --fix ``` -Run the TSAN build on an x86-64 host (or a 4K-page AArch64). TSAN cannot -initialise on a 16K-page AArch64 kernel (47-bit VMA); use a native or -ASan/UBSan build to validate the weak-memory path there. +The coverage build needs `-fprofile-update=atomic`. The concurrency tests update the same instrumented lines from several threads, and gcov's default counters are not thread-safe, so without it the arc counts race and gcov derives negative branch counts that abort `gcovr`. Do not hide that with `--gcov-ignore-parse-errors`. -`-fprofile-update=atomic` is required for the coverage build. gcov's profile -counters are not thread-safe by default, and the concurrency tests update the -same instrumented lines from multiple threads. Without atomic counters those -updates race, the arc counts become inconsistent, and gcov's flow-graph solver -derives negative branch counts that corrupt the report (and abort gcovr). The -atomic-update flag costs a little runtime but is the correct fix; do not paper -over the symptom with `--gcov-ignore-parse-errors`. +ThreadSanitizer and AddressSanitizer do not start on every AArch64 kernel; [integration.md](docs/integration.md#build-and-test) lists the limits. On such a host, run a plain native build of the full suite instead. ## Source style -- `.clang-format` is mandatory. Run `clang-format -i` on every modified - `.c` / `.h` file before submitting. -- 8-space indent, Linux brace style, 80-column limit. Match the existing - conventions; do not reformat unrelated code. -- Avoid em dashes in comments, doc-comments, and prose. -- The Meson build system is the single source of truth. Update - `meson.build` / `tests/meson.build` when adding or removing source files. -- No CMake, no Make, no other build systems. +- Formatting is mandatory. Run `scripts/format.sh --fix` before submitting, or `scripts/format.sh` to check without writing, as CI does. The script pins the clang-format release and runs it through `uvx`, so an editor formatter gives the same result only when it runs the same release. +- 8-space indent, Linux brace style, 80-column limit. Match the existing conventions, including each file's `/* ==== NAME ==== */` section banners, and do not reformat unrelated code. +- The Meson build system is the single source of truth. Update `meson.build` and `tests/meson.build` when you add or remove files. No CMake, no Make, and no other build systems. ## C language rules -- C11 only (uses `_Static_assert`, `_Atomic`, `_Alignof`, `_Alignas`). -- Use fixed-width types from `` and ``. Never plain - `int` for fixed-width fields. -- No heap allocation (`malloc`, `free`, VLAs), no syscalls, no blocking on - any path. -- Validate pointer arguments at every public-API boundary. -- All public identifiers use the `seqlock_` / `SEQLOCK_` prefix. -- Public functions return `void` or `bool` and validate via early return. No - `errno`, no exceptions. -- All atomics and fences go through the `seqlock_conf.h` macros so the - backend stays swappable; do not call `__atomic_*` or `` - directly from the core. +- C11 only. +- Use fixed-width types from `` and ``, and never plain `int` for a fixed-width quantity. +- No heap allocation (`malloc`, `free`, VLAs), no system calls, and no blocking on any path. +- Validate every pointer argument at the public API boundary. Public functions return `void` or `bool`; there is no `errno` and no exceptions. +- Every public identifier uses the `seqlock_` or `SEQLOCK_` prefix. +- Every atomic access and fence goes through the `seqlock_conf.h` macros, so that the backend stays selectable. Do not call `__atomic_*` or `` directly from the core; the race-free payload copy, which exists only on GCC and Clang, is the one exception. +- Reject an unusable configuration at compile time with `_Static_assert` or `#error`, rather than degrading at run time. ## Concurrency rules -The correctness of this library lives in its memory ordering. Keep these -invariants: - -- The writer's release fence after the odd increment (F1) is **mandatory** - on weakly-ordered CPUs. A plain compiler barrier is **not** sufficient; do - not "simplify" it away. -- The even increment publishes via a release store; the reader's first load - is acquire and its second load is preceded by an acquire fence. Do not - weaken these orderings. -- `store()` is single-producer; concurrent writers are undefined behaviour. -- The payload-copy race is intentional and benign. If you change the copy, - the TSAN concurrency test must stay clean **and** the deterministic - torn-read test must still pass. -- Any change to the protocol or payload copy must be validated under - ThreadSanitizer (race detection) and natively on AArch64 (real - weak-memory ordering). - -## MISRA C:2012 - -The library is written against MISRA C:2012. The full deviation record lives -in the file header of `src/seqlock.c`. If your change introduces a new -deviation: - -1. Add an entry to the file-header deviation record (rule, site, - justification). -2. Add an inline `/* MISRA */` marker at the deviation site. -3. Justify the deviation in the PR description. - -`required` rule deviations face a higher bar than `advisory`. We currently -have only advisory deviations and want to keep it that way. +- The writer's release fence after the odd counter store (F1) is required on weakly ordered CPUs. A compiler barrier is not enough; do not remove it. +- The completing counter store is a release store. The reader's first counter load is an acquire load, and its second is preceded by an acquire fence. Do not weaken any of them. +- `store` has one writer per cell; concurrent writers are undefined behaviour. +- The default payload copy races with the writer by design, and the counter check discards any copy the race affects. If you change the copy, ThreadSanitizer must stay clean and the mt and soak tests must still pass. +- Validate any change to the protocol or the payload copy under ThreadSanitizer, and natively on an AArch64 host, where stores can be reordered. + +## MISRA C:2023 + +The library is analysed with `misch` (cppcheck-backed MISRA C:2023 analysis), configured by `misra.toml`, over `include/` and `src/`. Each backend compiles different code, so the analysis runs three times: the `__atomic` backend in the base configuration, and the `c11` and `no_atomics` profiles. Each has its own baseline in `analysis/baseline/`, and CI fails on any finding that is not in the matching baseline. Run it from a configured `build/` directory, with `MISRA_RULE_TEXTS` unset, as CI does. If your change introduces a finding: + +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 finding from the checker; an honest deviation beats evasion. +2. Suppress at the point of use with `/* cppcheck-suppress misra-c2012- ; @deviation */`, or add a justified project-wide entry to `analysis/deviations/misra-deviations.txt` for a house-style rule. +3. Verify with all three `misch run` commands and `misch deviations`, which requires every suppression to carry a rationale, and justify the deviation in the pull request description. + +Do not regenerate a baseline to admit a new finding. A baseline changes only after a deliberate review, with `misch baseline` and the same `--profile`. + +Full tool-driven compliance beyond this analysis needs a certified static analyser, which this repository does not vendor. ## Tests and coverage - Add a test for every bug fix and every new feature. -- Tests live in `tests/test_*.c` using the built-in harness in - `tests/seqlock_test.h` (`TEST_CASE` / `TEST_ASSERT` / `run_test`). Do not - add Unity or other external test dependencies. -- The concurrent torn-read test (`tests/test_seqlock_mt.c`) doubles as the - TSAN gate. Its payload carries a self-checking invariant so a torn read is - caught at runtime, independent of the sanitiser. Keep new concurrency tests - deterministic in their pass/fail criterion (assert an invariant, not a - timing). -- Concurrency tests shrink their iteration budget under a sanitiser - (`SEQLOCK_TEST_SANITIZED` in `tests/seqlock_test.h`): sanitisers add a - 10-50x slowdown and race detection comes from interleavings, not volume. - Keep the full budget for native builds. Counts are `-D`-overridable. -- The type-erased core (`seqlock_core_*`) is exercised directly by - `tests/test_seqlock_core.c`, including its argument-validation paths, which - the typed shims cannot reach. New core behaviour needs a test there. -- CI gates on **100% line and branch coverage** of `src/` and `include/`, - merged across every backend build. Reach new branches deterministically, - not through the concurrent tests: `tests/test_seqlock_retry.c` shows how - the reader retry paths are driven single-threaded. New code without tests - fails the gate. -- Each non-default backend (C11, no-atomics) is built and run by - `tests/test_seqlock_backend.c`. -- All tests must pass on every CI configuration: Linux with - ASan/UBSan, the dedicated TSAN job, the coverage gate, and the release - build. +- Tests live in `tests/test_*.c`, written with the `TEST_CASE`, `TEST_ASSERT` and `run_test` macros from `tests/seqlock_test.h`. Do not add Unity or another external test framework. Each new file is listed in `tests/meson.build`. +- Concurrency tests assert an invariant, never a timing. The mt and soak payloads derive every word from one seed, so a mixed copy fails at run time whether or not a sanitiser is present. +- Concurrency tests run a smaller iteration count under a sanitiser, through `SEQLOCK_TEST_SANITIZED` in `tests/seqlock_test.h`: a sanitiser slows them by an order of magnitude, and it finds races from interleavings, not volume. The counts can be overridden with `-D`. +- `tests/test_seqlock_core.c` calls the core functions directly, including the argument checks the typed functions cannot reach. New core behaviour needs a test there. +- CI enforces 100 percent line and branch coverage of `src/` and `include/`, merged across every backend build. Reach new branches deterministically, not through the concurrent tests; `tests/test_seqlock_retry.c` shows how the reader retry paths are driven in a single thread. +- The `seqlock docs examples` test compiles every C code block in `README.md`, `CONTRIBUTING.md`, and `docs/` against the public headers, through `tests/docs/check_snippets.py`. A block compiles at file scope by default. On the line directly above the fence, put `` for a block of statements, or `` for pseudo-code or a copy of a header definition. + +## Documentation + +| File | Purpose | +| --- | --- | +| `README.md` | Landing page: quick start, description, validated toolchains, and links. Keep it short. | +| `docs/integration.md` | Requirements, installation, configuration consistency, building, and cross builds. | +| `docs/api.md` | Reference for the typed cell, the core functions, the configuration macros, and recipes. | +| `docs/design.md` | The protocol, memory ordering, backends, payload copy, progress, counter wrap, MISRA position, and verification. | + +Update `docs/api.md` and the header Doxygen together when an interface changes, and check every value an example states against a build. Update `docs/design.md` when the protocol, a backend, or the verification changes. Keep it standalone: describe how the library works, not how it was built or which other projects use it. Write prose in British English, one line per paragraph. ## API stability -- The public API in `seqlock.h` and the configuration surface in - `seqlock_conf.h` are stable across a minor (`0.x` / `x.y`) line. -- The generated cell layout `{ seqlock_hdr_t hdr; type payload; }` is part of - the contract; changing member order or names is a breaking change. -- Breaking changes go in a new major release and are recorded in - `CHANGELOG.md`. +- The public API in `seqlock.h` and the configuration macros in `seqlock_conf.h` are stable within a minor release line. +- The generated cell layout, `seqlock_hdr_t hdr` followed by `type payload`, is part of the contract; changing the member order or names is a breaking change. +- Changing a function signature, the meaning of a configuration macro, or a default that changes the layout of `seqlock_hdr_t` is a breaking change and needs a major release. ## Commits @@ -145,26 +115,21 @@ Use Conventional Commits: - `feat: ...` new feature - `fix: ...` bug fix -- `doc: ...` documentation only +- `docs: ...` documentation only - `test: ...` test-only changes - `chore: ...` build, CI, release work -- `refactor: ...` code change that neither fixes a bug nor adds a feature +- `refactor: ...` a change that neither fixes a bug nor adds a feature -Keep the subject under ~70 characters. Use the body to explain _why_ the -change is needed, not _what_ the diff already shows. +Keep the subject under about 70 characters. Use the body to explain why the change is needed. ## Pull requests -- Open an issue first for non-trivial changes, especially anything touching - the memory-ordering protocol, so the design can be agreed before - implementation. -- Keep PRs focused. One feature or one fix per PR. -- All CI checks must pass: tests under ASan/UBSan, the TSAN job, - and the release build. -- Flag any new MISRA deviation in the PR description. +- Open an issue first for non-trivial changes, and always for a change to the memory-ordering protocol, so the design can be agreed before implementation. +- Keep pull requests focused: one feature or one fix. +- All CI checks must pass. +- Add a `CHANGELOG.md` entry under `## [Unreleased]` for a user-visible change. +- Flag any new MISRA deviation, and any change to the protocol or the payload copy, in the description. ## When in doubt -Open an issue and discuss before writing code. The library is small and its -correctness is subtle; even modest changes to the protocol have outsized -implications. +Open an issue. The library is small, but a modest change to its ordering can break it on hardware that no CI runner uses. diff --git a/README.md b/README.md index 567f704..5f78b8f 100644 --- a/README.md +++ b/README.md @@ -1,254 +1,86 @@ # seqlock [![CI](https://github.com/aajll/seqlock/actions/workflows/ci.yml/badge.svg)](https://github.com/aajll/seqlock/actions/workflows/ci.yml) +[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) -Single-writer / multi-reader sequence lock for lock-free, internally consistent snapshots of a multi-word value in C. +**Single-writer, multi-reader sequence lock for C11: one producer publishes a multi-word value and any number of readers take consistent snapshots of it without locks.** -## Features +## Quick start -- **Lock-free readers, wait-free writer**: readers never block the writer and the writer never blocks on readers, so a slow or stalled consumer cannot stall the producer -- **Consistent multi-word snapshots**: a reader always observes either the complete previous value or the complete new one, never a torn tuple, even when the payload is wider than a machine word -- **Typed, zero-allocation cells**: `SEQLOCK_DEFINE(name, type)` generates a type-safe cell that stores the payload by value, with no heap, no syscalls, and no blocking on any path -- **Type-erased core**: the counter/fence/copy protocol is compiled once in `seqlock.c`; the typed API is a thin `static inline` shim, keeping the correctness-critical logic in one auditable place -- **Portable C11 atomics**: correct on weakly-ordered CPUs (AArch64) and x86-64, selecting a GCC/Clang `__atomic` path, a C11 `` path, or a uniprocessor fallback -- **ThreadSanitizer-clean**: auto-selects a race-free relaxed-atomic payload copy under TSAN and a fast benign-race-annotated `memcpy` otherwise -- **Bounded read variant**: `try_load()` gives up after a caller-set retry count instead of spinning, for callers that must not block -- **Configurable**: counter width, per-cell cache-line alignment, retry default, and copy strategy are all overridable through `seqlock_conf.h` -- **Auditable design**: static allocation, explicit per-function contracts, compile-time validation, and a small codebase - -## Installation - -### As a Meson subproject - -```meson -seqlock_dep = dependency('seqlock', fallback: ['seqlock', 'seqlock_dep']) -``` - -The project also exports `meson.override_dependency('seqlock', ...)` -so downstream Meson builds can resolve the subproject dependency by name. - -For subproject builds, include the public header directly: +Copy `include/` and `src/seqlock.c` into your project. For a Meson subproject or an installed `pkg-config` package, see the [integration guide](docs/integration.md). ```c -#include "seqlock.h" -``` - -`seqlock.h` includes `seqlock_conf.h` automatically, so a single include is -enough. To pin configuration in one place, include `seqlock_conf.h` first: - -```c -#define SEQLOCK_COUNTER_TYPE uint64_t -#include "seqlock_conf.h" -#include "seqlock.h" -``` - -### Project-level configuration - -Every option in `seqlock_conf.h` is `#ifndef`-guarded, so a consumer can -override it without forking the library. Place a `config/seqlock_conf.h` in your -project, put `config/` ahead of the subproject include path, and your header -wins while the shipped defaults remain the fallback (the same pattern used for -`queue_conf.h` in the supervisory controller). - -### As an installed dependency - -If the library is installed system-wide, include the namespaced header path: - -```c -#include -``` - -The public configuration header is also installed as: - -```c -#include -``` - -If `pkg-config` files are installed in your environment, downstream builds can -also discover the package as `seqlock`. - -The generated version header is available as `seqlock_version.h` in the -build tree and as `` after install. It is optional -and is not included by the library or its tests. - -## Quick Start - -```c -#include "seqlock.h" - #include #include -/* The value published by one producer and read by many consumers. */ typedef struct { - float value; + float value; uint64_t timestamp_ns; - bool valid; + bool valid; } io_sample_t; -/* Generate the typed cell `io_cache_t` and its init/store/load/try_load ops. */ +/* Generates the cell type io_cache_t and io_cache_init/store/load/try_load. */ SEQLOCK_DEFINE(io_cache, io_sample_t) -static io_cache_t cache; /* one cell; embed it anywhere, no heap needed */ +static io_cache_t cache; -/* --- producer side (sole writer) --- */ -void publish(float v, uint64_t ts, bool ok) +/* Producer: the only writer of this cell. */ +void +publish(float value, uint64_t timestamp_ns) { - io_sample_t s = { .value = v, .timestamp_ns = ts, .valid = ok }; - io_cache_store(&cache, &s); /* wait-free */ + io_sample_t s = {.value = value, .timestamp_ns = timestamp_ns, + .valid = true}; + io_cache_store(&cache, &s); } -/* --- consumer side (any number of readers) --- */ -bool sample_is_fresh(uint64_t now_ns, uint64_t max_age_ns) +/* Consumers: any number, concurrently with the producer. */ +bool +sample_is_fresh(uint64_t now_ns, uint64_t max_age_ns) { io_sample_t s; - io_cache_load(&cache, &s); /* lock-free, always a consistent tuple */ + io_cache_load(&cache, &s); /* never a mix of two stores */ return s.valid && (now_ns - s.timestamp_ns) <= max_age_ns; } -int main(void) +int +main(void) { - io_cache_init(&cache); /* setup-only: even counter, zeroed payload */ - publish(3.5f, 1000u, true); - - io_sample_t s; - io_cache_load(&cache, &s); - /* s holds {3.5f, 1000, true} as one consistent snapshot */ - return 0; + io_cache_init(&cache); /* before any store or load */ + publish(3.5f, 1000u); + return sample_is_fresh(1500u, 1000u) ? 0 : 1; /* returns 0 */ } ``` -## Building - -```sh -# Library only (release) -meson setup build --buildtype=release -Dbuild_tests=false -meson compile -C build - -# With unit tests -meson setup build --buildtype=debug -Dbuild_tests=true -meson compile -C build -meson test -C build --verbose - -# Concurrency check under ThreadSanitizer (x86-64 host; see Notes) -meson setup build-tsan --buildtype=debug -Dbuild_tests=true -Db_sanitize=thread -meson test -C build-tsan --verbose -``` - -## API Reference - -### Configuration Macros +## Description -| Macro | Description | -| -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `SEQLOCK_COUNTER_TYPE` | Unsigned integer type of the sequence counter (default: `uint32_t`; set `uint64_t` to remove the theoretical wrap concern). Must be lock-free on the target | -| `SEQLOCK_DEFAULT_MAX_RETRIES` | Suggested project-wide default bound for `try_load()` callers (default: 1000) | -| `SEQLOCK_CELL_ALIGNED` | When non-zero, pad each generated cell to a cache line to avoid false sharing in arrays of cells (default: 0) | -| `SEQLOCK_CACHELINE` | Cache-line size in bytes used when `SEQLOCK_CELL_ALIGNED` is set (default: 64) | -| `SEQLOCK_ATOMIC_PAYLOAD_COPY` | Payload-copy strategy: `0` = benign-race annotated `memcpy`, `1` = race-free relaxed-atomic copy. Auto-selects `1` under ThreadSanitizer, `0` otherwise | -| `SEQLOCK_USE_GNU_ATOMICS` / `SEQLOCK_USE_C11_ATOMICS` / `SEQLOCK_USE_NO_ATOMICS` | Advanced backend selection override. Define exactly one consistently for the seqlock library build and all consumers; do not override these only in an application using an already-built library. Otherwise the library auto-selects GCC/Clang `__atomic`, then C11 atomics, then the uniprocessor fallback | -| `SEQLOCK_NO_SANITIZE_THREAD` | Attribute used on the benign-race payload-copy helper when `SEQLOCK_ATOMIC_PAYLOAD_COPY == 0`. Override only when the compiler needs a different annotation or none | -| `SEQLOCK_CPU_RELAX` | Spin hint run on each reader retry (default: `pause` on x86, `yield` on AArch64, nothing elsewhere). Override to supply a platform relax primitive | +A sequence lock pairs a value with a counter that is odd while a write is in progress. The writer never waits for readers, and a reader that overlaps a write detects it from the counter and retries, so it only ever returns a complete value. -### Single-Include Override +- `SEQLOCK_DEFINE(name, type)` generates a typed cell that holds the payload by value, with no heap and no system calls +- Wait-free `store`, lock-free `load`, and a bounded `try_load` for callers that must not spin +- Correct on weakly ordered CPUs through acquire and release ordering, with GCC/Clang `__atomic`, C11 ``, or a uniprocessor `volatile` backend selected at compile time +- The counter, fence and copy protocol is compiled once, in `src/seqlock.c`, behind a type-erased core +- Unit, concurrency and soak tests under ASan, UBSan and ThreadSanitizer with 100% line and branch coverage, and MISRA C:2023 analysis with [`misch`](https://pypi.org/project/misch/) -Define macros before including `seqlock.h`; it pulls in the configuration -header automatically: +## Validated toolchains -```c -#define SEQLOCK_COUNTER_TYPE uint64_t -#define SEQLOCK_CELL_ALIGNED 1 -#include "seqlock.h" -``` +| Toolchain | Target | Validation | +| ----------------------- | ----------------------------- | ------------------------------------------------------------------ | +| GCC | x86_64 Linux | All tests under ASan and UBSan, and under ThreadSanitizer | +| DSP vendor C11 compiler | 16-bit MAU (`CHAR_BIT == 16`) | Library compile with the uniprocessor backend, two object formats | -### Type Definitions +Target linking and execution belong to the consuming firmware. See [cross builds](docs/integration.md#cross-builds). -| Type | Description | -| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -| `seqlock_hdr_t` | Sequence-counter header; the first member of every generated cell | -| `name##_t` | Generated by `SEQLOCK_DEFINE(name, type)`: a cell holding one `type` payload by value, laid out as `{ seqlock_hdr_t hdr; type payload; }` | +## Documentation -### Typed API +- [Integration guide](docs/integration.md) — copy-in, Meson subproject, installed package, configuration, building, and cross builds +- [API reference](docs/api.md) — the typed cell, the core functions, configuration macros, and recipes +- [Design](docs/design.md) — the protocol, memory ordering, backends, progress guarantees, and verification +- [Changelog](CHANGELOG.md) — release history -`SEQLOCK_DEFINE(name, type)` generates a typed cell and four operations. Each -forwards to the type-erased core and carries its contract: `store` is -single-producer, `load` / `try_load` serve any number of readers, and `type` -must be trivially copyable POD. Every operation validates its pointers. +## Contributing -```c -SEQLOCK_DEFINE(name, type) +Read [CONTRIBUTING.md](CONTRIBUTING.md) before you open a pull request. Report security issues as described in [SECURITY.md](.github/SECURITY.md). -void name##_init (name##_t *cell); /* setup-only */ -void name##_store(name##_t *cell, const type *in); /* sole producer, wait-free */ -void name##_load (const name##_t *cell, type *out); /* any readers, lock-free */ -bool name##_try_load(const name##_t *cell, type *out, uint32_t max_retries); -``` - -### Type-Erased Core - -The typed shims forward to these; a caller that prefers runtime sizing over the -macro can use them directly. - -```c -void seqlock_core_init (seqlock_hdr_t *hdr, void *payload, size_t size); -void seqlock_core_store(seqlock_hdr_t *hdr, void *payload, - const void *in, size_t size); -void seqlock_core_load (const seqlock_hdr_t *hdr, const void *payload, - void *out, size_t size); -bool seqlock_core_try_load(const seqlock_hdr_t *hdr, const void *payload, - void *out, size_t size, uint32_t max_retries); -``` +## License -## Use Cases - -- **Latest-known-value cache cell**: one bus worker publishes the newest sample, the control and monitor threads read whatever the current value is - - ```c - SEQLOCK_DEFINE(io_cache, io_sample_t) - io_cache_store(&cell, &sample); /* producer */ - io_cache_load(&cell, &out); /* any consumer */ - ``` - -- **Per-channel array without false sharing**: enable cache-line alignment so neighbouring cells written by different cores do not thrash a shared line - - ```c - #define SEQLOCK_CELL_ALIGNED 1 - #include "seqlock.h" - SEQLOCK_DEFINE(io_cache, io_sample_t) - static io_cache_t channels[NUM_CHANNELS]; - ``` - -- **Non-spinning read on a deadline-sensitive path**: bound the retry count and fall back instead of spinning under a hot writer - - ```c - io_sample_t out; - if (io_cache_try_load(&cell, &out, SEQLOCK_DEFAULT_MAX_RETRIES)) { - use(&out); - } else { - use_last_good(); /* out is unspecified on false */ - } - ``` - -- **Eliminate the theoretical counter wrap**: widen the counter for consumers that want the concern gone entirely - ```c - #define SEQLOCK_COUNTER_TYPE uint64_t - #include "seqlock.h" - ``` - -## Notes - -| Topic | Note | -| -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Single producer** | At most one thread may call `store()` on a given cell; concurrent writers are undefined behaviour. Use a write-side lock or a different primitive for multi-producer | -| **Readers** | `load()` and `try_load()` are safe for any number of concurrent readers, concurrent with the single writer | -| **Writer suspended mid-write** | A slow or hung producer between stores leaves the counter even, so `load()` returns the last stable snapshot immediately (freedom from interference holds). The only blocking window is if the writer is suspended or killed _between_ its two increments (the brief odd window); a reader then spins until it resumes. For a hard bound even in that pathological case, read with `try_load()` | -| **Reader progress under a hot writer** | A continuously-storing writer can force `load()` to retry; it still makes progress (not a hard livelock) but read throughput drops. `try_load()` bounds the work; `SEQLOCK_CPU_RELAX` eases contention while spinning | -| **POD payload** | The payload must be trivially copyable (no pointers needing a deep copy, no self-references); it is copied by value | -| **`init()` is setup-only** | Must not run concurrently with `store()` / `load()` on the same cell. It is idempotent; there is no destroy/reset because the cell owns no resources | -| **`try_load()` failure** | On `false` the contents of `*out` are unspecified (the no-allocation rule precludes a scratch buffer); branch on the return value, never on `*out` | -| **No dynamic memory** | No heap allocation, no syscalls, no blocking; cells are caller-owned and can be stack- or statically-allocated | -| **Memory ordering** | Correct under the C11 acquire/release model on weakly-ordered CPUs; validated natively on AArch64. All atomics route through `seqlock_conf.h` macros (`__atomic`, C11, or uniprocessor fallback) | -| **Counter wrap** | A `uint32_t` counter cannot cause an accepted torn read: that would require completing a full `2^32` write cycle during one reader's copy. Widen via `SEQLOCK_COUNTER_TYPE` if desired | -| **ThreadSanitizer** | The TSAN job auto-selects the race-free atomic copy and must run on an x86-64 (or 4K-page AArch64) host. TSAN cannot initialise on a 16K-page AArch64 kernel (47-bit VMA); use a native or ASAN/UBSan build there | -| **Lock-free counter** | A `_Static_assert` rejects a counter type that is not lock-free on the target, so the primitive fails to compile rather than degrade silently | -| **Version header** | `seqlock_version.h` is generated into the build folder and is optional | +MIT. See [LICENSE](LICENSE). diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 0000000..243d490 --- /dev/null +++ b/docs/api.md @@ -0,0 +1,173 @@ +# API reference + +`seqlock.h` declares the whole interface and includes `seqlock_conf.h`. The examples in this document compile together as one file after `#include "seqlock.h"`. + +## Conventions + +- One writer per cell. `store` must never run on two threads, or in a thread and an interrupt, for the same cell at once; that is undefined behaviour. Any number of readers may call `load` and `try_load` concurrently with each other and with the writer. +- The payload type must be trivially copyable: it is copied byte for byte, so a pointer member shares its target rather than copying it. +- `init` is for setup. Call it before any reader or the writer uses the cell, and never concurrently with them. +- No function allocates, makes a system call, or takes a lock. Every function checks its pointers; a NULL argument never dereferences. + +## Typed cells + +```c +#include + +typedef struct { + int32_t position; + int32_t velocity; +} axis_state_t; + +SEQLOCK_DEFINE(axis_cell, axis_state_t) +``` + +`SEQLOCK_DEFINE(name, type)` defines the cell type `name_t` and four `static inline` functions, `name_init`, `name_store`, `name_load` and `name_try_load`. Use it at file scope, without a trailing semicolon. It rejects a zero-size `type` and a `type` aligned more strictly than `max_align_t` at compile time. + +The cell holds the payload by value, so it can be static, on the stack, or a member of another structure. Its layout is part of the contract: + + +```c +typedef struct { + seqlock_hdr_t hdr; + type payload; +} name_t; +``` + +For `axis_cell` above, the generated functions are: + +```c +void axis_cell_init(axis_cell_t *cell); +void axis_cell_store(axis_cell_t *cell, const axis_state_t *in); +void axis_cell_load(const axis_cell_t *cell, axis_state_t *out); +bool axis_cell_try_load(const axis_cell_t *cell, axis_state_t *out, + uint32_t max_retries); +``` + +`name_init` sets the counter to zero and zeroes the payload, so a reader that runs before the first store reads an all-zero value. Calling it again resets the cell under the same setup-only rule. There is no destroy function, because the cell owns no resources. + +`name_store` copies `*in` into the cell. It is wait-free: it finishes in a bounded number of steps whatever the readers do. It does nothing if `cell` or `in` is NULL. + +`name_load` copies a consistent value into `*out`: the payload of one complete `store`, or the zeroed payload if no store has happened. It retries while a store overlaps the copy, and spins while a store is in progress, so it does not return if the writer stops part-way through a store; see [progress](design.md#progress). If `cell` is NULL and `out` is not, it zeroes `*out`. + +`name_try_load` does the same with at most `max_retries` attempts, and returns `true` with `*out` filled when one succeeds. It returns `false` when the attempts run out, when `max_retries` is 0, or when `cell` or `out` is NULL. After a `false` return the contents of `*out` are unspecified, because a failed attempt may have copied a mixture of two values; branch on the return value, never on `*out`. + +## Core functions + +```c +void seqlock_core_init(seqlock_hdr_t *hdr, void *payload, size_t size); +void seqlock_core_store(seqlock_hdr_t *hdr, void *payload, const void *in, + size_t size); +void seqlock_core_load(const seqlock_hdr_t *hdr, const void *payload, void *out, + size_t size); +bool seqlock_core_try_load(const seqlock_hdr_t *hdr, const void *payload, + void *out, size_t size, uint32_t max_retries); +``` + +The generated functions forward to these with `&cell->hdr`, `&cell->payload` and `sizeof(type)`. Call them directly when the payload size is known only at run time. The contracts are the same, with `size` as one more argument that must not be zero: + +- `seqlock_core_init` does nothing if `hdr` is NULL, and leaves the payload alone if `payload` is NULL or `size` is 0. +- `seqlock_core_store` does nothing if any pointer is NULL or `size` is 0. +- `seqlock_core_load` and `seqlock_core_try_load` treat a NULL pointer or a zero `size` as invalid. They zero `*out` when `out` is non-NULL and `size` is non-zero, and `seqlock_core_try_load` returns `false`. + +`seqlock_hdr_t` holds the sequence counter, `seq`. Only the library should read or write it while the cell is in use. + +## Configuration + +Each option is a macro in `seqlock_conf.h` with a default that a `-D` definition replaces. [integration.md](integration.md#configuration) explains which ones must match between the library and its callers. + +`SEQLOCK_COUNTER_TYPE` is the unsigned type of the sequence counter, `uint32_t` by default. A signed type fails to compile, and so does a type the target cannot access lock-free under the `__atomic` or C11 backend. A wider counter only lengthens the [wrap interval](design.md#counter-wrap). + +`SEQLOCK_DEFAULT_MAX_RETRIES` is 1000 by default. The library does not use it; it gives every caller of `try_load` in a project one shared bound. + +`SEQLOCK_CELL_ALIGNED`, 0 by default, aligns each generated cell to `SEQLOCK_CACHELINE` bytes, 64 by default, when non-zero. In an array of cells written by different cores, this keeps each cell's counter off its neighbours' cache lines. It needs `SEQLOCK_CACHELINE` to be an alignment the compiler supports for objects of that storage duration. + +`SEQLOCK_USE_GNU_ATOMICS`, `SEQLOCK_USE_C11_ATOMICS` and `SEQLOCK_USE_NO_ATOMICS` force a backend. Define at most one, to any value; defining two fails to compile. Without one, GCC and Clang use the `__atomic` backend, other C11 compilers with atomics use the C11 backend, and the rest use the uniprocessor backend. [design.md](design.md#backends) describes each. + +`SEQLOCK_CPU_RELAX()` runs once per reader retry. It is the `pause` instruction on x86 and `yield` on AArch64 under GCC and Clang, and does nothing elsewhere. Define it to a statement for another spin hint. It takes effect when `src/seqlock.c` is compiled. + +`SEQLOCK_ATOMIC_PAYLOAD_COPY` selects the payload copy. At 0 it is `memcpy`, marked with `SEQLOCK_NO_SANITIZE_THREAD`; at 1 it copies one byte at a time with relaxed `__atomic` operations. The default is 1 when ThreadSanitizer is active and 0 otherwise. The value 1 needs GCC or Clang. [design.md](design.md#payload-copy) explains the choice. + +`SEQLOCK_NO_SANITIZE_THREAD` is the attribute placed on the `memcpy` copy. It defaults to `__attribute__((no_sanitize("thread")))` where the compiler supports `no_sanitize`, and to nothing elsewhere. + +## Recipes + +### Bounded read + +A caller that must not spin, such as a control loop with a deadline, reads with a bound and falls back to its last good value: + +```c +static axis_cell_t axis; +static axis_state_t axis_last_good; + +/* Returns the current state, or the last one read if the writer is busy. */ +axis_state_t +axis_sample(void) +{ + axis_state_t s; + + if (axis_cell_try_load(&axis, &s, SEQLOCK_DEFAULT_MAX_RETRIES)) { + axis_last_good = s; + } + return axis_last_good; +} +``` + +On a single core where the reader is an interrupt handler and the writer runs at a lower priority, this is the only safe way to read: the handler can interrupt a store, and the store cannot finish until the handler returns, so `load` would never return. + +### One cell per channel + +```c +#define CHANNEL_COUNT 8u + +SEQLOCK_DEFINE(channel_cell, float) + +static channel_cell_t channels[CHANNEL_COUNT]; + +void +channels_init(void) +{ + uint32_t i; + + for (i = 0u; i < CHANNEL_COUNT; ++i) { + channel_cell_init(&channels[i]); + } +} +``` + +Each channel has its own writer. If those writers run on different cores, build with `-DSEQLOCK_CELL_ALIGNED=1` so that a store to one cell does not invalidate the cache line a reader of the next cell is using. + +### Run-time payload size + +The core functions take the cell as separate counter and payload pointers, so the caller owns the storage and its size: + +```c +#define RECORD_MAX_BYTES 64u + +typedef struct { + seqlock_hdr_t hdr; + _Alignas(max_align_t) unsigned char bytes[RECORD_MAX_BYTES]; + size_t size; +} record_cell_t; + +void +record_init(record_cell_t *cell, size_t size) +{ + cell->size = size; /* fixed before any reader or writer starts */ + seqlock_core_init(&cell->hdr, cell->bytes, cell->size); +} + +void +record_store(record_cell_t *cell, const void *in) +{ + seqlock_core_store(&cell->hdr, cell->bytes, in, cell->size); +} + +void +record_load(const record_cell_t *cell, void *out) +{ + seqlock_core_load(&cell->hdr, cell->bytes, out, cell->size); +} +``` + +`size` must not exceed `RECORD_MAX_BYTES` and must not change while the cell is in use, because the reader and the writer both copy that many bytes. diff --git a/docs/design.md b/docs/design.md new file mode 100644 index 0000000..c41766f --- /dev/null +++ b/docs/design.md @@ -0,0 +1,124 @@ +# Design + +This document is the design record for `seqlock`: the protocol, the memory ordering that makes it correct, what each backend guarantees, and how the library is verified. The API is described in [api.md](api.md). + +## Goals + +- Publish a value wider than one machine word from one writer to any number of readers, so that every reader gets the value of one complete store, never a mixture of two. +- Never make the writer wait for a reader, so a slow or stalled reader cannot delay the producer. +- No allocation, no system calls, no operating-system locks, and no global state. +- Keep the ordering logic in one compiled function per operation, behind a type-erased interface, so it can be reviewed once. + +## Non-goals + +- More than one writer per cell. Concurrent stores corrupt the counter; serialise writers outside the library or use another primitive. +- Payloads that need a deep copy. The payload is copied byte for byte. +- A history or queue of values. A reader sees only the latest complete store, and a reader that runs slower than the writer skips values. +- Fairness or a bounded wait for `load`. `try_load` is the bounded alternative. + +## Protocol + +Each cell holds a sequence counter and the payload. The counter is even while the payload is stable and odd while a store is in progress. It starts at zero. + +The writer, with the counter at an even value `s`: + +1. Stores `s + 1`, marking a store in progress. +2. Issues a release fence (F1). +3. Copies the new value into the payload. +4. Stores `s + 2` with release ordering, marking the store complete. + +The reader: + +1. Loads the counter with acquire ordering, as `s1`. If `s1` is odd, a store is in progress, so it retries. +2. Copies the payload out. +3. Issues an acquire fence (F2). +4. Loads the counter again, as `s2`. If `s2` equals `s1`, no store began during the copy, and it accepts the copy. Otherwise it retries. + +`try_load` runs the same loop and counts each pass, whether it saw an odd counter or a changed one, against its bound. + +## Memory ordering + +The acquire load of `s1` reads the value written by step 4 of some store. That release store synchronises with the acquire load, so every payload byte of that store is visible to the reader's copy. + +The second check rejects a copy that read any byte of a later store. Suppose the copy read a byte that a later store wrote in its step 3. That byte was written after F1, and read before F2, so F1 synchronises with F2. The later store's odd counter value therefore happens before the reader's load of `s2`, which reads that value or a newer one, and so differs from `s1`. A copy that saw any part of a newer value always fails the check. + +F1 is a hardware fence on a weakly ordered CPU, not just a compiler barrier. Without it, the payload stores of step 3 could become visible to another core before the odd counter of step 1, and a reader could copy half a new value between two loads of the same even counter. + +The argument treats the payload accesses as atomic, which they are with `SEQLOCK_ATOMIC_PAYLOAD_COPY` set to 1: each byte is copied with relaxed `__atomic` operations, the copy is free of data races in the C11 model, and the protocol matches the seqlock construction that Boehm describes in "Can Seqlocks Get Along With Programming Language Memory Models?" (MSPC 2012). With the default of 0, the copy is `memcpy`. A reader's copy that overlaps a store is then a data race, which the C11 standard leaves undefined. The library relies on GCC and Clang treating the fences and atomic counter accesses as compiler barriers, so that `memcpy` stays between them and compiles to ordinary loads and stores, whose result the counter check discards. See [payload copy](#payload-copy). + +## Backends + +`seqlock_conf.h` maps the counter accesses and fences onto one of three backends, chosen at compile time: + +- **GCC and Clang `__atomic` builtins**, the default on those compilers. The counter is a plain integer accessed with `__atomic_load_n` and `__atomic_store_n`, and the fences are `__atomic_thread_fence`. +- **C11 ``**, the default on other C11 compilers that do not define `__STDC_NO_ATOMICS__`. The counter is `_Atomic`, accessed with `atomic_load_explicit` and `atomic_store_explicit`, and the fences are `atomic_thread_fence`. +- **Uniprocessor**, the fallback for every other compiler. The counter is `volatile` and the fences do nothing. See [uniprocessor backend](#uniprocessor-backend). + +The two atomic backends refuse to compile when the target cannot access the counter type lock-free, rather than fall back to a lock that a reader could hold while the writer waits. The `__atomic` backend checks `__atomic_always_lock_free`. The C11 backend matches the counter's size to `char`, `short`, `int`, `long` or `long long` and requires the matching `ATOMIC_*_LOCK_FREE` macro to be 2, so a counter that is only sometimes lock-free is rejected. Both backends also reject a signed counter type, whose overflow would be undefined. + +### Uniprocessor backend + +This backend is correct only when a reader and the writer never run at the same time on different cores: a single-core target, or threads pinned to one core. Without fences, nothing orders the payload stores against the counter for another core. + +On one core, the writer and the readers interleave only through preemption, and the outcome depends on which preempts which: + +- A reader that preempts the writer, such as an interrupt handler reading a cell that the main loop writes, can arrive with the counter odd. The writer cannot finish until the reader returns, so `load` never returns. Read with `try_load` in that context, or make the store run with that reader masked. +- A writer that preempts a reader, such as an interrupt handler writing a cell that the main loop reads, always completes its store before the reader resumes. The reader sees the changed counter and retries. + +The backend has two further limits that the library cannot check: + +- `volatile` orders the counter accesses with respect to each other, but the C standard does not stop the compiler moving the non-volatile payload copy across them. The backend relies on the compiler keeping the copy between the two counter stores in the writer and between the two counter loads in the reader. Inspect the generated code for the store and load functions when you adopt a new compiler release or enable whole-program optimisation. +- The atomic backends check that the counter is lock-free; this one does not check that the target reads and writes the counter in one access. A counter that the target accesses in two halves can be read half old and half new when an interrupt arrives between them. Use a counter type the target accesses with one instruction. + +## Payload copy + +The writer's copy-in and the reader's copy-out share one helper, chosen by `SEQLOCK_ATOMIC_PAYLOAD_COPY`: + +- At 0, the default outside ThreadSanitizer, the helper calls `memcpy`. It is the fastest copy, and the only one available to compilers without `__atomic` builtins. The helper carries the `no_sanitize("thread")` attribute, so a ThreadSanitizer build that forces this copy does not report the race the counter check makes harmless. +- At 1, the default under ThreadSanitizer, the helper copies one byte at a time with relaxed atomic loads and stores. There is no data race for ThreadSanitizer to report, so a clean run does not depend on the sanitiser honouring an attribute through its `memcpy` interceptor, and every counter access stays instrumented. + +The concurrency tests therefore run with the race-free copy under ThreadSanitizer and with `memcpy` everywhere else. + +GCC reports `-Wtsan` for each standalone fence, because ThreadSanitizer does not model them. `src/seqlock.c` silences that warning only for GCC builds under ThreadSanitizer. The ordering ThreadSanitizer checks there comes from the acquire and release counter accesses, which it does model. + +## Progress + +The writer is wait-free. A store is two counter stores, a fence and a copy of fixed size, with no loop, so it finishes in a bounded number of steps whatever the readers do. + +A reader is lock-free while the writer runs. A reader retries only when a store was in progress or began during its copy, so every retry corresponds to progress by the writer. A writer that stores continuously can make one reader retry many times, lowering its read rate; `SEQLOCK_CPU_RELAX()` runs on every retry to ease the contention, and on a core shared with the writer through simultaneous multithreading it yields the pipeline to the writer. + +A reader is not wait-free, and not even lock-free when the writer stops mid-store. If the writer is suspended or killed between its two counter stores, the counter stays odd and `load` spins until the writer resumes. A writer suspended between stores leaves the counter even and does not affect readers. `try_load` bounds the work in every case. + +## Counter wrap + +The counter is unsigned and wraps through zero, so the parity test and the equality test stay correct across the wrap. Each store adds 2, so a reader could accept a mixed copy only if exactly 2^31 stores, with the default 32-bit counter, completed during one payload copy and brought the counter back to `s1`. A `uint64_t` counter raises that to 2^63 stores. + +## Failure behaviour + +The library has no error codes. Each function validates its pointers and size and degrades to a defined result: `init` and `store` do nothing, `load` zeroes the destination when it can, and `try_load` also returns `false`. [api.md](api.md#core-functions) lists the cases. A NULL cell is a caller defect, and zeroing the destination keeps a reader's result defined rather than stale. + +Breaking the single-writer rule, or calling `init` while the cell is in use, is undefined behaviour that the library cannot detect. + +## MISRA C:2023 + +`misch` analyses `include/` and `src/` once for each backend: the `__atomic` backend in the base configuration, and the C11 and uniprocessor backends through the `c11` and `no_atomics` profiles in `misra.toml`, because each backend compiles different code. Each analysis has a baseline in `analysis/baseline/` that records its accepted findings, and CI fails on any finding outside it. No deviation is recorded for any finding. + +The baselines hold 42, 36 and 35 findings. All three share the same core of Rules 2.5, 8.7, 12.1, 15.5 and 20.10. The rest follow from the backend: Rule 17.3 only for the `__atomic` backend, whose builtins have no declaration; Rule 10.4 only for the C11 backend; and Rules 12.3 and 13.4 only for the uniprocessor backend, whose counter-store macro uses the comma operator and an assignment as an operand. Full tool-driven compliance needs a certified static analyser, which this repository does not vendor. + +## Verification + +CI runs every test under ASan and UBSan, and again under ThreadSanitizer, on x86-64 Linux. A third build gates on 100% line and branch coverage of `src/` and `include/`, merged across the backend builds. The tests are: + +- **basic** and **core** — round trips through the typed and core interfaces, repeated stores, the zeroed value after `init`, the even counter between stores, a large payload, and every NULL and zero-size argument. +- **try_load** — success on a quiet cell, failure with a bound of 0, and failure when the counter is held odd. +- **wrap** — stores and loads across the counter's wrap from `UINT32_MAX` to 0. +- **c11** and **no_atomics** — the round trip with the library and the test both built for the C11 and uniprocessor backends. +- **retry** and **retry relax** — each reader retry branch reached in a single thread, by moving the counter during the copy and by holding it odd until a test hook runs in place of `SEQLOCK_CPU_RELAX()`. +- **mt** — 3 readers against a writer of 2,000,000 stores of a 128-byte payload: a seed and 15 words derived from it. Every accepted value is checked against its seed, so any mixed copy fails the test, and after the writer finishes the cell must hold its last value. +- **soak** — 4 readers against 5,000,000 stores of a 64-byte payload, a seed and 7 words, with the same kind of check. + +Under a sanitiser, mt and soak run 100,000 and 300,000 stores, because a sanitiser slows them by an order of magnitude and finds races from interleavings, not volume. + +Removing the reader's comparison of `s1` and `s2` makes both mt and soak fail with a mixed copy, so they detect the failure they exist for. On x86-64, whose stores are not reordered with other stores, they cannot detect a missing fence; the full suite and the ThreadSanitizer build also pass natively on an AArch64 host. + +CI also compiles the library with the TI C2000 code generation tools 22.6.2 and 25.11.1, for both the COFF and EABI object formats, with warnings as errors. That compiler selects the uniprocessor backend. The check covers the source dialect only; the consumer owns linking, execution, and the [uniprocessor limits](#uniprocessor-backend) on its target. diff --git a/docs/integration.md b/docs/integration.md new file mode 100644 index 0000000..690005e --- /dev/null +++ b/docs/integration.md @@ -0,0 +1,105 @@ +# Integration guide + +This guide shows how to add `seqlock` to a project, configure it, build it, and run its tests. The API is described in [api.md](api.md), and the protocol and its guarantees in [design.md](design.md). + +## Requirements + +- A C11 compiler; the headers use `_Static_assert`, `_Alignof` and, when cache-line padding is on, `_Alignas`. +- One of the three atomic backends: GCC or Clang `__atomic` builtins, C11 ``, or a single core on which readers and the writer never run in parallel. The header selects one automatically; [design.md](design.md#backends) sets out what each guarantees. +- A sequence counter type that the target reads and writes lock-free. The two atomic backends check this at compile time. +- For the tests: Meson, Ninja, Python 3, and POSIX threads. + +## Copy-in + +Copy three files into your source tree: + +``` +include/seqlock.h +include/seqlock_conf.h +src/seqlock.c +``` + +Keep both headers in the same directory, because `seqlock.h` includes `seqlock_conf.h`. Then include the public header: + +```c +#include "seqlock.h" +``` + +`seqlock_version.h` exists only in Meson builds. + +## Meson subproject + +Put the repository in `subprojects/seqlock`, as a checkout or through a wrap file, then declare the dependency: + +```meson +seqlock_dep = dependency('seqlock', fallback: ['seqlock', 'seqlock_dep']) +``` + +The build calls `meson.override_dependency('seqlock', ...)`, so other subprojects in the same build find `seqlock` by name. `seqlock_dep` links the static library. Include the header as `"seqlock.h"`. Tests are off unless the `build_tests` option is set. + +| Option | Default | Effect | +| --- | --- | --- | +| `build_tests` | `false` | Builds the unit, backend, concurrency and soak tests, and the documentation example test. | + +## Installed package + +```sh +meson setup build --buildtype=release -Dbuild_tests=false --prefix=/usr/local +meson compile -C build +meson install -C build +cc app.c $(pkg-config --cflags --libs seqlock) -o app +``` + +The install contains `libseqlock.a`, the headers in a `seqlock/` subdirectory, and `seqlock.pc`. The `pkg-config` flags add that directory to the include path, so the same include works as in a copy-in build. Without `pkg-config`, include the namespaced path instead: + + +```c +#include +#include +``` + +`seqlock_version.h` defines `SEQLOCK_VERSION_STRING` as the version string, and `SEQLOCK_VERSION_MAJOR`, `SEQLOCK_VERSION_MINOR` and `SEQLOCK_VERSION_PATCH` as integers. + +## Configuration + +Every option in `seqlock_conf.h` sits behind an `#ifndef` guard, so a `-D` definition replaces the shipped default. The options are described in [api.md](api.md#configuration). + +`SEQLOCK_COUNTER_TYPE` and the backend selection macros change the layout and access width of `seqlock_hdr_t`, which the library and its callers share. Define them identically for `src/seqlock.c` and for every file that includes `seqlock.h`. Nothing detects a mismatch: a caller built with a 64-bit counter against a library built with a 32-bit one compiles, links, and reads half a counter. `SEQLOCK_CELL_ALIGNED` and `SEQLOCK_CACHELINE` change the layout of the generated cell, so every file that shares a cell needs the same values. + +In a Meson build, set them in the top-level project's `c_args`, which also apply to subprojects: + +```sh +meson setup build "-Dc_args=-DSEQLOCK_COUNTER_TYPE=uint64_t" +``` + +A per-target `c_args` or an `add_project_arguments` call in the parent project does not reach the subproject, and an installed library keeps the values it was built with. + +`seqlock.h` includes `seqlock_conf.h` with quotes, so the compiler finds the copy beside `seqlock.h` before any directory on the include path. A project cannot replace it by putting its own `seqlock_conf.h` earlier on the include path; use `-D` definitions instead. + +## Build and test + +```sh +# Library only +meson setup build --buildtype=release -Dbuild_tests=false +meson compile -C build + +# All tests under ASan and UBSan +meson setup build --buildtype=debug -Dbuild_tests=true -Db_sanitize=address,undefined +meson compile -C build +meson test -C build --verbose + +# The same tests under ThreadSanitizer +meson setup build-tsan --buildtype=debug -Dbuild_tests=true -Db_sanitize=thread +meson compile -C build-tsan +meson test -C build-tsan --verbose +``` + +ThreadSanitizer and AddressSanitizer each need a large virtual address space. They run on x86-64 and on AArch64 kernels with 4 KiB pages and a 48-bit address space. ThreadSanitizer cannot start on a 16 KiB-page AArch64 kernel, and AddressSanitizer cannot start on a kernel with a 39-bit address space; run a plain native build there to exercise the weak-memory path. + +Coverage, formatting and MISRA commands are in [CONTRIBUTING.md](../CONTRIBUTING.md). + +## Cross builds + +The consuming firmware owns its cross file, linker command file, and memory placement. No cross file ships with this project. + +CI compiles the library with warnings as errors using two releases of a vendor C11 compiler for a 16-bit-MAU DSP target, under both of its object formats. That compiler provides neither GCC builtins nor ``, so it selects the uniprocessor backend. This covers the source dialect and type assumptions only; linking and execution remain checks for the consumer. Read the [uniprocessor backend](design.md#uniprocessor-backend) limits before you use it. diff --git a/tests/docs/check_snippets.py b/tests/docs/check_snippets.py new file mode 100755 index 0000000..9ad52ff --- /dev/null +++ b/tests/docs/check_snippets.py @@ -0,0 +1,315 @@ +#!/usr/bin/env python3 +"""Compile or syntax-check the code examples in a project's markdown. + +usage: check_snippets.py --lang LANG [--root DIR] [--doc GLOB ...] + [--prelude LINE ...] [--keep DIR] [--timeout S] + [-- COMMAND ...] + +Copy this file into the repository, for example as tests/docs/check_snippets.py, +and register it with the project's test runner so CI runs it. It needs only +the Python standard library. + +For each markdown file matched by --doc (default: README.md, CONTRIBUTING.md, +and docs/**/*.md), the blocks fenced as LANG form one generated source file in +document order, so a later block can use an earlier declaration. The --prelude +lines come first. COMMAND runs once per file, with {source} and {object} +replaced by generated paths. Without a COMMAND, --keep is required and the +files are only written for inspection. + +A block is file-level code unless the nearest non-blank line above its opening +fence is a marker comment, which markdown renderers hide: + + statements, wrapped in a generated function + pseudo-code, or a copy of a real definition + +Diagnostics name the markdown file and line. C and C++ sources carry #line +directives, and other tool output that names a generated file is rewritten. + +example (C): + check_snippets.py --lang c --prelude '#include "mylib.h"' -- \\ + cc -std=c11 -Wall -Wextra -Werror -Iinclude -c {source} -o {object} + +Exit status: 0 when every file passes, 1 when a file fails, a marker is +misplaced, or no block matched, and 2 on a usage error. +""" + +from __future__ import annotations + +import argparse +import re +import subprocess +import sys +import tempfile +from dataclasses import dataclass, field +from pathlib import Path +from typing import final + +DEFAULT_DOCS = ("README.md", "CONTRIBUTING.md", "docs/**/*.md") +FENCE = re.compile(r"^(\s*)(`{3,}|~{3,})\s*([^\s`{]*)") +MARKER = re.compile(r"^\s*\s*$") +KINDS = ("body", "skip") + + +@final +@dataclass(frozen=True) +class Language: + fences: frozenset[str] + extension: str + line_directive: bool + body_open: tuple[str, ...] + body_close: tuple[str, ...] + body_indent: str = "" + + +LANGUAGES = { + "c": Language( + frozenset({"c"}), + "c", + True, + ("void snippet_body_{index}(void);", "void snippet_body_{index}(void)", "{"), + ("}",), + ), + "cpp": Language( + frozenset({"cpp", "c++", "cxx"}), + "cpp", + True, + ("void snippet_body_{index}();", "void snippet_body_{index}()", "{"), + ("}",), + ), + "python": Language( + frozenset({"python", "py", "python3"}), + "py", + False, + ("def _snippet_body_{index}() -> None:",), + (" pass",), + " ", + ), + "sh": Language( + frozenset({"sh", "bash", "shell"}), + "sh", + False, + ("_snippet_body_{index}() {",), + (":", "}"), + ), +} + + +class SnippetError(Exception): + pass + + +@final +@dataclass +class Block: + line: int + kind: str + code: list[str] = field(default_factory=list) + + +@final +class Arguments(argparse.Namespace): + def __init__(self) -> None: + super().__init__() + self.lang: str = "" + self.root: Path = Path(".") + self.docs: list[str] = [] + self.prelude: list[str] = [] + self.keep: Path | None = None + self.timeout: float = 120.0 + + +def parse(path: Path, name: str, fences: frozenset[str]) -> list[Block]: + """Return the blocks fenced as one of fences, each with its marker kind.""" + blocks: list[Block] = [] + fence = "" + indent = 0 + current: Block | None = None + marker = "" + marker_line = 0 + text = path.read_text(encoding="utf-8") + for number, line in enumerate(text.splitlines(), start=1): + stripped = line.strip() + if fence: + if stripped.startswith(fence) and stripped == fence[0] * len(stripped): + if current is not None: + blocks.append(current) + fence = "" + current = None + elif current is not None: + prefix = line[:indent] + current.code.append(line[indent:] if not prefix.strip() else line) + continue + if not stripped: + continue + opening = FENCE.match(line) + if opening: + indent = len(opening.group(1)) + fence = opening.group(2) + if opening.group(3).lower() in fences: + current = Block(number + 1, marker or "file") + marker = "" + continue + if marker: + raise SnippetError(f"{name}:{marker_line}: marker is not above a block") + match = MARKER.match(line) + if match: + if match.group(1) not in KINDS: + raise SnippetError( + f"{name}:{number}: unknown marker {match.group(1)!r}" + ) + marker = match.group(1) + marker_line = number + if marker: + raise SnippetError(f"{name}:{marker_line}: marker is not above a block") + if fence: + raise SnippetError(f"{name}: unterminated code block") + return blocks + + +def assemble( + name: str, language: Language, prelude: list[str], blocks: list[Block] +) -> tuple[str, list[int | None]]: + """Return the generated source and the markdown line of each source line.""" + lines: list[str] = [] + origin: list[int | None] = [] + quoted = name.replace("\\", "\\\\").replace('"', '\\"') + + def emit(text: str, line: int | None = None) -> None: + lines.append(text) + origin.append(line) + + for text in prelude: + emit(text) + for index, block in enumerate(blocks, start=1): + if block.kind == "skip": + continue + body = block.kind == "body" + if body: + for text in language.body_open: + emit(text.replace("{index}", str(index))) + if language.line_directive: + emit(f'#line {block.line} "{quoted}"') + prefix = language.body_indent if body else "" + for offset, text in enumerate(block.code): + emit(prefix + text if text.strip() else text, block.line + offset) + if body: + for text in language.body_close: + emit(text) + return "\n".join(lines) + "\n", origin + + +def relabel(output: str, source: Path, name: str, origin: list[int | None]) -> str: + """Point tool output that names the generated file at the markdown line.""" + pattern = re.compile(re.escape(str(source)) + r'(", line |: line |:)(\d+)') + + def replace(match: re.Match[str]) -> str: + number = int(match.group(2)) + line = origin[number - 1] if 0 < number <= len(origin) else None + if line is None: + return match.group(0) + return f"{name}{match.group(1)}{line}" + + return pattern.sub(replace, output) + + +def check(args: Arguments, command: list[str], work: Path) -> int: + root = args.root.resolve() + language = LANGUAGES[args.lang] + patterns = args.docs or list(DEFAULT_DOCS) + documents = sorted( + {path for pattern in patterns for path in root.glob(pattern) if path.is_file()} + ) + passed = 0 + skipped = 0 + failures: list[str] = [] + + for index, path in enumerate(documents, start=1): + name = path.relative_to(root).as_posix() + try: + blocks = parse(path, name, language.fences) + except SnippetError as error: + failures.append(str(error)) + continue + active = sum(1 for block in blocks if block.kind != "skip") + skipped += len(blocks) - active + if not active: + continue + text, origin = assemble(name, language, args.prelude, blocks) + stem = name.removesuffix(".md").replace("/", "_") + source = work / f"{index:02d}-{stem}.{language.extension}" + _ = source.write_text(text, encoding="utf-8") + if not command: + passed += active + print(f"{name}: {active} blocks written to {source}") + continue + target = source.with_suffix(".o") + argv = [ + arg.replace("{source}", str(source)).replace("{object}", str(target)) + for arg in command + ] + try: + result = subprocess.run( + argv, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + timeout=args.timeout, + check=False, + ) + except (OSError, subprocess.TimeoutExpired) as error: + failures.append(f"{name}: {error}") + continue + if result.returncode != 0: + output = relabel(result.stdout, source, name, origin) + failures.append(f"{name}: examples fail\n{output}") + continue + passed += active + print(f"{name}: {active} blocks pass") + + for failure in failures: + print(failure, file=sys.stderr) + verb = "checked" if command else "written" + print(f"{args.lang}: {passed} blocks {verb}, {skipped} skipped") + if passed == 0 and not failures: + print(f"no {args.lang} blocks found under {root}", file=sys.stderr) + return 1 + return 1 if failures else 0 + + +def main(argv: list[str]) -> int: + options, command = argv, [] + if "--" in argv: + split = argv.index("--") + options, command = argv[:split], argv[split + 1 :] + + parser = argparse.ArgumentParser( + prog="check_snippets.py", + usage=argparse.SUPPRESS, + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + _ = parser.add_argument("--lang", required=True, choices=sorted(LANGUAGES)) + _ = parser.add_argument("--root", type=Path) + _ = parser.add_argument("--doc", dest="docs", action="append", metavar="GLOB") + _ = parser.add_argument("--prelude", action="append", metavar="LINE") + _ = parser.add_argument("--keep", type=Path, metavar="DIR") + _ = parser.add_argument("--timeout", type=float, metavar="S") + args = parser.parse_args(options, namespace=Arguments()) + + if not args.root.is_dir(): + parser.error(f"not a directory: {args.root}") + if command and not any("{source}" in arg for arg in command): + parser.error("COMMAND must contain {source}") + if not command and args.keep is None: + parser.error("give a COMMAND after --, or --keep DIR") + + with tempfile.TemporaryDirectory(prefix="snippets-") as temporary: + work = Path(temporary) + if args.keep is not None: + work = args.keep.resolve() + work.mkdir(parents=True, exist_ok=True) + return check(args, command, work) + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tests/meson.build b/tests/meson.build index 312525c..783096c 100644 --- a/tests/meson.build +++ b/tests/meson.build @@ -97,3 +97,28 @@ test_soak_exe = executable( include_directories: [public_headers, generated_headers], ) test('seqlock soak', test_soak_exe, timeout: 180) + +# Compiles every C block in README.md, CONTRIBUTING.md and docs/ against the +# public headers, so a documented signature cannot drift from the code. +test( + 'seqlock docs examples', + import('python').find_installation(), + args: [ + files('docs/check_snippets.py'), + '--root', meson.project_source_root(), + '--lang', 'c', + '--prelude', '#include "seqlock.h"', + '--', + ] + meson.get_compiler('c').cmd_array() + [ + '-std=c11', + '-Wall', + '-Wextra', + '-Wpedantic', + '-Werror', + '-Wno-unused-function', + '-Wno-unused-variable', + '-I' + (meson.project_source_root() / 'include'), + '-c', '{source}', '-o', '{object}', + ], + timeout: 60, +)