Files
frame/poc/apps/poc_a/plugins/check_plugin_elf.cmake
T
Lainandlain e71842aa8a 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]>
2026-09-07 20:02:18 +08:00

252 lines
11 KiB
CMake

# Static gates on a built plugin ELF (task T4; feeds the T5 allowlist work).
#
# Invoked as: cmake -D PLUGIN_NAME=<n> -D ELF=<file> -D READELF=<tool>
# -D NM=<tool> -D EXPECT_ENTRY=<sym>
# -D "EXPECT_UNDEFINED=<sym;...>" -P check_plugin_elf.cmake
#
# Gate 1 (relocation allowlist): every dynamic relocation emitted into the
# final image must be one of the types the vendored elf_loader implements
# on xtensa (esp_elf_xtensa.c): R_XTENSA_NONE/RELATIVE/RTLD/GLOB_DAT/
# JMP_SLOT. Anything else is a pipeline bug (fix the link flags), not a
# loader configuration problem. This also rejects every R_XTENSA_TLS_*
# type (dynamic TLS is a forbidden C++ feature, appendix C 11.2).
# Gate 4 (C++ feature policy, task T6, appendix C 11.2/11.3): the section
# table must not contain any C++ runtime feature section - static
# constructors/destructors (.init_array/.fini_array/.ctors/.dtors, this
# toolchain spells them .ctors/.dtors), dynamic TLS (.tdata/.tbss) or
# unwinding metadata (.eh_frame/.eh_frame_hdr/.gcc_except_table). The
# entry-point loader never runs these sections; admitting them would be a
# silent-misbehavior fail-open (constructor skipped) or worse. Loader
# patch p4 mirrors this list on target (defense in depth).
# Gate 2 (closed-world imports): every undefined symbol must appear in
# EXPECT_UNDEFINED, the plugin's declared import list (T5). Device-side
# enforcement is separate: only symbols registered at runtime through
# esp_elf_register_symbol() actually resolve, anything else fails the
# load with -ENOSYS before execute. This is also the build-side
# rejection layer for RTTI probes (undeclared __cxxabiv1/__dynamic_cast
# imports, appendix C 11.2).
# Gate 3 (shape): ELF32, little-endian, Xtensa machine, ET_DYN, non-zero
# entry, and the exported query entry present as a defined GLOBAL FUNC.
# Gate 5 (task T7, only with -D EXPECT_IRAM_SECTION=1): the image carries
# exactly one .plugin_iram PROGBITS ALLOC+EXEC section with no split
# .plugin_iram.* subsections (a leaked literal pool would be unreachable
# from the IRAM window), and no dynamic relocation patches a word inside
# the section span (relocation targets there would write through an
# unmapped window on any loader that does not know the section). Loader
# patch p5 maps the section; this gate keeps the producer honest.
set(allowed_types R_XTENSA_NONE R_XTENSA_RELATIVE R_XTENSA_RTLD R_XTENSA_GLOB_DAT R_XTENSA_JMP_SLOT)
execute_process(
COMMAND "${READELF}" -rW "${ELF}"
OUTPUT_VARIABLE reloc_out
RESULT_VARIABLE reloc_res
ERROR_VARIABLE reloc_err)
if(NOT reloc_res EQUAL 0)
message(FATAL_ERROR "[poca-plugin] ${PLUGIN_NAME}: readelf -r failed: ${reloc_err}")
endif()
string(REPLACE "\n" ";" reloc_lines "${reloc_out}")
set(type_names "")
foreach(line IN LISTS reloc_lines)
string(REGEX MATCH "R_XTENSA_[A-Z0-9_]+" reloc_type "${line}")
if(reloc_type)
list(APPEND type_names "${reloc_type}")
endif()
endforeach()
set(remaining "${type_names}")
set(offenders "")
set(summary "")
foreach(type IN LISTS allowed_types)
set(matches "${remaining}")
list(FILTER matches INCLUDE REGEX "^${type}$")
list(LENGTH matches count)
list(APPEND summary "${type}=${count}")
list(FILTER remaining EXCLUDE REGEX "^${type}$")
endforeach()
if(remaining)
list(REMOVE_DUPLICATES remaining)
set(offenders "${remaining}")
endif()
if(offenders)
message(FATAL_ERROR
"[poca-plugin] ${PLUGIN_NAME}: relocation allowlist violated (${offenders}); "
"fix the plugin link flags - the vendored loader rejects these on target")
endif()
# Gate 4 (task T6): C++ runtime feature sections are forbidden (appendix C
# 11.2/11.3). Matched against every section header name (readelf -SW), with
# an optional ".rela."/"."-suffix spelling so numbered subsections
# (.init_array.00001) and per-section relocation wrappers stay covered.
set(forbidden_stems
init_array fini_array preinit_array ctors dtors
tdata tbss eh_frame eh_frame_hdr gcc_except_table)
set(forbidden_sections "")
execute_process(
COMMAND "${READELF}" -SW "${ELF}"
OUTPUT_VARIABLE sec_out
RESULT_VARIABLE sec_res
ERROR_VARIABLE sec_err)
if(NOT sec_res EQUAL 0)
message(FATAL_ERROR "[poca-plugin] ${PLUGIN_NAME}: readelf -S failed: ${sec_err}")
endif()
string(REPLACE "\n" ";" sec_lines "${sec_out}")
foreach(line IN LISTS sec_lines)
set(sec_name "")
string(REGEX MATCH "\\[[ ]*[0-9]+\\][ ]+\\.[^ \t\n]+" sec_col "${line}")
if(sec_col)
string(REGEX REPLACE "\\[[ ]*[0-9]+\\][ ]+" "" sec_name "${sec_col}")
endif()
if(NOT sec_name STREQUAL "")
string(REGEX REPLACE "^\\.(rela?)?\\." "" sec_stem "${sec_name}")
string(REGEX REPLACE "^\\." "" sec_stem "${sec_stem}")
string(REGEX REPLACE "\\..*$" "" sec_stem "${sec_stem}")
list(FIND forbidden_stems "${sec_stem}" forbidden_idx)
if(NOT forbidden_idx EQUAL -1)
list(APPEND forbidden_sections "${sec_name}")
endif()
endif()
endforeach()
if(forbidden_sections)
list(REMOVE_DUPLICATES forbidden_sections)
message(FATAL_ERROR
"[poca-plugin] ${PLUGIN_NAME}: forbidden C++ feature section(s) "
"[${forbidden_sections}] present (appendix C 11.2/11.3: static "
"ctor/dtor, dynamic TLS and unwind metadata are default-forbidden; "
"the entry-point loader never runs them - loader patch p4 rejects "
"the same list on target)")
endif()
execute_process(
COMMAND "${NM}" -u "${ELF}"
OUTPUT_VARIABLE undef_out
RESULT_VARIABLE undef_res
ERROR_VARIABLE undef_err)
if(NOT undef_res EQUAL 0)
message(FATAL_ERROR "[poca-plugin] ${PLUGIN_NAME}: nm -u failed: ${undef_err}")
endif()
string(STRIP "${undef_out}" undef_out)
set(unexpected "${undef_out}")
if(unexpected)
string(REPLACE "\n" ";" undef_symbols "${undef_out}")
set(unexpected "")
foreach(sym IN LISTS undef_symbols)
string(STRIP "${sym}" sym)
string(REGEX REPLACE "^U[ ]+" "" sym "${sym}")
if(NOT sym STREQUAL "")
list(FIND EXPECT_UNDEFINED "${sym}" idx)
if(idx EQUAL -1)
list(APPEND unexpected "${sym}")
endif()
endif()
endforeach()
endif()
if(unexpected)
message(FATAL_ERROR "[poca-plugin] ${PLUGIN_NAME}: import gate failed, undeclared undefined symbols: ${unexpected} (declared: ${EXPECT_UNDEFINED})")
endif()
list(LENGTH EXPECT_UNDEFINED declared_count)
message(STATUS "[poca-plugin] ${PLUGIN_NAME}: declared imports=${declared_count} undefined-undeclared=0")
execute_process(
COMMAND "${READELF}" -hW "${ELF}"
OUTPUT_VARIABLE hdr_out
RESULT_VARIABLE hdr_res
ERROR_VARIABLE hdr_err)
if(NOT hdr_res EQUAL 0)
message(FATAL_ERROR "[poca-plugin] ${PLUGIN_NAME}: readelf -h failed: ${hdr_err}")
endif()
if(NOT hdr_out MATCHES "Class:.+ELF32")
message(FATAL_ERROR "[poca-plugin] ${PLUGIN_NAME}: expected ELF32 image")
endif()
if(NOT hdr_out MATCHES "Data:.+2.s complement, little endian")
message(FATAL_ERROR "[poca-plugin] ${PLUGIN_NAME}: expected little-endian image")
endif()
if(NOT hdr_out MATCHES "Machine:.+Xtensa")
message(FATAL_ERROR "[poca-plugin] ${PLUGIN_NAME}: expected Xtensa machine")
endif()
if(NOT hdr_out MATCHES "Type:.+DYN")
message(FATAL_ERROR "[poca-plugin] ${PLUGIN_NAME}: expected ET_DYN shared image")
endif()
if(hdr_out MATCHES "Entry point address:[ \\t]+0x0*[1-9a-fA-F]")
# non-zero entry address
else()
message(FATAL_ERROR "[poca-plugin] ${PLUGIN_NAME}: expected non-zero entry address")
endif()
execute_process(
COMMAND "${READELF}" -sW "${ELF}"
OUTPUT_VARIABLE sym_out
RESULT_VARIABLE sym_res
ERROR_VARIABLE sym_err)
if(NOT sym_res EQUAL 0)
message(FATAL_ERROR "[poca-plugin] ${PLUGIN_NAME}: readelf -s failed: ${sym_err}")
endif()
string(REGEX MATCH "\n[ ]*[0-9]+:[^\n]*FUNC[ \t]+GLOBAL[ \t]+DEFAULT[^\n]*[ \t]${EXPECT_ENTRY}([ \t\r\n]|$)" entry_line "${sym_out}")
if(NOT entry_line)
message(FATAL_ERROR "[poca-plugin] ${PLUGIN_NAME}: exported entry ${EXPECT_ENTRY} missing (GLOBAL FUNC DEFAULT)")
endif()
string(REPLACE ";" " " summary_line "${summary}")
message(STATUS "[poca-plugin] ${PLUGIN_NAME}: gates OK relocs(${summary_line}) undefined=0 entry=${EXPECT_ENTRY}")
# Gate 5 (task T7): optional .plugin_iram contract, enabled per plugin with
# -D EXPECT_IRAM_SECTION=1. Reuses the readelf -SW output from gate 4.
if(EXPECT_IRAM_SECTION)
set(iram_size "")
set(iram_addr "")
foreach(line IN LISTS sec_lines)
if(line MATCHES "\\.plugin_iram(\\.[^ ]+)?[ \\t]")
# cols = "[ Nr] name type addr off size" (readelf -SW columns,
# token numbers 1..5 after the bracket index)
string(REGEX MATCH "\\[[ ]*[0-9]+\\][ ]+[^ ]+[ ]+[^ ]+[ ]+[^ ]+[ ]+[^ ]+[ ]+[^ ]+" cols "${line}")
if(cols)
string(REGEX REPLACE "^\\[[ ]*[0-9]+\\][ ]+([^ ]+)[ ]+([^ ]+)[ ]+([^ ]+)[ ]+([^ ]+)[ ]+([^ ]+).*$"
"\\1;\\2;\\3;\\4;\\5" fields "${cols}")
list(GET fields 0 secname)
if(NOT secname STREQUAL ".plugin_iram")
message(FATAL_ERROR
"[poca-plugin] ${PLUGIN_NAME}: split IRAM subsection '${secname}' "
"present (literal pools must stay out of the IRAM window)")
endif()
if(NOT iram_size STREQUAL "")
message(FATAL_ERROR "[poca-plugin] ${PLUGIN_NAME}: duplicate .plugin_iram section")
endif()
list(GET fields 2 iram_addr)
list(GET fields 4 iram_size)
string(FIND "${line}" "AX" ax_idx)
if(ax_idx EQUAL -1)
message(FATAL_ERROR "[poca-plugin] ${PLUGIN_NAME}: .plugin_iram is not ALLOC+EXEC")
endif()
endif()
endif()
endforeach()
if(iram_size STREQUAL "")
message(FATAL_ERROR "[poca-plugin] ${PLUGIN_NAME}: required .plugin_iram section missing")
endif()
math(EXPR iram_addr_dec "0x${iram_addr}")
math(EXPR iram_size_dec "0x${iram_size}")
math(EXPR iram_span_end "${iram_addr_dec} + ${iram_size_dec}")
set(offending_offsets "")
foreach(line IN LISTS reloc_lines)
string(REGEX MATCH "^([0-9a-fA-F]{6,})" off_col "${line}")
if(off_col)
math(EXPR off_dec "0x${off_col}")
if(off_dec GREATER_EQUAL "${iram_addr_dec}" AND off_dec LESS "${iram_span_end}")
list(APPEND offending_offsets "0x${off_col}")
endif()
endif()
endforeach()
if(offending_offsets)
message(FATAL_ERROR
"[poca-plugin] ${PLUGIN_NAME}: dynamic relocations patch inside the "
".plugin_iram span [0x${iram_addr}, +0x${iram_size}): "
"${offending_offsets}")
endif()
message(STATUS "[poca-plugin] ${PLUGIN_NAME}: IRAM gate OK "
".plugin_iram addr=0x${iram_addr} size=0x${iram_size} span-relocs=0")
endif()