feat(poc-a): gate-a dynamic elf proof of concept (#13)

## Summary

PoC-A proved that dynamically loaded ELF plugins are workable on
ESP32-S3: plugins ship as signed MPB packages, are parsed by a strict
single-type parser shared between host and target, and execute from
PSRAM+IRAM within a measured admission budget. A 1000-cycle load/unload
soak passed 18/18 trend gates with stable heaps, the capacity ladder
settled at 8 coexisting plugin instances with a 3356B per-instance
budget, and the fail-closed corpus executed zero attacker-controlled
bytes across 14 rejection classes. Scheduler semantics (strand FIFO
ordering, completion-cancel CAS, quiesce-as-noop ABI) were validated on
both host (TSan suite) and target. **Gate-A verdict: PASS** — ADR-0002
moves to **Accepted** with the capacity value 8 and global-sum admission
rule as PoC-derived proposals.

## Changes by area

Grouped from `git log main..HEAD --oneline` (18 commits):

- **Vendored loader + patches**: `4bb53f2` vendor elf_loader 1.3.3 +
harness scaffold; `2f67b4f` plugin_iram loader patch with budget
consistency (p1-p5 patch series in `PATCHES.md`).
- **MPB toolchain**: `4793cc2` deterministic MPB manifest builder with
test signing; `408df44` strict single-type MPB parser shared
host/target; `796f9d2` host MPB corpus + policy CI lane.
- **Plugin pipeline + probes**: `21d2842` plugin pipeline and first
PSRAM execution on target; `cab9664` relocation/import allowlist matrix
with probes; `c5d6c6c` C++ feature rejection matrix.
- **Harness commands**: `e0e7159` generation coexistence with measured
admission budget; `2a37556` thousand-cycle lifecycle soak with heap
trend gate; `093a72b` on-target scheduler semantics validation (+
`eea3876` clang-format-18 sweep); `a302151` capacity ladder with signed
budget; `f34dc72` fail-closed corpus with execution sentinel.
- **Host prototypes**: `6198bca` strand FIFO prototype with TSan suite;
`1c3ad59` completion-cancel CAS and cleanup semantics.
- **Evidence + ADR/docs**: `887d0f7` Gate-A manifest and report;
`1c29e8a` ADR-0002 outcome + frozen PoC values.

## QA evidence

- `poc/evidence/poc-a-20260901/manifest.json` — 67-artifact hash index,
every sha256 recomputed at assembly.
- `poc/evidence/poc-a-20260901/GATE-A-REPORT.md` — full nine-item
development-plan §4 mapping; TEST-003 10/10 clauses.
- 14 verbatim per-task transcripts (`task-1` … `task-15-*.log`) + fresh
build artifacts (`build/frame_poc_a.map`, size components).
- Frozen in-repo references: `ALLOWLIST.md`, `REJECT-MATRIX.md`,
`ADMISSION-BUDGET.md`, `soak_samples_1000.csv`, fc corpus (33 committed
`.mpb` containers).
- F1-F4 final-wave verdicts: **APPROVE**.
- Key numbers: soak **18/18** trend gates over 1000 cycles; capacity
**8/8** instances, **3356B** per-instance; fc corpus **14 rejection
classes, zero attacker bytes executed**; **4 upstream loader defects
found and patched** (p1-p5).

## Requirement IDs (GOV-006)

ADR-0002; TEST-002, TEST-003; PLUG-001, PLUG-004, PLUG-008, PLUG-009;
MEM-001, MEM-003, MEM-007, MEM-008; LIFE-001, LIFE-002, LIFE-005,
LIFE-007; SEC-002, SEC-003, SEC-004, SEC-005; GH-003; GOV-004, GOV-005.

## Risks / known limitations

From `GATE-A-REPORT.md` §(f) plus the trade-off table:

1. **Capacity descent path 7-5 unexercised** — rung 8 passed first
attempt; rungs 7/6/5 and retry-once logic never ran on hardware
(untested against real OOM).
2. **No Wi-Fi in the harness (MEM-001 caveat)** — all PSRAM/IRAM budget
numbers are radio-off harness-class; product admission budgets must be
re-measured with the network stack active.
3. **On-target scheduler vectors are a subset of the host suite**
(256-node pool / 2e4 storm posts vs host 31000 / 1e5); consistency
declaration covers only the vectors actually run.
4. **Quiesce is a no-op by ABI semantics** — plugin ABI 1.2 has no
quiesce slot; NULL entry is defined as trivial success; real quiesce
coordination is later-gate work.
5. **MEMPROT=n trade-off** — `CONFIG_ESP_SYSTEM_MEMPROT=n` is required
for the IDF exec heap (`MALLOC_CAP_EXEC`) that `.plugin_iram` needs;
software-only PMP config, no eFuse burned (documented in `PATCHES.md`
p5); production must re-decide security vs plugin IRAM.
6. **Owner sign-off PENDING** — Gate-A PASS is the PoC team's verdict;
formal acceptance of ADR-0002 awaits the owner.

## Not in scope

- Product components (GOV-004) — this PR is PoC evidence only; no
product code paths change.
- **Merge is the owner's call** — do not merge without owner sign-off on
ADR-0002.

---------

Co-authored-by: ania-lain <[email protected]>
This commit is contained in:
Lain
2026-09-07 20:02:18 +08:00
committed by GitHub
co-authored by lain
parent 0018ebbb8f
commit e71842aa8a
163 changed files with 97525 additions and 50 deletions
+26 -1
View File
@@ -76,6 +76,10 @@ endif()
enable_testing()
add_library(frame_poc_strand STATIC src/frame_strand.cc)
target_include_directories(frame_poc_strand PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
target_link_libraries(frame_poc_strand PUBLIC frame_poc_contract)
add_executable(frame_abi_test tests/frame_abi_test.cc)
target_link_libraries(frame_abi_test PRIVATE frame_poc_contract GTest::gtest_main)
gtest_discover_tests(frame_abi_test)
@@ -92,9 +96,30 @@ add_executable(lifecycle_state_test tests/lifecycle_state_test.cc)
target_link_libraries(lifecycle_state_test PRIVATE frame_poc_contract GTest::gtest_main)
gtest_discover_tests(lifecycle_state_test)
add_executable(mpb_parser_test
tests/mpb_parser_test.cc
tests/sha256_ref.c
../common/components/frame_poc_mpb/src/mpb_parser.c)
target_include_directories(mpb_parser_test PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/../common/components/frame_poc_mpb/include"
"${CMAKE_CURRENT_SOURCE_DIR}/tests")
target_compile_definitions(mpb_parser_test PRIVATE
MPB_CORPUS_DIR="${CMAKE_CURRENT_SOURCE_DIR}/tests/mpb_corpus")
target_link_libraries(mpb_parser_test PRIVATE frame_poc_contract GTest::gtest_main)
gtest_discover_tests(mpb_parser_test)
add_executable(frame_strand_test tests/frame_strand_test.cc)
target_link_libraries(frame_strand_test PRIVATE frame_poc_strand GTest::gtest_main)
gtest_discover_tests(frame_strand_test)
add_executable(frame_completion_test tests/frame_completion_test.cc)
target_link_libraries(frame_completion_test PRIVATE frame_poc_strand GTest::gtest_main)
gtest_discover_tests(frame_completion_test)
if(ENABLE_CLANG_TIDY)
find_program(CLANG_TIDY_EXECUTABLE NAMES clang-tidy-18 clang-tidy REQUIRED)
foreach(target frame_abi_test frame_handle_test lifecycle_state_test)
foreach(target frame_abi_test frame_handle_test lifecycle_state_test frame_strand_test
frame_completion_test)
set_property(TARGET ${target} PROPERTY CXX_CLANG_TIDY "${CLANG_TIDY_EXECUTABLE}")
endforeach()
endif()
@@ -0,0 +1,95 @@
#ifndef FRAME_POC_FRAME_COMPLETION_HH
#define FRAME_POC_FRAME_COMPLETION_HH
#include <atomic>
#include <cstdint>
#include "frame_poc/frame_abi.h"
#include "frame_poc/frame_strand.hh"
namespace frame::poc {
// §4.1.4 / LIFE-005: every async operation resolves through one atomic
// terminal-state CAS. The winner (underlying completion vs cancel) decides
// the delivered error; the loser performs no delivery (a late result only
// releases underlying resources).
enum class completion_state : uint8_t { pending, completed, cancelled };
// Pre-allocated completion slot with pool semantics: the owner reserves
// BEFORE starting the underlying operation; a failed reserve means nothing
// was started and the caller keeps ownership. The delivery node is embedded
// (no allocation on the completion path, §4.1.2).
class completion_node {
public:
completion_node() = default;
completion_node(const completion_node&) = delete;
completion_node& operator=(const completion_node&) = delete;
// Owner-thread only. Returns false if the node is already reserved
// (in flight). On true the node is PENDING and bound to
// (target, generation, op).
bool reserve(strand& target, uint64_t generation, frame_completion_operation_t op) {
if (in_flight_.exchange(true, std::memory_order_acq_rel)) {
return false; // already used: service returns QUEUE_FULL, nothing started
}
target_ = &target;
generation_ = generation;
op_ = op;
delivery_ = strand_op_node{};
delivery_.kind = op_kind::completion;
delivery_.pooled = false;
delivery_.generation = generation;
delivery_.completion = op;
state_.store(completion_state::pending, std::memory_order_release);
return true;
}
// Owner-thread only, after the previous reservation's delivery has been
// observed (pool recycle). Never called on an in-flight node.
void recycle() {
state_.store(completion_state::pending, std::memory_order_relaxed);
in_flight_.store(false, std::memory_order_release);
}
// Underlying-operation completion. Winner CAS (PENDING -> COMPLETED)
// delivers `err` on the target strand and returns true; a late result
// after CANCELLED releases nothing here and returns false.
bool complete(frame_err_t err) {
completion_state expected = completion_state::pending;
if (!state_.compare_exchange_strong(expected, completion_state::completed,
std::memory_order_acq_rel)) {
return false;
}
delivery_.completion_err = err; // COMPLETED first wins keeps the original result
target_->post_completion(delivery_);
return true;
}
// Cancellation. Winner CAS (PENDING -> CANCELLED) delivers
// FRAME_ERR_CANCELLED on the target strand and returns true.
bool cancel() {
completion_state expected = completion_state::pending;
if (!state_.compare_exchange_strong(expected, completion_state::cancelled,
std::memory_order_acq_rel)) {
return false;
}
delivery_.completion_err = FRAME_ERR_CANCELLED;
target_->post_completion(delivery_);
return true;
}
completion_state state() const noexcept { return state_.load(std::memory_order_acquire); }
private:
std::atomic<completion_state> state_{completion_state::pending};
std::atomic<bool> in_flight_{false};
strand* target_ = nullptr;
uint64_t generation_ = 0;
frame_completion_operation_t op_{};
strand_op_node delivery_{}; // embedded delivery node (§4.1.2)
};
} // namespace frame::poc
#endif
+193
View File
@@ -0,0 +1,193 @@
#ifndef FRAME_POC_FRAME_STRAND_HH
#define FRAME_POC_FRAME_STRAND_HH
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <mutex>
#include <thread>
#include <vector>
#include "frame_poc/frame_abi.h"
namespace frame::poc {
// Scheduling protocol mapping (project.md §4.1.1-4.1.3):
//
// post(operation)
// -> operation enters target strand FIFO (linearization = strand mutex)
// -> strand IDLE -> SCHEDULED (CAS under the same lock)
// -> strand pointer enters the io_core ready ring (max-once invariant:
// a strand is in the ready ring only between a successful
// IDLE->SCHEDULED conversion and the worker's run_one, therefore a
// strand can appear in the ring at most once)
//
// io_core.run_loop()
// -> pop a ready strand
// -> run_one(): pop ONE node; FIFO still non-empty -> requeue at ring
// tail; FIFO empty -> IDLE (or STOPPED when closing)
// -> execute the popped node OUTSIDE the strand lock
//
// Anti-lost-wakeup protocol (§4.1.3): the FIFO empty-check and the IDLE
// store happen under the same strand mutex as enqueue + IDLE->SCHEDULED
// CAS. A post that acquires the lock before run_one's check sees a
// non-empty FIFO and keeps the strand scheduled; a post that acquires it
// after sees IDLE and schedules the strand itself. Either way a non-empty
// FIFO is always matched by a pending or upcoming ready-ring entry.
//
// FreeRTOS port note (T13): the strand mutex maps to a critical section
// (taskENTER_CRITICAL/taskEXIT_CRITICAL) around the identical FIFO +
// state-transition sequence; the ready ring maps to a bounded queue of
// strand handles; run_loop maps to the per-core worker task. The protocol
// itself is unchanged.
enum class strand_state : uint8_t { idle, scheduled, running, closing, stopped };
enum class op_kind : uint8_t { post, cleanup, completion };
// Intrusive FIFO node. Pool nodes (kind post) come from the strand's
// preallocated array; completion nodes (kind completion) are embedded in
// caller-owned storage and never touch the pool.
struct strand_op_node {
strand_op_node* next = nullptr;
op_kind kind = op_kind::post;
bool pooled = false;
uint64_t seq = 0;
uint64_t generation = 0;
frame_post_operation_t post{};
frame_completion_operation_t completion{};
frame_err_t completion_err = FRAME_OK;
};
class strand;
// One worker thread (host stand-in for one fixed-core FreeRTOS worker, §4.1.1).
// Preallocated fixed-capacity ring of strand pointers; capacity equals the
// maximum number of strands, so a legal SCHEDULED transition never blocks.
class io_core {
public:
explicit io_core(std::size_t max_strands);
~io_core();
io_core(const io_core&) = delete;
io_core& operator=(const io_core&) = delete;
// Spawns the worker thread. push_ready may be called before start();
// queued strands are drained once started.
void start();
// Idempotent. Wakes the worker, drains nothing, joins the thread.
void stop();
bool duplicate_detected() const noexcept {
return duplicate_fault_.load(std::memory_order_relaxed);
}
private:
friend class strand;
void push_ready(strand& target);
strand* pop_ready();
void run_loop();
const std::size_t capacity_;
std::vector<strand*> ring_;
std::size_t head_ = 0;
std::size_t count_ = 0;
std::mutex mutex_;
std::condition_variable not_empty_;
std::condition_variable not_full_;
bool stopping_ = false;
std::thread worker_;
bool started_ = false;
// Fault flag set under mutex_ when a strand is pushed while already
// enqueued (protocol violation detector; tests assert it stays clear).
std::atomic<bool> duplicate_fault_{false};
};
// Logical serial executor (§4.1.2): one FIFO, preallocated pool nodes,
// bounded outstanding-operations credit, exactly-once invoke/destroy.
class strand {
public:
strand(io_core& core, std::size_t op_capacity,
std::chrono::microseconds handler_budget = std::chrono::milliseconds{1});
~strand();
strand(const strand&) = delete;
strand& operator=(const strand&) = delete;
// Async post only (LIFE-002: no dispatch/defer). On FRAME_OK the strand
// owns `operation` and will call invoke then destroy exactly once. On
// FRAME_ERR_QUEUE_FULL the credit is exhausted and the caller keeps
// ownership (destroy is NOT called). On FRAME_ERR_PLUGIN_STOPPING the
// strand is closing/stopped and the caller keeps ownership.
frame_err_t post(frame_post_operation_t operation);
// §4.1.6 step 5 / LIFE-007: close the post entry, convert every queued
// un-run POST in place (kind -> cleanup, FIFO position preserved).
// When the FIFO drains in closing the state becomes stopped (poll via
// stopped()). Idempotent.
void begin_quiescing();
// Internal completion-delivery path (§4.1.4): bypasses credit and pool
// (caller-owned reserved node), allowed during closing (delivers cancel
// results), cannot fail. `reserved.completion` / `reserved.completion_err`
// must already be filled; the node is executed as kind completion:
// complete(user, err) then destroy(user), exactly once each.
void post_completion(strand_op_node& reserved);
// Executes one popped node; called by io_core's worker.
void run_one();
bool stopped() const noexcept {
return state_.load(std::memory_order_acquire) == strand_state::stopped;
}
strand_state state() const noexcept { return state_.load(std::memory_order_acquire); }
uint64_t generation() const noexcept { return generation_.load(std::memory_order_acquire); }
uint64_t advance_generation() noexcept {
return generation_.fetch_add(1, std::memory_order_acq_rel);
}
// Instrumentation (LIFE-002 handler budget, LIFE-007 stale drop).
uint64_t invoked_count() const noexcept { return invoked_.load(std::memory_order_acquire); }
uint64_t destroyed_count() const noexcept { return destroyed_.load(std::memory_order_acquire); }
uint64_t handler_overruns() const noexcept { return overruns_.load(std::memory_order_acquire); }
uint64_t stale_generation_dropped() const noexcept {
return stale_dropped_.load(std::memory_order_acquire);
}
private:
friend class io_core;
strand_op_node* pop_fifo_locked();
void push_fifo_locked(strand_op_node* node);
strand_op_node* pop_freelist_locked();
void push_freelist_locked(strand_op_node* node);
void execute_node(strand_op_node* node) noexcept;
io_core& core_;
const std::size_t capacity_;
const std::chrono::microseconds handler_budget_;
std::mutex mutex_;
strand_op_node* fifo_head_ = nullptr;
strand_op_node* fifo_tail_ = nullptr;
strand_op_node* free_head_ = nullptr;
std::vector<strand_op_node> pool_;
std::size_t outstanding_ = 0;
uint64_t ticket_ = 0;
bool ready_pending_ = false; // in ready ring (or push in flight); guarded by mutex_
bool closing_ = false; // quiescing flag; guarded by mutex_
std::atomic<strand_state> state_{strand_state::idle};
std::atomic<uint64_t> generation_{0};
std::atomic<uint64_t> invoked_{0};
std::atomic<uint64_t> destroyed_{0};
std::atomic<uint64_t> overruns_{0};
std::atomic<uint64_t> stale_dropped_{0};
};
} // namespace frame::poc
#endif
+281
View File
@@ -0,0 +1,281 @@
#include "frame_poc/frame_strand.hh"
#include <utility>
namespace frame::poc {
io_core::io_core(std::size_t max_strands)
: capacity_(max_strands == 0 ? 1 : max_strands), ring_(capacity_, nullptr) {}
io_core::~io_core() { stop(); }
void io_core::start() {
std::lock_guard<std::mutex> lock(mutex_);
if (started_ || stopping_) {
return;
}
started_ = true;
// Worker launched outside the lock; run_loop only touches members via
// pop_ready/push_ready which take the lock themselves.
worker_ = std::thread([this] { run_loop(); });
}
void io_core::stop() {
std::thread worker;
{
std::lock_guard<std::mutex> lock(mutex_);
if (stopping_) {
return;
}
stopping_ = true;
worker = std::move(worker_);
}
not_empty_.notify_all();
not_full_.notify_all();
if (worker.joinable()) {
worker.join();
}
}
void io_core::push_ready(strand& target) {
std::unique_lock<std::mutex> lock(mutex_);
// Duplicate detector: the max-once invariant (§4.1.3) says a strand is
// in the ring at most once. A second entry is a protocol fault.
for (std::size_t offset = 0; offset < count_; ++offset) {
if (ring_[(head_ + offset) % capacity_] == &target) {
duplicate_fault_.store(true, std::memory_order_relaxed);
return;
}
}
not_full_.wait(lock, [this] { return count_ < capacity_ || stopping_; });
if (count_ >= capacity_) {
return; // ring full during shutdown; drop (worker is exiting anyway)
}
ring_[(head_ + count_) % capacity_] = &target;
++count_;
not_empty_.notify_one();
}
strand* io_core::pop_ready() {
std::unique_lock<std::mutex> lock(mutex_);
not_empty_.wait(lock, [this] { return count_ > 0 || stopping_; });
if (count_ == 0) {
return nullptr;
}
strand* target = ring_[head_];
ring_[head_] = nullptr;
head_ = (head_ + 1) % capacity_;
--count_;
not_full_.notify_one();
return target;
}
void io_core::run_loop() {
while (strand* target = pop_ready()) {
target->run_one();
}
}
strand::strand(io_core& core, std::size_t op_capacity, std::chrono::microseconds handler_budget)
: core_(core), capacity_(op_capacity), handler_budget_(handler_budget) {
// Construction-time preallocation: zero hot-path allocation (§4.1.2).
pool_.resize(capacity_);
for (std::size_t index = 0; index < capacity_; ++index) {
pool_[index].pooled = true;
push_freelist_locked(&pool_[index]);
}
}
strand::~strand() {
// Caller contract: quiesce and drain (or stop the core) before destruction.
}
frame_err_t strand::post(frame_post_operation_t operation) {
bool need_push = false;
{
std::lock_guard<std::mutex> lock(mutex_);
if (closing_) {
return FRAME_ERR_PLUGIN_STOPPING; // caller keeps ownership
}
if (outstanding_ >= capacity_) {
return FRAME_ERR_QUEUE_FULL; // caller keeps ownership; destroy NOT called
}
strand_op_node* node = pop_freelist_locked();
if (node == nullptr) {
return FRAME_ERR_QUEUE_FULL;
}
node->kind = op_kind::post;
node->seq = ++ticket_;
node->generation = generation_.load(std::memory_order_relaxed);
node->post = operation;
push_fifo_locked(node);
++outstanding_;
// IDLE -> SCHEDULED conversion happens under the same lock as the
// enqueue (anti-lost-wakeup protocol, §4.1.3). The CAS mirrors the
// FreeRTOS critical-section sequence used by the T13 port; under the
// host mutex it cannot observe a concurrent state.
strand_state expected = strand_state::idle;
if (state_.compare_exchange_strong(expected, strand_state::scheduled,
std::memory_order_relaxed)) {
ready_pending_ = true;
need_push = true;
}
}
if (need_push) {
core_.push_ready(*this);
}
return FRAME_OK;
}
void strand::begin_quiescing() {
std::lock_guard<std::mutex> lock(mutex_);
if (closing_) {
return; // idempotent
}
closing_ = true;
// §4.1.6 step 5 / LIFE-007: convert queued un-run POSTs in place;
// FIFO position preserved so destroys stay on-strand and ordered.
for (strand_op_node* node = fifo_head_; node != nullptr; node = node->next) {
if (node->kind == op_kind::post) {
node->kind = op_kind::cleanup;
}
}
if (!ready_pending_ && fifo_head_ == nullptr) {
state_.store(strand_state::stopped, std::memory_order_relaxed);
} else {
state_.store(strand_state::closing, std::memory_order_relaxed);
}
}
void strand::post_completion(strand_op_node& reserved) {
bool need_push = false;
{
std::lock_guard<std::mutex> lock(mutex_);
push_fifo_locked(&reserved);
if (!ready_pending_) {
// Allowed during closing/stopped (§4.1.4): cancel results must
// still be delivered. The closing_ flag, not the observable
// state, drives the terminal transition in run_one.
ready_pending_ = true;
need_push = true;
if (state_.load(std::memory_order_relaxed) == strand_state::idle) {
state_.store(strand_state::scheduled, std::memory_order_relaxed);
}
}
}
if (need_push) {
core_.push_ready(*this);
}
}
void strand::run_one() {
strand_op_node* node = nullptr;
bool requeue = false;
{
std::lock_guard<std::mutex> lock(mutex_);
ready_pending_ = false; // worker owns the strand while not requeued
state_.store(strand_state::running, std::memory_order_relaxed);
node = pop_fifo_locked();
if (fifo_head_ != nullptr) {
// Still non-empty: round-robin fairness (§4.1.3) — one operation
// per ready visit, then back to the ring tail.
ready_pending_ = true;
requeue = true;
state_.store(closing_ ? strand_state::closing : strand_state::scheduled,
std::memory_order_relaxed);
} else {
// Empty-check and IDLE/STOPPED store are atomic with respect to
// concurrent post() under this mutex: no lost wakeup is possible.
state_.store(closing_ ? strand_state::stopped : strand_state::idle,
std::memory_order_relaxed);
}
}
if (requeue) {
core_.push_ready(*this);
}
if (node != nullptr) {
execute_node(node);
}
}
void strand::execute_node(strand_op_node* node) noexcept {
// Generation check before any user code (LIFE-007): stale callbacks are
// skipped but still destroyed exactly once.
const bool fresh = node->generation == generation_.load(std::memory_order_acquire);
switch (node->kind) {
case op_kind::post:
if (fresh) {
const auto begin = std::chrono::steady_clock::now();
node->post.invoke(node->post.user);
const auto elapsed = std::chrono::steady_clock::now() - begin;
if (elapsed > handler_budget_) {
overruns_.fetch_add(1, std::memory_order_seq_cst);
}
// seq_cst: publishes handler-side writes to polling test threads.
invoked_.fetch_add(1, std::memory_order_seq_cst);
} else {
stale_dropped_.fetch_add(1, std::memory_order_seq_cst);
}
node->post.destroy(node->post.user);
destroyed_.fetch_add(1, std::memory_order_seq_cst);
break;
case op_kind::cleanup:
// Converted POST: skip invoke, destroy exactly once on-strand.
node->post.destroy(node->post.user);
destroyed_.fetch_add(1, std::memory_order_seq_cst);
break;
case op_kind::completion:
if (fresh) {
node->completion.complete(node->completion.user, node->completion_err);
} else {
stale_dropped_.fetch_add(1, std::memory_order_seq_cst);
}
node->completion.destroy(node->completion.user);
destroyed_.fetch_add(1, std::memory_order_seq_cst);
break;
}
if (node->pooled) {
std::lock_guard<std::mutex> lock(mutex_);
push_freelist_locked(node);
--outstanding_;
}
}
strand_op_node* strand::pop_fifo_locked() {
strand_op_node* node = fifo_head_;
if (node == nullptr) {
return nullptr;
}
fifo_head_ = node->next;
if (fifo_head_ == nullptr) {
fifo_tail_ = nullptr;
}
node->next = nullptr;
return node;
}
void strand::push_fifo_locked(strand_op_node* node) {
node->next = nullptr;
if (fifo_tail_ == nullptr) {
fifo_head_ = node;
} else {
fifo_tail_->next = node;
}
fifo_tail_ = node;
}
strand_op_node* strand::pop_freelist_locked() {
strand_op_node* node = free_head_;
if (node != nullptr) {
free_head_ = node->next;
node->next = nullptr;
}
return node;
}
void strand::push_freelist_locked(strand_op_node* node) {
node->next = free_head_;
free_head_ = node;
}
} // namespace frame::poc
+366
View File
@@ -0,0 +1,366 @@
#include <atomic>
#include <chrono>
#include <cstdint>
#include <functional>
#include <thread>
#include <vector>
#include <gtest/gtest.h>
#include "frame_poc/frame_completion.hh"
#include "frame_poc/frame_strand.hh"
using frame::poc::completion_node;
using frame::poc::completion_state;
using frame::poc::io_core;
using frame::poc::strand;
namespace {
constexpr auto kPollDelay = std::chrono::microseconds{50};
constexpr frame_err_t kOriginalErr = FRAME_ERR_TIMEOUT; // -2, distinct from CANCELLED (-15)
bool wait_until(const std::function<bool()>& predicate, std::chrono::milliseconds timeout) {
const auto deadline = std::chrono::steady_clock::now() + timeout;
while (!predicate()) {
if (std::chrono::steady_clock::now() > deadline) {
return false;
}
std::this_thread::sleep_for(kPollDelay);
}
return true;
}
struct completion_rec {
std::atomic<uint64_t> complete_delivered{0}; // err != CANCELLED
std::atomic<uint64_t> cancel_delivered{0}; // err == FRAME_ERR_CANCELLED
std::atomic<uint64_t> destroyed{0};
std::vector<frame_err_t> delivered_errs; // written only by the worker
std::vector<std::thread::id> destroy_threads; // written only by the worker
uint64_t deliveries() const {
return complete_delivered.load(std::memory_order_acquire) +
cancel_delivered.load(std::memory_order_acquire);
}
};
struct post_rec {
std::atomic<bool> invoked{false};
std::atomic<bool> destroyed{false};
std::thread::id destroy_thread{}; // written only by the worker
};
frame_completion_operation_t make_completion_op(completion_rec* rec) {
frame_completion_operation_t op{};
op.user = rec;
op.complete = [](void* user, frame_err_t err) {
auto* target = static_cast<completion_rec*>(user);
if (err == FRAME_ERR_CANCELLED) {
target->cancel_delivered.fetch_add(1, std::memory_order_seq_cst);
} else {
target->complete_delivered.fetch_add(1, std::memory_order_seq_cst);
}
target->delivered_errs.push_back(err);
};
op.destroy = [](void* user) {
auto* target = static_cast<completion_rec*>(user);
target->destroy_threads.push_back(std::this_thread::get_id());
target->destroyed.fetch_add(1, std::memory_order_seq_cst);
};
return op;
}
} // namespace
// T12 (1): complete-vs-cancel race, two persistent threads, atomic round
// gate, 1e5 rounds. Exactly one CAS winner per round; deliveries partition
// into complete/cancel; destroy exactly once per op.
TEST(FrameCompletion, CompleteVsCancelRaceExactlyOnce) {
io_core core(1);
strand s(core, 64);
constexpr uint64_t kRounds = 100000;
constexpr std::size_t kPool = 64;
std::vector<completion_node> nodes(kPool);
completion_rec rec;
std::atomic<uint64_t> gate{0};
std::atomic<uint64_t> done_complete{0};
std::atomic<uint64_t> done_cancel{0};
std::atomic<bool> shutdown{false};
std::atomic<uint64_t> reserve_failures{0};
core.start();
auto spinner = [&](auto act, std::atomic<uint64_t>& done) {
uint64_t next = 1;
while (!shutdown.load(std::memory_order_acquire)) {
while (gate.load(std::memory_order_acquire) < next) {
if (shutdown.load(std::memory_order_acquire)) {
return;
}
std::this_thread::yield();
}
act(next - 1, nodes[(next - 1) % kPool]);
done.store(next, std::memory_order_release);
++next;
}
};
std::thread complete_thread(
spinner,
[&](uint64_t, completion_node& node) {
if (!node.complete(kOriginalErr)) {
// losing the CAS is legal; only the winner delivers
}
},
std::ref(done_complete));
std::thread cancel_thread(
spinner, [&](uint64_t, completion_node& node) { (void)node.cancel(); },
std::ref(done_cancel));
for (uint64_t round = 0; round < kRounds; ++round) {
completion_node& node = nodes[round % kPool];
if (!node.reserve(s, s.generation(), make_completion_op(&rec))) {
reserve_failures.fetch_add(1);
break;
}
gate.store(round + 1, std::memory_order_release);
ASSERT_TRUE(wait_until(
[&] {
return done_complete.load(std::memory_order_acquire) >= round + 1 &&
done_cancel.load(std::memory_order_acquire) >= round + 1 &&
rec.deliveries() == round + 1 && rec.destroyed.load() == round + 1 &&
s.destroyed_count() == round + 1;
},
std::chrono::seconds{30}))
<< "stalled at round " << round;
node.recycle();
}
// Release spinners via the shutdown flag only: bumping the gate here
// would unlock one extra act() on a recycled (PENDING) node.
shutdown.store(true, std::memory_order_release);
complete_thread.join();
cancel_thread.join();
EXPECT_EQ(reserve_failures.load(), 0u);
EXPECT_EQ(rec.deliveries(), kRounds);
EXPECT_EQ(rec.complete_delivered.load() + rec.cancel_delivered.load(), kRounds);
EXPECT_EQ(rec.destroyed.load(), kRounds);
EXPECT_EQ(s.destroyed_count(), kRounds);
ASSERT_EQ(rec.delivered_errs.size(), kRounds);
for (const frame_err_t err : rec.delivered_errs) {
EXPECT_TRUE(err == kOriginalErr || err == FRAME_ERR_CANCELLED);
}
core.stop();
}
// T12 (2): COMPLETED wins the CAS first -> the original error is delivered;
// a later cancel is a no-op (late result releases nothing).
TEST(FrameCompletion, CancelAfterCompleteKeepsOriginalErr) {
io_core core(1);
strand s(core, 4);
completion_node node;
completion_rec rec;
core.start();
ASSERT_TRUE(node.reserve(s, s.generation(), make_completion_op(&rec)));
ASSERT_TRUE(node.complete(kOriginalErr));
ASSERT_FALSE(node.cancel());
ASSERT_FALSE(node.complete(FRAME_ERR_BUSY));
EXPECT_EQ(node.state(), completion_state::completed);
ASSERT_TRUE(wait_until([&] { return rec.destroyed.load() == 1; }, std::chrono::seconds{10}));
ASSERT_EQ(rec.delivered_errs.size(), 1u);
EXPECT_EQ(rec.delivered_errs[0], kOriginalErr);
EXPECT_EQ(rec.cancel_delivered.load(), 0u);
EXPECT_EQ(rec.complete_delivered.load(), 1u);
EXPECT_EQ(s.destroyed_count(), 1u);
core.stop();
}
// T12 (3): reservation failure means nothing was started: the service
// returns QUEUE_FULL synchronously and never touches the caller's op.
TEST(FrameCompletion, ReserveFailureStartsNothing) {
io_core core(1);
strand s(core, 4);
completion_node node;
completion_rec rec;
const frame_completion_operation_t op = make_completion_op(&rec);
ASSERT_TRUE(node.reserve(s, s.generation(), op));
ASSERT_FALSE(node.reserve(s, s.generation(), op)); // already used
// Service-side contract on the failed path: synchronous QUEUE_FULL.
const frame_err_t started =
node.reserve(s, s.generation(), op) ? FRAME_OK : FRAME_ERR_QUEUE_FULL;
EXPECT_EQ(started, FRAME_ERR_QUEUE_FULL);
EXPECT_EQ(rec.deliveries(), 0u);
EXPECT_EQ(rec.destroyed.load(), 0u);
EXPECT_EQ(s.invoked_count(), 0u);
EXPECT_EQ(s.destroyed_count(), 0u);
core.stop();
}
// T12 (4): QUIESCING converts queued un-run POSTs to CLEANUP in place; every
// destroy runs on the worker thread (LIFE-007), no handler is invoked.
TEST(FrameCompletion, QuiescingCleanupRunsOnWorkerThread) {
io_core core(1);
strand s(core, 16);
constexpr int kPosts = 16;
std::vector<post_rec> posts(kPosts);
for (auto& post : posts) {
frame_post_operation_t op{};
op.user = &post;
op.invoke = [](void* user) { static_cast<post_rec*>(user)->invoked.store(true); };
op.destroy = [](void* user) {
auto* post = static_cast<post_rec*>(user);
post->destroy_thread = std::this_thread::get_id();
post->destroyed.store(true);
};
ASSERT_EQ(s.post(op), FRAME_OK);
}
s.begin_quiescing();
core.start();
ASSERT_TRUE(
wait_until([&] { return s.destroyed_count() == kPosts; }, std::chrono::seconds{10}));
ASSERT_TRUE(wait_until([&] { return s.stopped(); }, std::chrono::seconds{10}));
EXPECT_EQ(s.invoked_count(), 0u);
EXPECT_EQ(s.stale_generation_dropped(), 0u);
const std::thread::id main_id = std::this_thread::get_id();
for (const auto& post : posts) {
EXPECT_FALSE(post.invoked.load());
EXPECT_TRUE(post.destroyed.load());
EXPECT_NE(post.destroy_thread, std::thread::id{});
EXPECT_NE(post.destroy_thread, main_id); // destroys ran on the worker
EXPECT_EQ(post.destroy_thread, posts.front().destroy_thread);
}
core.stop();
}
// T12 (5): stale generation callbacks are dropped (no complete/invoke) but
// still destroyed exactly once and counted.
TEST(FrameCompletion, StaleGenerationDroppedButDestroyed) {
io_core core(1);
strand s(core, 8);
std::vector<post_rec> posts(4);
for (auto& post : posts) {
frame_post_operation_t op{};
op.user = &post;
op.invoke = [](void* user) { static_cast<post_rec*>(user)->invoked.store(true); };
op.destroy = [](void* user) { static_cast<post_rec*>(user)->destroyed.store(true); };
ASSERT_EQ(s.post(op), FRAME_OK);
}
const uint64_t stale_generation = s.generation();
s.advance_generation();
core.start();
ASSERT_TRUE(wait_until([&] { return s.destroyed_count() == 4; }, std::chrono::seconds{10}));
EXPECT_EQ(s.invoked_count(), 0u);
EXPECT_EQ(s.stale_generation_dropped(), 4u);
for (const auto& post : posts) {
EXPECT_FALSE(post.invoked.load());
EXPECT_TRUE(post.destroyed.load());
}
completion_node node;
completion_rec rec;
ASSERT_TRUE(node.reserve(s, stale_generation, make_completion_op(&rec)));
ASSERT_TRUE(node.complete(kOriginalErr));
ASSERT_TRUE(wait_until([&] { return rec.destroyed.load() == 1; }, std::chrono::seconds{10}));
EXPECT_EQ(rec.deliveries(), 0u); // stale: complete() skipped
EXPECT_EQ(rec.destroyed.load(), 1u);
EXPECT_EQ(s.stale_generation_dropped(), 5u);
core.stop();
}
// T12 (6): three-way race complete/cancel/quiesce per round on a fresh
// strand (quiesce is terminal). Invariants: exactly one completion delivery
// (original err or CANCELLED), every accepted post destroyed exactly once
// (invoked or cleaned up), the strand reaches stopped.
TEST(FrameCompletion, ThreeWayRaceCompleteCancelQuiesce) {
io_core core(1);
constexpr uint64_t kRounds = 20000;
constexpr std::size_t kPool = 64;
constexpr int kPostsPerRound = 3;
std::vector<completion_node> nodes(kPool);
std::vector<post_rec> posts(kPostsPerRound);
completion_rec rec;
std::atomic<uint64_t> gate{0};
std::atomic<uint64_t> done[3] = {{0}, {0}, {0}};
std::atomic<bool> shutdown{false};
std::atomic<strand*> current{nullptr};
std::atomic<uint64_t> reserve_failures{0};
core.start();
auto spinner = [&](int slot, auto act) {
uint64_t next = 1;
while (!shutdown.load(std::memory_order_acquire)) {
while (gate.load(std::memory_order_acquire) < next) {
if (shutdown.load(std::memory_order_acquire)) {
return;
}
std::this_thread::yield();
}
act(next - 1, nodes[(next - 1) % kPool]);
done[slot].store(next, std::memory_order_release);
++next;
}
};
std::thread complete_thread(
spinner, 0, [&](uint64_t, completion_node& node) { (void)node.complete(kOriginalErr); });
std::thread cancel_thread(spinner, 1,
[&](uint64_t, completion_node& node) { (void)node.cancel(); });
std::thread quiesce_thread(spinner, 2, [&](uint64_t, completion_node&) {
current.load(std::memory_order_acquire)->begin_quiescing();
});
for (uint64_t round = 0; round < kRounds; ++round) {
strand round_strand(core, 8);
for (auto& post : posts) {
post.invoked.store(false);
post.destroyed.store(false);
}
completion_node& node = nodes[round % kPool];
if (!node.reserve(round_strand, round_strand.generation(), make_completion_op(&rec))) {
reserve_failures.fetch_add(1);
break;
}
for (auto& post : posts) {
frame_post_operation_t op{};
op.user = &post;
op.invoke = [](void* user) { static_cast<post_rec*>(user)->invoked.store(true); };
op.destroy = [](void* user) {
auto* item = static_cast<post_rec*>(user);
item->destroy_thread = std::this_thread::get_id();
item->destroyed.store(true);
};
ASSERT_EQ(round_strand.post(op), FRAME_OK) << "round " << round;
}
current.store(&round_strand, std::memory_order_release);
gate.store(round + 1, std::memory_order_release);
ASSERT_TRUE(wait_until(
[&] {
return done[0].load(std::memory_order_acquire) >= round + 1 &&
done[1].load(std::memory_order_acquire) >= round + 1 &&
done[2].load(std::memory_order_acquire) >= round + 1 &&
rec.deliveries() == round + 1 && rec.destroyed.load() == round + 1 &&
round_strand.destroyed_count() == kPostsPerRound + 1 &&
round_strand.stopped();
},
std::chrono::seconds{30}))
<< "stalled at round " << round;
for (const auto& post : posts) {
ASSERT_TRUE(post.destroyed.load()) << "round " << round;
}
node.recycle();
}
shutdown.store(true, std::memory_order_release);
complete_thread.join();
cancel_thread.join();
quiesce_thread.join();
EXPECT_EQ(reserve_failures.load(), 0u);
EXPECT_EQ(rec.deliveries(), kRounds);
EXPECT_EQ(rec.complete_delivered.load() + rec.cancel_delivered.load(), kRounds);
EXPECT_EQ(rec.destroyed.load(), kRounds);
core.stop();
}
+359
View File
@@ -0,0 +1,359 @@
#include <atomic>
#include <chrono>
#include <cstdint>
#include <functional>
#include <thread>
#include <vector>
#include <gtest/gtest.h>
#include "frame_poc/frame_strand.hh"
using frame::poc::io_core;
using frame::poc::strand;
namespace {
constexpr auto kPollDelay = std::chrono::microseconds{50};
bool wait_until(const std::function<bool()>& predicate, std::chrono::milliseconds timeout) {
const auto deadline = std::chrono::steady_clock::now() + timeout;
while (!predicate()) {
if (std::chrono::steady_clock::now() > deadline) {
return false;
}
std::this_thread::sleep_for(kPollDelay);
}
return true;
}
struct ticket_cell {
std::vector<uint64_t> observed; // written only by the worker, read after destroy gate
};
struct ticket_payload {
ticket_cell* cell;
uint64_t ticket;
};
struct concurrency_guard {
std::atomic<bool> in_flight[2] = {false, false};
std::atomic<bool> fault{false};
std::atomic<bool> first{true};
std::atomic<bool> id_mismatch{false};
std::thread::id worker{}; // touched only by the single worker thread
};
struct slot_payload {
concurrency_guard* guard;
int slot;
};
struct flag_payload {
std::atomic<bool>* invoked;
std::atomic<bool>* destroyed;
};
struct slow_payload {
std::chrono::milliseconds nap;
};
} // namespace
// T11 (1): one strand, 3 producer threads x 10k posts each. Per-producer
// ticket order must be strictly increasing in the handler (FIFO + 4.1.2
// linearization at the strand mutex).
TEST(FrameStrand, StrictFifoOrderAcrossProducers) {
io_core core(1);
strand s(core, 31000);
constexpr int kProducers = 3;
constexpr uint64_t kPerProducer = 10000;
std::vector<ticket_cell> cells(kProducers);
std::vector<ticket_payload> payloads;
payloads.reserve(static_cast<size_t>(kProducers) * kPerProducer);
for (int producer = 0; producer < kProducers; ++producer) {
for (uint64_t ticket = 0; ticket < kPerProducer; ++ticket) {
payloads.push_back(ticket_payload{&cells[static_cast<size_t>(producer)], ticket});
}
}
core.start();
std::vector<std::thread> producers;
producers.reserve(kProducers);
for (int producer = 0; producer < kProducers; ++producer) {
producers.emplace_back([&, producer] {
for (uint64_t ticket = 0; ticket < kPerProducer; ++ticket) {
ticket_payload& payload =
payloads[static_cast<size_t>(producer) * kPerProducer + ticket];
frame_post_operation_t op{};
op.user = &payload;
op.invoke = [](void* user) {
auto* item = static_cast<ticket_payload*>(user);
item->cell->observed.push_back(item->ticket);
};
op.destroy = [](void*) {};
ASSERT_EQ(s.post(op), FRAME_OK);
}
});
}
for (auto& producer : producers) {
producer.join();
}
const uint64_t total = static_cast<uint64_t>(kProducers) * kPerProducer;
ASSERT_TRUE(wait_until([&] { return s.destroyed_count() == total; }, std::chrono::seconds{30}));
for (int producer = 0; producer < kProducers; ++producer) {
const auto& observed = cells[static_cast<size_t>(producer)].observed;
ASSERT_EQ(observed.size(), kPerProducer);
for (uint64_t index = 0; index < kPerProducer; ++index) {
ASSERT_EQ(observed[index], index)
<< "producer " << producer << " ticket order broken at " << index;
}
}
EXPECT_EQ(s.invoked_count(), total);
core.stop();
}
// T11 (2): same-strand handlers never overlap (in-flight CAS guard) and all
// handlers run on one worker thread (LIFE-001 serialization).
TEST(FrameStrand, SameStrandHandlersNeverConcurrent) {
io_core core(2);
strand strands[2]{strand(core, 512), strand(core, 512)};
concurrency_guard guard;
slot_payload payloads[2]{{&guard, 0}, {&guard, 1}};
core.start();
auto launch = [&](int slot, int count) {
return std::thread([&, this_slot = slot, this_count = count] {
strand& target = strands[this_slot];
for (int index = 0; index < this_count; ++index) {
frame_post_operation_t op{};
op.user = &payloads[this_slot];
op.invoke = [](void* user) {
auto* item = static_cast<slot_payload*>(user);
auto* shared = item->guard;
const int slot = item->slot;
bool expected = false;
if (!shared->in_flight[slot].compare_exchange_strong(expected, true)) {
shared->fault.store(true);
}
const std::thread::id current = std::this_thread::get_id();
if (shared->first.exchange(false)) {
shared->worker = current;
} else if (current != shared->worker) {
shared->id_mismatch.store(true);
}
std::this_thread::sleep_for(std::chrono::microseconds{20});
shared->in_flight[slot].store(false);
};
op.destroy = [](void*) {};
while (target.post(op) == FRAME_ERR_QUEUE_FULL) {
std::this_thread::yield();
}
}
});
};
std::vector<std::thread> threads;
for (int index = 0; index < 2; ++index) {
threads.push_back(launch(0, 400));
threads.push_back(launch(1, 400));
}
for (auto& thread : threads) {
thread.join();
}
const uint64_t total = 1600;
ASSERT_TRUE(wait_until(
[&] { return strands[0].destroyed_count() + strands[1].destroyed_count() == total; },
std::chrono::seconds{30}));
EXPECT_FALSE(guard.fault.load());
EXPECT_FALSE(guard.id_mismatch.load());
core.stop();
}
// T11 (3): the ready-ring duplicate detector stays clear under multi-producer
// stress against a single strand (max-once invariant, 4.1.3).
TEST(FrameStrand, ReadyQueueNeverDuplicatesStrand) {
io_core core(1);
strand s(core, 256);
constexpr int kProducers = 8;
constexpr int kPerProducer = 5000;
core.start();
auto producer = [&] {
for (int index = 0; index < kPerProducer; ++index) {
frame_post_operation_t op{};
op.user = nullptr;
op.invoke = [](void*) {};
op.destroy = [](void*) {};
while (s.post(op) == FRAME_ERR_QUEUE_FULL) {
std::this_thread::yield();
}
}
};
std::vector<std::thread> threads;
threads.reserve(kProducers);
for (int index = 0; index < kProducers; ++index) {
threads.emplace_back(producer);
}
for (auto& thread : threads) {
thread.join();
}
const uint64_t total = static_cast<uint64_t>(kProducers) * kPerProducer;
ASSERT_TRUE(wait_until([&] { return s.destroyed_count() == total; }, std::chrono::seconds{30}));
EXPECT_FALSE(core.duplicate_detected());
EXPECT_EQ(s.invoked_count(), total);
core.stop();
}
// T11 (4): producer storm vs drain with a tiny credit window (capacity 64):
// after 1e5 accepted posts every operation must be invoked and destroyed —
// a lost wakeup would strand FIFO nodes forever (4.1.3 anti-lost-wakeup).
TEST(FrameStrand, NoLostWakeupUnderProducerStorm) {
io_core core(1);
strand s(core, 64);
constexpr int kProducers = 4;
constexpr uint64_t kTotal = 100000;
std::atomic<uint64_t> accepted{0};
core.start();
auto producer = [&] {
for (;;) {
if (accepted.load() >= kTotal) {
return;
}
frame_post_operation_t op{};
op.user = nullptr;
op.invoke = [](void*) {};
op.destroy = [](void*) {};
while (s.post(op) == FRAME_ERR_QUEUE_FULL) {
std::this_thread::yield();
}
accepted.fetch_add(1);
}
};
std::vector<std::thread> threads;
threads.reserve(kProducers);
for (int index = 0; index < kProducers; ++index) {
threads.emplace_back(producer);
}
for (auto& thread : threads) {
thread.join();
}
// The claim check races, so the exact accepted total can exceed kTotal by
// up to kProducers-1; every accepted post must still be invoked+destroyed.
const uint64_t total = accepted.load(std::memory_order_acquire);
ASSERT_GE(total, kTotal);
ASSERT_TRUE(wait_until([&] { return s.invoked_count() == total; }, std::chrono::seconds{60}));
ASSERT_TRUE(wait_until([&] { return s.destroyed_count() == total; }, std::chrono::seconds{60}));
s.begin_quiescing();
ASSERT_TRUE(wait_until([&] { return s.stopped(); }, std::chrono::seconds{10}));
EXPECT_EQ(s.stale_generation_dropped(), 0u);
core.stop();
}
// T11 (5): credit exhaustion returns FRAME_ERR_QUEUE_FULL and the caller
// keeps ownership (destroy NOT called on reject, 4.1.2).
TEST(FrameStrand, QueueFullRejectKeepsCallerOwnership) {
io_core core(1);
strand s(core, 8);
std::vector<std::atomic<bool>> invoked_flags(8);
std::atomic<bool> reject_destroyed{false};
for (auto& flag : invoked_flags) {
flag.store(false);
}
for (auto& flag : invoked_flags) {
frame_post_operation_t op{};
op.user = &flag;
op.invoke = [](void*) {};
op.destroy = [](void* user) { static_cast<std::atomic<bool>*>(user)->store(true); };
ASSERT_EQ(s.post(op), FRAME_OK);
}
frame_post_operation_t overflow{};
overflow.user = &reject_destroyed;
overflow.invoke = [](void*) {};
overflow.destroy = [](void* user) { static_cast<std::atomic<bool>*>(user)->store(true); };
ASSERT_EQ(s.post(overflow), FRAME_ERR_QUEUE_FULL);
ASSERT_FALSE(reject_destroyed.load());
core.start();
ASSERT_TRUE(wait_until([&] { return s.destroyed_count() == 8; }, std::chrono::seconds{10}));
EXPECT_EQ(s.invoked_count(), 8u);
EXPECT_FALSE(reject_destroyed.load());
for (const auto& flag : invoked_flags) {
EXPECT_TRUE(flag.load());
}
core.stop();
}
// T11 (6): a handler slower than the budget bumps handler_overruns
// (LIFE-002 metric only — no preemption, no isolation).
TEST(FrameStrand, OverrunCounterIncrementsOnSlowHandler) {
io_core core(1);
strand s(core, 8);
core.start();
frame_post_operation_t fast{};
fast.user = nullptr;
fast.invoke = [](void*) {};
fast.destroy = [](void*) {};
ASSERT_EQ(s.post(fast), FRAME_OK);
ASSERT_TRUE(wait_until([&] { return s.destroyed_count() == 1; }, std::chrono::seconds{10}));
EXPECT_EQ(s.handler_overruns(), 0u);
slow_payload slow{std::chrono::milliseconds{3}};
for (int index = 0; index < 3; ++index) {
frame_post_operation_t op{};
op.user = &slow;
op.invoke = [](void* user) {
std::this_thread::sleep_for(static_cast<slow_payload*>(user)->nap);
};
op.destroy = [](void*) {};
ASSERT_EQ(s.post(op), FRAME_OK);
}
ASSERT_TRUE(wait_until([&] { return s.destroyed_count() == 4; }, std::chrono::seconds{10}));
EXPECT_EQ(s.handler_overruns(), 3u);
core.stop();
}
// T11 (7): posts are rejected with FRAME_ERR_PLUGIN_STOPPING once the strand
// is closing, and queued un-run posts are cleaned up (invoke skipped,
// destroy exactly once, LIFE-007).
TEST(FrameStrand, ClosingRejectsPostsAndCleansUp) {
io_core core(1);
strand s(core, 4);
std::vector<std::atomic<bool>> invoked_flags(2);
std::vector<std::atomic<bool>> destroy_flags(2);
for (size_t index = 0; index < 2; ++index) {
invoked_flags[index].store(false);
destroy_flags[index].store(false);
}
std::vector<flag_payload> payloads;
for (size_t index = 0; index < 2; ++index) {
payloads.push_back(flag_payload{&invoked_flags[index], &destroy_flags[index]});
}
for (auto& payload : payloads) {
frame_post_operation_t op{};
op.user = &payload;
op.invoke = [](void* user) { static_cast<flag_payload*>(user)->invoked->store(true); };
op.destroy = [](void* user) { static_cast<flag_payload*>(user)->destroyed->store(true); };
ASSERT_EQ(s.post(op), FRAME_OK);
}
s.begin_quiescing();
frame_post_operation_t late{};
late.user = nullptr;
late.invoke = [](void*) {};
late.destroy = [](void*) {};
ASSERT_EQ(s.post(late), FRAME_ERR_PLUGIN_STOPPING);
core.start();
ASSERT_TRUE(wait_until([&] { return s.destroyed_count() == 2; }, std::chrono::seconds{10}));
ASSERT_TRUE(wait_until([&] { return s.stopped(); }, std::chrono::seconds{10}));
EXPECT_EQ(s.invoked_count(), 0u);
for (size_t index = 0; index < 2; ++index) {
EXPECT_FALSE(invoked_flags[index].load());
EXPECT_TRUE(destroy_flags[index].load());
}
core.stop();
}
+534
View File
@@ -0,0 +1,534 @@
"""Generate the deterministic host test corpus for the T3 MPB C parser.
Usage (repository root or any directory):
uv run python poc/host/tests/gen_mpb_corpus.py
Calls the pinned worktree builder ``tools/frame_tools/manifest_builder.py``
(commit 4793cc2) to emit every fixture into ``poc/host/tests/mpb_corpus/``
together with ``corpus_manifest.inc`` (the data table the GoogleTest binary
walks) and this directory's README. The python oracle re-verifies each
expectation before it is written, so a regenerated corpus that does not
reproduce the recorded expectations fails loudly instead of silently
drifting. The ``.inc`` extension keeps generated data outside the
clang-format gate's source globs.
Host known-answer (KAT) signature strategy, documented here because it is a
deliberate simplification: host tests inject an ``ecdsa_verify_fn`` test
double that accepts exactly the (key_id, digest, signature) triple the
builder produced, as recorded in this corpus. Equality stands in for the
P-256 math: any tamper of the signed prefix changes the digest side, any
tamper of the signature record changes the signature side, and the wrong-key
fixture fails the key_id comparison. The target build performs real ECDSA
verification through the PSA crypto glue instead.
"""
from __future__ import annotations
import hashlib
import struct
import sys
from pathlib import Path
from typing import Any, Callable
from cryptography.hazmat.primitives.asymmetric import ec
REPO_ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(REPO_ROOT / "tools"))
from frame_tools.manifest_builder import ( # noqa: E402
FLAG_RESOURCE_ONLY,
FRAME_ERR_ABI_MISMATCH,
FRAME_ERR_EPOCH_ROLLBACK,
FRAME_ERR_HASH_MISMATCH,
FRAME_ERR_PACKAGE_INVALID,
FRAME_ERR_SIGNATURE_INVALID,
FRAME_ERR_TARGET_MISMATCH,
MpbError,
PAYLOAD_ENTRY_SIZE,
PAYLOAD_TYPE_ELF,
PAYLOAD_TYPE_RESOURCE,
SIGNATURE_RECORD_SIZE,
TLV_FLAG_REQUIRED,
Manifest,
Payload,
assemble_mpb,
build_mpb,
derive_key_id,
load_private_key,
load_public_key,
sign_digest_deterministic,
verify_mpb,
)
CORPUS_DIR = Path(__file__).resolve().parent / "mpb_corpus"
KEYS = REPO_ROOT / "tools/frame_tools/testdata/keys"
PRIVATE_PEM = KEYS / "poc_a_test_signing_key.pem"
PUBLIC_PEM = KEYS / "poc_a_test_signing_key.pub.pem"
IRAM_SIZE = 0x1234
IRAM_ADDR = 0x40378000
KEY_B_SEED = b"poc-a-mpb-corpus-key-b"
EPOCH_FLOOR = 1
def synthetic_elf(iram_size: int = IRAM_SIZE, iram_addr: int = IRAM_ADDR) -> bytes:
"""Same minimal ELF32 LE Xtensa image as tests/test_manifest_builder.py."""
shstrtab = b"\x00" + b".plugin_iram\x00" + b".shstrtab\x00"
body = b"\x00" * 8
shoff = 52 + len(body) + len(shstrtab)
ident = b"\x7fELF" + bytes([1, 1, 1, 0]) + b"\x00" * 8
ehdr = ident + struct.pack(
"<HHIIIIIHHHHHH", 2, 94, 1, iram_addr, 0, shoff, 0, 52, 0, 0, 40, 3, 2
)
iram_name = 1
shstr_name = 1 + len(b".plugin_iram\x00")
shdrs = (
b"\x00" * 40
+ struct.pack("<10I", iram_name, 1, 0x6, iram_addr, 52, iram_size, 0, 0, 16, 0)
+ struct.pack("<10I", shstr_name, 3, 0, 0, 52 + len(body), len(shstrtab), 0, 0, 1, 0)
)
return ehdr + body + shstrtab + shdrs
def tlv(field_id: int, flags: int, value: bytes) -> bytes:
return struct.pack("<HHI", field_id, flags, len(value)) + value
def header_u32(container: bytes, offset: int) -> int:
return struct.unpack_from("<I", container, offset)[0]
def header_u16(container: bytes, offset: int) -> int:
return struct.unpack_from("<H", container, offset)[0]
def sign_crafted(container: bytes, key: ec.EllipticCurvePrivateKey) -> bytes:
"""Sign a container whose structure the oracle would reject (hostile path)."""
table_end = header_u32(container, 52) + header_u16(container, 56) * PAYLOAD_ENTRY_SIZE
digest = hashlib.sha256(container[:table_end]).digest()
signature = sign_digest_deterministic(key, digest)
out = bytearray(container)
offset = header_u32(container, 60)
out[offset + 8 : offset + SIGNATURE_RECORD_SIZE] = signature
return bytes(out)
def hostile_unsigned(
payloads: list[Payload],
*,
flags: int,
key: ec.EllipticCurvePrivateKey,
manifest_bytes: bytes,
**kwargs: Any,
) -> bytes:
return assemble_mpb(
manifest_bytes=manifest_bytes,
payloads=payloads,
key_id=derive_key_id(key.public_key()),
flags=flags,
**kwargs,
)
def payload_spans_and_hashes(container: bytes) -> list[tuple[int, int, str]]:
table_offset = header_u32(container, 52)
count = header_u16(container, 56)
spans = []
for index in range(count):
entry = table_offset + index * PAYLOAD_ENTRY_SIZE
offset, length = struct.unpack_from("<II", container, entry + 4)
spans.append(
(offset, length, hashlib.sha256(container[offset : offset + length]).hexdigest())
)
return spans
def kat_of(container: bytes, signature_override: bytes | None = None) -> tuple[str, str]:
"""Known-answer (digest, signature) of a fixture.
digest is always recomputed from the fixture's final bytes (that is what
the C parser will hash). signature is the legitimate builder signature
for fixtures that were not tampered inside the signature record itself;
for signature-tamper fixtures the caller passes the pre-tamper value so
the known-answer double still detects the tamper.
"""
table_end = header_u32(container, 52) + header_u16(container, 56) * PAYLOAD_ENTRY_SIZE
digest = hashlib.sha256(container[:table_end]).hexdigest()
signature_offset = header_u32(container, 60)
if signature_override is not None:
signature = signature_override
else:
signature = container[signature_offset + 8 : signature_offset + SIGNATURE_RECORD_SIZE]
return digest, signature.hex()
def expect_oracle(
code: int,
data: bytes,
key: ec.EllipticCurvePublicKey,
*,
expect_ok: bool = False,
) -> None:
try:
verify_mpb(
data,
key,
epoch_floor=EPOCH_FLOOR,
device_abi=(1, 0),
device_features=0,
)
except MpbError as error:
if expect_ok or error.code != code:
raise AssertionError(f"oracle returned {error}, expected {code}") from error
else:
if not expect_ok:
raise AssertionError(f"oracle accepted a fixture expected to fail with {code}")
def flip(data: bytes, offset: int) -> bytes:
out = bytearray(data)
out[offset] ^= 0x01
return bytes(out)
def entry() -> dict[str, Any]:
return {
"name": "",
"version": "",
"epoch": 0,
"iram": 0,
"max_memory": 0,
"payloads": [],
"digest": "",
"signature": "",
"kind": 0,
}
def main() -> int:
key_a = load_private_key(PRIVATE_PEM)
pub_a = load_public_key(PUBLIC_PEM)
key_b = ec.derive_private_key(
int.from_bytes(hashlib.sha256(KEY_B_SEED).digest(), "big"), ec.SECP256R1()
)
code_manifest = Manifest("poc-a-baseline", "1.2.3")
code_manifest.set("max_memory_bytes", 262144)
code_manifest.set("requires", ("frame/core>=1.0.0",))
resource_manifest = Manifest("poc-a-assets", "2.0.0")
resource_manifest.set("max_memory_bytes", 65536)
pos_code = build_mpb(
code_manifest,
[Payload(PAYLOAD_TYPE_ELF, synthetic_elf(), alignment=4)],
signing_key=key_a,
security_epoch=1,
)
pos_resource = build_mpb(
resource_manifest,
[
Payload(PAYLOAD_TYPE_RESOURCE, b"alpha-asset-bytes", alignment=4),
Payload(PAYLOAD_TYPE_RESOURCE, b"omega!" * 3, alignment=16),
],
signing_key=key_a,
security_epoch=1,
)
assert verify_mpb(pos_code, pub_a, epoch_floor=EPOCH_FLOOR).package_type == "code"
assert (
verify_mpb(pos_resource, pub_a, epoch_floor=EPOCH_FLOOR).package_type
== "resource-only"
)
sig_offset = header_u32(pos_code, 60)
untampered_signature = pos_code[sig_offset + 8 : sig_offset + SIGNATURE_RECORD_SIZE]
elf_table = header_u32(pos_code, 52)
elf_offset, elf_length = struct.unpack_from("<II", pos_code, elf_table + 4)
neg_magic = flip(pos_code, 0)
neg_total_size = pos_code[:-1]
neg_payload_hash = flip(pos_code, elf_offset + elf_length // 2)
neg_signature = flip(pos_code, sig_offset + 8 + 10)
neg_double_fault = flip(neg_payload_hash, sig_offset + 8 + 10)
def signed_patch(
payloads: list[Payload],
flags: int,
manifest_bytes: bytes,
patch: Callable[[bytearray], None],
) -> bytes:
crafted = bytearray(hostile_unsigned(payloads, flags=flags, key=key_a,
manifest_bytes=manifest_bytes))
patch(crafted)
return sign_crafted(bytes(crafted), key_a)
def patch_offset_oob(buf: bytearray) -> None:
window_end = header_u32(bytes(buf), 60)
struct.pack_into("<I", buf, header_u32(bytes(buf), 52) + 4, window_end)
def patch_overlap(buf: bytearray) -> None:
table = header_u32(bytes(buf), 52)
first_offset = struct.unpack_from("<I", buf, table + 4)[0]
struct.pack_into("<I", buf, table + PAYLOAD_ENTRY_SIZE + 4, first_offset)
neg_offset_oob = signed_patch(
[Payload(PAYLOAD_TYPE_RESOURCE, b"r", alignment=4)],
FLAG_RESOURCE_ONLY,
Manifest("oob", "0.0.1").encode(),
patch_offset_oob,
)
neg_overlap = signed_patch(
[
Payload(PAYLOAD_TYPE_RESOURCE, b"aaaa", alignment=4),
Payload(PAYLOAD_TYPE_RESOURCE, b"bbbb", alignment=4),
],
FLAG_RESOURCE_ONLY,
Manifest("overlap", "0.0.2").encode(),
patch_overlap,
)
neg_dup_required = sign_crafted(
hostile_unsigned(
[Payload(PAYLOAD_TYPE_RESOURCE, b"dup", alignment=4)],
flags=FLAG_RESOURCE_ONLY,
key=key_a,
manifest_bytes=tlv(1, TLV_FLAG_REQUIRED, b"dup-name")
+ tlv(1, TLV_FLAG_REQUIRED, b"dup-name"),
),
key_a,
)
neg_unknown_required_tlv = sign_crafted(
hostile_unsigned(
[Payload(PAYLOAD_TYPE_RESOURCE, b"unk", alignment=4)],
flags=FLAG_RESOURCE_ONLY,
key=key_a,
manifest_bytes=tlv(1, TLV_FLAG_REQUIRED, b"unknown-field")
+ tlv(2, TLV_FLAG_REQUIRED, b"1.0.0")
+ tlv(99, TLV_FLAG_REQUIRED, b"x"),
),
key_a,
)
def mixed_hostile(flags: int, name: str) -> bytes:
return sign_crafted(
hostile_unsigned(
[
Payload(PAYLOAD_TYPE_ELF, synthetic_elf(), alignment=4),
Payload(PAYLOAD_TYPE_RESOURCE, b"stowaway", alignment=4),
],
flags=flags,
key=key_a,
manifest_bytes=Manifest(name, "0.1.0").encode(),
),
key_a,
)
neg_mixed_elf_in_res = mixed_hostile(FLAG_RESOURCE_ONLY, "mixed-a")
neg_mixed_res_in_elf = mixed_hostile(0, "mixed-b")
neg_key_id = build_mpb(
Manifest("wrong-key", "0.9.0"),
[Payload(PAYLOAD_TYPE_RESOURCE, b"signed-by-b", alignment=4)],
signing_key=key_b,
security_epoch=1,
)
assert verify_mpb(neg_key_id, key_b.public_key(), epoch_floor=EPOCH_FLOOR)
neg_target = sign_crafted(
hostile_unsigned(
[Payload(PAYLOAD_TYPE_ELF, synthetic_elf(), alignment=4)],
flags=0,
key=key_a,
manifest_bytes=Manifest("wrong-target", "0.9.1").encode(),
target_id=0x53454C46,
),
key_a,
)
neg_abi = build_mpb(
Manifest("abi-future", "0.9.2"),
[Payload(PAYLOAD_TYPE_ELF, synthetic_elf(), alignment=4)],
signing_key=key_a,
security_epoch=1,
core_abi_major=2,
)
neg_features = build_mpb(
Manifest("features-beyond", "0.9.3"),
[Payload(PAYLOAD_TYPE_ELF, synthetic_elf(), alignment=4)],
signing_key=key_a,
security_epoch=1,
required_features=0x3,
)
neg_epoch = build_mpb(
Manifest("stale-epoch", "0.9.4"),
[Payload(PAYLOAD_TYPE_ELF, synthetic_elf(), alignment=4)],
signing_key=key_a,
security_epoch=0,
)
expect_oracle(0, pos_code, pub_a, expect_ok=True)
expect_oracle(0, pos_resource, pub_a, expect_ok=True)
expect_oracle(FRAME_ERR_PACKAGE_INVALID, neg_magic, pub_a)
expect_oracle(FRAME_ERR_PACKAGE_INVALID, neg_total_size, pub_a)
expect_oracle(FRAME_ERR_PACKAGE_INVALID, neg_offset_oob, pub_a)
expect_oracle(FRAME_ERR_PACKAGE_INVALID, neg_overlap, pub_a)
expect_oracle(FRAME_ERR_PACKAGE_INVALID, neg_dup_required, pub_a)
expect_oracle(FRAME_ERR_PACKAGE_INVALID, neg_unknown_required_tlv, pub_a)
expect_oracle(FRAME_ERR_PACKAGE_INVALID, neg_mixed_elf_in_res, pub_a)
expect_oracle(FRAME_ERR_PACKAGE_INVALID, neg_mixed_res_in_elf, pub_a)
expect_oracle(FRAME_ERR_HASH_MISMATCH, neg_payload_hash, pub_a)
expect_oracle(FRAME_ERR_SIGNATURE_INVALID, neg_signature, pub_a)
expect_oracle(FRAME_ERR_SIGNATURE_INVALID, neg_double_fault, pub_a)
expect_oracle(FRAME_ERR_TARGET_MISMATCH, neg_target, pub_a)
expect_oracle(FRAME_ERR_ABI_MISMATCH, neg_abi, pub_a)
expect_oracle(FRAME_ERR_ABI_MISMATCH, neg_features, pub_a)
expect_oracle(FRAME_ERR_EPOCH_ROLLBACK, neg_epoch, pub_a)
def positive(file_: str, klass: str, kind: int, name: str, version: str, epoch: int,
iram: int, max_memory: int, container: bytes) -> dict[str, Any]:
digest, signature = kat_of(container)
item = entry()
item.update(
file=file_,
corpus_class=klass,
sha256=hashlib.sha256(container).hexdigest(),
expected=0,
kind=kind,
name=name,
version=version,
epoch=epoch,
iram=iram,
max_memory=max_memory,
payloads=payload_spans_and_hashes(container),
digest=digest,
signature=signature,
)
return item
def negative(file_: str, klass: str, expected: int, container: bytes,
signature_override: bytes | None = None) -> dict[str, Any]:
item = entry()
digest, signature = kat_of(container, signature_override)
item.update(
file=file_,
corpus_class=klass,
sha256=hashlib.sha256(container).hexdigest(),
expected=expected,
digest=digest,
signature=signature,
)
return item
entries = [
positive("pos_code.mpb", "positive-code", 1, "poc-a-baseline", "1.2.3", 1,
IRAM_SIZE, 262144, pos_code),
positive("pos_resource_only.mpb", "positive-resource-only", 2, "poc-a-assets",
"2.0.0", 1, 0, 65536, pos_resource),
negative("neg_magic.mpb", "negative-magic", FRAME_ERR_PACKAGE_INVALID, neg_magic),
negative("neg_total_size.mpb", "negative-total-size", FRAME_ERR_PACKAGE_INVALID,
neg_total_size, untampered_signature),
negative("neg_offset_oob.mpb", "negative-offset-oob", FRAME_ERR_PACKAGE_INVALID,
neg_offset_oob),
negative("neg_overlap.mpb", "negative-overlap", FRAME_ERR_PACKAGE_INVALID,
neg_overlap),
negative("neg_dup_required.mpb", "negative-dup-required",
FRAME_ERR_PACKAGE_INVALID, neg_dup_required),
negative("neg_unknown_required_tlv.mpb", "negative-unknown-required-tlv",
FRAME_ERR_PACKAGE_INVALID, neg_unknown_required_tlv),
negative("neg_mixed_elf_in_res.mpb", "negative-mixed-elf-in-res",
FRAME_ERR_PACKAGE_INVALID, neg_mixed_elf_in_res),
negative("neg_mixed_res_in_elf.mpb", "negative-mixed-res-in-elf",
FRAME_ERR_PACKAGE_INVALID, neg_mixed_res_in_elf),
negative("neg_payload_hash.mpb", "negative-payload-hash",
FRAME_ERR_HASH_MISMATCH, neg_payload_hash),
negative("neg_signature.mpb", "negative-signature",
FRAME_ERR_SIGNATURE_INVALID, neg_signature, untampered_signature),
negative("neg_double_fault.mpb", "negative-double-fault",
FRAME_ERR_SIGNATURE_INVALID, neg_double_fault, untampered_signature),
negative("neg_key_id.mpb", "negative-key-id", FRAME_ERR_SIGNATURE_INVALID,
neg_key_id),
negative("neg_target.mpb", "negative-target", FRAME_ERR_TARGET_MISMATCH,
neg_target),
negative("neg_abi.mpb", "negative-abi", FRAME_ERR_ABI_MISMATCH, neg_abi),
negative("neg_features.mpb", "negative-features", FRAME_ERR_ABI_MISMATCH,
neg_features),
negative("neg_epoch.mpb", "negative-epoch", FRAME_ERR_EPOCH_ROLLBACK, neg_epoch),
]
binaries = {
"pos_code.mpb": pos_code,
"pos_resource_only.mpb": pos_resource,
"neg_magic.mpb": neg_magic,
"neg_total_size.mpb": neg_total_size,
"neg_offset_oob.mpb": neg_offset_oob,
"neg_overlap.mpb": neg_overlap,
"neg_dup_required.mpb": neg_dup_required,
"neg_unknown_required_tlv.mpb": neg_unknown_required_tlv,
"neg_mixed_elf_in_res.mpb": neg_mixed_elf_in_res,
"neg_mixed_res_in_elf.mpb": neg_mixed_res_in_elf,
"neg_payload_hash.mpb": neg_payload_hash,
"neg_signature.mpb": neg_signature,
"neg_double_fault.mpb": neg_double_fault,
"neg_key_id.mpb": neg_key_id,
"neg_target.mpb": neg_target,
"neg_abi.mpb": neg_abi,
"neg_features.mpb": neg_features,
"neg_epoch.mpb": neg_epoch,
}
CORPUS_DIR.mkdir(parents=True, exist_ok=True)
for name, data in binaries.items():
(CORPUS_DIR / name).write_bytes(data)
key_id_a = derive_key_id(pub_a)
lines = [
"/* GENERATED by poc/host/tests/gen_mpb_corpus.py - do not edit.",
" * Builder pin: tools/frame_tools/manifest_builder.py @4793cc2.",
" * expected codes are frame_err_t values from frame_poc/frame_abi.h.",
" */",
"#ifndef MPB_TEST_CORPUS_MANIFEST_H",
"#define MPB_TEST_CORPUS_MANIFEST_H",
"",
"#include <stdint.h>",
"",
f'#define MPB_CORPUS_KEY_ID_A UINT32_C(0x{key_id_a:08x})',
"#define MPB_CORPUS_EPOCH_FLOOR UINT32_C(1)",
"",
"typedef struct {",
" const char* file;",
" const char* corpus_class;",
" const char* file_sha256_hex;",
" int32_t expected_error;",
" int16_t package_kind; /* 0 n/a, 1 code, 2 resource-only */",
" const char* name;",
" const char* version;",
" uint32_t epoch;",
" uint32_t iram_required_bytes;",
" uint32_t max_memory_bytes;",
" int16_t payload_count;",
" const char* payload_sha256_hex[16];",
" const char* kat_digest_hex;",
" const char* kat_signature_hex;",
"} mpb_corpus_entry_t;",
"",
"static const mpb_corpus_entry_t k_mpb_corpus[] = {",
]
for item in entries:
payloads = item["payloads"]
hexes = [f'"{span[2]}"' for span in payloads] + ["0"] * (16 - len(payloads))
lines.append(
" {"
f'"{item["file"]}", "{item["corpus_class"]}", "{item["sha256"]}", '
f'{item["expected"]}, {item["kind"]}, "{item["name"]}", '
f'"{item["version"]}", UINT32_C({item["epoch"]}), '
f'UINT32_C({item["iram"]}), UINT32_C({item["max_memory"]}), '
f'{len(payloads)}, {{{", ".join(hexes)}}}, '
f'"{item["digest"]}", "{item["signature"]}"'
"},"
)
lines += ["};", "", "#endif", ""]
(CORPUS_DIR / "corpus_manifest.inc").write_text("\n".join(lines), encoding="utf-8")
print(f"wrote {len(binaries)} fixtures + corpus_manifest.inc to {CORPUS_DIR}")
for item in entries:
print(f' {item["file"]:28s} expected={item["expected"]:4d} {item["corpus_class"]}')
return 0
if __name__ == "__main__":
raise SystemExit(main())
+46
View File
@@ -0,0 +1,46 @@
# MPB host test corpus (T3)
Deterministic fixtures consumed by `mpb_parser_test` in `poc/host`. Binary
corpus in git is intentional: the builder is fully deterministic (RFC 6979
signing), so regeneration reproduces byte-identical files.
## Regeneration
```
uv run python poc/host/tests/gen_mpb_corpus.py
```
The generator calls the worktree's python oracle
`tools/frame_tools/manifest_builder.py` (pinned at commit `4793cc2`) and
re-verifies every fixture expectation against `verify_mpb` before writing.
Run it from the worktree after any builder change; commit the `.mpb` files
together with `corpus_manifest.inc`.
## Contents
2 positives (`pos_code`, `pos_resource_only` — the resource package carries
two payloads with alignments 4 and 16 so alignment padding inside the payload
window is exercised) and 16 negatives covering the 13 required tamper
classes plus two extras (`neg_double_fault` proves signature is reported
before payload hash, `neg_features` proves required-features policy), plus
the wrong-key variant inside the signature class (`neg_key_id`, signed by a
deterministically derived second key; the KAT context only trusts key
`e5677a1c`).
Expected error codes are `frame_err_t` values; see `corpus_manifest.inc`.
## Host signature known-answer strategy
The host `ecdsa_verify_fn` test double accepts exactly the
`(key_id, digest, signature)` triple the builder produced, recorded in
`corpus_manifest.h`. Equality stands in for the P-256 math: tampering the
signed prefix changes the recomputed digest, tampering the record changes
the signature bytes, and the wrong-key fixture fails the key comparison.
The target build performs real ECDSA P-256 verification through PSA crypto
(`mpb_mbedtls_glue.c`).
Each fixture records its whole-file SHA-256; the test re-hashes every file
with the reference SHA-256 before parsing, so a stale or partially
regenerated corpus fails loudly instead of silently drifting.
All key material here is TEST-ONLY (SEC-003/SEC-005 dev default).
@@ -0,0 +1,51 @@
/* GENERATED by poc/host/tests/gen_mpb_corpus.py - do not edit.
* Builder pin: tools/frame_tools/manifest_builder.py @4793cc2.
* expected codes are frame_err_t values from frame_poc/frame_abi.h.
*/
#ifndef MPB_TEST_CORPUS_MANIFEST_H
#define MPB_TEST_CORPUS_MANIFEST_H
#include <stdint.h>
#define MPB_CORPUS_KEY_ID_A UINT32_C(0xe5677a1c)
#define MPB_CORPUS_EPOCH_FLOOR UINT32_C(1)
typedef struct {
const char* file;
const char* corpus_class;
const char* file_sha256_hex;
int32_t expected_error;
int16_t package_kind; /* 0 n/a, 1 code, 2 resource-only */
const char* name;
const char* version;
uint32_t epoch;
uint32_t iram_required_bytes;
uint32_t max_memory_bytes;
int16_t payload_count;
const char* payload_sha256_hex[16];
const char* kat_digest_hex;
const char* kat_signature_hex;
} mpb_corpus_entry_t;
static const mpb_corpus_entry_t k_mpb_corpus[] = {
{"pos_code.mpb", "positive-code", "d86937e9540d3b188d31fbd6ba67b5319694923d0210db2b4383a4724f0101ef", 0, 1, "poc-a-baseline", "1.2.3", UINT32_C(1), UINT32_C(4660), UINT32_C(262144), 1, {"1cc38307f9f8a8e8cd10b32fd066b0192c1b7c151f90e8f1d44de883b2992949", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, "f713b27b437fac4cd727f9e3c2a584c0432d06ea3ecdaf6de721efdb16406a48", "05506860beee543b0271814c339f1c1710cf800438e0a3fae89e487bbc54081c4407c72a38c3283ac56ccb9a6c60cef720db3f5d8dae4bde29147ddc9d4a30b4"},
{"pos_resource_only.mpb", "positive-resource-only", "318872c5ac2b50747d066e572c3d815688ec5c8fe74ab2147a5bfe1d8855b399", 0, 2, "poc-a-assets", "2.0.0", UINT32_C(1), UINT32_C(0), UINT32_C(65536), 2, {"f8add4c487fcf37675adecf84c265368e189649270036ece4a0fa331da472bc9", "4876cd4d6aade0bdb9a7460d5655b6d68e0aa58b390e7285eb6d573fa8aeb9b9", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, "d6cbcd1f73181c668928cca3c7f0276d26e3b65653470eb03ee0d4f0746cd1ee", "31e5432fc49443a3e9f64911c5ae4fb08c8b1d1f8fa0b08d319df941fcc7faf6b0678fcb4e36c8ed8a031d067ebd01e23b7c7a5e0e6b519497ee67352195919d"},
{"neg_magic.mpb", "negative-magic", "edca005c4f67db79386c136f91caf7cc2c41964eab064cea2049a4acf5eafde2", -18, 0, "", "", UINT32_C(0), UINT32_C(0), UINT32_C(0), 0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, "17d85c9114adc6327d9de1373b2529f50c98f9a2fca1e96a26860f74aa63b55c", "05506860beee543b0271814c339f1c1710cf800438e0a3fae89e487bbc54081c4407c72a38c3283ac56ccb9a6c60cef720db3f5d8dae4bde29147ddc9d4a30b4"},
{"neg_total_size.mpb", "negative-total-size", "e5fc8d7b2bb8d13dc7839692f70eda8e62bbeb9ef664c855533fbd4dc3d3edfe", -18, 0, "", "", UINT32_C(0), UINT32_C(0), UINT32_C(0), 0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, "f713b27b437fac4cd727f9e3c2a584c0432d06ea3ecdaf6de721efdb16406a48", "05506860beee543b0271814c339f1c1710cf800438e0a3fae89e487bbc54081c4407c72a38c3283ac56ccb9a6c60cef720db3f5d8dae4bde29147ddc9d4a30b4"},
{"neg_offset_oob.mpb", "negative-offset-oob", "525065064fabe251b3ba1f96b8d6843e03c5c893e7901b99c07381e20f05ab49", -18, 0, "", "", UINT32_C(0), UINT32_C(0), UINT32_C(0), 0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, "a79965cdbf2f11a44edb30c2c3ca13a18bc938c42d0c7b7a92c2bacaadc011bd", "9e23f1737edd216066fa7497446ba6cbff16cd13cbc9d3c84e32ea14a2408eaddc25a69d1cb746f0b6e402772ee3527df5b939f0b68db67692091ca961710ee8"},
{"neg_overlap.mpb", "negative-overlap", "6c61b658fcdccc1ebbecaae90a81994aedad44039a9a7a90df15d205d23feec8", -18, 0, "", "", UINT32_C(0), UINT32_C(0), UINT32_C(0), 0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, "542e1c107fa181e346f4fb7a2ffee4faf0a7117fea2a8e13e879921cf36b348e", "b05e8353d37247fb6075b211497f1448bf961ff8ab3e97ea45bf1775807f64991eee71e2533e0f491547b0a7d0d1a612e3f4266e8a721cb0e69539c03fab7b64"},
{"neg_dup_required.mpb", "negative-dup-required", "1441b28ea2034e122919467efa7d76b6911ed093fbf5f0931d6f0ad267893494", -18, 0, "", "", UINT32_C(0), UINT32_C(0), UINT32_C(0), 0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, "53cd687b7afb38e2124140811f7921d062dd45244ffe7eee475fe9ab29cd5c04", "f36a3f3ad0758a7925ad0efa97e8dffd2d9991d4907c51c1ef0f0ddbd63bdccd3a2521bc7b8572291ac29158bdd926928f96f09a62d60c4a3a964df1a3ad479b"},
{"neg_unknown_required_tlv.mpb", "negative-unknown-required-tlv", "0a6ba33bf7a6f3bc60687f4fabb1506b34fc46cd4d6d628438474dff1728cea6", -18, 0, "", "", UINT32_C(0), UINT32_C(0), UINT32_C(0), 0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, "ff91e4871d41f90739837b692719730ac7037da536fe688a034691814ba9e595", "8594502f348fd09417d64d9393956c2eb347273e48a80da34963aab42401fb2e0feabbdd798df72329b557dadf7914d094d2f53cb70692f3d60d4b5d7295e55e"},
{"neg_mixed_elf_in_res.mpb", "negative-mixed-elf-in-res", "80cca8ba5dc83103436791913990747bfd677f0e60263de5fae1f339fc08d05e", -18, 0, "", "", UINT32_C(0), UINT32_C(0), UINT32_C(0), 0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, "2ce94249905d33b0d84830d6ad93458dcd4c816c72eeba069d1fa817491b97bd", "065935ded27bdc81ecb8bca064c5014c99c8304ac2988ba8e988024074e6e14e7d0dd99b857d4ba1f46e5d4b0e2af302fcb3b5048047230494f9457dcde66cb3"},
{"neg_mixed_res_in_elf.mpb", "negative-mixed-res-in-elf", "872ee8e818f0708bcc4be4c043ce3cb68878a2825078dfed7835ea51ea800c7e", -18, 0, "", "", UINT32_C(0), UINT32_C(0), UINT32_C(0), 0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, "36369ca5aaeb12d033d96c8a70c3acf543729c28fbe44ebe2381f51e97f72d35", "abe079192ee0b4e3102e50fa4218a5c1eb4c66c735ebfc98c0f821fba38c8c072185066a348666f2e1d30036248e04aaef5867e3aa9a58b21b43e72a17fa4ae4"},
{"neg_payload_hash.mpb", "negative-payload-hash", "191059b17c44e0a5c1ea52a7a17a3d7594fb37662b45e030e618a3f4d36e4fd1", -19, 0, "", "", UINT32_C(0), UINT32_C(0), UINT32_C(0), 0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, "f713b27b437fac4cd727f9e3c2a584c0432d06ea3ecdaf6de721efdb16406a48", "05506860beee543b0271814c339f1c1710cf800438e0a3fae89e487bbc54081c4407c72a38c3283ac56ccb9a6c60cef720db3f5d8dae4bde29147ddc9d4a30b4"},
{"neg_signature.mpb", "negative-signature", "b7673bf613240bb6d596c53b83752ef4f2d0fc465bfd273ff0c4840c5c62a532", -17, 0, "", "", UINT32_C(0), UINT32_C(0), UINT32_C(0), 0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, "f713b27b437fac4cd727f9e3c2a584c0432d06ea3ecdaf6de721efdb16406a48", "05506860beee543b0271814c339f1c1710cf800438e0a3fae89e487bbc54081c4407c72a38c3283ac56ccb9a6c60cef720db3f5d8dae4bde29147ddc9d4a30b4"},
{"neg_double_fault.mpb", "negative-double-fault", "b29fed6c397ed193fbc55b44cc957311d5e1e79946206f4cf51e498e3b9cde65", -17, 0, "", "", UINT32_C(0), UINT32_C(0), UINT32_C(0), 0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, "f713b27b437fac4cd727f9e3c2a584c0432d06ea3ecdaf6de721efdb16406a48", "05506860beee543b0271814c339f1c1710cf800438e0a3fae89e487bbc54081c4407c72a38c3283ac56ccb9a6c60cef720db3f5d8dae4bde29147ddc9d4a30b4"},
{"neg_key_id.mpb", "negative-key-id", "aa23322034e7502a9537eaa5af800fe5cfa435503d37f32a01a8af3f859e6e70", -17, 0, "", "", UINT32_C(0), UINT32_C(0), UINT32_C(0), 0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, "35f037f8c6bf1450a89b65e249d2d44d9f3744170bb24b350da17a775588e8fc", "9d6c021378ebf66ce80e95307373bcd02dce15533ab35866dbfe232224a0d36e16373243c941f14effa3903326752b6545cc7034e49e259a483450fd07db40cb"},
{"neg_target.mpb", "negative-target", "8703e1b8cd9bd1e3d7afc857b618b3c50b14051bf3b5a37129153fae37252000", -35, 0, "", "", UINT32_C(0), UINT32_C(0), UINT32_C(0), 0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, "8ffeea4acea13b9b9911c4498410fa0544ea25b784045ce0504755675febe777", "c31a66754f06438ffcb7bab13d6856a3229bf81b81ac02df3a9eeb10ac7d7f30049cf7dca5034ee2e50d9052c6bd8fa068e6fa9db24363744e9cd65a82bfe85c"},
{"neg_abi.mpb", "negative-abi", "f6b9002aee6885719404b6feeb566a412a94e09d9d792bfb1b866998cac6f6dc", -7, 0, "", "", UINT32_C(0), UINT32_C(0), UINT32_C(0), 0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, "8d0ad121e71b9659793c2627c48dd72e63a3ff12403bb8ce103444705a217c47", "a1eba6491128221124f5f7f73cad6ae7cbc402d471cd2db087bd98da5ca9f3d8afecd6f38639928f7e555a05114139b0f9f0cf3c214a02fc194702f34a3495d8"},
{"neg_features.mpb", "negative-features", "87fe364bf95aeb74a3dc05d59da79e14a63a4c34a941f480755e5c1b15f152ba", -7, 0, "", "", UINT32_C(0), UINT32_C(0), UINT32_C(0), 0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, "d5957ba810c8395557156badeccdb52174b86e3a1319db6f92ea8becd3a2998f", "1c95c633538f233881740b54c033b5268da8cf6cb2e565866118407ad1e9c17f35d6f64265adac778b73942447fb1a67ade1fe4d36833250e365f26e470a66b1"},
{"neg_epoch.mpb", "negative-epoch", "ec9297e6cb6507073287216e1f311e14f161fc4e711c564943005debc0c5c76b", -34, 0, "", "", UINT32_C(0), UINT32_C(0), UINT32_C(0), 0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, "d1eab515460355f871bcdb6e51e4fa1b329b1223bf2bf8beb486dee5dcc42a66", "9f5530c715cff919190815d896973cd42561a21304de25e44d93e53070bc92ef83004524e429dc346b725cc01b2336ba6fb2347af83e58f340345c6ab26dfbf5"},
};
#endif
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+542
View File
@@ -0,0 +1,542 @@
#include <gtest/gtest.h>
#include <cstdint>
#include <cstdio>
#include <string>
#include <vector>
#include "frame_poc/mpb_parser.h"
#include "mpb_corpus/corpus_manifest.inc"
#include "sha256_ref.h"
namespace {
std::vector<uint8_t> read_file(const std::string& path) {
std::FILE* handle = std::fopen(path.c_str(), "rb");
if (handle == nullptr) {
ADD_FAILURE() << "cannot open " << path;
return {};
}
std::fseek(handle, 0, SEEK_END);
long size = std::ftell(handle);
std::fseek(handle, 0, SEEK_SET);
std::vector<uint8_t> data(static_cast<size_t>(size));
if (size > 0 && std::fread(data.data(), 1, data.size(), handle) != data.size()) {
ADD_FAILURE() << "short read on " << path;
data.clear();
}
std::fclose(handle);
return data;
}
std::string to_hex(const uint8_t* data, size_t length) {
static const char kDigits[] = "0123456789abcdef";
std::string out;
out.reserve(length * 2);
for (size_t i = 0; i < length; ++i) {
out.push_back(kDigits[data[i] >> 4]);
out.push_back(kDigits[data[i] & 0xF]);
}
return out;
}
int from_hex(const std::string& hex, uint8_t* out, size_t capacity) {
if (hex.size() / 2 > capacity || hex.size() % 2 != 0) {
return -1;
}
for (size_t i = 0; i < hex.size() / 2; ++i) {
out[i] = static_cast<uint8_t>(std::stoul(hex.substr(i * 2, 2), nullptr, 16));
}
return static_cast<int>(hex.size() / 2);
}
/* Known-answer crypto double: sha256 is the local reference implementation,
* ecdsa verification accepts exactly the builder-produced triple recorded in
* the corpus (see tests/mpb_corpus/README.md for the strategy). */
struct KatCrypto {
uint8_t expected_digest[32];
uint8_t expected_signature[64];
uint32_t trusted_key_id;
int sha_calls = 0;
int verify_calls = 0;
};
int ct_equal(const uint8_t* a, const uint8_t* b, size_t n) {
uint8_t diff = 0;
for (size_t i = 0; i < n; ++i) {
diff = static_cast<uint8_t>(diff | (a[i] ^ b[i]));
}
return diff == 0;
}
void kat_sha256(void* ctx, const uint8_t* data, size_t length, uint8_t out[32]) {
auto* kat = static_cast<KatCrypto*>(ctx);
++kat->sha_calls;
sha256_ref(data, length, out);
}
int kat_verify(void* ctx, uint32_t key_id, const uint8_t digest[32], const uint8_t signature[64]) {
auto* kat = static_cast<KatCrypto*>(ctx);
++kat->verify_calls;
if (key_id != kat->trusted_key_id) {
return 0;
}
return ct_equal(digest, kat->expected_digest, 32) &&
ct_equal(signature, kat->expected_signature, 64);
}
mpb_policy_t default_policy() {
return mpb_policy_t{
.max_package_bytes = 512u * 1024u,
.epoch_floor = MPB_CORPUS_EPOCH_FLOOR,
.abi_major = 1,
.abi_minor = 0,
.device_features = 0,
};
}
void kat_crypto_for(const mpb_corpus_entry_t& entry, mpb_crypto_t* crypto, KatCrypto* kat) {
/* Every fixture records the legitimate (digest, signature) pair; see
* tests/mpb_corpus/README.md for the known-answer strategy. */
ASSERT_EQ(from_hex(entry.kat_digest_hex, kat->expected_digest, 32), 32);
ASSERT_EQ(from_hex(entry.kat_signature_hex, kat->expected_signature, 64), 64);
kat->trusted_key_id = MPB_CORPUS_KEY_ID_A;
crypto->ctx = kat;
crypto->sha256_fn = &kat_sha256;
crypto->ecdsa_verify_fn = &kat_verify;
}
const mpb_corpus_entry_t* find_entry(const char* name) {
for (const auto& entry : k_mpb_corpus) {
if (std::string(entry.file) == name) {
return &entry;
}
}
ADD_FAILURE() << "corpus entry " << name << " missing";
return nullptr;
}
std::vector<uint8_t> load_entry(const mpb_corpus_entry_t& entry) {
std::vector<uint8_t> data = read_file(std::string(MPB_CORPUS_DIR) + "/" + entry.file);
uint8_t actual[32];
sha256_ref(data.data(), data.size(), actual);
EXPECT_EQ(to_hex(actual, 32), std::string(entry.file_sha256_hex))
<< "corpus file " << entry.file << " does not match its recorded sha256";
return data;
}
frame_err_t parse_with(const mpb_corpus_entry_t& entry, const std::vector<uint8_t>& data,
const mpb_policy_t& policy, mpb_view_t* view, KatCrypto* kat) {
mpb_crypto_t crypto{};
kat_crypto_for(entry, &crypto, kat);
return mpb_parse(data.data(), data.size(), &policy, &crypto, view);
}
TEST(MpbParser, EveryFixtureMatchesItsExpectedErrorCode) {
for (const auto& entry : k_mpb_corpus) {
SCOPED_TRACE(entry.file);
std::vector<uint8_t> data = load_entry(entry);
ASSERT_FALSE(data.empty());
mpb_view_t view{};
KatCrypto kat{};
frame_err_t err = parse_with(entry, data, default_policy(), &view, &kat);
EXPECT_EQ(err, entry.expected_error);
if (entry.expected_error != FRAME_OK) {
EXPECT_EQ(view.staging, nullptr) << "view must stay zeroed on failure";
}
}
}
TEST(MpbParser, CodePositiveVerifiesAndExposesView) {
const mpb_corpus_entry_t* entry = find_entry("pos_code.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
ASSERT_EQ(parse_with(*entry, data, default_policy(), &view, &kat), FRAME_OK);
EXPECT_EQ(view.package_kind, MPB_PACKAGE_CODE);
EXPECT_EQ(view.payload_count, 1);
EXPECT_EQ(view.security_epoch, 1u);
EXPECT_EQ(view.key_id, MPB_CORPUS_KEY_ID_A);
EXPECT_EQ(view.target_id, 0x33505345u);
EXPECT_EQ(view.core_abi_major, 1);
EXPECT_EQ(view.core_abi_minor, 0);
EXPECT_EQ(view.required_features, 0u);
EXPECT_EQ(std::string(reinterpret_cast<const char*>(view.name), view.name_length),
std::string(entry->name));
EXPECT_EQ(std::string(reinterpret_cast<const char*>(view.version), view.version_length),
std::string(entry->version));
EXPECT_EQ(view.max_memory_bytes, 262144u);
EXPECT_EQ(view.iram_required_bytes, 4660u);
ASSERT_EQ(view.payload_count, 1);
const uint8_t* elf = view.staging + view.payloads[0].offset;
EXPECT_EQ(view.payloads[0].length,
data.size() - view.payloads[0].offset - MPB_SIGNATURE_RECORD_SIZE);
EXPECT_EQ(elf[0], 0x7F);
EXPECT_EQ(elf[1], 'E');
EXPECT_EQ(elf[2], 'L');
EXPECT_EQ(elf[3], 'F');
uint8_t span_digest[32];
sha256_ref(elf, view.payloads[0].length, span_digest);
EXPECT_EQ(to_hex(span_digest, 32), std::string(entry->payload_sha256_hex[0]));
EXPECT_EQ(kat.sha_calls, 2); /* signing digest + one payload hash */
EXPECT_EQ(kat.verify_calls, 1);
}
TEST(MpbParser, ResourceOnlyPositiveVerifiesWithWindowPadding) {
const mpb_corpus_entry_t* entry = find_entry("pos_resource_only.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
ASSERT_EQ(parse_with(*entry, data, default_policy(), &view, &kat), FRAME_OK);
EXPECT_EQ(view.package_kind, MPB_PACKAGE_RESOURCE_ONLY);
ASSERT_EQ(view.payload_count, 2);
EXPECT_EQ(view.iram_required_bytes, 0u);
for (int i = 0; i < view.payload_count; ++i) {
SCOPED_TRACE(i);
uint8_t span_digest[32];
sha256_ref(view.staging + view.payloads[i].offset, view.payloads[i].length, span_digest);
EXPECT_EQ(to_hex(span_digest, 32), std::string(entry->payload_sha256_hex[i]));
}
EXPECT_EQ(kat.sha_calls, 3); /* signing digest + two payload hashes */
}
TEST(MpbParser, ManifestFieldAccessorRoundTrip) {
const mpb_corpus_entry_t* entry = find_entry("pos_code.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
ASSERT_EQ(parse_with(*entry, data, default_policy(), &view, &kat), FRAME_OK);
mpb_field_t field{};
EXPECT_EQ(mpb_manifest_field(&view, MPB_TLV_NAME, &field), FRAME_OK);
EXPECT_EQ(field.flags, MPB_TLV_FLAG_REQUIRED);
EXPECT_EQ(std::string(reinterpret_cast<const char*>(field.value), field.value_length),
"poc-a-baseline");
EXPECT_EQ(mpb_manifest_field(&view, MPB_TLV_REQUIRES, &field), FRAME_OK);
EXPECT_EQ(field.flags, 0);
/* requires encoding: count u8 | len u16 | bytes */
ASSERT_GE(field.value_length, 3u);
EXPECT_EQ(field.value[0], 1);
EXPECT_EQ(std::string(reinterpret_cast<const char*>(field.value + 3), field.value_length - 3),
"frame/core>=1.0.0");
EXPECT_EQ(mpb_manifest_field(&view, MPB_TLV_STATE_SCHEMA_ID, &field), FRAME_ERR_NOT_FOUND);
EXPECT_EQ(mpb_manifest_field(&view, 99, &field), FRAME_ERR_NOT_FOUND);
EXPECT_EQ(mpb_manifest_field(&view, MPB_TLV_NAME, nullptr), FRAME_ERR_INVALID_ARGUMENT);
EXPECT_EQ(mpb_manifest_field(nullptr, MPB_TLV_NAME, &field), FRAME_ERR_INVALID_ARGUMENT);
}
TEST(MpbParser, NullArgumentsAreRejected) {
const mpb_corpus_entry_t* entry = find_entry("pos_code.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
mpb_crypto_t crypto{};
kat_crypto_for(*entry, &crypto, &kat);
mpb_policy_t policy = default_policy();
EXPECT_EQ(mpb_parse(nullptr, data.size(), &policy, &crypto, &view), FRAME_ERR_INVALID_ARGUMENT);
EXPECT_EQ(mpb_parse(data.data(), data.size(), nullptr, &crypto, &view),
FRAME_ERR_INVALID_ARGUMENT);
EXPECT_EQ(mpb_parse(data.data(), data.size(), &policy, nullptr, &view),
FRAME_ERR_INVALID_ARGUMENT);
EXPECT_EQ(mpb_parse(data.data(), data.size(), &policy, &crypto, nullptr),
FRAME_ERR_INVALID_ARGUMENT);
crypto.ecdsa_verify_fn = nullptr;
EXPECT_EQ(mpb_parse(data.data(), data.size(), &policy, &crypto, &view),
FRAME_ERR_INVALID_ARGUMENT);
EXPECT_EQ(view.staging, nullptr);
}
TEST(MpbParser, CorpusMagic) {
const mpb_corpus_entry_t* entry = find_entry("neg_magic.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
EXPECT_EQ(parse_with(*entry, data, default_policy(), &view, &kat), FRAME_ERR_PACKAGE_INVALID);
EXPECT_EQ(kat.verify_calls, 0); /* structure is checked before the signature */
}
TEST(MpbParser, CorpusTotalSize) {
const mpb_corpus_entry_t* entry = find_entry("neg_total_size.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
EXPECT_EQ(parse_with(*entry, data, default_policy(), &view, &kat), FRAME_ERR_PACKAGE_INVALID);
}
TEST(MpbParser, CorpusOffsetOutOfBounds) {
const mpb_corpus_entry_t* entry = find_entry("neg_offset_oob.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
EXPECT_EQ(parse_with(*entry, data, default_policy(), &view, &kat), FRAME_ERR_PACKAGE_INVALID);
EXPECT_EQ(kat.verify_calls, 0);
}
TEST(MpbParser, CorpusRegionOverlap) {
const mpb_corpus_entry_t* entry = find_entry("neg_overlap.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
EXPECT_EQ(parse_with(*entry, data, default_policy(), &view, &kat), FRAME_ERR_PACKAGE_INVALID);
}
TEST(MpbParser, CorpusDuplicateRequiredTlv) {
const mpb_corpus_entry_t* entry = find_entry("neg_dup_required.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
EXPECT_EQ(parse_with(*entry, data, default_policy(), &view, &kat), FRAME_ERR_PACKAGE_INVALID);
}
TEST(MpbParser, CorpusUnknownRequiredTlv) {
const mpb_corpus_entry_t* entry = find_entry("neg_unknown_required_tlv.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
EXPECT_EQ(parse_with(*entry, data, default_policy(), &view, &kat), FRAME_ERR_PACKAGE_INVALID);
}
TEST(MpbParser, CorpusMixedElfInResourceOnly) {
const mpb_corpus_entry_t* entry = find_entry("neg_mixed_elf_in_res.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
EXPECT_EQ(parse_with(*entry, data, default_policy(), &view, &kat), FRAME_ERR_PACKAGE_INVALID);
}
TEST(MpbParser, CorpusMixedResourceInCode) {
const mpb_corpus_entry_t* entry = find_entry("neg_mixed_res_in_elf.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
EXPECT_EQ(parse_with(*entry, data, default_policy(), &view, &kat), FRAME_ERR_PACKAGE_INVALID);
}
TEST(MpbParser, CorpusPayloadHash) {
const mpb_corpus_entry_t* entry = find_entry("neg_payload_hash.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
EXPECT_EQ(parse_with(*entry, data, default_policy(), &view, &kat), FRAME_ERR_HASH_MISMATCH);
EXPECT_EQ(kat.verify_calls, 1); /* signature must have passed first */
}
TEST(MpbParser, CorpusSignatureTamper) {
const mpb_corpus_entry_t* entry = find_entry("neg_signature.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
EXPECT_EQ(parse_with(*entry, data, default_policy(), &view, &kat), FRAME_ERR_SIGNATURE_INVALID);
EXPECT_EQ(kat.sha_calls, 1); /* digest computed, payload hashes never reached */
}
TEST(MpbParser, CorpusWrongKeyId) {
const mpb_corpus_entry_t* entry = find_entry("neg_key_id.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
EXPECT_EQ(parse_with(*entry, data, default_policy(), &view, &kat), FRAME_ERR_SIGNATURE_INVALID);
}
TEST(MpbParser, CorpusTargetMismatch) {
const mpb_corpus_entry_t* entry = find_entry("neg_target.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
EXPECT_EQ(parse_with(*entry, data, default_policy(), &view, &kat), FRAME_ERR_TARGET_MISMATCH);
EXPECT_EQ(kat.sha_calls, 2); /* signature and payload hash both passed */
}
TEST(MpbParser, CorpusAbiMismatch) {
const mpb_corpus_entry_t* entry = find_entry("neg_abi.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
EXPECT_EQ(parse_with(*entry, data, default_policy(), &view, &kat), FRAME_ERR_ABI_MISMATCH);
}
TEST(MpbParser, CorpusFeaturesExceedDevice) {
const mpb_corpus_entry_t* entry = find_entry("neg_features.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
EXPECT_EQ(parse_with(*entry, data, default_policy(), &view, &kat), FRAME_ERR_ABI_MISMATCH);
}
TEST(MpbParser, CorpusEpochRollback) {
const mpb_corpus_entry_t* entry = find_entry("neg_epoch.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
EXPECT_EQ(parse_with(*entry, data, default_policy(), &view, &kat), FRAME_ERR_EPOCH_ROLLBACK);
}
TEST(MpbParser, DoubleFaultReportsSignatureBeforeHash) {
const mpb_corpus_entry_t* entry = find_entry("neg_double_fault.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
EXPECT_EQ(parse_with(*entry, data, default_policy(), &view, &kat), FRAME_ERR_SIGNATURE_INVALID);
EXPECT_EQ(kat.sha_calls, 1); /* stopped after the signing digest */
}
TEST(MpbParser, MaxPackageBytesPolicyRejectsOversize) {
const mpb_corpus_entry_t* entry = find_entry("pos_code.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_policy_t policy = default_policy();
policy.max_package_bytes = static_cast<uint32_t>(data.size() - 1);
mpb_view_t view{};
KatCrypto kat{};
EXPECT_EQ(parse_with(*entry, data, policy, &view, &kat), FRAME_ERR_PACKAGE_INVALID);
}
TEST(MpbParser, EpochFloorEqualStillVerifies) {
const mpb_corpus_entry_t* entry = find_entry("pos_code.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_policy_t policy = default_policy();
policy.epoch_floor = 1;
mpb_view_t view{};
KatCrypto kat{};
EXPECT_EQ(parse_with(*entry, data, policy, &view, &kat), FRAME_OK);
policy.epoch_floor = 2;
view = mpb_view_t{};
EXPECT_EQ(parse_with(*entry, data, policy, &view, &kat), FRAME_ERR_EPOCH_ROLLBACK);
}
TEST(MpbParser, SignatureRecordFieldsAreStructural) {
const mpb_corpus_entry_t* entry = find_entry("pos_code.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
const uint32_t sig_offset = static_cast<uint32_t>(
data[60] | (data[61] << 8) | (data[62] << 16) | ((uint32_t)data[63] << 24));
std::vector<uint8_t> tampered = data;
tampered[sig_offset] ^= 0x01; /* algorithm != 1 */
mpb_view_t view{};
mpb_crypto_t crypto{};
KatCrypto kat{};
kat_crypto_for(*entry, &crypto, &kat);
mpb_policy_t policy = default_policy();
EXPECT_EQ(mpb_parse(tampered.data(), tampered.size(), &policy, &crypto, &view),
FRAME_ERR_PACKAGE_INVALID);
EXPECT_EQ(kat.verify_calls, 0);
}
TEST(MpbParser, TamperedElfPayloadByteRejectedAsHashMismatch) {
const mpb_corpus_entry_t* entry = find_entry("pos_code.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_view_t view{};
KatCrypto kat{};
ASSERT_EQ(parse_with(*entry, data, default_policy(), &view, &kat), FRAME_OK);
std::vector<uint8_t> tampered = data;
tampered[view.payloads[0].offset + view.payloads[0].length / 2] ^= 0x80;
view = mpb_view_t{};
EXPECT_EQ(parse_with(*entry, tampered, default_policy(), &view, &kat), FRAME_ERR_HASH_MISMATCH);
}
TEST(MpbParser, TruncationFuzzAlwaysFailsClosed) {
for (const char* name : {"pos_code.mpb", "pos_resource_only.mpb"}) {
SCOPED_TRACE(name);
const mpb_corpus_entry_t* entry = find_entry(name);
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
mpb_policy_t policy = default_policy();
for (size_t cut = 0; cut < data.size(); ++cut) {
mpb_view_t view{};
KatCrypto kat{};
std::vector<uint8_t> truncated(data.begin(), data.begin() + cut);
mpb_crypto_t crypto{};
kat_crypto_for(*entry, &crypto, &kat);
frame_err_t err =
mpb_parse(truncated.data(), truncated.size(), &policy, &crypto, &view);
EXPECT_NE(err, FRAME_OK) << "truncation to " << cut << " accepted";
EXPECT_EQ(view.staging, nullptr);
}
}
}
TEST(MpbParser, RandomTruncationsFailClosed) {
const mpb_corpus_entry_t* entry = find_entry("pos_code.mpb");
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
uint32_t state = 0x12345678u;
auto next = [&state](uint32_t bound) {
state = state * 1664525u + 1013904223u;
return state % bound;
};
mpb_policy_t policy = default_policy();
for (int i = 0; i < 1000; ++i) {
size_t cut = next(static_cast<uint32_t>(data.size()));
mpb_view_t view{};
mpb_crypto_t crypto{};
KatCrypto kat{};
kat_crypto_for(*entry, &crypto, &kat);
std::vector<uint8_t> truncated(data.begin(), data.begin() + cut);
frame_err_t err = mpb_parse(truncated.data(), truncated.size(), &policy, &crypto, &view);
ASSERT_NE(err, FRAME_OK) << "random truncation " << cut << " accepted";
ASSERT_EQ(view.staging, nullptr);
}
}
TEST(MpbParser, ByteFlipFuzzNeverCrashes) {
for (const char* name : {"pos_code.mpb", "pos_resource_only.mpb"}) {
SCOPED_TRACE(name);
const mpb_corpus_entry_t* entry = find_entry(name);
ASSERT_NE(entry, nullptr);
std::vector<uint8_t> data = load_entry(*entry);
uint32_t state = 0xC0FFEEu;
auto next = [&state](uint32_t bound) {
state = state * 1664525u + 1013904223u;
return state % bound;
};
mpb_policy_t policy = default_policy();
for (int i = 0; i < 1000; ++i) {
size_t offset = next(static_cast<uint32_t>(data.size()));
uint8_t bit = static_cast<uint8_t>(1u << (next(8)));
std::vector<uint8_t> flipped = data;
flipped[offset] ^= bit;
mpb_view_t view{};
mpb_crypto_t crypto{};
KatCrypto kat{};
kat_crypto_for(*entry, &crypto, &kat);
frame_err_t err = mpb_parse(flipped.data(), flipped.size(), &policy, &crypto, &view);
if (err == FRAME_OK) {
/* accepted only when the flip hit unauthenticated padding */
ASSERT_EQ(view.package_kind, entry->package_kind);
ASSERT_EQ(view.staging, flipped.data());
ASSERT_LT(view.payloads[0].offset, flipped.size());
} else {
ASSERT_EQ(view.staging, nullptr);
}
}
}
}
} // namespace
+105
View File
@@ -0,0 +1,105 @@
#include "sha256_ref.h"
/* FIPS 180-4 SHA-256, written directly from the specification. Host test
* helper only; the target build uses PSA crypto via mpb_mbedtls_glue.c. */
static const uint32_t k[64] = {
0x428a2f98u, 0x71374491u, 0xb5c0fbcfu, 0xe9b5dba5u, 0x3956c25bu, 0x59f111f1u, 0x923f82a4u,
0xab1c5ed5u, 0xd807aa98u, 0x12835b01u, 0x243185beu, 0x550c7dc3u, 0x72be5d74u, 0x80deb1feu,
0x9bdc06a7u, 0xc19bf174u, 0xe49b69c1u, 0xefbe4786u, 0x0fc19dc6u, 0x240ca1ccu, 0x2de92c6fu,
0x4a7484aau, 0x5cb0a9dcu, 0x76f988dau, 0x983e5152u, 0xa831c66du, 0xb00327c8u, 0xbf597fc7u,
0xc6e00bf3u, 0xd5a79147u, 0x06ca6351u, 0x14292967u, 0x27b70a85u, 0x2e1b2138u, 0x4d2c6dfcu,
0x53380d13u, 0x650a7354u, 0x766a0abbu, 0x81c2c92eu, 0x92722c85u, 0xa2bfe8a1u, 0xa81a664bu,
0xc24b8b70u, 0xc76c51a3u, 0xd192e819u, 0xd6990624u, 0xf40e3585u, 0x106aa070u, 0x19a4c116u,
0x1e376c08u, 0x2748774cu, 0x34b0bcb5u, 0x391c0cb3u, 0x4ed8aa4au, 0x5b9cca4fu, 0x682e6ff3u,
0x748f82eeu, 0x78a5636fu, 0x84c87814u, 0x8cc70208u, 0x90befffau, 0xa4506cebu, 0xbef9a3f7u,
0xc67178f2u,
};
static uint32_t rotr(uint32_t x, uint32_t n) { return (x >> n) | (x << (32 - n)); }
static void sha256_block(const uint32_t state_in[8], const uint8_t block[64],
uint32_t state_out[8]) {
uint32_t w[64];
for (int i = 0; i < 16; ++i) {
w[i] = ((uint32_t)block[i * 4] << 24) | ((uint32_t)block[i * 4 + 1] << 16) |
((uint32_t)block[i * 4 + 2] << 8) | (uint32_t)block[i * 4 + 3];
}
for (int i = 16; i < 64; ++i) {
uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
}
uint32_t a = state_in[0];
uint32_t b = state_in[1];
uint32_t c = state_in[2];
uint32_t d = state_in[3];
uint32_t e = state_in[4];
uint32_t f = state_in[5];
uint32_t g = state_in[6];
uint32_t h = state_in[7];
for (int i = 0; i < 64; ++i) {
uint32_t s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
uint32_t ch = (e & f) ^ (~e & g);
uint32_t t1 = h + s1 + ch + k[i] + w[i];
uint32_t s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
uint32_t maj = (a & b) ^ (a & c) ^ (b & c);
uint32_t t2 = s0 + maj;
h = g;
g = f;
f = e;
e = d + t1;
d = c;
c = b;
b = a;
a = t1 + t2;
}
state_out[0] = state_in[0] + a;
state_out[1] = state_in[1] + b;
state_out[2] = state_in[2] + c;
state_out[3] = state_in[3] + d;
state_out[4] = state_in[4] + e;
state_out[5] = state_in[5] + f;
state_out[6] = state_in[6] + g;
state_out[7] = state_in[7] + h;
}
void sha256_ref(const uint8_t* data, size_t length, uint8_t digest_out[32]) {
uint32_t state[8] = {
0x6a09e667u, 0xbb67ae85u, 0x3c6ef372u, 0xa54ff53au,
0x510e527fu, 0x9b05688cu, 0x1f83d9abu, 0x5be0cd19u,
};
size_t full_blocks = length / 64;
for (size_t i = 0; i < full_blocks; ++i) {
uint32_t next[8];
sha256_block(state, data + i * 64, next);
for (int j = 0; j < 8; ++j) {
state[j] = next[j];
}
}
uint8_t tail[128];
size_t remainder = length - full_blocks * 64;
for (size_t i = 0; i < remainder; ++i) {
tail[i] = data[full_blocks * 64 + i];
}
tail[remainder] = 0x80;
size_t tail_length = remainder + 1 <= 56 ? 64 : 128;
for (size_t i = remainder + 1; i < tail_length; ++i) {
tail[i] = 0x00;
}
uint64_t bits = (uint64_t)length * 8;
for (int i = 0; i < 8; ++i) {
tail[tail_length - 1 - i] = (uint8_t)(bits >> (8 * i));
}
uint32_t next[8];
sha256_block(state, tail, next);
if (tail_length == 128) {
sha256_block(next, tail + 64, next);
}
for (int i = 0; i < 8; ++i) {
digest_out[i * 4] = (uint8_t)(next[i] >> 24);
digest_out[i * 4 + 1] = (uint8_t)(next[i] >> 16);
digest_out[i * 4 + 2] = (uint8_t)(next[i] >> 8);
digest_out[i * 4 + 3] = (uint8_t)next[i];
}
}
+20
View File
@@ -0,0 +1,20 @@
#ifndef MPB_TEST_SHA256_REF_H
#define MPB_TEST_SHA256_REF_H
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Reference FIPS 180-4 SHA-256 for host tests only. Correctness is
* self-checked against the known-answer digests that the corpus generator
* (python oracle) records for every positive fixture. */
void sha256_ref(const uint8_t* data, size_t length, uint8_t digest_out[32]);
#ifdef __cplusplus
}
#endif
#endif