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:
+268
@@ -0,0 +1,268 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import logging
|
||||
import os
|
||||
import argparse
|
||||
import sys
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
def get_global_symbols(lines, type, undefined=False, symbol_types=None):
|
||||
"""
|
||||
Extract global symbols from the given lines of a symbol table.
|
||||
|
||||
:param lines: List of lines from the symbol table, each representing a symbol.
|
||||
:param type: Type of the input file ('e' for ELF files, 'l' for static libraries).
|
||||
:param undefined: If True, only extract undefined (UND) symbols; otherwise, extract all GLOBAL symbols.
|
||||
:param symbol_types: A list of symbol types to filter by (e.g., ['FUNC', 'OBJECT']). If None, no filtering by type.
|
||||
:return: List of symbol names if any match the criteria; otherwise, returns an empty list.
|
||||
"""
|
||||
symbols = []
|
||||
|
||||
if type == 'e':
|
||||
# Pattern for ELF files
|
||||
if not undefined:
|
||||
pattern = re.compile(
|
||||
r'^\s*\d+:\s+(\S+)\s+(\d+)\s+(FUNC|OBJECT)\s+GLOBAL\s+DEFAULT\s+(?:\d+|ABS|UND|COM|DEBUG)\s+(\S+)',
|
||||
re.MULTILINE
|
||||
)
|
||||
else:
|
||||
pattern = re.compile(
|
||||
r'^\s*\d*:\s*\w*\s*\d*\s*NOTYPE\s*GLOBAL\s*DEFAULT\s*UND\s+(\S*)',
|
||||
re.MULTILINE
|
||||
)
|
||||
|
||||
for line in lines:
|
||||
match = pattern.match(line)
|
||||
if match:
|
||||
if not undefined:
|
||||
address, size, symbol_type, symbol_name = match.groups()
|
||||
|
||||
# Filter by symbol type if specified
|
||||
if symbol_types and symbol_type not in symbol_types:
|
||||
continue
|
||||
|
||||
symbols.append(symbol_name)
|
||||
else:
|
||||
symbol_name = match.group(1)
|
||||
symbols.append(symbol_name)
|
||||
|
||||
elif type == 'l':
|
||||
# Patterns for static libraries
|
||||
func_pattern = re.compile(r'^\s*[0-9a-fA-F]+\s+[TD]\s+(\S+)$')
|
||||
var_pattern = re.compile(r'^\s*[0-9a-fA-F]+\s+[BD]\s+(\S+)$')
|
||||
|
||||
for line in lines:
|
||||
if not undefined:
|
||||
func_match = func_pattern.match(line)
|
||||
var_match = var_pattern.match(line)
|
||||
|
||||
if func_match:
|
||||
symbols.append(func_match.group(1))
|
||||
elif var_match:
|
||||
symbols.append(var_match.group(1))
|
||||
|
||||
return symbols
|
||||
|
||||
def save_c_file(symbols, output, symbol_table, exclude_symbols=None):
|
||||
"""
|
||||
Write extern declarations and ESP_ELFSYM structure to a C file, excluding specified symbols.
|
||||
|
||||
:param symbols: List of symbol names.
|
||||
:param output: Path to the output C file.
|
||||
:param exclude_symbols: List of symbol names to exclude; defaults to ['elf_find_sym'].
|
||||
"""
|
||||
if exclude_symbols is None:
|
||||
exclude_symbols = ['elf_find_sym'] # Set default excluded symbols
|
||||
|
||||
# Filter out excluded symbols
|
||||
filtered_symbols = [name for name in symbols if name not in exclude_symbols]
|
||||
|
||||
# Build the content of the C file
|
||||
buf = '/*\n'
|
||||
buf += ' * SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD\n'
|
||||
buf += ' *\n'
|
||||
buf += ' * SPDX-License-Identifier: Apache-2.0\n'
|
||||
buf += ' */\n\n'
|
||||
|
||||
# Add standard library headers
|
||||
libc_headers = ['stddef'] # Add more headers as needed
|
||||
buf += '\n'.join([f'#include <{h}.h>' for h in libc_headers]) + '\n\n'
|
||||
|
||||
# Add custom header
|
||||
buf += '#include "private/elf_symbol.h"\n\n'
|
||||
|
||||
# Generate extern declarations if there are symbols
|
||||
if filtered_symbols:
|
||||
buf += '/* Extern declarations from ELF symbol table */\n\n'
|
||||
buf += '#pragma GCC diagnostic push\n'
|
||||
buf += '#pragma GCC diagnostic ignored "-Wbuiltin-declaration-mismatch"\n'
|
||||
for symbol_name in filtered_symbols:
|
||||
buf += f'extern int {symbol_name};\n'
|
||||
buf += '#pragma GCC diagnostic pop\n\n'
|
||||
|
||||
# Define the symbol table structure with dynamic variable name
|
||||
symbol_table_var = f'g_{symbol_table}_elfsyms'
|
||||
buf += f'/* Available ELF symbols table: {symbol_table_var} */\n'
|
||||
buf += f'\nconst struct esp_elfsym {symbol_table_var}[] = {{\n'
|
||||
|
||||
# Generate ESP_ELFSYM_EXPORT entries
|
||||
if filtered_symbols:
|
||||
for symbol_name in filtered_symbols:
|
||||
buf += f' ESP_ELFSYM_EXPORT({symbol_name}),\n'
|
||||
|
||||
# End the symbol table
|
||||
buf += ' ESP_ELFSYM_END\n'
|
||||
buf += '};\n'
|
||||
|
||||
# Write to the file
|
||||
with open(output, 'w+') as f:
|
||||
f.write(buf)
|
||||
|
||||
def main():
|
||||
"""
|
||||
Main function to parse command-line arguments and process the input file's symbol table.
|
||||
"""
|
||||
parser = argparse.ArgumentParser(description='Extract all public functions from an application project', prog='symbols')
|
||||
|
||||
parser.add_argument(
|
||||
'--output-file', '-of',
|
||||
help='Custom output file path with filename (overrides --output)',
|
||||
default=None
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--input', '-i',
|
||||
help='Input file name with full path',
|
||||
required=True
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--undefined', '-u',
|
||||
action='store_true',
|
||||
help='If set, only extract undefined (UND) symbols; otherwise, extract all GLOBAL symbols.',
|
||||
default=False
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--exclude', '-e',
|
||||
nargs='+',
|
||||
help='Symbols to exclude from the generated C file (e.g., memcpy __ltdf2). Default: elf_find_sym',
|
||||
default=[] # User can extend this list
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--type', '-t',
|
||||
choices=['e', 'l'],
|
||||
required=True,
|
||||
help='Type of the input file: "elf" for ELF file, "lib" for static library (.a)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--debug', '-d',
|
||||
help='Debug level(option is \'debug\')',
|
||||
default='no',
|
||||
type=str)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# Configure logging
|
||||
if args.debug == 'debug':
|
||||
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||
else:
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||
|
||||
# Get the absolute path of the current file
|
||||
cur_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
if args.type == 'e':
|
||||
extracted_part = 'customer'
|
||||
elif args.type == 'l':
|
||||
# Convert relative path to absolute path
|
||||
input_abs_path = os.path.abspath(args.input)
|
||||
|
||||
# Get the base name of the input file (without extension)
|
||||
input_basename = os.path.basename(input_abs_path)
|
||||
|
||||
# Use a regular expression to extract the middle part
|
||||
match = re.search(r'^lib(.+)\.a$', input_basename)
|
||||
if match:
|
||||
extracted_part = match.group(1)
|
||||
else:
|
||||
logging.error('Invalid input file name format. Expected format: lib<name>.a')
|
||||
sys.exit(1)
|
||||
|
||||
# Determine the output file path
|
||||
if args.output_file:
|
||||
# Use the custom file path provided by the user
|
||||
elfsym_file_dir = os.path.abspath(args.output_file)
|
||||
output_dir = os.path.dirname(elfsym_file_dir)
|
||||
output_abs_path = os.path.abspath(args.output_file)
|
||||
output_basename = os.path.basename(output_abs_path)
|
||||
extracted_part = os.path.splitext(output_basename)[0]
|
||||
else:
|
||||
# Use the default behavior: generate the file in the parent directory's 'src' folder
|
||||
parent_dir = os.path.dirname(cur_dir)
|
||||
output_dir = os.path.join(parent_dir, 'src') # Default directory is 'src' under the parent directory
|
||||
output_file_name = f'esp_all_symbol.c'
|
||||
elfsym_file_dir = os.path.join(output_dir, output_file_name)
|
||||
|
||||
# Ensure the output directory exists
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
# Set default excluded symbols and allow user to extend the list
|
||||
exclude_symbols = ['elf_find_sym', 'g_customer_elfsyms'] + args.exclude
|
||||
|
||||
if args.type == 'e':
|
||||
cmd = ['readelf', '-s', '-W', args.input]
|
||||
elif args.type == 'l':
|
||||
cmd = ['nm', '--defined-only', '-g', args.input]
|
||||
|
||||
# Execute the readelf or nm command for static libraries
|
||||
try:
|
||||
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
|
||||
lines = result.stdout.splitlines()
|
||||
except subprocess.CalledProcessError as e:
|
||||
logging.error(f'Error executing command: {e.stderr}')
|
||||
sys.exit(1)
|
||||
except FileNotFoundError:
|
||||
logging.error('nm command not found. Please ensure it is installed and available in your PATH.')
|
||||
sys.exit(1)
|
||||
|
||||
# Extract global symbols from ELF file or static library
|
||||
symbols = get_global_symbols(lines, type=args.type, undefined=args.undefined, symbol_types=['FUNC', 'OBJECT'])
|
||||
|
||||
if not symbols:
|
||||
logging.warning('No global symbols found in the input file.')
|
||||
sys.exit(0)
|
||||
|
||||
logging.debug('symbols: %s'%(cmd))
|
||||
logging.debug('symbols: %s'%(symbols))
|
||||
logging.debug('elfsym_file_dir: %s'%(elfsym_file_dir))
|
||||
logging.debug('extracted_part: %s'%(extracted_part))
|
||||
logging.debug('exclude_symbols: %s'%(exclude_symbols))
|
||||
|
||||
# Save the C file
|
||||
try:
|
||||
save_c_file(symbols, elfsym_file_dir, extracted_part, exclude_symbols=exclude_symbols)
|
||||
logging.info(f"C file with extern declarations and symbol table has been saved to '{elfsym_file_dir}'.")
|
||||
except Exception as e:
|
||||
logging.error(f'Error writing C file: {e}')
|
||||
sys.exit(1)
|
||||
|
||||
def _main():
|
||||
"""
|
||||
Wrapper for the main function to catch and handle runtime errors.
|
||||
"""
|
||||
try:
|
||||
main()
|
||||
except RuntimeError as e:
|
||||
logging.error(f'A fatal error occurred: {e}')
|
||||
sys.exit(2)
|
||||
|
||||
if __name__ == '__main__':
|
||||
_main()
|
||||
Reference in New Issue
Block a user