Files
frame/poc/apps/poc_a/components/elf_loader/elf_loader.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

259 lines
11 KiB
CMake

# The script is to generate ELF or shared library for application
#
# Cache this file's directory so macros invoked from other CMakeLists
# can still reference companion scripts in this folder.
set(ELF_LOADER_CMAKE_DIR "${CMAKE_CURRENT_LIST_DIR}")
# Trick to temporarily redefine project(). When functions are overridden in CMake, the originals can still be accessed
# using an underscore prefixed function of the same name. The following lines make sure that project calls
# the original project(). See https://cmake.org/pipermail/cmake/2015-October/061751.html.
function(project_elf)
endfunction()
function(_project_elf)
endfunction()
macro(project_elf project_name)
# Enable these options to remove unused symbols and reduce linked objects
set(cflags -nostartfiles
-nostdlib
-fPIC
-shared
-e app_main
-fdata-sections
-ffunction-sections
-Wl,--gc-sections
-fvisibility=hidden)
# Enable this options to remove unnecessary sections in
list(APPEND cflags -Wl,--strip-all
-Wl,--strip-debug
-Wl,--strip-discarded)
list(APPEND cflags -Dmain=app_main)
idf_build_set_property(COMPILE_OPTIONS "${cflags}" APPEND)
set(elf_app "${CMAKE_PROJECT_NAME}.app.elf")
# Remove more unused sections
string(REPLACE "-elf-gcc" "-elf-strip" CMAKE_STRIP ${CMAKE_C_COMPILER})
set(strip_flags --strip-unneeded
--remove-section=.comment
--remove-section=.got.loc
--remove-section=.dynamic)
if(CONFIG_IDF_TARGET_ARCH_XTENSA)
list(APPEND strip_flags --remove-section=.xt.lit
--remove-section=.xt.prop
--remove-section=.xtensa.info)
elseif(CONFIG_IDF_TARGET_ARCH_RISCV)
list(APPEND strip_flags --remove-section=.riscv.attributes)
endif()
# Link input list of libraries to ELF
list(PREPEND ELF_COMPONENTS "main")
set(elf_libs "")
set(elf_dependencies "")
if(ELF_COMPONENTS)
foreach(c ${ELF_COMPONENTS})
list(APPEND elf_libs "esp-idf/${c}/lib${c}.a")
if(${CMAKE_GENERATOR} STREQUAL "Unix Makefiles")
add_custom_command(OUTPUT elf_${c}_app
COMMAND +${CMAKE_MAKE_PROGRAM} "__idf_${c}/fast"
COMMENT "Build Component: ${c}"
)
list(APPEND elf_dependencies "elf_${c}_app")
else()
list(APPEND elf_dependencies "idf::${c}")
endif()
endforeach()
endif()
if (ELF_LIBS)
list(APPEND elf_libs "${ELF_LIBS}")
endif()
spaces2list(elf_libs)
# Define how to build the ELF file
add_custom_command(
OUTPUT ${elf_app}
COMMAND ${CMAKE_C_COMPILER} ${cflags} ${elf_libs} -o ${elf_app}
COMMAND ${CMAKE_STRIP} ${strip_flags} ${elf_app}
DEPENDS ${elf_dependencies}
COMMENT "Build ELF: ${elf_app}"
)
# Create a custom target to generate the ELF file
add_custom_target(elf ALL DEPENDS ${elf_app})
endmacro()
# Trick to temporarily redefine project(). When functions are overridden in CMake, the originals can still be accessed
# using an underscore prefixed function of the same name. The following lines make sure that project calls
# the original project(). See https://cmake.org/pipermail/cmake/2015-October/061751.html.
function(project_so)
endfunction()
function(_project_so)
endfunction()
macro(project_so project_name)
if(CONFIG_ELF_DYNAMIC_LOAD_SHARED_OBJECT)
# Compile flags for building component sources into position-independent .o files
set(so_compile_flags -c
-fPIC
-DCONFIG_ELF_DYNAMIC_LOAD_SHARED_OBJECT)
# Link flags for producing a shared object from the collected .o files.
# This setup favors size reduction (gc-sections, hidden visibility) and
# passes strip flags to the linker to remove unneeded content.
set(so_link_flags -shared
-fPIC
-static-libgcc
-nostdlib
-nostartfiles
#-Wl,-E
#-Wl,--export-dynamic
-fdata-sections
-ffunction-sections
-Wl,--gc-sections
-fvisibility=hidden)
list(APPEND so_link_flags -Wl,--strip-all
-Wl,--strip-debug
-Wl,--strip-discarded)
# Output file name for shared object
set(so_output "${CMAKE_PROJECT_NAME}.so")
# Strip flags for final .so file: remove unneeded symbols and selected sections
# to reduce size. The .dynamic section is also removed to match current loader flow.
string(REPLACE "-elf-gcc" "-elf-strip" CMAKE_STRIP_SO ${CMAKE_C_COMPILER})
set(so_strip_flags --strip-unneeded
--remove-section=.comment
--remove-section=.got.loc
--remove-section=.dynamic)
if(CONFIG_IDF_TARGET_ARCH_XTENSA)
list(APPEND so_strip_flags --remove-section=.xt.lit
--remove-section=.xt.prop
--remove-section=.xtensa.info)
elseif(CONFIG_IDF_TARGET_ARCH_RISCV)
list(APPEND so_strip_flags --remove-section=.riscv.attributes)
endif()
# Get ESP-IDF compile definitions and include directories
idf_build_get_property(build_dir BUILD_DIR)
idf_build_get_property(idf_path IDF_PATH)
idf_build_get_property(target IDF_TARGET)
# Collect all C source files from components
list(PREPEND ELF_COMPONENTS "main")
set(so_c_sources "")
set(so_dependencies "")
set(so_obj_files "")
set(so_link_libs "")
if(ELF_COMPONENTS)
foreach(c ${ELF_COMPONENTS})
# Get component directory
idf_component_get_property(component_dir ${c} COMPONENT_DIR)
# Find all C source files in component directory
file(GLOB_RECURSE component_sources
CONFIGURE_DEPENDS
"${component_dir}/*.c")
# Filter out test files and build files
# NOTE: Use relative path from component_dir to avoid false matches
# on parent path components (e.g., workspaces under /test/).
foreach(src ${component_sources})
file(RELATIVE_PATH src_rel ${component_dir} ${src})
# Skip files in test directories and build directories
if(NOT src_rel MATCHES "^(.*/)?(test|tests|testing)/" AND
NOT src_rel MATCHES "(^|/)test_[^/]*\\.c$" AND
NOT src MATCHES "${build_dir}")
list(APPEND so_c_sources ${src})
endif()
endforeach()
# Ensure component is built first (to get dependencies resolved)
if(${CMAKE_GENERATOR} STREQUAL "Unix Makefiles")
add_custom_command(OUTPUT so_${c}_app
COMMAND +${CMAKE_MAKE_PROGRAM} "__idf_${c}/fast"
COMMENT "Build Component: ${c}"
)
list(APPEND so_dependencies "so_${c}_app")
else()
list(APPEND so_dependencies "idf::${c}")
endif()
endforeach()
endif()
# Handle ELF_LIBS if specified (for external sources and libraries)
if(ELF_LIBS)
foreach(lib ${ELF_LIBS})
if(lib MATCHES "\\.c$")
# Direct C file
get_filename_component(lib_abs ${lib} ABSOLUTE BASE_DIR ${CMAKE_SOURCE_DIR})
list(APPEND so_c_sources ${lib_abs})
elseif(lib MATCHES "\\.(a|o|so)$")
# Linkable library/object
list(APPEND so_link_libs ${lib})
else()
message(WARNING "ELF_LIBS entry '${lib}' has unsupported extension and will be ignored")
endif()
endforeach()
spaces2list(so_link_libs)
endif()
# Get ESP-IDF compile definitions and includes from config
idf_build_get_property(compile_defs COMPILE_DEFINITIONS)
idf_build_get_property(include_dirs COMPILE_INCLUDE_DIRECTORIES)
# Build include flags as a list
set(include_flags "")
foreach(inc_dir ${include_dirs})
list(APPEND include_flags "-I${inc_dir}")
endforeach()
# Build definition flags as a list
set(def_flags "")
foreach(def ${compile_defs})
list(APPEND def_flags "-D${def}")
endforeach()
# Compile each C file to .o file
set(so_obj_dir "${CMAKE_BINARY_DIR}/so_objs")
foreach(c_file ${so_c_sources})
# Create a unique object file name based on relative path
file(RELATIVE_PATH c_file_rel ${CMAKE_SOURCE_DIR} ${c_file})
string(REPLACE "/" "_" obj_file_name ${c_file_rel})
string(REPLACE ".c" ".o" obj_file_name ${obj_file_name})
set(obj_file "${so_obj_dir}/${obj_file_name}")
list(APPEND so_obj_files ${obj_file})
# Compile C file to .o file with ESP-IDF includes and definitions
# Use list variables directly, not strings
add_custom_command(OUTPUT ${obj_file}
COMMAND ${CMAKE_COMMAND} -E make_directory ${so_obj_dir}
COMMAND ${CMAKE_C_COMPILER} ${so_compile_flags} ${def_flags} ${include_flags} ${c_file} -o ${obj_file}
DEPENDS ${c_file}
COMMENT "Compile ${c_file} to ${obj_file_name}"
)
endforeach()
# Link all .o files to .so file
# Use list variables directly for link flags
add_custom_command(OUTPUT ${so_output}
# Undefined symbols are allowed to support modules resolved at runtime.
COMMAND ${CMAKE_C_COMPILER} ${so_link_flags} -o ${so_output} ${so_obj_files} ${so_link_libs} -Wl,--allow-shlib-undefined
COMMAND ${CMAKE_COMMAND} -DOUT=${so_output} -P ${ELF_LOADER_CMAKE_DIR}/check_shared_object.cmake
COMMAND ${CMAKE_COMMAND} -E echo "Linking ${so_output} completed"
COMMAND ${CMAKE_STRIP_SO} ${so_strip_flags} ${so_output}
DEPENDS ${so_dependencies} ${so_obj_files}
COMMENT "Build Shared Object: ${so_output}"
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
)
add_custom_target(so ALL DEPENDS ${so_output})
endif()
endmacro()