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
+204 -3
View File
@@ -1,5 +1,206 @@
idf_component_register(
SRCS "poc_a_main.cc"
PRIV_REQUIRES frame_poc_runtime unity)
SRCS
"abi_smoke.cc"
"poc_a_main.cc"
"poca_console.cc"
"poca_plugin.cc"
"poca_sched.cc"
INCLUDE_DIRS "."
PRIV_REQUIRES
console
elf_loader
esp_hw_support
esp_timer
frame_poc_mpb
frame_poc_runtime
mbedtls
)
target_compile_options(${COMPONENT_LIB} PRIVATE -std=c++26)
include("${CMAKE_CURRENT_LIST_DIR}/../plugins/plugins.cmake")
poca_pubkey_header(
"${CMAKE_CURRENT_LIST_DIR}/../../../../tools/frame_tools/testdata/keys/poc_a_test_signing_key.pub.pem"
"${CMAKE_BINARY_DIR}/plugins/generated/poca_pubkey.h"
"0xe5677a1c")
poca_plugin(baseline
SOURCE "${CMAKE_CURRENT_LIST_DIR}/../plugins/baseline/baseline.c"
VERSION "1.0.0"
ENTRY "frame_plugin_entry"
MANIFEST "${CMAKE_CURRENT_LIST_DIR}/../plugins/baseline/manifest.json")
poca_plugin(globdat
SOURCE "${CMAKE_CURRENT_LIST_DIR}/../plugins/globdat/globdat.c"
VERSION "1.0.0"
ENTRY "frame_plugin_entry"
MANIFEST "${CMAKE_CURRENT_LIST_DIR}/../plugins/globdat/manifest.json"
IMPORTS "poca_host_sentinel")
poca_plugin(plt
SOURCE "${CMAKE_CURRENT_LIST_DIR}/../plugins/plt/plt.c"
VERSION "1.0.0"
ENTRY "frame_plugin_entry"
MANIFEST "${CMAKE_CURRENT_LIST_DIR}/../plugins/plt/manifest.json"
IMPORTS "poca_host_add")
poca_plugin(import_neg
SOURCE "${CMAKE_CURRENT_LIST_DIR}/../plugins/import_neg/import_neg.c"
VERSION "1.0.0"
ENTRY "frame_plugin_entry"
MANIFEST "${CMAKE_CURRENT_LIST_DIR}/../plugins/import_neg/manifest.json"
IMPORTS "frame_unknown_symbol")
# T7 IRAM probe: hot functions in .plugin_iram (gate 5 + objdump l32r check
# in the corpus step below).
string(REPLACE "-gcc" "-objdump" plugin_objdump "${CMAKE_C_COMPILER}")
poca_plugin(iram_probe
SOURCE "${CMAKE_CURRENT_LIST_DIR}/../plugins/iram_probe/iram_probe.c"
VERSION "1.0.0"
ENTRY "frame_plugin_entry"
MANIFEST "${CMAKE_CURRENT_LIST_DIR}/../plugins/iram_probe/manifest.json"
IRAM)
poca_iram_corpus(
PROBE_ELF "${CMAKE_BINARY_DIR}/plugins/iram_probe/iram_probe.elf"
OBJDUMP "${plugin_objdump}")
add_dependencies(poca_iram_corpus poca_plugin_iram_probe)
# T10 capacity ladder: eight name-parameterized plugins cap01..cap08. All
# share the baseline source template (the T8 generation-variant pattern) but
# each is packaged with a DISTINCT manifest name, version and activate()
# magic, so N concurrently resident instances prove N distinct live
# generations (PLUG-004: one ACTIVE generation per name - eight distinct
# names, no collisions). `poca capacity <n>` loads n of them, each into its
# own esp_elf_t instance, before the respond round.
set(POCA_CAP_NAMES "")
foreach(cap_idx RANGE 1 8)
set(cap_name "cap0${cap_idx}")
poca_plugin(${cap_name}
SOURCE "${CMAKE_CURRENT_LIST_DIR}/../plugins/baseline/baseline.c"
VERSION "1.0.${cap_idx}"
ENTRY "frame_plugin_entry"
MANIFEST "${CMAKE_CURRENT_LIST_DIR}/../plugins/cap/manifest.json"
MAGIC "0x4341503${cap_idx}u")
list(APPEND POCA_CAP_NAMES ${cap_name})
endforeach()
poca_negative_corpus(
BASELINE_ELF "${CMAKE_BINARY_DIR}/plugins/baseline/baseline.elf")
# negatives derive from the gated baseline ELF: gate first, then fabricate
add_dependencies(poca_negative_corpus poca_plugin_baseline)
# T8 generation coexistence: baseline_v2 is the SAME source packaged as the
# same manifest name "baseline" with version 2.0.0 and a distinct activate()
# magic; baseline_300k proves a >256KiB default-arena declaration (300KiB)
# is admission-requestable under the 512KiB hard max (MEM-003); neg_maxmem
# hostile-declares 600KiB and must be rejected on-board before esp_elf_init.
poca_plugin(baseline_v2
SOURCE "${CMAKE_CURRENT_LIST_DIR}/../plugins/baseline/baseline.c"
VERSION "2.0.0"
ENTRY "frame_plugin_entry"
MANIFEST "${CMAKE_CURRENT_LIST_DIR}/../plugins/baseline_v2/manifest.json"
MPB_NAME "baseline"
MAGIC "0x32504F43u")
poca_plugin(baseline_300k
SOURCE "${CMAKE_CURRENT_LIST_DIR}/../plugins/baseline/baseline.c"
VERSION "1.0.1"
ENTRY "frame_plugin_entry"
MANIFEST "${CMAKE_CURRENT_LIST_DIR}/../plugins/baseline_300k/manifest.json"
MPB_NAME "baseline")
poca_maxmem_corpus(
BASELINE_ELF "${CMAKE_BINARY_DIR}/plugins/baseline/baseline.elf")
add_dependencies(poca_maxmem_corpus poca_plugin_baseline)
# T6 C++ feature-rejection probes: each variant must be REJECTED by the
# same gates that protect the positive builds (expected-failure wrapper
# echoes the verbatim gate error). NEEDLES name the required rejection
# reason (plain substrings); gate order is reloc-allowlist -> C++-sections
# -> imports -> shape.
poca_cxx_probe(cxx_ctor
SOURCE "${CMAKE_CURRENT_LIST_DIR}/../plugins/cxx_probes/cxx_static_ctor.cpp"
ENTRY "frame_plugin_entry"
NEEDLES "forbidden C++ feature section" ".ctors")
poca_cxx_probe(cxx_dtor
SOURCE "${CMAKE_CURRENT_LIST_DIR}/../plugins/cxx_probes/cxx_static_dtor.cpp"
ENTRY "frame_plugin_entry"
NEEDLES "forbidden C++ feature section" ".dtors")
poca_cxx_probe(cxx_tls
SOURCE "${CMAKE_CURRENT_LIST_DIR}/../plugins/cxx_probes/cxx_tls.cpp"
ENTRY "frame_plugin_entry"
NEEDLES "relocation allowlist violated" "R_XTENSA_TLS")
poca_cxx_probe(cxx_exceptions
SOURCE "${CMAKE_CURRENT_LIST_DIR}/../plugins/cxx_probes/cxx_exceptions.cpp"
ENTRY "frame_plugin_entry"
EXTRA_FLAGS -fexceptions -funwind-tables
NEEDLES "forbidden C++ feature section" ".eh_frame")
poca_cxx_probe(cxx_rtti
SOURCE "${CMAKE_CURRENT_LIST_DIR}/../plugins/cxx_probes/cxx_rtti.cpp"
ENTRY "frame_plugin_entry"
EXTRA_FLAGS -frtti
NEEDLES "import gate failed" "__dynamic_cast")
poca_cxx_probe(cxx_unwind
SOURCE "${CMAKE_CURRENT_LIST_DIR}/../plugins/cxx_probes/cxx_unwind.cpp"
ENTRY "frame_plugin_entry"
EXTRA_FLAGS -funwind-tables -fasynchronous-unwind-tables
NEEDLES "forbidden C++ feature section" ".eh_frame")
poca_cxx_probe_corpus(
CTOR_ELF "${CMAKE_BINARY_DIR}/plugins/cxx_ctor/cxx_ctor.elf"
TLS_ELF "${CMAKE_BINARY_DIR}/plugins/cxx_tls/cxx_tls.elf")
add_dependencies(poca_cxx_probe_corpus poca_cxx_probe_cxx_ctor poca_cxx_probe_cxx_tls)
target_include_directories(${COMPONENT_LIB} PRIVATE
"${CMAKE_CURRENT_LIST_DIR}/../plugins"
"${CMAKE_BINARY_DIR}/plugins/generated")
add_dependencies(${COMPONENT_LIB}
poca_plugin_baseline
poca_plugin_baseline_v2
poca_plugin_baseline_300k
poca_plugin_globdat
poca_plugin_plt
poca_plugin_import_neg
poca_plugin_iram_probe
poca_negative_corpus
poca_maxmem_corpus
poca_cxx_probe_cxx_ctor
poca_cxx_probe_cxx_dtor
poca_cxx_probe_cxx_tls
poca_cxx_probe_cxx_exceptions
poca_cxx_probe_cxx_rtti
poca_cxx_probe_cxx_unwind
poca_cxx_probe_corpus
poca_iram_corpus)
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_BINARY_DIR}/plugins/baseline.mpb" BINARY)
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_BINARY_DIR}/plugins/baseline_v2.mpb" BINARY)
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_BINARY_DIR}/plugins/baseline_300k.mpb" BINARY)
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_BINARY_DIR}/plugins/globdat.mpb" BINARY)
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_BINARY_DIR}/plugins/plt.mpb" BINARY)
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_BINARY_DIR}/plugins/import_neg.mpb" BINARY)
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_BINARY_DIR}/plugins/iram_probe.mpb" BINARY)
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_BINARY_DIR}/plugins/iram_mismatch.mpb" BINARY)
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_BINARY_DIR}/plugins/neg_r32.mpb" BINARY)
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_BINARY_DIR}/plugins/neg_s0op.mpb" BINARY)
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_BINARY_DIR}/plugins/neg_phspan.mpb" BINARY)
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_BINARY_DIR}/plugins/neg_phbe.mpb" BINARY)
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_BINARY_DIR}/plugins/neg_ph64.mpb" BINARY)
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_BINARY_DIR}/plugins/neg_phmach.mpb" BINARY)
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_BINARY_DIR}/plugins/neg_maxmem.mpb" BINARY)
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_BINARY_DIR}/plugins/cxx_ctor.mpb" BINARY)
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_BINARY_DIR}/plugins/cxx_tls.mpb" BINARY)
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_BINARY_DIR}/plugins/neg_tls_nosect.mpb" BINARY)
foreach(cap_name IN LISTS POCA_CAP_NAMES)
add_dependencies(${COMPONENT_LIB} poca_plugin_${cap_name})
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_BINARY_DIR}/plugins/${cap_name}.mpb" BINARY)
endforeach()
target_compile_options(${COMPONENT_LIB} PRIVATE
-std=c++26
-Wall
-Wextra
-Wconversion
-Werror=return-type
-fno-exceptions
-fno-rtti
-fno-unwind-tables
)
+62
View File
@@ -0,0 +1,62 @@
#include "abi_smoke.hh"
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <type_traits>
#include "frame_poc/frame_abi.h"
namespace frame::poca {
namespace {
int check(bool passed, const char* label) {
std::printf("%s %s\n", passed ? "PASS:" : "FAIL:", label);
return passed ? 0 : 1;
}
int layout_checks() {
int failures = 0;
failures += check(offsetof(frame_abi_header_t, struct_size) == 0,
"frame_abi_header_t.struct_size offset is 0");
failures += check(sizeof(frame_abi_header_t) == 16, "frame_abi_header_t size is 16");
failures += check(sizeof(plugin_instance_handle_t) == 8, "plugin_instance_handle_t size is 8");
return failures;
}
int compatibility_checks() {
constexpr uint64_t required_feature = UINT64_C(1) << 12;
const frame_abi_header_t offered{
.struct_size = sizeof(frame_abi_header_t),
.abi_major = FRAME_ABI_MAJOR,
.abi_minor = FRAME_ABI_MINOR,
.feature_bits = required_feature,
};
int failures = 0;
failures += check(frame_abi_supports(&offered, FRAME_ABI_MAJOR, FRAME_ABI_MINOR,
sizeof(frame_abi_header_t), required_feature),
"frame_abi_supports accepts matching major/minor/size/features");
failures += check(!frame_abi_supports(&offered, FRAME_ABI_MAJOR + 1, FRAME_ABI_MINOR,
sizeof(frame_abi_header_t), required_feature),
"frame_abi_supports rejects newer abi_major");
failures += check(!frame_abi_supports(&offered, FRAME_ABI_MAJOR, FRAME_ABI_MINOR,
sizeof(frame_abi_header_t) + 1, required_feature),
"frame_abi_supports rejects larger struct_size");
return failures;
}
static_assert(__cplusplus >= 202302L);
static_assert(std::is_standard_layout_v<frame_abi_header_t>);
} // namespace
int run_abi_smoke() {
int failures = layout_checks();
failures += compatibility_checks();
std::printf("poca abi: %s (%d failure%s)\n", failures == 0 ? "PASS" : "FAIL", failures,
failures == 1 ? "" : "s");
return failures == 0 ? 0 : 1;
}
} // namespace frame::poca
+10
View File
@@ -0,0 +1,10 @@
#pragma once
namespace frame::poca {
// Runs the PoC-A ABI smoke checks (header layout, size negotiation, and
// feature-bit compatibility) and prints one PASS/FAIL line per check.
// Returns 0 when every check passes, 1 otherwise.
int run_abi_smoke();
} // namespace frame::poca
+13 -39
View File
@@ -1,42 +1,16 @@
#include <cstddef>
#include <cstdint>
#include <type_traits>
#include <cstdio>
#include "frame_poc/frame_abi.h"
#include "unity.h"
#include "esp_log.h"
#include "poca_console.hh"
TEST_CASE("C ABI header layout is stable", "[poc-a][abi]")
{
TEST_ASSERT_EQUAL_UINT32(0, offsetof(frame_abi_header_t, struct_size));
TEST_ASSERT_EQUAL_UINT32(16, sizeof(frame_abi_header_t));
TEST_ASSERT_EQUAL_UINT32(8, sizeof(plugin_instance_handle_t));
namespace {
constexpr char kTag[] = "poc-a";
} // namespace
extern "C" void app_main(void) {
ESP_LOGI(kTag, "frame poc-a dynamic-elf harness; loader elf_loader 1.3.3 @6526c5b1");
const esp_err_t console_result = frame::poca::start_console();
ESP_LOGI(kTag, "console=%s", esp_err_to_name(console_result));
}
TEST_CASE("C ABI compatibility checks size version and features", "[poc-a][abi]")
{
constexpr uint64_t required_feature = UINT64_C(1) << 12;
const frame_abi_header_t offered{
.struct_size = sizeof(frame_abi_header_t),
.abi_major = FRAME_ABI_MAJOR,
.abi_minor = FRAME_ABI_MINOR,
.feature_bits = required_feature,
};
TEST_ASSERT_TRUE(frame_abi_supports(
&offered, FRAME_ABI_MAJOR, FRAME_ABI_MINOR,
sizeof(frame_abi_header_t), required_feature));
TEST_ASSERT_FALSE(frame_abi_supports(
&offered, FRAME_ABI_MAJOR + 1, FRAME_ABI_MINOR,
sizeof(frame_abi_header_t), required_feature));
TEST_ASSERT_FALSE(frame_abi_supports(
&offered, FRAME_ABI_MAJOR, FRAME_ABI_MINOR,
sizeof(frame_abi_header_t) + 1, required_feature));
}
static_assert(__cplusplus >= 202302L);
static_assert(std::is_standard_layout_v<frame_abi_header_t>);
extern "C" void app_main(void)
{
unity_run_menu();
}
+182
View File
@@ -0,0 +1,182 @@
#include "poca_console.hh"
#include <cinttypes>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "abi_smoke.hh"
#include "esp_console.h"
#include "esp_elf.h"
#include "esp_heap_caps.h"
#include "poca_plugin.hh"
#include "poca_sched.hh"
#include "private/elf_platform.h"
#include "sdkconfig.h"
#ifndef CONFIG_ELF_LOADER_LOAD_PSRAM
#define CONFIG_ELF_LOADER_LOAD_PSRAM 0
#endif
#ifndef CONFIG_ELF_LOADER_CACHE_OFFSET
#define CONFIG_ELF_LOADER_CACHE_OFFSET 0
#endif
#ifndef CONFIG_ELF_LOADER_SET_MMU
#define CONFIG_ELF_LOADER_SET_MMU 0
#endif
#ifndef CONFIG_ELF_DYNAMIC_LOAD_SHARED_OBJECT
#define CONFIG_ELF_DYNAMIC_LOAD_SHARED_OBJECT 0
#endif
namespace frame::poca {
namespace {
const char* on_off(int flag) { return flag != 0 ? "y" : "n"; }
void print_loader_config() {
std::printf("elf_loader: vendored espressif 1.3.3 @6526c5b1 (esp-iot-solution)\n");
std::printf(" ELF_LOADER=y LOAD_PSRAM=%s CACHE_OFFSET=%s SET_MMU=%s DLSO=%s\n",
on_off(CONFIG_ELF_LOADER_LOAD_PSRAM), on_off(CONFIG_ELF_LOADER_CACHE_OFFSET),
on_off(CONFIG_ELF_LOADER_SET_MMU), on_off(CONFIG_ELF_DYNAMIC_LOAD_SHARED_OBJECT));
std::printf(" esp_elf_t state size: %u bytes\n", static_cast<unsigned>(sizeof(esp_elf_t)));
std::printf(" loader entries: esp_elf_init=%p esp_elf_relocate=%p\n",
reinterpret_cast<void*>(&esp_elf_init), reinterpret_cast<void*>(&esp_elf_relocate));
}
void print_heap_caps(const char* label, uint32_t caps) {
multi_heap_info_t info{};
heap_caps_get_info(&info, caps);
const unsigned size = static_cast<unsigned>(info.total_free_bytes + info.total_allocated_bytes);
std::printf("heap %-9s size=%10u free=%10u largest=%10u min_ever=%10u\n", label, size,
static_cast<unsigned>(info.total_free_bytes),
static_cast<unsigned>(info.largest_free_block),
static_cast<unsigned>(info.minimum_free_bytes));
}
int poca_command(int argc, char** argv) {
if (argc == 2 && std::strcmp(argv[1], "status") == 0) {
print_loader_config();
std::printf(" registered host imports: poca_host_sentinel poca_host_add\n");
std::printf(" entry queries so far: %u (execution canary)\n",
static_cast<unsigned>(poca_entry_queries()));
std::printf(" iram cache syncs so far: %u (p5 counter)\n",
static_cast<unsigned>(esp_elf_iram_cache_sync_count()));
print_heap_caps("internal", MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
print_heap_caps("iram-exec", MALLOC_CAP_EXEC | MALLOC_CAP_INTERNAL);
print_heap_caps("psram", MALLOC_CAP_SPIRAM);
return 0;
}
if (argc == 2 && std::strcmp(argv[1], "abi") == 0) {
return run_abi_smoke();
}
if ((argc == 2 || argc == 3) && std::strcmp(argv[1], "verify") == 0) {
return cmd_poca_verify(argc == 3 ? argv[2] : "baseline");
}
if ((argc == 2 || argc == 3) && std::strcmp(argv[1], "load") == 0) {
return cmd_poca_load(argc == 3 ? argv[2] : "baseline");
}
if (argc == 2 && std::strcmp(argv[1], "activate") == 0) {
return cmd_poca_activate();
}
if (argc == 2 && std::strcmp(argv[1], "unload") == 0) {
return cmd_poca_unload();
}
if ((argc == 2 || argc == 3) && std::strcmp(argv[1], "iram") == 0) {
unsigned iterations = 1;
if (argc == 3) {
const int parsed = std::atoi(argv[2]);
if (parsed < 1 || parsed > 100000) {
std::printf("[poca-iram] FAIL iteration count out of range (1..100000)\n");
return 1;
}
iterations = static_cast<unsigned>(parsed);
}
return cmd_poca_iram(iterations);
}
if (argc == 2 && std::strcmp(argv[1], "coexist") == 0) {
return cmd_poca_coexist();
}
if ((argc == 3 || argc == 4) && std::strcmp(argv[1], "soak") == 0) {
const int parsed = std::atoi(argv[2]);
if (parsed < 1 || parsed > 10000) {
std::printf("[poca-soak] FAIL cycle count out of range (1..10000)\n");
return 1;
}
return cmd_poca_soak(static_cast<unsigned>(parsed), argc == 4 ? argv[3] : "default");
}
if (argc == 3 && std::strcmp(argv[1], "sched") == 0) {
return cmd_poca_sched(argv[2]);
}
if (argc == 3 && std::strcmp(argv[1], "capacity") == 0) {
const int parsed = std::atoi(argv[2]);
if (parsed < 1 || parsed > 8) {
std::printf("[poca-cap] FAIL count out of range (1..8)\n");
return 1;
}
return cmd_poca_capacity(static_cast<unsigned>(parsed));
}
if (argc == 3 && std::strcmp(argv[1], "fcbegin") == 0) {
char* end = nullptr;
const long parsed = std::strtol(argv[2], &end, 10);
if (end == argv[2] || *end != '\0' || parsed < 1 || parsed > 512 * 1024) {
std::printf("[fc] FAIL size out of range (1..%d)\n", 512 * 1024);
return 1;
}
return cmd_poca_fcbegin(static_cast<size_t>(parsed));
}
if (argc == 3 && std::strcmp(argv[1], "fcwr") == 0) {
return cmd_poca_fcwr(argv[2]);
}
if (argc == 5 && std::strcmp(argv[1], "fcgo") == 0) {
const int parsed = std::atoi(argv[4]);
if (parsed == 0 && std::strcmp(argv[4], "0") != 0) {
std::printf("[FC] FAIL expected code not an integer: %s\n", argv[4]);
return 1;
}
return cmd_poca_fcgo(argv[2], argv[3], parsed);
}
std::printf("usage: poca status | poca abi | poca verify [name] | poca load [name] | "
"poca activate | poca unload | poca iram [n] | poca coexist | poca soak <n> "
"[mix] | poca sched <test> | poca capacity <n> | poca fcbegin <n> | "
"poca fcwr <hex> | poca fcgo <name> <stage> <code>\n");
return 1;
}
} // namespace
esp_err_t start_console() {
const esp_console_cmd_t poca_cmd{
.command = "poca",
.help = "poca status | abi | verify [name] | load [name] | activate | unload | iram [n] | "
"coexist | soak <n> [mix] | sched <test> | capacity <n> | fcbegin <n> | "
"fcwr <hex> | fcgo <name> <stage> <code>",
.hint = nullptr,
.func = &poca_command,
.argtable = nullptr,
.func_w_context = nullptr,
.context = nullptr,
};
esp_err_t result = esp_console_cmd_register(&poca_cmd);
if (result != ESP_OK) {
return result;
}
esp_console_repl_config_t repl_config = ESP_CONSOLE_REPL_CONFIG_DEFAULT();
repl_config.prompt = "poca> ";
/* 600 (T14): the fail-closed corpus streams fixtures as hex chunks on
* single console lines ("poca fcwr " + 2*N hex chars); 128-byte chunks
* need 266 characters, and the extra headroom keeps the chunk size a
* runner-side choice. */
repl_config.max_cmdline_length = 600;
repl_config.max_cmdline_args = 8;
repl_config.task_stack_size = kPocaReplStackBytes;
repl_config.task_priority = 5;
repl_config.task_core_id = 1;
esp_console_dev_usb_serial_jtag_config_t device_config =
ESP_CONSOLE_DEV_USB_SERIAL_JTAG_CONFIG_DEFAULT();
esp_console_repl_t* repl = nullptr;
result = esp_console_new_repl_usb_serial_jtag(&device_config, &repl_config, &repl);
return result == ESP_OK ? esp_console_start_repl(repl) : result;
}
} // namespace frame::poca
+15
View File
@@ -0,0 +1,15 @@
#pragma once
#include "esp_err.h"
namespace frame::poca {
// Registers the `poca` console command group and starts the USB-Serial-JTAG
// REPL. Returns ESP_OK once the console task is running.
esp_err_t start_console();
// Stack size of the console REPL task (pinned core 1); the T9 soak reports
// it as the stack budget of the task the soak loop runs on.
inline constexpr uint32_t kPocaReplStackBytes = 6144;
} // namespace frame::poca
File diff suppressed because it is too large Load Diff
+77
View File
@@ -0,0 +1,77 @@
#ifndef POC_A_MAIN_POCA_PLUGIN_HH
#define POC_A_MAIN_POCA_PLUGIN_HH
#include <cstddef>
#include <cstdint>
namespace frame::poca {
/* Console subcommands implemented in poca_plugin.cc (task T4, extended in
* T5 with the named-package relocation/import allowlist matrix, in T7 with
* the IRAM probe, in T8 with generation coexistence, in T9 with the
* lifecycle soak):
* poca verify [name] parse-only view of an embedded signed package
* poca load [name] stage + verify + admission + relocate + query
* + prepare; negatives assert fail-before-execute
* poca activate call the loaded plugin's activate() (magic check)
* poca unload esp_elf_deinit + staging release
* poca iram [n] T7: n x (load iram_probe -> IRAM fn proofs ->
* unload); IRAM watermark every 20 iterations
* poca coexist T8: v1 ACTIVE + 500ms self-call loop, v2 staged as
* CANDIDATE in an independent arena, single-candidate
* guard, both generations callable, swap+unload old,
* per-phase heap/stack snapshots + budget summary
* poca soak <n> [mix] T9: n lifecycle cycles (load->verify->relocate->
* prepare->activate+value assert->quiesce(no-op;
* NULL entry = trivial success)->unload); schedule:
* mix=default cycles%3==0 iram_probe else baseline,
* mix=baseline / mix=iram force one plugin; every
* 100th cycle a v1/v2 coexistence swap; heap+stack
* sample ring every 10 cycles printed as a
* machine-parsable SOAKSMP table; heap integrity
* probe every 50 cycles; SOAKSUM summary line (the
* PASS/FAIL verdict authority is the host judge)
* poca capacity <n> T10: capacity ladder step - sequentially load n
* distinct-name plugins cap01..cap0n (each its own
* esp_elf_t instance held live), check-fn round over
* all n resident generations (n distinct magics +
* pairwise-distinct PSRAM text bases), peak heap/stack
* snapshot + CAPBUD cost line, reverse-order unload;
* markers [PASS-cap-N-load|respond|unload] and
* [PASS-capacity-N] (the 8->7->6->5 descent with the
* retry-once fail-closed policy lives in the host
* runner plugins/capacity_ladder.py)
* poca fcbegin <n> T14: size and allocate the fail-closed corpus
* poca fcwr <hex> upload staging (PSRAM, immutable after the last
* write); fcgo then runs the SAME parse+verify+
* poca fcgo <name> <stage> <code>
* admission+relocate pipeline on the streamed bytes
* and asserts the rejection stage+error code against
* the host expectation with the entry-query canary
* bracketing the run (execution sentinel).
* Package names: baseline baseline_v2 baseline_300k globdat plt import_neg
* iram_probe iram_mismatch neg_maxmem neg_r32 neg_s0op neg_phspan neg_phbe
* neg_ph64 neg_phmach cap01..cap08 (default baseline).
*/
int cmd_poca_verify(const char* name);
int cmd_poca_load(const char* name);
int cmd_poca_activate();
int cmd_poca_unload();
int cmd_poca_iram(unsigned iterations);
int cmd_poca_coexist();
int cmd_poca_soak(unsigned cycles, const char* mix);
int cmd_poca_capacity(unsigned count);
int cmd_poca_fcbegin(size_t size);
int cmd_poca_fcwr(const char* hex);
int cmd_poca_fcgo(const char* name, const char* stage, int expected);
uint32_t poca_entry_queries();
// T13 loader-strand hookup: activate() pointer of the ACTIVE plugin slot
// (nullptr when nothing is loaded) and the firmware-side expected activate
// value, so a strand handler can call plugin entry code and check it.
const void* poca_active_activate_fn();
int32_t poca_active_expected_activate();
} // namespace frame::poca
#endif /* POC_A_MAIN_POCA_PLUGIN_HH */
File diff suppressed because it is too large Load Diff
+300
View File
@@ -0,0 +1,300 @@
#ifndef POC_A_MAIN_POCA_SCHED_HH
#define POC_A_MAIN_POCA_SCHED_HH
#include <atomic>
#include <cstddef>
#include <cstdint>
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/task.h"
#include "frame_poc/frame_abi.h"
// FreeRTOS realization of the host strand/completion scheduling protocol.
//
// Derived from poc/host/include/frame_poc/frame_strand.hh and
// poc/host/include/frame_poc/frame_completion.hh @2a37556,
// protocol-identical; drift checked by the on-target vector suite
// (`poca sched`, poca_sched.cc) which re-runs the host assertions.
//
// Port deltas (all mechanical, none protocol-visible; the T11/T12 notepad
// thread-mapping note is the authority this realizes):
// * std::mutex (strand, io_core) -> portENTER_CRITICAL(&portMUX_TYPE)
// cross-core spinlock. The scheduling protocol tasks (producers,
// workers) are pinned across both cores on this SMP target, so the
// host mutex's cross-thread exclusion needs a spinlock, not a
// local-interrupt critical section.
// * io_core std::thread worker -> one FreeRTOS task pinned to one core,
// priority 4 per project.md 4.1.1 (host header pins this mapping).
// * io_core ring + condition variables -> one FreeRTOS bounded queue of
// strand pointers (capacity = max strands, so a legal SCHEDULED
// transition never blocks) plus an in-ring shadow bitmap under the
// io_core mux: the host duplicate detector scans its ring vector;
// queue internals are not public API, so the shadow provides the same
// max-once fault detection with identical set/clear points.
// * std::chrono::steady_clock handler budget -> esp_timer_get_time()
// microseconds.
// * std::thread::id -> TaskHandle_t (worker identity assertions).
// * std::vector node pool -> caller-provided static arena (strand ctor
// takes the pool pointer; zero dynamic allocation anywhere on the
// scheduling path, 4.1.2).
// Everything else - the strand FIFO, the IDLE/SCHEDULED CAS-under-lock
// sequence, the ready_pending_ invariant, the anti-lost-wakeup protocol,
// exactly-once invoke/destroy, the completion PENDING/COMPLETED/CANCELLED
// CAS, the closing_-driven terminal transitions - is line-for-line the
// host protocol.
namespace frame::poc {
enum class strand_state : uint8_t { idle, scheduled, running, closing, stopped };
enum class op_kind : uint8_t { post, cleanup, completion };
// Intrusive FIFO node (host shape, verbatim). Pool nodes (kind post) come
// from the caller-provided preallocated arena; 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 task pinned to one fixed core (host io_core, 4.1.1). The
// ready ring is a bounded queue with capacity equal to the maximum number
// of strands, so a legal SCHEDULED transition never blocks the poster.
class io_core {
public:
static constexpr std::size_t kMaxStrandsPerCore = 4;
static constexpr UBaseType_t kWorkerPrio = 4;
static constexpr uint32_t kWorkerStackBytes = 8192;
explicit io_core(std::size_t max_strands, BaseType_t core_id);
~io_core();
io_core(const io_core&) = delete;
io_core& operator=(const io_core&) = delete;
// Creates and pins the worker task. push_ready may be called before
// start(); queued strands are drained once started (host semantics).
void start();
// Idempotent. Enqueues the stop sentinel, waits for the worker to exit,
// deletes the task handle and the queue. Drains nothing.
void stop();
bool duplicate_detected() const noexcept {
return duplicate_fault_.load(std::memory_order_relaxed);
}
bool queue_fault() const noexcept { return queue_fault_.load(std::memory_order_relaxed); }
TaskHandle_t worker_handle() const noexcept { return worker_; }
BaseType_t core() const noexcept { return core_id_; }
private:
friend class strand;
void push_ready(strand& target);
static void run_trampoline(void* arg);
void run_loop();
std::size_t acquire_slot();
void release_slot(std::size_t slot);
const std::size_t capacity_;
const BaseType_t core_id_;
QueueHandle_t queue_ = nullptr;
portMUX_TYPE mux_{};
bool slot_used_[kMaxStrandsPerCore] = {};
bool in_ring_[kMaxStrandsPerCore] = {}; // ring-membership shadow (see header deltas)
std::atomic<bool> duplicate_fault_{false};
std::atomic<bool> queue_fault_{false};
std::atomic<bool> stopping_{false};
std::atomic<bool> started_{false};
std::atomic<bool> worker_done_{false};
TaskHandle_t worker_ = nullptr;
};
// Logical serial executor (host strand, 4.1.2): one FIFO, preallocated
// pool nodes (caller arena), bounded outstanding-operations credit,
// exactly-once invoke/destroy.
class strand {
public:
strand(io_core& core, strand_op_node* pool, std::size_t op_capacity,
uint64_t handler_budget_us = 1000);
~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 the io_core 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_;
std::size_t slot_ = 0; // io_core ring-membership shadow slot
const std::size_t capacity_;
const uint64_t handler_budget_us_;
portMUX_TYPE mutex_{};
strand_op_node* fifo_head_ = nullptr;
strand_op_node* fifo_tail_ = nullptr;
strand_op_node* free_head_ = nullptr;
strand_op_node* pool_ = nullptr; // caller-owned arena, not freed here
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};
};
// Host frame_completion.hh @2a37556, verbatim: only std::atomic members,
// fully portable to the target toolchain.
//
// 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 };
class completion_node {
public:
completion_node() = default;
completion_node(const completion_node&) = delete;
completion_node& operator=(const completion_node&) = delete;
// Owner-task 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-task 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
namespace frame::poca {
// `poca sched <test>` (poca_sched.cc): runs one on-target scheduling
// semantics vector, or `all`. Each vector re-runs a host-suite assertion
// subset on the FreeRTOS realization and prints a [PASS-<vector>] marker
// driven by programmatic counter/continuity checks.
int cmd_poca_sched(const char* test);
} // namespace frame::poca
#endif