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
@@ -0,0 +1,44 @@
# ChangeLog
## v1.3.3 - 2026-07-28
* Fixed intermittent crash during long-term ELF execution from PSRAM on ESP32-S31 (use full cache flush instead of ranged API)
## v1.3.2 - 2026-07-09
* Added support for ESP32-S31
* Fixed ELF execution from PSRAM on ESP32-S31 (enable IBUS1 instruction bus)
## v1.3.1 - 2026-02-10
* Added support for overriding symbol resolution with `elf_set_symbol_resolver()`
## v1.3.0 - 2026-01-08
* Added support for generating a shared library
* Added support for dynamically loading shared objects
## v1.2.0 - 2026-01-05
* Support compiling ELF application into main binary firmware
## v1.1.1 - 2025-06-26
* Added support for ESP32-C61
## v1.1.0 - 2025-05-06
* Added fast build for ELF application
* Added a script to generate the symbol table for the ELF APP:
* Supports generating symbols table based on ELF file
* Supports generating symbols table based on static libraries
## v1.0.0 - 2024-12-09
* Added support for the following RISC-V chips: ESP32-P4 and ESP32-C6
* Added support for linking other components to ELF file
* Fixed the issue of getting wrong symbol type
## v0.1.0 - 2023-08-14
* Add basic ELF loader component
@@ -0,0 +1,45 @@
if(CONFIG_ELF_LOADER)
set(srcs "src/esp_elf_symbol.c"
"src/esp_elf.c"
"src/esp_elf_adapter.c")
if(CONFIG_ELF_LOADER_CUSTOMER_SYMBOLS)
list(APPEND srcs "src/esp_all_symbol.c")
endif()
if(CONFIG_IDF_TARGET_ARCH_XTENSA)
list(APPEND srcs "src/arch/esp_elf_xtensa.c")
# ESP32-S2 need to set MMU to run ELF
if(CONFIG_IDF_TARGET_ESP32S2 AND (CONFIG_ELF_LOADER_LOAD_PSRAM))
list(APPEND srcs "src/soc/esp_elf_esp32s2.c")
endif()
elseif(CONFIG_IDF_TARGET_ARCH_RISCV)
list(APPEND srcs "src/arch/esp_elf_riscv.c")
endif()
if(CONFIG_ELF_DYNAMIC_LOAD_SHARED_OBJECT)
list(APPEND srcs "src/dlso/dlfcn.c"
"src/dlso/dlmod.c")
endif()
set(include_dirs "include")
set(ldfragments "linker.lf")
endif()
set(priv_req spi_flash)
if(CONFIG_IDF_TARGET_ESP32P4)
list(APPEND priv_req esp_mm)
endif()
idf_component_register(SRCS ${srcs}
INCLUDE_DIRS ${include_dirs}
PRIV_REQUIRES ${priv_req}
LDFRAGMENTS ${ldfragments})
include(package_manager)
if(CONFIG_ELF_LOADER)
cu_pkg_define_version(${CMAKE_CURRENT_LIST_DIR})
endif()
@@ -0,0 +1,76 @@
menu "Espressif ELF Loader Configuration"
visible if (IDF_TARGET_ESP32 || IDF_TARGET_ESP32S2 || IDF_TARGET_ESP32S3 || IDF_TARGET_ESP32S31 || IDF_TARGET_ESP32C6 || IDF_TARGET_ESP32P4 || IDF_TARGET_ESP32C61)
config ELF_LOADER_BUS_ADDRESS_MIRROR
bool
default y if (IDF_TARGET_ESP32 || IDF_TARGET_ESP32S2 || IDF_TARGET_ESP32S3)
default n if (IDF_TARGET_ESP32S31 || IDF_TARGET_ESP32C6 || IDF_TARGET_ESP32P4 || IDF_TARGET_ESP32C61)
config ELF_LOADER
bool "Enable Espressif ELF Loader"
default y
depends on (IDF_TARGET_ESP32 || IDF_TARGET_ESP32S2 || IDF_TARGET_ESP32S3 || IDF_TARGET_ESP32S31 || IDF_TARGET_ESP32C6 || IDF_TARGET_ESP32P4 || IDF_TARGET_ESP32C61)
help
Select this option to enable ELF Loader and show the submenu with ELF Loader configuration choices.
if ELF_LOADER
config ELF_DYNAMIC_LOAD_SHARED_OBJECT
bool "Enable dynamic load shared object"
default n
help
Select this option to enable dynamic loading of shared objects (.so files) at runtime.
config ELF_FILE_SYSTEM_BASE_PATH
string "File-system base path"
depends on ELF_DYNAMIC_LOAD_SHARED_OBJECT
default "/storage"
help
Specify the base path for the file system where ELF files and shared objects are stored.
This path will be used as the root directory for loading ELF binaries.
Default is "/storage".
config ELF_LOADER_CACHE_OFFSET
bool
default n
help
Select this option if D-cache and I-cache has different offset to access the same physical address.
config ELF_LOADER_SET_MMU
bool
default n
help
Select this option if D-cache and I-cache are not symmetric.
config ELF_LOADER_LOAD_PSRAM
bool "Load ELF to PSRAM"
default y
depends on (IDF_TARGET_ESP32S2 || IDF_TARGET_ESP32S3 || IDF_TARGET_ESP32S31 || IDF_TARGET_ESP32P4 || IDF_TARGET_ESP32C61) && SPIRAM
select ELF_LOADER_CACHE_OFFSET if (IDF_TARGET_ESP32S2 || IDF_TARGET_ESP32S3)
select ELF_LOADER_SET_MMU if IDF_TARGET_ESP32S2
help
Load ELF file into PSRAM instead of internal SRAM.
menu "ELF Symbols Table"
config ELF_LOADER_LIBC_SYMBOLS
bool "Libc Symbols Table"
default y
config ELF_LOADER_ESPIDF_SYMBOLS
bool "ESP-IDF Symbols Table"
default y
config ELF_LOADER_CUSTOMER_SYMBOLS
bool "Customer Symbols Table"
default n
config ELF_LOADER_NUMBER_SYMBOLS
int "Maximum Number of registered symbol tables"
range 1 4096
default 32
help
This configuration is the maximum number of registered symbol tables,
which can be configured according to the number of embedded ELF applications
endmenu
endif
endmenu
@@ -0,0 +1,637 @@
# PATCHES.md — vendored elf_loader provenance and patch registry
## Upstream source
- Repository: https://github.com/espressif/esp-iot-solution
- Path: `components/elf_loader`
- Commit: `6526c5b18e156cfbda2c7ce48e282e384c43b485` (short `6526c5b1`)
"fix(elf_loader): Use full cache flush instead of ranged API on ESP32-S31"
- Component version at that commit: `1.3.3` (per `idf_component.yml`)
- Fetch date: 2026-08-31 (partial clone `--filter=blob:none`, exact-commit
checkout of `components/elf_loader`; commit identity verified via the GitHub
commits API before checkout)
- Files vendored: 26 (all component files, verbatim — see verification below)
## License / NOTICE
Upstream license: **Apache License 2.0**. The full license text is vendored
verbatim as [`license.txt`](license.txt) in this directory
(sha256 `cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30`,
the canonical Apache-2.0 text). Every upstream source file carries the header:
> SPDX-FileCopyrightText: 2023-2026 Espressif Systems (Shanghai) CO LTD
>
> SPDX-License-Identifier: Apache-2.0
NOTICE: This directory contains software licensed under the Apache License,
Version 2.0, copyright Espressif Systems (Shanghai) CO LTD. It is vendored
into this repository (whose own license is GPLv3-or-later; see root LICENSE
and NOTICE) for the PoC-A dynamic-ELF proof of concept. The upstream Apache-2.0
text and copyright headers are retained in full; Apache-2.0 compatibility with
GPLv3 is documented in the GPL "License Compatibility" appendix.
## Verification
The vendored tree is byte-identical to upstream at the pinned commit:
```sh
# offline self-consistency (sufficient per plan fallback rule):
cd poc/apps/poc_a/components/elf_loader
find . -type f ! -name 'tree.sha256' ! -name 'PATCHES.md' | sort | xargs sha256sum | diff - tree.sha256
# online (enhancement): compare against the pinned commit
git clone --filter=blob:none https://github.com/espressif/esp-iot-solution.git
cd esp-iot-solution && git checkout 6526c5b1 -- components/elf_loader
diff -r components/elf_loader <this directory excluding PATCHES.md/tree.sha256>
```
`tree.sha256` (committed alongside) is the sorted sha256 manifest of the 26
upstream files only; `PATCHES.md` and `tree.sha256` itself are excluded so the
manifest stays recomputable. Manifest-file sha256:
`41874265d531ed6d95a39daca006251f3d3fa3b6ee2af220afd846e4787a8861`.
## Patch registry
All local modifications to the vendored tree MUST be registered here as
numbered patches (`p1`, `p2`, ...) with motivation, diff, and post-patch
`tree.sha256` recomputation.
| Patch | Task | Scope | Diff | Post-patch tree.sha256 |
| ----- | ---- | ----- | ---- | ---------------------- |
| p1 fail-closed arch relocate | T5 | `src/esp_elf.c` (1 hunk) | below | manifest sha256 `16f67a5112e08e40cda6db67873dd5ce8c5c2b82fe24580aa3a32caada3a6524` (p1+p2 only) |
| p2 ELF header validation | T5 | `src/esp_elf.c` (1 hunk) | below | (as above; both patches touch only `src/esp_elf.c`) |
| p3 true .text window size | T5 | `src/esp_elf.c` (1 hunk) | below | manifest sha256 `77a95ceccd65bcdf773d0f415f5136d17e2d9382f9b04fe005545c02d5547637`; `src/esp_elf.c` sha256 `c13652c1f2921bb516d6dc206816d20b59d21c7e2771738f4da9a4ae4040f024` (current, p1+p2+p3) |
| p4 forbidden C++ feature sections | T6 | `src/esp_elf.c` (1 hunk) | below | manifest sha256 `1602131050e4667d48b4bee7ec3a80464f091af5eaaaf72b7ff7ffe96999f336`; `src/esp_elf.c` sha256 `63162dbce031de712fd06f449a4f0b05a697c30354329cf5845490205438711d` (current, p1..p4) |
| p5 `.plugin_iram` IRAM section | T7 | `include/private/elf_types.h`, `include/private/elf_platform.h`, `src/esp_elf_adapter.c`, `src/esp_elf.c` | below | manifest sha256 `3c7706cbec751d5dce06bd733d1b3452b5be712e9123b02f413e666936b49a81`; per-file sha256 (current, p1..p5): `src/esp_elf.c` `e3aecd2dccd963440b28cee811158e917825bd59683898df0815014c529df40c`, `src/esp_elf_adapter.c` `76bc197b51844110e73962c4a0be98965a0ed9028f4a27725185eabb332dcb2c`, `include/private/elf_types.h` `b1e946cbb34dad91aa8913724022577154806ad32291d1ed4888e579d2897292`, `include/private/elf_platform.h` `4dcdcb6a11aaf5156ea978019acc484f687234bedaa32fb2fececc652cac3cfe` |
### p1 — fail-closed relocation (T5)
**Rationale:** upstream `esp_elf_relocate()` called
`esp_elf_arch_relocate()` and **ignored its return value**; the arch layer
returns `-EINVAL` for every relocation type outside
{RELATIVE, RTLD, GLOB_DAT, JMP_SLOT}, but the load only logged
`elf_arch: info=N is not supported` and continued with unrelocated words
(FAIL-OPEN, verified during T4). TEST-003 requires "unknown relocation
types are rejected before any plugin code executes", so the error must
propagate. Cleanup mirrors the existing `-ENOSYS` failure path in the same
loop (no internal free; the caller releases via `esp_elf_deinit()`, which
the poc_a harness does on every load failure).
```diff
@@ -620,7 +620,17 @@ int esp_elf_relocate(esp_elf_t *elf, const uint8_t *pbuf)
ESP_LOGD(TAG, "Find function %s addr=%x", func_name, addr);
}
- esp_elf_arch_relocate(elf, &rela_buf, sym, addr);
+ /* [patch p1] Fail closed on unsupported relocations: upstream
+ * ignored esp_elf_arch_relocate()'s -EINVAL, so out-of-allowlist
+ * relocation types only logged an error and loading continued
+ * with unrelocated words. Abort the load instead (TEST-003:
+ * unknown types are rejected before any plugin code runs). */
+ ret = esp_elf_arch_relocate(elf, &rela_buf, sym, addr);
+ if (ret) {
+ ESP_LOGE(TAG, "Failed to relocate type=%d offset=0x%x ret=%d",
+ ELF_R_TYPE(rela_buf.info), rela_buf.offset, ret);
+ return ret;
+ }
}
#if CONFIG_ELF_DYNAMIC_LOAD_SHARED_OBJECT
} else {
```
### p2 — ELF header validation before parse/copy (T5)
**Rationale:** upstream `esp_elf_relocate()` cast the payload to
`elf32_hdr_t` and started parsing with **no** validation of `e_ident`
magic, EI_CLASS, EI_DATA or `e_machine`. On ESP32-S3 (BUS_ADDRESS_MIRROR
section path) a big-endian-marked, ELF64-marked or non-Xtensa payload is
indistinguishable from a valid image at the byte level the loader reads
(LE field reads are unaffected by the EI_DATA flag), so such images were
**loaded and executed** (verified by construction in T5: the build-time
gates and the manifest builder's `extract_plugin_iram_size()` both reject
these images, but a hand-crafted signed container reaches the loader with
them). Minimal fail-closed gate before any header-driven access. This is
also the loader-side half of T14's 14th tamper class (ELF class/machine).
```diff
@@ -531,6 +531,23 @@ int esp_elf_relocate(esp_elf_t *elf, const uint8_t *pbuf)
}
ehdr = (const elf32_hdr_t *)pbuf;
+
+ /* [patch p2] Fail closed on malformed or foreign-architecture images
+ * before any header-driven parsing or segment copy: ELF magic,
+ * ELFCLASS32, little-endian data encoding and an Xtensa machine type
+ * are required. Without this check the loader happily interprets
+ * arbitrary bytes as section/program headers (verified in T5). */
+ if (ehdr->ident[0] != 0x7f || ehdr->ident[1] != 'E' ||
+ ehdr->ident[2] != 'L' || ehdr->ident[3] != 'F' ||
+ ehdr->ident[4] != 1 /* ELFCLASS32 */ ||
+ ehdr->ident[5] != 1 /* ELFDATA2LSB */ ||
+ ehdr->machine != 94 /* EM_XTENSA */) {
+ ESP_LOGE(TAG, "Invalid ELF image: magic/class/data/machine mismatch "
+ "(class=%u data=%u machine=%u)",
+ ehdr->ident[4], ehdr->ident[5], ehdr->machine);
+ return -EINVAL;
+ }
+
shdr = (const elf32_shdr_t *)(pbuf + ehdr->shoff);
shstrab = (const char *)pbuf + shdr[ehdr->shstrndx].offset;
```
### p3 — record true .text window size (T5)
**Rationale:** upstream recorded `sec[TEXT].size = ELF_ALIGN(shdr.size, 4)`.
That recorded size is also the `esp_elf_map_sym()` / `elf_remap_text()`
window. Xtensa places `.rodata` (alignment 1) directly after `.text`, so
when the true `.text` size is not a multiple of 4 the rounded-up window
swallows the first vaddr(s) of `.rodata`: a data pointer with such a vaddr
is mapped into the `.text` window and then mirrored into the instruction
alias (`+0x06000000`), and the first data load through it takes a
LoadStoreError. Observed on target with the T5 `globdat` probe (`.text`
size 0xd3 → `.rodata` vaddr 0x2ab inside the aligned window [0x1d8,
0x2ac)); T4's baseline survived only because its `.text` size happened to
be 4-aligned. Every other recorded section already uses the true size;
allocation is unaffected (the allocator returns aligned blocks regardless
of requested size). Note for T7: `.plugin_iram` handling must copy this
pattern (true size, never a rounded window).
```diff
@@ -190,7 +190,7 @@ static int esp_elf_load_section(esp_elf_t *elf, const uint8_t
elf->sec[ELF_SEC_TEXT].v_addr = shdr[i].addr;
- elf->sec[ELF_SEC_TEXT].size = ELF_ALIGN(shdr[i].size, 4);
+ elf->sec[ELF_SEC_TEXT].size = shdr[i].size;
elf->sec[ELF_SEC_TEXT].offset = shdr[i].offset;
```
(the hunk carries the `[patch p3]` comment block verbatim from the source)
### p4 — forbidden C++ feature sections (T6)
**Rationale:** upstream `esp_elf_relocate()` parses the section table but
silently ignores every section name it does not know. A signed container
carrying C++ runtime feature sections therefore reaches the copy/relocation
path unchallenged (appendix C 11.2 default-forbidden features; the PoC-A
loader has no runner for static constructors/destructors, no TLS block and
no unwinder). Consequences observed on target **before** this patch (T6
pre-patch board run, signed `cxx_ctor` probe with a `.ctors` section whose
only dynamic relocations are allowlisted `R_XTENSA_RELATIVE`):
- the `.ctors` function-pointer relocation makes
`esp_elf_arch_relocate()` write through `esp_elf_map_sym(0x12c4) == 0`
(the section was never loaded, so no recorded window covers the offset)
-> `Guru Meditation LoadProhibited, EXCVADDR=0x0`, firmware reboot -
a fail-open crash, not the TEST-003-required fail-before-execute
rejection;
- the build-time gate (check_plugin_elf.cmake gate 4) and the manifest
builder never see the artifact because a hostile producer bypasses both
(the T5 `hostile_signed` lesson: loader-side checks are the last layer).
The patch scans section names (prefix match, so numbered subsections like
`.init_array.00001` stay covered) immediately after the `shstrab` pointer
is computed - before any allocation or copy - and returns `-EINVAL`. The
list mirrors gate 4 exactly: `.init_array/.fini_array/.preinit_array/
.ctors/.dtors/.tdata/.tbss/.eh_frame/.eh_frame_hdr/.gcc_except_table`.
TLS relocation types remain independently fatal through patch p1 (proven
on board by the `neg_tls_nosect` row, whose sections were renamed away).
```diff
@@ -562,6 +562,34 @@ int esp_elf_relocate(esp_elf_t *elf, const uint8_t *pbuf)
shdr = (const elf32_shdr_t *)(pbuf + ehdr->shoff);
shstrab = (const char *)pbuf + shdr[ehdr->shstrndx].offset;
+ /* [patch p4] Reject C++ runtime feature sections before any section is
+ * allocated, copied or relocated (appendix C 11.2 default-forbidden
+ * features; task T6). The entry-point model has no runner for static
+ * constructors/destructors (.init_array/.fini_array, spelled .ctors/
+ * .dtors by the xtensa toolchain), no TLS block support (.tdata/.tbss)
+ * and no unwinder (.eh_frame/.eh_frame_hdr/.gcc_except_table).
+ * Upstream silently ignored these sections, and their relocations then
+ * write through esp_elf_map_sym()==0 (observed: LoadProhibited crash
+ * on a signed .ctors probe, T6 pre-patch board run) - fail closed. */
+ {
+ static const char *const forbidden[] = {
+ ".init_array", ".fini_array", ".preinit_array",
+ ".ctors", ".dtors",
+ ".tdata", ".tbss",
+ ".eh_frame", ".eh_frame_hdr", ".gcc_except_table",
+ };
+ for (uint32_t i = 0; i < ehdr->shnum; i++) {
+ const char *name = shstrab + shdr[i].name;
+ for (size_t f = 0; f < sizeof(forbidden) / sizeof(forbidden[0]); f++) {
+ if (strncmp(name, forbidden[f], strlen(forbidden[f])) == 0) {
+ ESP_LOGE(TAG, "Forbidden C++ feature section '%s' "
+ "(appendix C 11.2); rejecting image before load", name);
+ return -EINVAL;
+ }
+ }
+ }
+ }
+
/* Load section or segment to memory space */
```
(the hunk carries the `[patch p4]` comment block verbatim from the source)
### p5 — `.plugin_iram` IRAM section support (T7)
**Rationale:** requirements 4.10.3/4.10.4 budget plugin hot functions into
internal executable RAM; upstream `esp_elf_load_section()` knows only
`.text/.data/.rodata/.data.rel.ro/.bss` (all SPIRAM under
`CONFIG_ELF_LOADER_LOAD_PSRAM`) and silently ignores every other ALLOC
section — so a `.plugin_iram` section's relocations would write through
`esp_elf_map_sym()==0` (the patch p4 crash pattern). The patch, in scan
order inside `esp_elf_load_section()`:
1. **scan** section names for `.plugin_iram` (PROGBITS+ALLOC+EXECINSTR
required; missing EXECINSTR or a duplicate section is `-EINVAL`) and
record v_addr/size/offset with the **TRUE size** (patch p3 rationale:
the recorded size is the `map_sym()`/`elf_remap_text()` window);
2. **budget consistency** (PLUG-009 / MEM 4.2.4): the caller copies the
verified manifest's `iram_required_bytes` into `elf->iram_required_bytes`
between `esp_elf_init()` and `esp_elf_relocate()`; the load aborts with
`-EINVAL` **before any allocation** unless it equals the measured
`sh_size` exactly, in both directions (0 is required for images without
the section). Proven on board by the `iram_mismatch` negative
(manifest 97+16 vs section 97 → `-EINVAL`, canary untouched);
3. **allocate** the copy via the new adapter helper `esp_elf_malloc_iram()`
— explicit `MALLOC_CAP_EXEC|MALLOC_CAP_INTERNAL` (the analogue of the
adapter's own internal-exec branch used when PSRAM loading is disabled),
because `esp_elf_malloc()` hard-routes to SPIRAM. On S3 the IDF exec
heap returns the IRAM-alias pointer (native `0x4037..` window, no bus
mirror) with a stash word that `heap_caps_free()` unconverts, so
`esp_elf_deinit()` releasing `piram` through the existing
`esp_elf_free()` is exact;
4. **copy word-wise**: the S3 data bus can touch the instruction-bus SRAM
window only with 32-bit accesses — the first board run crashed in ROM
`memcpy`'s tail byte store (`s8i` to `0x403dbf54`, LoadStoreError,
EXCCAUSE=3) after 96 bytes of word stores had succeeded; the same rule
is why IDF provides the separate `MALLOC_CAP_IRAM_8BIT` cap. The copy
loop assembles each word from source bytes (no source alignment
assumption, no out-of-bounds read for byte-granular `sh_size`), and the
recorded window keeps the true size so the zero padding in the final
word is never mapped;
5. **relocations** need no new code: recording `sec[ELF_SEC_IRAM].addr`
extends `esp_elf_map_sym()`, so the existing arch relocate loop covers
`r_offsets` inside the section, and value relocations whose addend is an
IRAM vaddr produce the native `0x40..` address because
`elf_remap_text()` only remaps the PSRAM `.text` window (IRAM needs no
`+0x06000000` mirror);
6. **cache sync**: `esp_elf_iram_cache_sync()` after the relocation loop
uses the component's **full-writeback + cross-core-guard convention**
(`Cache_WriteBack_All` via `esp_elf_arch_flush()`), NOT the ranged
`esp_cache_msync()` on the IRAM span — justified by the pinned upstream
commit itself (`6526c5b1` "Use full cache flush instead of ranged API on
ESP32-S31": ranged cache APIs fault intermittently on unaligned spans,
and a section copy is byte-granular by construction). On ESP32-S3
internal SRAM sits behind no cache (the caches front external memory
only; `SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE` is not defined), so the sync
is defense-in-depth for the same load's PSRAM `.text` side and the
required mechanism on L1-internal parts. A counter
(`esp_elf_iram_cache_sync_count()`) makes the sync observable: it must
advance by exactly one per IRAM load (T7 acceptance);
7. **deinit** frees `piram` mirroring `ptext`/`pdata` (100-cycle board
soak: IRAM free watermark flat, drift +0);
8. drive-by fix in the same patch: `esp_elf_print_sec()`'s name array
under-counted `ELF_SECS` upstream (read past the array for index ≥ 4);
now lists all six slots.
Harness-side integration (poc_a app, outside the vendored tree): the mpb
view's `iram_required_bytes` is copied into the elf struct after
`esp_elf_init()`; `sdkconfig.defaults` sets `CONFIG_ESP_SYSTEM_MEMPROT=n`
because the IDF Kconfig for it states `MALLOC_CAP_EXEC` allocation is
impossible while memory protection is enabled (software-only PMP config,
no eFuse; required by 4.10.3/4.10.4).
Diff (paths relative to the component root; applies on top of p1..p4):
```diff
diff --git a/include/private/elf_platform.h b/include/private/elf_platform.h
index b346737..9ee3a2a 100644
--- a/include/private/elf_platform.h
+++ b/include/private/elf_platform.h
@@ -36,6 +36,14 @@ void *esp_elf_malloc(uint32_t n, bool exec);
*/
void esp_elf_free(void *ptr);
+/* [patch p5] Allocate n bytes of internal executable memory for the
+ * .plugin_iram section copy (task T7). The regular esp_elf_malloc()
+ * hard-routes to SPIRAM under CONFIG_ELF_LOADER_LOAD_PSRAM, which is right
+ * for .text/.data but wrong for the IRAM budget; this helper keeps the
+ * allocation policy in the adapter like every other allocation of the
+ * component. */
+void *esp_elf_malloc_iram(uint32_t n);
+
/**
* @brief Relocates target architecture symbol of ELF
*
@@ -70,6 +78,11 @@ uintptr_t elf_remap_text(esp_elf_t *elf, uintptr_t sym);
void esp_elf_arch_flush(void);
#endif
+/* [patch p5] Number of times the IRAM copy/relocation cache-sync routine
+ * has run (task T7 cache-sync observability: the counter must increment
+ * with every .plugin_iram load). */
+uint32_t esp_elf_iram_cache_sync_count(void);
+
/**
* @brief Initialize MMU hardware remapping function.
*
diff --git a/include/private/elf_types.h b/include/private/elf_types.h
index c9b4f7a..0ac8022 100644
--- a/include/private/elf_types.h
+++ b/include/private/elf_types.h
@@ -119,6 +119,11 @@ extern "C" {
#define ELF_PLT ".plt" /*!< procedure linkage table. */
#define ELF_GOT_PLT ".got.plt" /*!< a table where resolved addresses from external functions are stored */
+/* [patch p5] Plugin hot-function section (task T7 of poc-a-dynamic-elf,
+ * requirements 4.10.3/4.10.4): plugin code the manifest budgets into
+ * internal executable RAM. Parsed only on the BUS_ADDRESS_MIRROR path. */
+#define ELF_IRAM ".plugin_iram" /*!< plugin IRAM-resident code */
+
/** @brief ELF section and symbol operation */
#define ELF_SEC_TEXT 0
@@ -126,7 +131,8 @@ extern "C" {
#define ELF_SEC_DATA 2
#define ELF_SEC_RODATA 3
#define ELF_SEC_DRLRO 4
-#define ELF_SECS 5
+#define ELF_SEC_IRAM 5 /* [patch p5] */
+#define ELF_SECS 6
#define ELF_ST_BIND(_i) ((_i) >> 4)
#define ELF_ST_TYPE(_i) ((_i) & 0xf)
@@ -241,6 +247,7 @@ typedef struct esp_elf {
#ifdef CONFIG_ELF_LOADER_BUS_ADDRESS_MIRROR
unsigned char *ptext; /*!< instruction buffer pointer */
unsigned char *pdata; /*!< data buffer pointer */
+ unsigned char *piram; /*!< [patch p5] .plugin_iram buffer (internal EXEC) */
#else
unsigned char *psegment; /*!< segment buffer pointer */
uint32_t svaddr; /*!< start virtual address of segment */
@@ -250,6 +257,15 @@ typedef struct esp_elf {
int (*entry)(int argc, char *argv[]); /*!< Entry pointer of ELF */
+ /* [patch p5] Manifest-declared .plugin_iram budget (PLUG-009 / MEM
+ * 4.2.4): the caller copies iram_required_bytes from the verified mpb
+ * manifest view into this field between esp_elf_init() and
+ * esp_elf_relocate(); the load aborts with -EINVAL before any
+ * allocation unless it equals the section's measured sh_size. Zero
+ * (the esp_elf_init() reset) is the correct value for images without
+ * a .plugin_iram section. */
+ uint32_t iram_required_bytes;
+
#ifdef CONFIG_ELF_LOADER_SET_MMU
uint32_t text_off; /*!< .text symbol offset */
diff --git a/src/esp_elf_adapter.c b/src/esp_elf_adapter.c
index 36a17bc..6b4c08f 100644
--- a/src/esp_elf_adapter.c
+++ b/src/esp_elf_adapter.c
@@ -70,6 +70,29 @@ void esp_elf_free(void *ptr)
heap_caps_free(ptr);
}
+/* [patch p5] Internal-EXEC allocation for the .plugin_iram section copy
+ * (task T7). Mirrors the adapter's own internal-exec selection used when
+ * PSRAM loading is disabled (esp_elf_malloc()'s exec branch): explicit
+ * EXEC|INTERNAL caps, so the section copy lands in the native IRAM
+ * execution window (0x4037_0000..0x403E_0000 on ESP32-S3) instead of the
+ * PSRAM data window. MALLOC_CAP_EXEC exists only when the IDF exec heap is
+ * available (CONFIG_HEAP_HAS_EXEC_HEAP, i.e. CONFIG_ESP_SYSTEM_MEMPROT=n;
+ * the IDF Kconfig help states EXEC allocation is impossible under memory
+ * protection), EXEC cannot be combined with 8BIT/DMA, and heap_caps
+ * transparently returns the IRAM-alias pointer with a stash word that
+ * heap_caps_free() unconverts - so esp_elf_free() stays correct. Fail
+ * closed (NULL) when the exec heap is not configured. */
+void *esp_elf_malloc_iram(uint32_t n)
+{
+#ifdef MALLOC_CAP_EXEC
+ return heap_caps_malloc(n, MALLOC_CAP_EXEC | MALLOC_CAP_INTERNAL);
+#else
+ ESP_LOGE("elf_adapter", "MALLOC_CAP_EXEC unavailable (enable by setting "
+ "CONFIG_ESP_SYSTEM_MEMPROT=n); cannot load .plugin_iram");
+ return NULL;
+#endif
+}
+
/**
* @brief Remap symbol from ".data" to ".text" section.
*
diff --git a/src/esp_elf.c b/src/esp_elf.c
index 0c03f2f..401b776 100644
--- a/src/esp_elf.c
+++ b/src/esp_elf.c
@@ -43,6 +43,41 @@ static const char *TAG = "ELF";
static esp_elf_symbol_table_t *g_symbol_tables[SYMBOL_TABLES_NO];
static _Atomic(symbol_resolver) current_resolver = elf_find_sym_default;
+/* [patch p5] Cache-sync observability counter (task T7): incremented every
+ * time the IRAM copy/relocation cache-sync routine runs; must advance with
+ * every .plugin_iram load. */
+static uint32_t g_iram_cache_syncs;
+
+uint32_t esp_elf_iram_cache_sync_count(void)
+{
+ return g_iram_cache_syncs;
+}
+
+/* [patch p5] Cache sync for the .plugin_iram copy + its relocations.
+ *
+ * Choice: the component's full-writeback convention (Cache_WriteBack_All +
+ * cross-core guard via esp_elf_arch_flush()), NOT the ranged
+ * esp_cache_msync() on the IRAM span. Justification from the pinned
+ * upstream evidence (commit 6526c5b1 "Use full cache flush instead of
+ * ranged API on ESP32-S31", the ADR-0002 archive note): the ranged cache
+ * APIs fault intermittently on unaligned addr/size spans, and a section
+ * copy is byte-granular by construction (sh_size is not line-aligned), so
+ * the IRAM span is exactly the hazard class that commit reverted away
+ * from. On ESP32-S3 internal SRAM sits behind no cache (the caches front
+ * external memory only), so D-side stores are already coherent with
+ * I-fetch and this sync is defense-in-depth for the same load's PSRAM
+ * .text side; on parts whose internal memory IS L1-cached the full
+ * writeback is the required sync. Called once per load after the
+ * relocation loop so both the copy and any relocations into the window
+ * are covered. */
+static void esp_elf_iram_cache_sync(void)
+{
+#ifdef CONFIG_ELF_LOADER_LOAD_PSRAM
+ esp_elf_arch_flush();
+#endif
+ g_iram_cache_syncs++;
+}
+
/**
* @brief Open and load an ELF file into memory.
*
@@ -218,6 +253,31 @@ static int esp_elf_load_section(esp_elf_t *elf, const uint8_t *pbuf)
ESP_LOGD(TAG, ".data offset is 0x%lx size is 0x%x",
elf->sec[ELF_SEC_DATA].offset,
elf->sec[ELF_SEC_DATA].size);
+ } else if (!strcmp(ELF_IRAM, name)) {
+ /* [patch p5] .plugin_iram (task T7, requirements 4.10.3/
+ * 4.10.4): recorded like every other section with its TRUE
+ * size - the recorded size is the map_sym()/elf_remap_text()
+ * window and must never swallow the neighbouring section's
+ * first vaddr(s) (patch p3 rationale). Duplicates and
+ * non-executable spellings are rejected: the IRAM window is
+ * only meaningful for code, and a silently ignored alias
+ * would leave its relocations writing through
+ * esp_elf_map_sym()==0 (the patch p4 crash pattern). */
+ if (!sflags(&shdr[i], SHF_EXECINSTR)) {
+ ESP_LOGE(TAG, "Section %s lacks SHF_EXECINSTR; rejecting image", name);
+ return -EINVAL;
+ }
+ if (elf->sec[ELF_SEC_IRAM].size) {
+ ESP_LOGE(TAG, "Duplicate %s section; rejecting image", name);
+ return -EINVAL;
+ }
+
+ ESP_LOGD(TAG, ".plugin_iram sec addr=0x%08x size=0x%08x offset=0x%08x",
+ shdr[i].addr, shdr[i].size, shdr[i].offset);
+
+ elf->sec[ELF_SEC_IRAM].v_addr = shdr[i].addr;
+ elf->sec[ELF_SEC_IRAM].size = shdr[i].size;
+ elf->sec[ELF_SEC_IRAM].offset = shdr[i].offset;
} else if (!strcmp(ELF_RODATA, name)) {
ESP_LOGD(TAG, ".rodata sec addr=0x%08x size=0x%08x offset=0x%08x",
shdr[i].addr, shdr[i].size, shdr[i].offset);
@@ -263,6 +323,20 @@ static int esp_elf_load_section(esp_elf_t *elf, const uint8_t *pbuf)
return -EINVAL;
}
+ /* [patch p5] IRAM budget consistency (PLUG-009 / MEM 4.2.4): the
+ * manifest-declared iram_required_bytes (caller-copied from the
+ * verified mpb manifest view) must equal the section's measured sh_size
+ * exactly, in BOTH directions, checked before any allocation. An
+ * under-declared section would silently spend internal EXEC memory the
+ * admission layer never granted; an over-declared one hides the true
+ * footprint. Images without .plugin_iram must carry budget 0. */
+ if (elf->iram_required_bytes != elf->sec[ELF_SEC_IRAM].size) {
+ ESP_LOGE(TAG, ".plugin_iram budget mismatch: manifest=%" PRIu32
+ " section=%" PRIu32 "; rejecting before allocation",
+ elf->iram_required_bytes, (uint32_t)elf->sec[ELF_SEC_IRAM].size);
+ return -EINVAL;
+ }
+
elf->ptext = esp_elf_malloc(elf->sec[ELF_SEC_TEXT].size, true);
if (!elf->ptext) {
ESP_LOGE(TAG, "Failed to malloc %"PRIu32" bytes for text section",
@@ -283,6 +357,23 @@ static int esp_elf_load_section(esp_elf_t *elf, const uint8_t *pbuf)
}
}
+ /* [patch p5] .plugin_iram copy target: internal EXEC memory (native
+ * 0x4037.. instruction window on ESP32-S3), NOT the PSRAM text window.
+ * Allocated through the adapter's explicit EXEC|INTERNAL selection
+ * because esp_elf_malloc() hard-routes to SPIRAM under
+ * CONFIG_ELF_LOADER_LOAD_PSRAM (the adapter's own internal-exec path,
+ * used upstream when PSRAM loading is disabled, is the analogue). */
+ if (elf->sec[ELF_SEC_IRAM].size) {
+ elf->piram = esp_elf_malloc_iram((uint32_t)elf->sec[ELF_SEC_IRAM].size);
+ if (!elf->piram) {
+ ESP_LOGE(TAG, "Failed to malloc %"PRIu32" bytes for plugin_iram section",
+ (uint32_t)elf->sec[ELF_SEC_IRAM].size);
+ esp_elf_free(elf->pdata);
+ esp_elf_free(elf->ptext);
+ return -ENOMEM;
+ }
+ }
+
/* Dump ".text" from ELF to executable space memory */
elf->sec[ELF_SEC_TEXT].addr = (Elf32_Addr)elf->ptext;
@@ -339,6 +430,38 @@ static int esp_elf_load_section(esp_elf_t *elf, const uint8_t *pbuf)
}
}
+ /* [patch p5] Dump ".plugin_iram" to the internal executable window.
+ * Recording sec[ELF_SEC_IRAM].addr extends esp_elf_map_sym() so the
+ * generic relocation loop resolves r_offsets inside the section's
+ * vaddr window to the IRAM copy, and value relocations whose addend is
+ * an IRAM vaddr produce the native 0x40.. address - elf_remap_text()
+ * correctly leaves those untouched (they are outside the PSRAM .text
+ * window, and the IRAM window needs no +0x06000000 bus mirror).
+ * The copy itself is WORD-WISE: on ESP32-S3 the data bus can touch the
+ * instruction-bus SRAM window only with 32-bit accesses (byte stores
+ * raise LoadStoreError - the same rule that makes IDF provide the
+ * separate MALLOC_CAP_IRAM_8BIT cap). Verified on target: ROM memcpy's
+ * tail s8i to the alias faulted with EXCCAUSE=3. Source bytes are read
+ * individually so no source alignment is assumed. */
+ if (elf->sec[ELF_SEC_IRAM].size) {
+ const uint8_t *src = pbuf + elf->sec[ELF_SEC_IRAM].offset;
+ volatile uint32_t *dst = (volatile uint32_t *)(uintptr_t)elf->piram;
+ const uint32_t total = (uint32_t)elf->sec[ELF_SEC_IRAM].size;
+ elf->sec[ELF_SEC_IRAM].addr = (Elf32_Addr)elf->piram;
+
+ for (uint32_t off = 0; off < total; off += 4u) {
+ uint32_t word = 0;
+ const uint32_t remain = total - off;
+ for (uint32_t b = 0; b < 4u && b < remain; b++) {
+ word |= (uint32_t)src[off + b] << (8u * b);
+ }
+ dst[off >> 2] = word;
+ }
+
+ ESP_LOGI(TAG, ".plugin_iram copied to 0x%08x size %"PRIu32,
+ (uint32_t)(uintptr_t)elf->piram, (uint32_t)elf->sec[ELF_SEC_IRAM].size);
+ }
+
/* Set ELF entry */
entry = ehdr->entry + elf->sec[ELF_SEC_TEXT].addr -
@@ -742,8 +865,17 @@ int esp_elf_relocate(esp_elf_t *elf, const uint8_t *pbuf)
}
}
+ /* [patch p5] IRAM loads sync through esp_elf_iram_cache_sync() (which
+ * performs the same full writeback + cross-core guard and counts it);
+ * the plain flush stays on the no-IRAM path so its behaviour is
+ * unchanged. */
+ if (elf->piram) {
+ esp_elf_iram_cache_sync();
+ } else
#ifdef CONFIG_ELF_LOADER_LOAD_PSRAM
- esp_elf_arch_flush();
+ {
+ esp_elf_arch_flush();
+ }
#endif
return 0;
@@ -792,6 +924,13 @@ void esp_elf_deinit(esp_elf_t *elf)
elf->pdata = NULL;
}
+ /* [patch p5] release the .plugin_iram copy (mirrors ptext/pdata) so
+ * load/unload cycles return the internal EXEC watermark to baseline */
+ if (elf->piram) {
+ esp_elf_free(elf->piram);
+ elf->piram = NULL;
+ }
+
if (elf->ptext) {
esp_elf_free(elf->ptext);
elf->ptext = NULL;
@@ -946,8 +1085,11 @@ void esp_elf_print_shdr(const uint8_t *pbuf)
*/
void esp_elf_print_sec(esp_elf_t *elf)
{
+ /* [patch p5] ELF_SECS grew to 6 (ELF_SEC_IRAM); the name array must
+ * cover every slot or the loop below reads past it (it already
+ * under-counted ELF_SEC_DRLRO upstream). */
const char *sec_names[ELF_SECS] = {
- "text", "bss", "data", "rodata"
+ "text", "bss", "data", "rodata", "drlro", "iram"
};
for (int i = 0; i < ELF_SECS; i++) {
```
Upstream files are NEVER edited in place without a registry entry; the
unpatched state must always be reproducible from this table (apply the
hunks above in reverse to `git show 6526c5b1:components/elf_loader/src/esp_elf.c`).
@@ -0,0 +1,207 @@
## Description
[![Component Registry](https://components.espressif.com/components/espressif/elf_loader/badge.svg)](https://components.espressif.com/components/espressif/elf_loader)
Espressif ELF(Executable and Linkable Format) loader is a software development kit that is developed based on the ESP-IDF, mainly used to load ELF file compiled based on ESP32 series SoCs to the executable memory area, then link and execute it.
In this way, the application does not need compile into the whole firmware in advance. It is like running the compiled program through terminal input `./main.o` on the Ubuntu platform automatically, which realizes the separation of application and kernel.
This ELF loader supports following SoCs:
- ESP32
- ESP32-S2, support running ELF in PSRAM
- ESP32-S3, support running ELF in PSRAM
- ESP32-S31, support running ELF in PSRAM
- ESP32-P4, support running ELF in PSRAM
- ESP32-C6
- ESP32-C61, support running ELF in PSRAM
### Usage
#### Firmware
Add a dependency on this component in your component or project's idf_component.yml file.
```yml
dependencies:
espressif/elf_loader: "1.*"
```
Enable ELF loader in the menuconfig:
```
Component config --->
ESP-ELFLoader Configuration --->
[*] Enable Espressif ELF Loader
```
You can then optionally enable dynamic load shared object in the menuconfig:
```
Component config --->
ESP-ELFLoader Configuration --->
[*] Enable dynamic load shared object
```
Add API calls in your project as follows:
```c
#include "esp_elf.h"
esp_elf_t elf;
// Your Code
esp_elf_init(&elf);
esp_elf_relocate(&elf, elf_file_data_bytes);
esp_elf_request(&elf, 0, argc, argv);
esp_elf_deinit(&elf);
```
If dynamic load shared object is enabled, you can use the following APIs in your project:
#### Dynamic Shared Object API
Include the dynamic loader header and use the dl* APIs to load, resolve symbols, and unload shared objects:
```c
#include "esp_dlfcn.h"
```
**Common API list**
- `void *dlopen(const char *file, int mode)` loads a shared object from a filesystem path and returns a module handle (NULL on failure).
- `void *dlsym(void *handle, const char *name)` returns the address of a symbol in the module (NULL if not found).
- `int dlclose(void *handle)` closes the module handle (0 on success, -1 on invalid handle).
- `const char *dlerror(void)` returns the last error message (NULL if no error); copy the string immediately if needed.
- `void dllist(dl_list_t type)` prints module or symbol information (`LIST_MODULE` or `LIST_SYMBOL`).
**Mode flags**
- `RTLD_LAZY`, `RTLD_NOW`, `RTLD_NOLOAD`, `RTLD_DEEPBIND` (use one of the binding modes plus optional flags).
**Typical flow**
```c
#include "esp_dlfcn.h"
#include <stdio.h>
typedef int (*lib_func2)(int);
void run_plugin(void)
{
void *handle = dlopen("/riscv/lib.so", RTLD_NOW);
if (!handle) {
printf("dlopen failed: %s\n", dlerror());
return;
}
lib_func2 fibonacci_function = (lib_func2)dlsym(handle, "fibonacci");
if (!fibonacci_function) {
printf("dlsym failed: %s\n", dlerror());
dlclose(handle);
return;
}
printf("Fibonacci number at position %d is %d\n", 10, fibonacci_function(10));
dlclose(handle);
}
```
#### ELF APP
To use this feature to compile ELF file, including the required CMake file in your project's CMakeLists.txt file after the line project(XXXX).
```cmake
project(XXXX)
# Add
include(elf_loader)
project_elf(XXXX)
```
Build the project as an ordinary ESP-IDF project, and then the ELF file named `XXXX.app.elf` is in the build directory.
#### Shared library
To use this feature to compile Shared library file, including the required CMake file in your project's CMakeLists.txt file after the line project(XXXX).
```cmake
project(XXXX)
# Add
include(elf_loader)
project_so(XXXX)
```
Build the project as an ordinary ESP-IDF project, and then the Shared library file named `XXXX.so` is in the build directory.
### ELF APP Fast Build
Users can enable ELF fast build functionality by configuring CMAKE's generator as Unix Makefiles. The reference command is as follows:
```bash
idf.py -G 'Unix Makefiles' set-target <chip-name>
```
Then input the ELF APP build command as follows:
```
idf.py elf
```
The build system will only build ELF target components and show the following logs:
```
Building C object esp-idf/main/CMakeFiles/__idf_main.dir/main.c.obj
Linking C static library libmain.a
Build ELF: hello_world.app.elf
Built target elf
```
### Shared library Fast Build
Users can enable shared library fast build functionality by configuring CMAKE's generator as Unix Makefiles. The reference command is as follows:
```bash
idf.py -G 'Unix Makefiles' set-target <chip-name>
```
Then input the shared library build command as follows:
```
idf.py so
```
The build system will only build shared library target components and show the following logs:
```
[100%] Building C object esp-idf/main/CMakeFiles/__idf_main.dir/lib.c.obj
[100%] Linking C static library libmain.a
[100%] Build Shared Object: lib.so
Linking lib.so completed
[100%] Built target so
```
### Adding the Component to Your Project
Please use the component manager command add-dependency to add the elf_loader component as a dependency in your project. During the CMake step, the component will be downloaded automatically.
```
idf.py add-dependency "espressif/elf_loader=*"
```
### Examples
Please use the component manager command create-project-from-example to create a project from the example template.
```
idf.py create-project-from-example "espressif/elf_loader=*:elf_loader_example"
```
This command will download the example elf_loader_example into the current folder. You can navigate into it to build and flash the example.
Alternatively, you can download examples from the esp-iot-solution repository:
1. [build_elf_file_example](https://github.com/espressif/esp-iot-solution/tree/master/examples/elf_loader/build_elf_file_example)
2. [build_shared_library_example](https://github.com/espressif/esp-iot-solution/tree/master/examples/elf_loader/build_shared_library_example)
3. [elf_embed_example](https://github.com/espressif/esp-iot-solution/tree/master/examples/elf_loader/elf_embed_example)
4. [elf_loader_example](https://github.com/espressif/esp-iot-solution/tree/master/examples/elf_loader/elf_loader_example)
5. [elf_console_example](https://github.com/espressif/esp-iot-solution/tree/master/examples/elf_loader/elf_console_example)
@@ -0,0 +1,8 @@
if(NOT EXISTS "${OUT}")
message(FATAL_ERROR "Error: ${OUT} was not created")
endif()
file(SIZE "${OUT}" SIZE_VAR)
if(SIZE_VAR EQUAL 0)
message(FATAL_ERROR "Error: ${OUT} is empty")
endif()
@@ -0,0 +1,258 @@
# 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()
@@ -0,0 +1,23 @@
version: "1.3.3"
targets:
- esp32
- esp32s2
- esp32s3
- esp32s31
- esp32c6
- esp32c61
- esp32p4
description: Espressif ELF(Executable and Linkable Format) Loader
url: https://github.com/espressif/esp-iot-solution/tree/master/components/elf_loader
dependencies:
idf: ">=4.4.3"
espressif/cmake_utilities: "0.*"
examples:
- path: ../../examples/elf_loader/build_elf_file_example
- path: ../../examples/elf_loader/build_shared_library_example
- path: ../../examples/elf_loader/elf_embed_example
- path: ../../examples/elf_loader/elf_loader_example
- path: ../../examples/elf_loader/elf_console_example
sbom:
supplier: 'Organization: Espressif Systems (Shanghai) CO LTD'
originator: 'Organization: Espressif Systems (Shanghai) CO LTD'
@@ -0,0 +1,79 @@
/*
* SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
/** @brief The MODE argument to `dlopen' contains one of the following: */
#define RTLD_LAZY 0x00001 /*!< Lazy function call binding. */
#define RTLD_NOW 0x00002 /*!< Immediate function call binding. */
#define RTLD_BINDING_MASK 0x00003 /*!< Mask of binding time value. */
#define RTLD_NOLOAD 0x00004 /*!< Do not load the object. */
#define RTLD_DEEPBIND 0x00008 /*!< Use deep binding. */
/**
* @brief Enum for symbol table list type
*
*/
typedef enum {
LIST_MODULE,
LIST_SYMBOL,
} dl_list_t;
/**
* @brief Dynamic loader compatibility interface - Load a shared object.
*
* @param file - Filesystem path to the ELF binary
* @param mode - Mode flags (RTLD_LAZY, RTLD_NOW, etc.)
*
* @return Module handle on success, NULL on failure.
*/
void *dlopen(const char *file, int mode);
/**
* @brief Dynamic loader compatibility interface - Look up symbol address.
*
* @param handle - Module handle from dlopen()
* @param name - Symbol name to locate
*
* @return Memory address of the symbol if found, NULL otherwise.
*/
void *dlsym(void *handle, const char *name);
/**
* @brief Dynamic loader compatibility interface - Close a module handle.
*
* @param handle - Module handle to close
*
* @return 0 on success, -1 on invalid handle.
*/
int dlclose(void *handle);
/**
* @brief Dynamic loader compatibility interface - Get error message.
*
* @note Thread safety: The returned pointer points to a static buffer that
* may be overwritten by subsequent calls to dl* functions from any
* thread. Callers should copy the string immediately if needed.
*
* @return Pointer to error message string, or NULL if no error occurred.
*/
const char *dlerror(void);
/**
* @brief Display system module/symbol information.
*
* @param type - Listing type (LIST_MODULE for modules, LIST_SYMBOL for symbols)
*/
void dllist(dl_list_t type);
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,181 @@
/*
* SPDX-FileCopyrightText: 2023-2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <stdint.h>
#include <stddef.h>
#include "private/elf_types.h"
#include "private/elf_symbol.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct elf_file {
uint8_t *payload;
size_t size;
} elf_file_t;
/**
* @brief Symbol table type
*
* A symbol table is an array of esp_elfsym structures terminated with ESP_ELFSYM_END.
*/
typedef const struct esp_elfsym esp_elf_symbol_table_t;
/**
* @brief Open and load an ELF file into memory.
*
* @param file - Pointer to elf_file_t structure to store loaded file content
* @param name - Filename (without path) of the ELF file to open
*
* @return 0 on success, -1 on failure with errno set. Error cases include:
* - Invalid parameters
* - Path generation failure
* - File open/read errors
* - Memory allocation failures
*
* @note The actual file path will be constructed as "FS_PATH/name"
* @note Allocates memory for file content using esp_elf_malloc()
*/
int esp_elf_open(elf_file_t *file, const char *name);
/**
* @brief Close ELF file and release associated resources.
*
* @param file - Pointer to opened elf_file_t structure
*
* @note Releases memory allocated by esp_elf_open() for payload data
* @note Should be called paired with esp_elf_open() to prevent memory leaks
* @note If file is NULL, this function does nothing (null-safe)
*/
void esp_elf_close(elf_file_t *file);
/**
* @brief Map symbol's address of ELF to physic space.
*
* @param elf - ELF object pointer
* @param sym - ELF symbol address
*
* @return Mapped physic address.
*/
uintptr_t esp_elf_map_sym(esp_elf_t *elf, uintptr_t sym);
/**
* @brief Initialize ELF object.
*
* @param elf - ELF object pointer
*
* @return ESP_OK if success or other if failed.
*/
int esp_elf_init(esp_elf_t *elf);
/**
* @brief Decode and relocate ELF data.
*
* @param elf - ELF object pointer
* @param pbuf - ELF data buffer
*
* @return ESP_OK if success or other if failed.
*/
int esp_elf_relocate(esp_elf_t *elf, const uint8_t *pbuf);
/**
* @brief Request running relocated ELF function.
*
* @param elf - ELF object pointer
* @param opt - Request options
* @param argc - Arguments number
* @param argv - Arguments value array
*
* @return ESP_OK if success or other if failed.
*/
int esp_elf_request(esp_elf_t *elf, int opt, int argc, char *argv[]);
/**
* @brief Deinitialize ELF object.
*
* @param elf - ELF object pointer
*
* @return None
*/
void esp_elf_deinit(esp_elf_t *elf);
/**
* @brief Print header description information of ELF.
*
* @param pbuf - ELF data buffer
*
* @return None
*/
void esp_elf_print_ehdr(const uint8_t *pbuf);
/**
* @brief Print program header description information of ELF.
*
* @param pbuf - ELF data buffer
*
* @return None
*/
void esp_elf_print_phdr(const uint8_t *pbuf);
/**
* @brief Print section header description information of ELF.
*
* @param pbuf - ELF data buffer
*
* @return None
*/
void esp_elf_print_shdr(const uint8_t *pbuf);
/**
* @brief Print section information of ELF.
*
* @param pbuf - ELF data buffer
*
* @return None
*/
void esp_elf_print_sec(esp_elf_t *elf);
/**
* @brief Register symbol table to global symbol tables array.
*
* @param symbol_table - Pointer to symbol table structure (array of esp_elfsym terminated by ESP_ELFSYM_END)
*
* @return 0 if success, -EINVAL if symbol_table is NULL, -EEXIST if already registered, -ENOMEM if no space.
*
* @note This function is not thread-safe. External synchronization must be used if calling
* this function concurrently from multiple threads.
*/
int esp_elf_register_symbol(esp_elf_symbol_table_t *symbol_table);
/**
* @brief Unregister symbol table from global symbol tables array.
*
* @param symbol_table - Pointer to symbol table structure to remove
*
* @return 0 if success, -EINVAL if symbol_table is NULL or symbol table not found.
*
* @note This function is not thread-safe. External synchronization must be used if calling
* this function concurrently from multiple threads.
*/
int esp_elf_unregister_symbol(esp_elf_symbol_table_t *symbol_table);
/**
* @brief Find symbol address by symbol name in registered tables.
*
* @param sym_name - Symbol name string to search
*
* @return Symbol address if found, 0 if not found.
* @note Search order is reverse registration order (latest registered first).
*/
uintptr_t esp_elf_find_symbol(const char *sym_name);
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,110 @@
/*
* SPDX-FileCopyrightText: 2023-2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include "private/elf_types.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Notes: align_size needs to be a power of 2 */
#define ELF_ALIGN(_a, align_size) (((_a) + (align_size - 1)) & \
~(align_size - 1))
/**
* @brief Allocate block of memory.
*
* @param n - Memory size in byte
* @param exec - True: memory can run executable code; False: memory can R/W data
*
* @return Memory pointer if success or NULL if failed.
*/
void *esp_elf_malloc(uint32_t n, bool exec);
/**
* @brief Free block of memory.
*
* @param ptr - memory block pointer allocated by "esp_elf_malloc"
*
* @return None
*/
void esp_elf_free(void *ptr);
/* [patch p5] Allocate n bytes of internal executable memory for the
* .plugin_iram section copy (task T7). The regular esp_elf_malloc()
* hard-routes to SPIRAM under CONFIG_ELF_LOADER_LOAD_PSRAM, which is right
* for .text/.data but wrong for the IRAM budget; this helper keeps the
* allocation policy in the adapter like every other allocation of the
* component. */
void *esp_elf_malloc_iram(uint32_t n);
/**
* @brief Relocates target architecture symbol of ELF
*
* @param elf - ELF object pointer
* @param rela - Relocated symbol data
* @param sym - ELF symbol table
* @param addr - Jumping target address
*
* @return ESP_OK if success or other if failed.
*/
int esp_elf_arch_relocate(esp_elf_t *elf, const elf32_rela_t *rela,
const elf32_sym_t *sym, uint32_t addr);
/**
* @brief Remap symbol from ".data" to ".text" section.
*
* @param elf - ELF object pointer
* @param sym - ELF symbol table
*
* @return Remapped symbol value
*/
#ifdef CONFIG_ELF_LOADER_CACHE_OFFSET
uintptr_t elf_remap_text(esp_elf_t *elf, uintptr_t sym);
#endif
/**
* @brief Flush data from cache to external RAM.
*
* @return None
*/
#ifdef CONFIG_ELF_LOADER_LOAD_PSRAM
void esp_elf_arch_flush(void);
#endif
/* [patch p5] Number of times the IRAM copy/relocation cache-sync routine
* has run (task T7 cache-sync observability: the counter must increment
* with every .plugin_iram load). */
uint32_t esp_elf_iram_cache_sync_count(void);
/**
* @brief Initialize MMU hardware remapping function.
*
* @param elf - ELF object pointer
*
* @return 0 if success or a negative value if failed.
*/
#ifdef CONFIG_ELF_LOADER_SET_MMU
int esp_elf_arch_init_mmu(esp_elf_t *elf);
#endif
/**
* @brief De-initialize MMU hardware remapping function.
*
* @param elf - ELF object pointer
*
* @return None
*/
#ifdef CONFIG_ELF_LOADER_SET_MMU
void esp_elf_arch_deinit_mmu(esp_elf_t *elf);
#endif
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,128 @@
/*
* SPDX-FileCopyrightText: 2023-2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Macro to export a symbol for ELF loading.
*
* @param _sym Symbol name (function or variable)
*
* @note The (void*) cast is necessary to convert the symbol address
* to the generic pointer type used in esp_elfsym structure.
* This is safe for functions and objects with static storage duration.
*/
#define ESP_ELFSYM_EXPORT(_sym) { #_sym, (void*)&_sym }
/* End of symbol table marker */
#define ESP_ELFSYM_END { NULL, NULL }
/** @brief Function symbol description */
struct esp_elfsym {
const char *name; /*!< Function name */
const void *sym; /*!< Function pointer */
};
/**
* @brief Symbol resolver function type.
*
* Resolves a symbol name (e.g. function name) to its address.
* Custom resolvers allow dynamic symbol lookup beyond the static
* symbol tables configured by KConfig.
*
* @param sym_name Symbol name to resolve (null-terminated string)
* @return Symbol address if success, or 0 if the symbol is not found.
*
* @note The resolver function should be thread-safe if used in multi-threaded contexts.
* @note The resolver should return 0 for unknown symbols, not a random address.
*
* @example Example implementation:
* ```c
* uintptr_t my_resolver(const char *sym_name)
* {
* // Check custom symbol table first
* if (strcmp(sym_name, "my_function") == 0) {
* return (uintptr_t)my_function;
* }
*
* // Fall back to default resolver
* return elf_find_sym_default(sym_name);
* }
*
* // Usage:
* elf_set_symbol_resolver(my_resolver);
* ```
*/
typedef uintptr_t (*symbol_resolver)(const char *sym_name);
/**
* @brief Find symbol address by name.
*
* @param sym_name - Symbol name
*
* @return Symbol address if success or 0 if failed.
*/
uintptr_t elf_find_sym(const char *sym_name);
/**
* @brief Find symbol address by name.
*
* @param sym_name - Symbol name
*
* @return Symbol address if success or 0 if failed.
*/
uintptr_t elf_find_sym_default(const char *sym_name);
/**
* @brief Override the internal symbol resolver.
*
* This override allows for an arbitrary implementation, enabling:
* - Dynamic symbol loading
* - Custom symbol resolution strategies
* - Symbol interception and hooking
*
* @param resolver The resolver function. Must not be NULL.
* To reset to default resolver, use elf_reset_symbol_resolver().
*
* @note This function is not thread-safe. Ensure proper synchronization
* when calling from multiple threads.
* @note The resolver function pointer must remain valid during its lifetime.
*
* @warning Calling this function affects all subsequent symbol resolutions
* globally. Use with caution.
*
* @example Example usage:
* ```c
* // Set custom resolver
* elf_set_symbol_resolver(my_custom_resolver);
*
* // Load and use ELF file
* esp_elf_t elf;
* esp_elf_load(&elf, elf_data);
*
* // Reset to default if needed
* elf_reset_symbol_resolver();
* ```
*/
void elf_set_symbol_resolver(symbol_resolver resolver);
/**
* @brief Reset the symbol resolver to the default (static tables from KConfig).
*
* Equivalent to elf_set_symbol_resolver(elf_find_sym_default).
*/
void elf_reset_symbol_resolver(void);
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,284 @@
/*
* SPDX-FileCopyrightText: 2023-2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <unistd.h>
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#include "sdkconfig.h"
#ifdef __cplusplus
extern "C" {
#endif
#define EI_NIDENT 16 /*!< Magic number and other information length */
/** @brief Type of segment */
#define PT_NULL 0 /*!< Program header table entry unused */
#define PT_LOAD 1 /*!< Loadable program segment */
#define PT_DYNAMIC 2 /*!< Dynamic linking information */
#define PT_INTERP 3 /*!< Program interpreter */
#define PT_NOTE 4 /*!< Auxiliary information */
#define PT_SHLIB 5 /*!< Reserved */
#define PT_PHDR 6 /*!< Entry for header table itself */
#define PT_TLS 7 /*!< Thread-local storage segment */
#define PT_NUM 8 /*!< Number of defined types */
#define PT_LOOS 0x60000000 /*!< Start of OS-specific */
#define PT_GNU_EH_FRAME 0x6474e550 /*!< GCC .eh_frame_hdr segment */
#define PT_GNU_STACK 0x6474e551 /*!< Indicates stack executability */
#define PT_GNU_RELRO 0x6474e552 /*!< Read-only after relocation */
#define PT_LOSUNW 0x6ffffffa
#define PT_SUNWBSS 0x6ffffffa /*!< Sun Specific segment */
#define PT_SUNWSTACK 0x6ffffffb /*!< Stack segment */
#define PT_HISUNW 0x6fffffff
#define PT_HIOS 0x6fffffff /*!< End of OS-specific */
#define PT_LOPROC 0x70000000 /*!< Start of processor-specific */
#define PT_HIPROC 0x7fffffff /*!< End of processor-specific */
/** @brief Section Type */
#define SHT_NULL 0 /*!< invalid section header */
#define SHT_PROGBITS 1 /*!< some useful section like .text, .data .got, .plt .rodata .interp and so on */
#define SHT_SYMTAB 2 /*!< symbol table */
#define SHT_STRTAB 3 /*!< string table */
#define SHT_RELA 4 /*!< relocation table */
#define SHT_HASH 5 /*!< HASH table */
#define SHT_SYNAMIC 6 /*!< dynamic symbol table */
#define SHT_NOTE 7 /*!< note information */
#define SHT_NOBITS 8 /*!< .bss */
#define SHT_REL 9 /*!< relocation table */
#define SHT_SHKIB 10 /*!< reserved but has unspecified semantics. */
#define SHT_SYNSYM 11 /*!< dynamic symbol */
#define SHT_LOPROC 0x70000000 /*!< reserved for processor-specific semantics */
#define SHT_LOUSER 0x7fffffff /*!< lower bound of the range of indexes reserved for application programs */
#define SHT_HIUSER 0xffffffff /*!< upper bound of the range of indexes reserved for application programs. */
/** @brief Section Attribute Flags */
#define SHF_WRITE 1 /*!< writable when task runs */
#define SHF_ALLOC 2 /*!< allocated when task runs */
#define SHF_EXECINSTR 4 /*!< machine code */
#define SHF_MASKPROG 0xf0000000 /*!< reserved for processor-specific semantics */
/** @brief Symbol Binding */
#define STB_LOCAL 0 /*!< Local symbols are not visible outside the object file containing their definition. */
#define STB_GLOBAL 1 /*!< Global symbols are visible to all object files being combined. */
#define STB_WEAK 2 /*!< Weak symbols resemble global symbols, but their definitions have lower precedence. */
#define STB_NUM 3 /*!< Number of defined types */
/** @brief Symbol Types */
#define STT_NOTYPE 0 /*!< symbol type is unspecified */
#define STT_OBJECT 1 /*!< data object */
#define STT_FUNC 2 /*!< code object */
#define STT_SECTION 3 /*!< symbol identifies an ELF section */
#define STT_FILE 4 /*!< symbol's name is file name */
#define STT_COMMON 5 /*!< common data object */
#define STT_TLS 6 /*!< thread-local data object */
#define STT_NUM 7 /*!< defined types in generic range */
#define STT_LOOS 10 /*!< Low OS specific range */
#define STT_HIOS 12 /*!< High OS specific range */
#define STT_LOPROC 13 /*!< processor specific range */
#define STT_HIPROC 15 /*!< processor specific link range */
/** @brief Special Section Indices */
#define SHN_UNDEF 0 /*!< undefined */
/** @brief Section names */
#define ELF_BSS ".bss" /*!< uninitialized data */
#define ELF_DATA ".data" /*!< initialized data */
#define ELF_DEBUG ".debug" /*!< debug */
#define ELF_DYNAMIC ".dynamic" /*!< dynamic linking information */
#define ELF_DYNSTR ".dynstr" /*!< dynamic string table */
#define ELF_DYNSYM ".dynsym" /*!< dynamic symbol table */
#define ELF_FINI ".fini" /*!< termination code */
#define ELF_GOT ".got" /*!< global offset table */
#define ELF_HASH ".hash" /*!< symbol hash table */
#define ELF_INIT ".init" /*!< initialization code */
#define ELF_REL_DATA ".rel.data" /*!< relocation data */
#define ELF_REL_FINI ".rel.fini" /*!< relocation termination code */
#define ELF_REL_INIT ".rel.init" /*!< relocation initialization code */
#define ELF_REL_DYN ".rel.dyn" /*!< relocaltion dynamic link info */
#define ELF_REL_RODATA ".rel.rodata" /*!< relocation read-only data */
#define ELF_REL_TEXT ".rel.text" /*!< relocation code */
#define ELF_RODATA ".rodata" /*!< read-only data */
#define ELF_SHSTRTAB ".shstrtab" /*!< section header string table */
#define ELF_STRTAB ".strtab" /*!< string table */
#define ELF_SYMTAB ".symtab" /*!< symbol table */
#define ELF_TEXT ".text" /*!< code */
#define ELF_DATA_REL_RO ".data.rel.ro" /*!< dynamic read-only data */
#define ELF_PLT ".plt" /*!< procedure linkage table. */
#define ELF_GOT_PLT ".got.plt" /*!< a table where resolved addresses from external functions are stored */
/* [patch p5] Plugin hot-function section (task T7 of poc-a-dynamic-elf,
* requirements 4.10.3/4.10.4): plugin code the manifest budgets into
* internal executable RAM. Parsed only on the BUS_ADDRESS_MIRROR path. */
#define ELF_IRAM ".plugin_iram" /*!< plugin IRAM-resident code */
/** @brief ELF section and symbol operation */
#define ELF_SEC_TEXT 0
#define ELF_SEC_BSS 1
#define ELF_SEC_DATA 2
#define ELF_SEC_RODATA 3
#define ELF_SEC_DRLRO 4
#define ELF_SEC_IRAM 5 /* [patch p5] */
#define ELF_SECS 6
#define ELF_ST_BIND(_i) ((_i) >> 4)
#define ELF_ST_TYPE(_i) ((_i) & 0xf)
#define ELF_ST_INFO(_b, _t) (((_b)<<4) + ((_t) & 0xf))
#define ELF_R_SYM(_i) ((_i) >> 8)
#define ELF_R_TYPE(_i) ((unsigned char)(_i))
#define ELF_R_INFO(_s, _t) (((_s) << 8) + (unsigned char)(_t))
#define ELF_SEC_MAP(_elf, _sec, _addr) \
((_elf)->sec[(_sec)].addr - \
(_elf)->sec[(_sec)].v_addr + \
(_addr))
typedef unsigned int Elf32_Addr;
typedef unsigned int Elf32_Off;
typedef unsigned int Elf32_Word;
typedef unsigned short Elf32_Half;
typedef int Elf32_Sword;
/** @brief ELF Header */
typedef struct elf32_hdr {
unsigned char ident[EI_NIDENT]; /*!< ELF Identification */
Elf32_Half type; /*!< object file type */
Elf32_Half machine; /*!< machine */
Elf32_Word version; /*!< object file version */
Elf32_Addr entry; /*!< virtual entry point */
Elf32_Off phoff; /*!< program header table offset */
Elf32_Off shoff; /*!< section header table offset */
Elf32_Word flags; /*!< processor-specific flags */
Elf32_Half ehsize; /*!< ELF header size */
Elf32_Half phentsize; /*!< program header entry size */
Elf32_Half phnum; /*!< number of program header entries */
Elf32_Half shentsize; /*!< section header entry size */
Elf32_Half shnum; /*!< number of section header entries */
Elf32_Half shstrndx; /*!< section header table's "section header string table" entry offset */
} elf32_hdr_t;
/** @brief Program Header */
typedef struct elf32_phdr {
Elf32_Word type; /* segment type */
Elf32_Off offset; /* segment offset */
Elf32_Addr vaddr; /* virtual address of segment */
Elf32_Addr paddr; /* physical address - ignored? */
Elf32_Word filesz; /* number of bytes in file for seg. */
Elf32_Word memsz; /* number of bytes in mem. for seg. */
Elf32_Word flags; /* flags */
Elf32_Word align; /* memory alignment */
} elf32_phdr_t;
/** @brief Section Header */
typedef struct elf32_shdr {
Elf32_Word name; /*!< section index and it is offset in section .shstrtab */
Elf32_Word type; /*!< type */
Elf32_Word flags; /*!< flags */
Elf32_Addr addr; /*!< start address when map to task space */
Elf32_Off offset; /*!< offset address from file start address */
Elf32_Word size; /*!< size */
Elf32_Word link; /*!< link to another section */
Elf32_Word info; /*!< additional section information */
Elf32_Word addralign; /*!< address align */
Elf32_Word entsize; /*!< index table size */
} elf32_shdr_t;
/** @brief Symbol Table Entry */
typedef struct elf32_sym {
Elf32_Word name; /*!< name - index into string table */
Elf32_Addr value; /*!< symbol value */
Elf32_Word size; /*!< symbol size */
unsigned char info; /*!< type and binding */
unsigned char other; /*!< 0 - no defined meaning */
Elf32_Half shndx; /*!< section header index */
} elf32_sym_t;
/** @brief Relocation entry with implicit addend */
typedef struct elf32_rel {
Elf32_Addr offset; /*!< offset of relocation */
Elf32_Word info; /*!< symbol table index and type */
} elf32_rel_t;
/** @brief Relocation entry with explicit addend */
typedef struct elf32_rela {
Elf32_Addr offset; /*!< offset of relocation */
Elf32_Word info; /*!< symbol table index and type */
Elf32_Sword addend; /*!< Added information */
} elf32_rela_t;
/** @brief ELF section object */
typedef struct esp_elf_sec {
uintptr_t v_addr; /*!< symbol virtual address */
off_t offset; /*!< offset in ELF */
uintptr_t addr; /*!< section physic address in memory */
size_t size; /*!< section size */
} esp_elf_sec_t;
typedef struct esp_symtab {
void *addr; /*!< symbol address */
char *name; /*!< symbol name */
} esp_symtab_t;
/** @brief ELF object */
typedef struct esp_elf {
#ifdef CONFIG_ELF_LOADER_BUS_ADDRESS_MIRROR
unsigned char *ptext; /*!< instruction buffer pointer */
unsigned char *pdata; /*!< data buffer pointer */
unsigned char *piram; /*!< [patch p5] .plugin_iram buffer (internal EXEC) */
#else
unsigned char *psegment; /*!< segment buffer pointer */
uint32_t svaddr; /*!< start virtual address of segment */
#endif
esp_elf_sec_t sec[ELF_SECS]; /*!< ".bss", "data", "rodata", ".text" */
int (*entry)(int argc, char *argv[]); /*!< Entry pointer of ELF */
/* [patch p5] Manifest-declared .plugin_iram budget (PLUG-009 / MEM
* 4.2.4): the caller copies iram_required_bytes from the verified mpb
* manifest view into this field between esp_elf_init() and
* esp_elf_relocate(); the load aborts with -EINVAL before any
* allocation unless it equals the section's measured sh_size. Zero
* (the esp_elf_init() reset) is the correct value for images without
* a .plugin_iram section. */
uint32_t iram_required_bytes;
#ifdef CONFIG_ELF_LOADER_SET_MMU
uint32_t text_off; /*!< .text symbol offset */
uint32_t mmu_off; /*!< MMU unit offset */
uint32_t mmu_num; /*!< MMU unit total number */
#endif
#ifdef CONFIG_ELF_DYNAMIC_LOAD_SHARED_OBJECT
uint16_t num; /*!< number of symbols in the dynamic object */
esp_symtab_t *symtab; /*!< symbol table of dynamic object pointer */
#endif
} esp_elf_t;
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,112 @@
/*
* SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/queue.h>
#include "private/elf_types.h"
#ifdef __cplusplus
extern "C" {
#endif
#define FILE_NAME_MAX 64
#define DLMOD_HANDLE_MAGIC 0x444C4D4FUL
/**
* @brief Module list entry used as a module handle.
*/
struct dlmod_slist_t {
uint32_t magic;
char name[FILE_NAME_MAX];
esp_elf_t *elf;
SLIST_ENTRY(dlmod_slist_t) next;
};
/**
* @brief Extract the base filename from a given path, removing directory and extension.
*
* @param path - Full path to the file
* @param filename - Buffer to store the extracted filename
* @param len - Length of the filename buffer
*
* @return Pointer to the filename buffer on success, NULL on invalid parameters or truncation.
*/
char *dlmod_getname(const char *path, char *filename, size_t len);
/**
* @brief Retrieve a module handle by name from the global module list.
*
* @param name - Name of the module to find (without .so extension)
*
* @return Pointer to the module handle if found, NULL if not found or invalid parameters.
*/
void *dlmod_gethandle(const char *name);
/**
* @brief Relocate and load an ELF file from the specified path.
*
* @param path - Filesystem path to the ELF binary
*
* @return Pointer to the relocated ELF structure (esp_elf_t), NULL on relocation failure.
*/
esp_elf_t *dlmod_relocate(const char *path);
/**
* @brief Insert a new module into the global module list.
*
* @param path - Filesystem path to the ELF binary
* @param name - Module name to register (should match filename base)
*
* @return Pointer to the new module entry (struct dlmod_slist_t), NULL on failure
* (existing entry or relocation error).
*/
struct dlmod_slist_t *dlmod_insert(const char *path, const char *name);
/**
* @brief Remove a module from the global module list and free resources.
*
* @param handle - Module handle to remove
*
* @return 0 on successful removal, -1 if handle not found.
*/
int dlmod_remove(void *handle);
/**
* @brief Validate a module handle returned by dlmod_insert() or dlmod_gethandle().
*
* @param handle - Module handle to validate
*
* @return true if the handle is a valid module entry, false otherwise.
*/
bool dlmod_validate_handle(struct dlmod_slist_t *handle);
/**
* @brief Find a symbol address by name across all loaded modules.
*
* @param sym_name - Symbol name to search for
*
* @return Memory address of the symbol if found, NULL otherwise.
*/
void *dlmod_getaddr(const char *sym_name);
/**
* @brief List all loaded module names in the system.
*/
void dlmod_listname(void);
/**
* @brief List all symbols from all loaded modules with their addresses.
*/
void dlmod_listsymbol(void);
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,14 @@
[sections:elf_loader_got_plt]
entries:
.got.plt
.got
[scheme:elf_loader_default]
entries:
elf_loader_got_plt -> flash_rodata
[mapping:elf_loader]
archive: *
entries:
* (elf_loader_default);
elf_loader_got_plt -> flash_rodata KEEP() SURROUND(_esp_elf_loader_got_plt)
@@ -0,0 +1,73 @@
set(PY_PATH ${CMAKE_CURRENT_LIST_DIR})
set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR} ${CMAKE_MODULE_PATH})
# elf_embed_binary
#
# Create a c file corresponding to ELF and embed into the application.
function(elf_embed_binary app_name app_path output_bin)
idf_build_get_property(idf_path IDF_PATH)
idf_build_get_property(idf_target IDF_TARGET)
idf_build_get_property(build_dir BUILD_DIR)
# Clean and set up external project paths
file(REMOVE ${app_path}/sdkconfig)
set(gen_dir "${build_dir}/generated/${app_name}")
file(MAKE_DIRECTORY ${gen_dir})
# Compile project files paths
set(elf_app_dir "${CMAKE_CURRENT_BINARY_DIR}/elf_${app_name}")
set(elf_file "${elf_app_dir}/${app_name}.app.elf")
set(elf_output_bin "${build_dir}/${output_bin}.bin")
# Script paths
set(symbols_script "${PY_PATH}/tool/symbols.py")
set(symbol_c_file "${gen_dir}/esp_${app_name}.c")
# Add external project (to generate ELF)
externalproject_add(${app_name}
SOURCE_DIR ${app_path}
INSTALL_COMMAND ""
CMAKE_ARGS
-DIDF_PATH=${idf_path}
-DIDF_TARGET=${idf_target}
-DSDKCONFIG=${app_path}/sdkconfig
BINARY_DIR ${elf_app_dir}
BUILD_BYPRODUCTS ${elf_file}
BUILD_ALWAYS 1
CMAKE_GENERATOR "Unix Makefiles"
BUILD_COMMAND make elf
)
# Binary file generation
add_custom_command(
OUTPUT ${elf_output_bin}
COMMAND ${CMAKE_COMMAND} -E copy ${elf_file} ${elf_output_bin}
DEPENDS ${app_name}
COMMENT "Generating BIN file"
)
# Symbol file generation
add_custom_command(
OUTPUT ${symbol_c_file}
COMMAND ${Python_EXECUTABLE} ${symbols_script}
--undefined
--input ${elf_file}
--type e
--output ${symbol_c_file}
--exclude elf_find_sym
DEPENDS ${app_name}
COMMENT "Generating ${app_name} symbol table"
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
)
# Combined build target
add_custom_target(${app_name}_generate ALL
DEPENDS ${symbol_c_file} ${elf_output_bin}
)
target_sources(${COMPONENT_LIB} PRIVATE ${symbol_c_file})
add_dependencies(${COMPONENT_LIB} ${app_name}_generate)
target_add_binary_data(${COMPONENT_LIB} ${elf_output_bin} BINARY)
endfunction()
@@ -0,0 +1,112 @@
/*
* SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <assert.h>
#include <sys/errno.h>
#include "esp_elf.h"
#include "esp_log.h"
#include "private/elf_platform.h"
/** @brief RISC-V relocations defined by the ABIs */
#define R_RISCV_NONE 0
#define R_RISCV_32 1
#define R_RISCV_64 2
#define R_RISCV_RELATIVE 3
#define R_RISCV_COPY 4
#define R_RISCV_JUMP_SLOT 5
#define R_RISCV_TLS_DTPMOD32 6
#define R_RISCV_TLS_DTPMOD64 7
#define R_RISCV_TLS_DTPREL32 8
#define R_RISCV_TLS_DTPREL64 9
#define R_RISCV_TLS_TPREL32 10
#define R_RISCV_TLS_TPREL64 11
#define R_RISCV_TLS_DESC 12
#define R_RISCV_BRANCH 16
#define R_RISCV_JAL 17
#define R_RISCV_CALL 18
#define R_RISCV_CALL_PLT 19
#define R_RISCV_GOT_HI20 20
#define R_RISCV_TLS_GOT_HI20 21
#define R_RISCV_TLS_GD_HI20 22
#define R_RISCV_PCREL_HI20 23
#define R_RISCV_PCREL_LO12_I 24
#define R_RISCV_PCREL_LO12_S 25
#define R_RISCV_HI20 26
#define R_RISCV_LO12_I 27
#define R_RISCV_LO12_S 28
#define R_RISCV_TPREL_HI20 29
#define R_RISCV_TPREL_LO12_I 30
#define R_RISCV_TPREL_LO12_S 31
#define R_RISCV_TPREL_ADD 32
#define R_RISCV_ADD8 33
#define R_RISCV_ADD16 34
#define R_RISCV_ADD32 35
#define R_RISCV_ADD64 36
#define R_RISCV_SUB8 37
#define R_RISCV_SUB16 38
#define R_RISCV_SUB32 39
#define R_RISCV_SUB64 40
#define R_RISCV_GNU_VTINHERIT 41
#define R_RISCV_GNU_VTENTRY 42
#define R_RISCV_ALIGN 43
#define R_RISCV_RVC_BRANCH 44
#define R_RISCV_RVC_JUMP 45
#define R_RISCV_RVC_LUI 46
#define R_RISCV_RELAX 51
#define R_RISCV_SUB6 52
#define R_RISCV_SET6 53
#define R_RISCV_SET8 54
#define R_RISCV_SET16 55
#define R_RISCV_SET32 56
#define R_RISCV_32_PCREL 57
#define R_RISCV_IRELATIVE 58
#define R_RISCV_PLT32 59
static const char *TAG = "elf_arch";
/**
* @brief Relocates target architecture symbol of ELF
*
* @param elf - ELF object pointer
* @param rela - Relocated symbol data
* @param sym - ELF symbol table
* @param addr - Jumping target address
*
* @return ESP_OK if success or other if failed.
*/
int esp_elf_arch_relocate(esp_elf_t *elf, const elf32_rela_t *rela,
const elf32_sym_t *sym, uint32_t addr)
{
uint32_t *where;
assert(elf && rela);
where = (uint32_t *)((uint8_t *)elf->psegment + rela->offset + elf->svaddr);
ESP_LOGD(TAG, "type: %d, where=%p addr=0x%x offset=0x%x",
ELF_R_TYPE(rela->info), where, (int)elf->psegment, (int)rela->offset);
/* Do relocation based on relocation type */
switch (ELF_R_TYPE(rela->info)) {
case R_RISCV_NONE:
break;
case R_RISCV_32:
*where = addr + rela->addend;
break;
case R_RISCV_RELATIVE:
*where = (Elf32_Addr)((uint8_t *)elf->psegment - elf->svaddr + rela->addend);
break;
case R_RISCV_JUMP_SLOT:
*where = addr;
break;
default:
ESP_LOGE(TAG, "info=%d is not supported\n", ELF_R_TYPE(rela->info));
return -EINVAL;
}
return 0;
}
@@ -0,0 +1,113 @@
/*
* SPDX-FileCopyrightText: 2023-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <assert.h>
#include <sys/errno.h>
#include "esp_elf.h"
#include "esp_log.h"
#include "private/elf_platform.h"
/** @brief Xtensa relocations defined by the ABIs */
#define R_XTENSA_NONE 0
#define R_XTENSA_32 1
#define R_XTENSA_RTLD 2
#define R_XTENSA_GLOB_DAT 3
#define R_XTENSA_JMP_SLOT 4
#define R_XTENSA_RELATIVE 5
#define R_XTENSA_PLT 6
#define R_XTENSA_OP0 8
#define R_XTENSA_OP1 9
#define R_XTENSA_OP2 10
#define R_XTENSA_ASM_EXPAND 11
#define R_XTENSA_ASM_SIMPLIFY 12
#define R_XTENSA_GNU_VTINHERIT 15
#define R_XTENSA_GNU_VTENTRY 16
#define R_XTENSA_DIFF8 17
#define R_XTENSA_DIFF16 18
#define R_XTENSA_DIFF32 19
#define R_XTENSA_SLOT0_OP 20
#define R_XTENSA_SLOT1_OP 21
#define R_XTENSA_SLOT2_OP 22
#define R_XTENSA_SLOT3_OP 23
#define R_XTENSA_SLOT4_OP 24
#define R_XTENSA_SLOT5_OP 25
#define R_XTENSA_SLOT6_OP 26
#define R_XTENSA_SLOT7_OP 27
#define R_XTENSA_SLOT8_OP 28
#define R_XTENSA_SLOT9_OP 29
#define R_XTENSA_SLOT10_OP 30
#define R_XTENSA_SLOT11_OP 31
#define R_XTENSA_SLOT12_OP 32
#define R_XTENSA_SLOT13_OP 33
#define R_XTENSA_SLOT14_OP 34
#define R_XTENSA_SLOT0_ALT 35
#define R_XTENSA_SLOT1_ALT 36
#define R_XTENSA_SLOT2_ALT 37
#define R_XTENSA_SLOT3_ALT 38
#define R_XTENSA_SLOT4_ALT 39
#define R_XTENSA_SLOT5_ALT 40
#define R_XTENSA_SLOT6_ALT 41
#define R_XTENSA_SLOT7_ALT 42
#define R_XTENSA_SLOT8_ALT 43
#define R_XTENSA_SLOT9_ALT 44
#define R_XTENSA_SLOT10_ALT 45
#define R_XTENSA_SLOT11_ALT 46
#define R_XTENSA_SLOT12_ALT 47
#define R_XTENSA_SLOT13_ALT 48
#define R_XTENSA_SLOT14_ALT 49
static const char *TAG = "elf_arch";
/**
* @brief Relocates target architecture symbol of ELF
*
* @param elf - ELF object pointer
* @param rela - Relocated symbol data
* @param sym - ELF symbol table
* @param addr - Jumping target address
*
* @return ESP_OK if success or other if failed.
*/
int esp_elf_arch_relocate(esp_elf_t *elf, const elf32_rela_t *rela,
const elf32_sym_t *sym, uint32_t addr)
{
uint32_t val;
uint32_t *where;
assert(elf && rela);
where = (uint32_t *)esp_elf_map_sym(elf, rela->offset);
ESP_LOGD(TAG, "type: %d, where=%p addr=0x%x offset=0x%x\n",
ELF_R_TYPE(rela->info), where, (int)addr, (int)rela->offset);
switch (ELF_R_TYPE(rela->info)) {
case R_XTENSA_RELATIVE:
val = esp_elf_map_sym(elf, *where);
#ifdef CONFIG_ELF_LOADER_CACHE_OFFSET
*where = elf_remap_text(elf, val);
#else
*where = val;
#endif
break;
case R_XTENSA_RTLD:
break;
case R_XTENSA_GLOB_DAT:
case R_XTENSA_JMP_SLOT:
#ifdef CONFIG_ELF_LOADER_CACHE_OFFSET
*where = elf_remap_text(elf, addr);
#else
*where = addr;
#endif
break;
default:
ESP_LOGE(TAG, "info=%d is not supported", ELF_R_TYPE(rela->info));
return -EINVAL;
}
return 0;
}
@@ -0,0 +1,238 @@
/*
* SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <string.h>
#include <stdbool.h>
#include <stddef.h>
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "esp_log.h"
#include "esp_dlfcn.h"
#include "private/esp_dlmod.h"
#include "private/elf_platform.h"
static const char *TAG = "DLFCN";
#define DL_ERROR_MSG_MAX_LEN 128
static char g_dlerror_msg[DL_ERROR_MSG_MAX_LEN] = {0};
static bool g_dlerror_set = false;
/**
* @brief Initialize the mutex for thread-safe error state access
* @note Uses static allocation to avoid race conditions
*/
static StaticSemaphore_t g_dlerror_mutex_buffer;
static SemaphoreHandle_t g_dlerror_mutex = NULL;
__attribute__((constructor))
static void dlerror_mutex_init(void)
{
if (g_dlerror_mutex == NULL) {
g_dlerror_mutex = xSemaphoreCreateMutexStatic(&g_dlerror_mutex_buffer);
if (g_dlerror_mutex == NULL) {
ESP_LOGE(TAG, "Failed to create mutex for dlerror");
}
}
}
/**
* @brief Set error message for dlerror()
*/
static void dlerror_set(const char *msg)
{
dlerror_mutex_init();
if (g_dlerror_mutex == NULL) {
// If mutex creation failed, still try to set error (best effort)
if (msg) {
strncpy(g_dlerror_msg, msg, DL_ERROR_MSG_MAX_LEN - 1);
g_dlerror_msg[DL_ERROR_MSG_MAX_LEN - 1] = '\0';
g_dlerror_set = true;
} else {
g_dlerror_set = false;
g_dlerror_msg[0] = '\0';
}
return;
}
if (xSemaphoreTake(g_dlerror_mutex, portMAX_DELAY) != pdTRUE) {
ESP_LOGE(TAG, "Failed to take dlerror mutex");
return;
}
if (msg) {
strncpy(g_dlerror_msg, msg, DL_ERROR_MSG_MAX_LEN - 1);
g_dlerror_msg[DL_ERROR_MSG_MAX_LEN - 1] = '\0';
g_dlerror_set = true;
} else {
g_dlerror_set = false;
g_dlerror_msg[0] = '\0';
}
xSemaphoreGive(g_dlerror_mutex);
}
/**
* @brief Dynamic loader compatibility interface - Get error message.
*
* @note Thread safety: The returned pointer points to a static buffer that
* may be overwritten by subsequent calls to dl* functions from any
* thread. Callers should copy the string immediately if needed.
*
* @return Pointer to error message string, or NULL if no error occurred.
*/
const char *dlerror(void)
{
dlerror_mutex_init();
if (g_dlerror_mutex == NULL) {
// If mutex creation failed, still try to read error (best effort)
if (g_dlerror_set) {
g_dlerror_set = false;
return g_dlerror_msg;
}
return NULL;
}
if (xSemaphoreTake(g_dlerror_mutex, portMAX_DELAY) != pdTRUE) {
ESP_LOGE(TAG, "Failed to take dlerror mutex");
return NULL;
}
const char *result = NULL;
if (g_dlerror_set) {
g_dlerror_set = false;
result = g_dlerror_msg;
}
xSemaphoreGive(g_dlerror_mutex);
return result;
}
/**
* @brief Dynamic loader compatibility interface - Load a shared object.
*
* @param file - Filesystem path to the ELF binary
* @param mode - Mode flags (RTLD_LAZY, RTLD_NOW, etc.)
*
* @return Module handle on success, NULL on failure.
*/
void *dlopen(const char *file, int mode)
{
(void)mode; // TODO: The current implementation ignores the mode flag.
if (!file) {
dlerror_set("Invalid NULL file path");
return NULL;
}
char filename[FILE_NAME_MAX] = {0};
if (!dlmod_getname(file, filename, FILE_NAME_MAX)) {
dlerror_set("Failed to extract filename from path");
return NULL;
}
void *handle = dlmod_insert(file, filename);
if (!handle) {
dlerror_set("Failed to load module");
return NULL;
}
dlerror_set(NULL); // Clear error on success
return handle;
}
/**
* @brief Dynamic loader compatibility interface - Close a module handle.
*
* @param handle - Module handle to close
*
* @return 0 on success, -1 on invalid handle.
*/
int dlclose(void *handle)
{
if (!handle) {
dlerror_set("Invalid NULL handle");
return -1;
}
if (!dlmod_validate_handle(handle)) {
dlerror_set("Invalid module handle");
return -1;
}
int ret = dlmod_remove(handle);
if (ret != 0) {
dlerror_set("Failed to close module");
return -1;
}
dlerror_set(NULL); // Clear error on success
return 0;
}
/**
* @brief Dynamic loader compatibility interface - Look up symbol address.
*
* @param handle - Module handle from dlopen()
* @param name - Symbol name to locate
*
* @return Memory address of the symbol if found, NULL otherwise.
*/
void *dlsym(void *handle, const char *name)
{
if (!handle) {
dlerror_set("Invalid NULL handle");
return NULL;
}
if (!dlmod_validate_handle(handle)) {
dlerror_set("Invalid module handle");
return NULL;
}
if (!name) {
dlerror_set("Invalid NULL symbol name");
return NULL;
}
struct dlmod_slist_t *mod = (struct dlmod_slist_t *)handle;
if (!mod->elf || !mod->elf->symtab) {
dlerror_set("Module has no symbol table");
return NULL;
}
if (mod->elf->num > 0) {
for (size_t i = 0; i < mod->elf->num; i++) {
if (mod->elf->symtab[i].name &&
strcmp(mod->elf->symtab[i].name, name) == 0) {
dlerror_set(NULL); // Clear error on success
return mod->elf->symtab[i].addr;
}
}
}
dlerror_set("Symbol not found");
return NULL;
}
/**
* @brief Display system module/symbol information.
*
* @param type - Listing type (LIST_MODULE for modules, LIST_SYMBOL for symbols)
*/
void dllist(dl_list_t type)
{
if (type == LIST_MODULE) {
dlmod_listname();
} else if (type == LIST_SYMBOL) {
dlmod_listsymbol();
} else {
ESP_LOGW(TAG, "Unknown list type: %d", type);
}
}
@@ -0,0 +1,455 @@
/*
* SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "esp_elf.h"
#include "esp_log.h"
#include "esp_dlfcn.h"
#include "private/esp_dlmod.h"
#include "private/elf_platform.h"
static const char *TAG = "DLMOD";
typedef SLIST_HEAD(dlmod_slist_head, dlmod_slist_t) dlmod_slist_head_t;
static dlmod_slist_head_t g_dlmod_slist_head = SLIST_HEAD_INITIALIZER(g_dlmod_slist_head);
static StaticSemaphore_t g_dlmod_mutex_buffer;
static SemaphoreHandle_t g_dlmod_mutex = NULL;
static portMUX_TYPE g_dlmod_mutex_init_lock = portMUX_INITIALIZER_UNLOCKED;
static void dlmod_mutex_init(void)
{
taskENTER_CRITICAL(&g_dlmod_mutex_init_lock);
if (g_dlmod_mutex == NULL) {
g_dlmod_mutex = xSemaphoreCreateMutexStatic(&g_dlmod_mutex_buffer);
if (g_dlmod_mutex == NULL) {
ESP_LOGE(TAG, "Failed to create mutex for dlmod");
}
}
taskEXIT_CRITICAL(&g_dlmod_mutex_init_lock);
}
bool dlmod_validate_handle(struct dlmod_slist_t *handle)
{
if (!handle) {
return false;
}
dlmod_mutex_init();
if (g_dlmod_mutex == NULL) {
return false;
}
if (xSemaphoreTake(g_dlmod_mutex, portMAX_DELAY) != pdTRUE) {
return false;
}
bool valid = false;
struct dlmod_slist_t *current;
SLIST_FOREACH(current, &g_dlmod_slist_head, next) {
if (current == handle && current->magic == DLMOD_HANDLE_MAGIC) {
valid = true;
break;
}
}
xSemaphoreGive(g_dlmod_mutex);
return valid;
}
/**
* @brief Extract the base filename from a given path, removing directory and extension.
*
* @param path - Full path to the file
* @param filename - Buffer to store the extracted filename
* @param len - Length of the filename buffer
*
* @return Pointer to the filename buffer on success, NULL on invalid parameters or truncation.
*/
char *dlmod_getname(const char *path, char *filename, size_t len)
{
if (!path || path[0] == '\0' || !filename || len == 0) {
return NULL;
}
const char *filename_start = strrchr(path, '/');
if (filename_start == NULL) {
filename_start = path;
} else {
filename_start++;
}
const char *extension_start = strrchr(filename_start, '.');
size_t filename_len = (extension_start ? extension_start - filename_start : strlen(filename_start));
if (filename_len >= len) {
return NULL;
}
strncpy(filename, filename_start, filename_len);
filename[filename_len] = '\0';
if (filename[0] == '\0') {
return NULL;
}
return filename;
}
/**
* @brief Retrieve a module handle by name from the global module list.
*
* @param name - Name of the module to find (without .so extension)
*
* @return Pointer to the module handle if found, NULL if not found or invalid parameters.
*/
void *dlmod_gethandle(const char *name)
{
if (!name || name[0] == '\0') {
return NULL;
}
dlmod_mutex_init();
if (g_dlmod_mutex == NULL) {
return NULL;
}
if (xSemaphoreTake(g_dlmod_mutex, portMAX_DELAY) != pdTRUE) {
return NULL;
}
void *result = NULL;
if (SLIST_EMPTY(&g_dlmod_slist_head)) {
ESP_LOGD(TAG, "The list is empty, no module found.");
} else {
struct dlmod_slist_t *current;
SLIST_FOREACH(current, &g_dlmod_slist_head, next) {
if (strcmp(current->name, name) == 0) {
result = current;
break;
}
}
}
xSemaphoreGive(g_dlmod_mutex);
return result;
}
/**
* @brief List all loaded module names in the system.
*/
void dlmod_listname(void)
{
dlmod_mutex_init();
if (g_dlmod_mutex == NULL) {
return;
}
if (xSemaphoreTake(g_dlmod_mutex, portMAX_DELAY) != pdTRUE) {
return;
}
if (SLIST_EMPTY(&g_dlmod_slist_head)) {
ESP_LOGI(TAG, "No shared objects loaded");
} else {
struct dlmod_slist_t *current;
ESP_LOGI(TAG, "Shared objects in the list:");
SLIST_FOREACH(current, &g_dlmod_slist_head, next) {
ESP_LOGI(TAG, "%s.so", current->name);
}
}
xSemaphoreGive(g_dlmod_mutex);
}
/**
* @brief List all symbols from all loaded modules with their addresses.
*/
void dlmod_listsymbol(void)
{
dlmod_mutex_init();
if (g_dlmod_mutex == NULL) {
return;
}
if (xSemaphoreTake(g_dlmod_mutex, portMAX_DELAY) != pdTRUE) {
return;
}
if (SLIST_EMPTY(&g_dlmod_slist_head)) {
ESP_LOGI(TAG, "Symbols table is empty");
} else {
struct dlmod_slist_t *current;
char *name;
ESP_LOGI(TAG, "Shared objects symbols table in the list:");
SLIST_FOREACH(current, &g_dlmod_slist_head, next) {
if (current->elf && current->elf->symtab && current->elf->num) {
for (uint16_t i = 0; i < current->elf->num; i++) {
name = current->elf->symtab[i].name;
ESP_LOGI(TAG, "%s, addr: %p", name ? name : "(null)",
current->elf->symtab[i].addr);
}
}
}
}
xSemaphoreGive(g_dlmod_mutex);
}
/**
* @brief Relocate and load an ELF file from the specified path.
*
* @param path - Filesystem path to the ELF binary
*
* @return Pointer to the relocated ELF structure (esp_elf_t), NULL on relocation failure.
*/
esp_elf_t *dlmod_relocate(const char *path)
{
if (!path || path[0] == '\0') {
return NULL;
}
int ret;
elf_file_t file;
ret = esp_elf_open(&file, path);
if (ret < 0) {
ESP_LOGE(TAG, "Failed to open file %s", path);
return NULL;
}
ESP_LOGD(TAG, "Open file:%s, len=%d", path, file.size);
esp_elf_t *elf_dl = (esp_elf_t *)esp_elf_malloc(sizeof(esp_elf_t), false);
if (!elf_dl) {
ESP_LOGE(TAG, "Failed to allocate memory for ELF");
esp_elf_close(&file);
return NULL;
}
ret = esp_elf_init(elf_dl);
if (ret < 0) {
ESP_LOGE(TAG, "Failed to initialize ELF file errno=%d", ret);
esp_elf_free(elf_dl);
esp_elf_close(&file);
return NULL;
}
ret = esp_elf_relocate(elf_dl, file.payload);
if (ret < 0) {
ESP_LOGE(TAG, "Failed to relocate ELF file errno=%d", ret);
esp_elf_deinit(elf_dl);
esp_elf_free(elf_dl);
esp_elf_close(&file);
return NULL;
}
esp_elf_close(&file);
return elf_dl;
}
/**
* @brief Insert a new module into the global module list.
*
* @param path - Filesystem path to the ELF binary
* @param name - Module name to register (should match filename base)
*
* @return Pointer to the new module entry (struct dlmod_slist_t), NULL on failure
* (existing entry or relocation error).
*/
struct dlmod_slist_t *dlmod_insert(const char *path, const char *name)
{
if (!path || path[0] == '\0' || !name || name[0] == '\0') {
return NULL;
}
dlmod_mutex_init();
if (g_dlmod_mutex == NULL) {
return NULL;
}
// Check if module already exists (with mutex protection)
if (xSemaphoreTake(g_dlmod_mutex, portMAX_DELAY) != pdTRUE) {
return NULL;
}
if (!SLIST_EMPTY(&g_dlmod_slist_head)) {
struct dlmod_slist_t *current;
SLIST_FOREACH(current, &g_dlmod_slist_head, next) {
if (strcmp(current->name, name) == 0) {
ESP_LOGD(TAG, "%s.so has been dynamically loaded", name);
xSemaphoreGive(g_dlmod_mutex);
return current;
}
}
}
xSemaphoreGive(g_dlmod_mutex);
// Module doesn't exist, create new one (without mutex - these are not list operations)
struct dlmod_slist_t *new_node;
new_node = esp_elf_malloc(sizeof(struct dlmod_slist_t), false);
if (!new_node) {
ESP_LOGE(TAG, "Failed to allocate memory for new node");
return NULL;
}
new_node->magic = DLMOD_HANDLE_MAGIC;
strncpy(new_node->name, name, FILE_NAME_MAX - 1);
new_node->name[FILE_NAME_MAX - 1] = '\0';
new_node->elf = dlmod_relocate(path);
if (!new_node->elf) {
ESP_LOGE(TAG, "Failed to relocate");
esp_elf_free(new_node);
return NULL;
}
// Insert into list (with mutex protection)
if (xSemaphoreTake(g_dlmod_mutex, portMAX_DELAY) != pdTRUE) {
esp_elf_deinit(new_node->elf);
esp_elf_free(new_node->elf);
esp_elf_free(new_node);
return NULL;
}
// Re-check if module was inserted by another thread
struct dlmod_slist_t *existing;
SLIST_FOREACH(existing, &g_dlmod_slist_head, next) {
if (strcmp(existing->name, name) == 0) {
ESP_LOGD(TAG, "%s.so already loaded by another thread", name);
xSemaphoreGive(g_dlmod_mutex);
esp_elf_deinit(new_node->elf);
esp_elf_free(new_node->elf);
esp_elf_free(new_node);
return existing;
}
}
SLIST_INSERT_HEAD(&g_dlmod_slist_head, new_node, next);
xSemaphoreGive(g_dlmod_mutex);
return new_node;
}
/**
* @brief Remove a module from the global module list and free resources.
*
* @param handle - Module handle to remove
*
* @return 0 on successful removal, -1 if handle not found.
*/
int dlmod_remove(void *handle)
{
if (!handle) {
return -1;
}
dlmod_mutex_init();
if (g_dlmod_mutex == NULL) {
return -1;
}
if (xSemaphoreTake(g_dlmod_mutex, portMAX_DELAY) != pdTRUE) {
return -1;
}
// Find and remove from list (with mutex protection)
struct dlmod_slist_t *mod = (struct dlmod_slist_t *)handle;
struct dlmod_slist_t *current;
struct dlmod_slist_t *prev = NULL;
int ret = -1;
current = SLIST_FIRST(&g_dlmod_slist_head);
while (current != NULL) {
if (current == handle) {
if (current->magic != DLMOD_HANDLE_MAGIC) {
break;
}
if (prev == NULL) {
SLIST_REMOVE_HEAD(&g_dlmod_slist_head, next);
} else {
SLIST_REMOVE(&g_dlmod_slist_head, current, dlmod_slist_t, next);
}
ESP_LOGI(TAG, "Removed node with name: %s.so", current->name);
ret = 0;
break;
}
prev = current;
current = SLIST_NEXT(current, next);
}
if (ret != 0) {
ESP_LOGD(TAG, "Node not found in the list");
}
xSemaphoreGive(g_dlmod_mutex);
// Free resources (without mutex - not a list operation)
if (ret == 0 && mod && mod->elf) {
esp_elf_deinit(mod->elf);
esp_elf_free(mod->elf);
}
if (ret == 0) {
mod->magic = 0;
esp_elf_free(mod);
}
return ret;
}
/**
* @brief Find a symbol address by name across all loaded modules.
*
* @param sym_name - Symbol name to search for
*
* @return Memory address of the symbol if found, NULL otherwise.
*/
void *dlmod_getaddr(const char *sym_name)
{
if (!sym_name || sym_name[0] == '\0') {
return NULL;
}
dlmod_mutex_init();
if (g_dlmod_mutex == NULL) {
return NULL;
}
if (xSemaphoreTake(g_dlmod_mutex, portMAX_DELAY) != pdTRUE) {
return NULL;
}
void *result = NULL;
struct dlmod_slist_t *current;
SLIST_FOREACH(current, &g_dlmod_slist_head, next) {
if (current->elf && current->elf->symtab && current->elf->num) {
for (uint16_t i = 0; i < current->elf->num; i++) {
const char *name = current->elf->symtab[i].name;
if (name && strcmp(name, sym_name) == 0) {
ESP_LOGD(TAG, "Found node with sym_name: %s, addr: %p",
sym_name, current->elf->symtab[i].addr);
result = current->elf->symtab[i].addr;
break;
}
}
if (result != NULL) {
break;
}
}
}
if (result == NULL) {
ESP_LOGD(TAG, "Node with elf name '%s' not found", sym_name);
}
xSemaphoreGive(g_dlmod_mutex);
return result;
}
@@ -0,0 +1,21 @@
/*
* SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stddef.h>
#include "private/elf_symbol.h"
/* Extern declarations from ELF symbol table */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wbuiltin-declaration-mismatch"
#pragma GCC diagnostic pop
/* Available ELF symbols table: g_customer_elfsyms */
const struct esp_elfsym g_customer_elfsyms[] = {
ESP_ELFSYM_END
};
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,165 @@
/*
* SPDX-FileCopyrightText: 2023-2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <assert.h>
#include <sys/errno.h>
#include "esp_idf_version.h"
#include "esp_attr.h"
#include "esp_heap_caps.h"
#include "soc/soc.h"
#if CONFIG_IDF_TARGET_ESP32S31
#include "esp32s31/rom/cache.h"
#include "soc/cache_reg.h"
#endif
#include "private/elf_platform.h"
#ifdef CONFIG_ELF_LOADER_LOAD_PSRAM
#ifdef CONFIG_IDF_TARGET_ESP32S3
#define OFFSET_TEXT_VALUE (SOC_IROM_LOW - SOC_DROM_LOW)
#endif
#endif
/**
* @brief Allocate block of memory.
*
* @param n - Memory size in byte
* @param exec - True: memory can run executable code; False: memory can R/W data
*
* @return Memory pointer if success or NULL if failed.
*/
void *esp_elf_malloc(uint32_t n, bool exec)
{
uint32_t caps;
#if CONFIG_ELF_LOADER_BUS_ADDRESS_MIRROR
#ifdef CONFIG_ELF_LOADER_LOAD_PSRAM
caps = MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT;
#else
#ifdef MALLOC_CAP_EXEC
caps = exec ? MALLOC_CAP_EXEC : MALLOC_CAP_8BIT;
#else
caps = MALLOC_CAP_8BIT | MALLOC_CAP_32BIT;
#endif
#endif
#else
#ifdef CONFIG_ELF_LOADER_LOAD_PSRAM
caps = MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT;
#else
caps = MALLOC_CAP_8BIT;
#endif
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
caps |= MALLOC_CAP_CACHE_ALIGNED;
#endif
#endif
return heap_caps_malloc(n, caps);
}
/**
* @brief Free block of memory.
*
* @param ptr - memory block pointer allocated by "esp_elf_malloc"
*
* @return None
*/
void esp_elf_free(void *ptr)
{
heap_caps_free(ptr);
}
/* [patch p5] Internal-EXEC allocation for the .plugin_iram section copy
* (task T7). Mirrors the adapter's own internal-exec selection used when
* PSRAM loading is disabled (esp_elf_malloc()'s exec branch): explicit
* EXEC|INTERNAL caps, so the section copy lands in the native IRAM
* execution window (0x4037_0000..0x403E_0000 on ESP32-S3) instead of the
* PSRAM data window. MALLOC_CAP_EXEC exists only when the IDF exec heap is
* available (CONFIG_HEAP_HAS_EXEC_HEAP, i.e. CONFIG_ESP_SYSTEM_MEMPROT=n;
* the IDF Kconfig help states EXEC allocation is impossible under memory
* protection), EXEC cannot be combined with 8BIT/DMA, and heap_caps
* transparently returns the IRAM-alias pointer with a stash word that
* heap_caps_free() unconverts - so esp_elf_free() stays correct. Fail
* closed (NULL) when the exec heap is not configured. */
void *esp_elf_malloc_iram(uint32_t n)
{
#ifdef MALLOC_CAP_EXEC
return heap_caps_malloc(n, MALLOC_CAP_EXEC | MALLOC_CAP_INTERNAL);
#else
ESP_LOGE("elf_adapter", "MALLOC_CAP_EXEC unavailable (enable by setting "
"CONFIG_ESP_SYSTEM_MEMPROT=n); cannot load .plugin_iram");
return NULL;
#endif
}
/**
* @brief Remap symbol from ".data" to ".text" section.
*
* @param elf - ELF object pointer
* @param sym - ELF symbol table
*
* @return Remapped symbol value
*/
#ifdef CONFIG_ELF_LOADER_CACHE_OFFSET
uintptr_t elf_remap_text(esp_elf_t *elf, uintptr_t sym)
{
uintptr_t mapped_sym;
esp_elf_sec_t *sec = &elf->sec[ELF_SEC_TEXT];
if ((sym >= sec->addr) &&
(sym < (sec->addr + sec->size))) {
#ifdef CONFIG_ELF_LOADER_SET_MMU
mapped_sym = sym + elf->text_off;
#else
mapped_sym = sym + OFFSET_TEXT_VALUE;
#endif
} else {
mapped_sym = sym;
}
return mapped_sym;
}
#endif
/**
* @brief Flush data from cache to external RAM.
*
* @param None
*
* @return None
*/
#ifdef CONFIG_ELF_LOADER_LOAD_PSRAM
void IRAM_ATTR esp_elf_arch_flush(void)
{
extern void spi_flash_disable_interrupts_caches_and_other_cpu(void);
extern void spi_flash_enable_interrupts_caches_and_other_cpu(void);
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)
#if CONFIG_IDF_TARGET_ESP32S31
/* ESP32-S31: Ranged cache APIs (Cache_WriteBack_Addr/Cache_Invalidate_Addr)
* cause intermittent Instruction access faults (MCAUSE=0x01,
* MEPC=0x00000000) during long-term ELF execution from PSRAM, likely
* related to unaligned addr/size (e.g. seg_size=0x136a8, cache_line=64B).
* Use full D-writeback + I-invalidate like other targets. */
Cache_WriteBack_All(CACHE_MAP_L1_DCACHE);
spi_flash_disable_interrupts_caches_and_other_cpu();
Cache_Invalidate_All(CACHE_MAP_L1_ICACHE_MASK);
spi_flash_enable_interrupts_caches_and_other_cpu();
REG_CLR_BIT(CACHE_L1_ICACHE_CTRL_REG, CACHE_L1_ICACHE_SHUT_IBUS1);
#else
extern void Cache_WriteBack_All(void);
Cache_WriteBack_All();
spi_flash_disable_interrupts_caches_and_other_cpu();
spi_flash_enable_interrupts_caches_and_other_cpu();
#endif
#else
void esp_spiram_writeback_cache(void);
esp_spiram_writeback_cache();
spi_flash_disable_interrupts_caches_and_other_cpu();
spi_flash_enable_interrupts_caches_and_other_cpu();
#endif
}
#endif
@@ -0,0 +1,262 @@
/*
* SPDX-FileCopyrightText: 2023-2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <reent.h>
#include <errno.h>
#include <pthread.h>
#include <setjmp.h>
#include <getopt.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <ctype.h>
#if CONFIG_LIBC_PICOLIBC
/*
* picolibc compatibility wrappers.
*
* In picolibc:
* - __errno is not a function (errno is a _Thread_local int variable).
* - __getreent() is a macro defined as NULL by ESP-IDF platform reent.h.
* - _ctype_ is a macro (_ctype_b + _CTYPE_OFFSET) in ctype.h; picolibc
* exports the underlying _ctype_b[384] table. Newlib-built ELFs resolve
* _ctype_ and index it as (_ctype_ + 1)[c]; _CTYPE_OFFSET is 127.
*/
static int *s_picolibc_errno_func(void)
{
return &errno;
}
static struct _reent *s_picolibc_getreent_func(void)
{
return NULL;
}
extern const char _ctype_b[];
#ifndef _CTYPE_OFFSET
#define _CTYPE_OFFSET 127
#endif
static const char * const s_picolibc_ctype_tbl = _ctype_b + _CTYPE_OFFSET;
#endif /* CONFIG_LIBC_PICOLIBC */
#include "rom/ets_sys.h"
#include "esp_log.h"
#include "esp_elf.h"
#if CONFIG_ELF_DYNAMIC_LOAD_SHARED_OBJECT
#include "private/esp_dlmod.h"
#endif
#include "private/elf_symbol.h"
extern int __ltdf2(double a, double b);
extern unsigned int __fixunsdfsi(double a);
extern int __gtdf2(double a, double b);
extern double __floatunsidf(unsigned int i);
extern double __divdf3(double a, double b);
static const char *TAG = "ELF_SYMBOL";
/** @brief Libc public functions symbols look-up table */
static const struct esp_elfsym g_esp_libc_elfsyms[] = {
/* string.h */
ESP_ELFSYM_EXPORT(strerror),
ESP_ELFSYM_EXPORT(memset),
ESP_ELFSYM_EXPORT(memcpy),
ESP_ELFSYM_EXPORT(strlen),
ESP_ELFSYM_EXPORT(strtod),
ESP_ELFSYM_EXPORT(strrchr),
ESP_ELFSYM_EXPORT(strchr),
ESP_ELFSYM_EXPORT(strcmp),
ESP_ELFSYM_EXPORT(strtol),
ESP_ELFSYM_EXPORT(strcspn),
ESP_ELFSYM_EXPORT(strncat),
/* stdio.h */
ESP_ELFSYM_EXPORT(puts),
ESP_ELFSYM_EXPORT(putchar),
ESP_ELFSYM_EXPORT(fputc),
ESP_ELFSYM_EXPORT(fputs),
ESP_ELFSYM_EXPORT(printf),
ESP_ELFSYM_EXPORT(vfprintf),
ESP_ELFSYM_EXPORT(fprintf),
ESP_ELFSYM_EXPORT(fwrite),
/* unistd.h */
ESP_ELFSYM_EXPORT(usleep),
ESP_ELFSYM_EXPORT(sleep),
ESP_ELFSYM_EXPORT(exit),
ESP_ELFSYM_EXPORT(close),
/* stdlib.h */
ESP_ELFSYM_EXPORT(malloc),
ESP_ELFSYM_EXPORT(calloc),
ESP_ELFSYM_EXPORT(realloc),
ESP_ELFSYM_EXPORT(free),
/* time.h */
ESP_ELFSYM_EXPORT(clock_gettime),
ESP_ELFSYM_EXPORT(strftime),
/* pthread.h */
ESP_ELFSYM_EXPORT(pthread_create),
ESP_ELFSYM_EXPORT(pthread_attr_init),
ESP_ELFSYM_EXPORT(pthread_attr_setstacksize),
ESP_ELFSYM_EXPORT(pthread_detach),
ESP_ELFSYM_EXPORT(pthread_join),
ESP_ELFSYM_EXPORT(pthread_exit),
/* libc (newlib / picolibc) */
#if CONFIG_LIBC_PICOLIBC
{ "__errno", (void*)s_picolibc_errno_func },
{ "__getreent", (void*)s_picolibc_getreent_func },
{ "_ctype_", (void*)s_picolibc_ctype_tbl },
#elif defined(__HAVE_LOCALE_INFO__) && __HAVE_LOCALE_INFO__
ESP_ELFSYM_EXPORT(__errno),
ESP_ELFSYM_EXPORT(__getreent),
ESP_ELFSYM_EXPORT(__locale_ctype_ptr),
#else
ESP_ELFSYM_EXPORT(__errno),
ESP_ELFSYM_EXPORT(__getreent),
ESP_ELFSYM_EXPORT(_ctype_),
#endif
/* math */
ESP_ELFSYM_EXPORT(__ltdf2),
ESP_ELFSYM_EXPORT(__fixunsdfsi),
ESP_ELFSYM_EXPORT(__gtdf2),
ESP_ELFSYM_EXPORT(__floatunsidf),
ESP_ELFSYM_EXPORT(__divdf3),
/* getopt.h */
ESP_ELFSYM_EXPORT(getopt_long),
ESP_ELFSYM_EXPORT(optind),
ESP_ELFSYM_EXPORT(opterr),
ESP_ELFSYM_EXPORT(optarg),
ESP_ELFSYM_EXPORT(optopt),
/* setjmp.h */
ESP_ELFSYM_EXPORT(longjmp),
ESP_ELFSYM_EXPORT(setjmp),
ESP_ELFSYM_END
};
/** @brief ESP-IDF public functions symbols look-up table */
static const struct esp_elfsym g_esp_espidf_elfsyms[] = {
/* sys/socket.h */
ESP_ELFSYM_EXPORT(lwip_bind),
ESP_ELFSYM_EXPORT(lwip_setsockopt),
ESP_ELFSYM_EXPORT(lwip_socket),
ESP_ELFSYM_EXPORT(lwip_listen),
ESP_ELFSYM_EXPORT(lwip_accept),
ESP_ELFSYM_EXPORT(lwip_recv),
ESP_ELFSYM_EXPORT(lwip_recvfrom),
ESP_ELFSYM_EXPORT(lwip_send),
ESP_ELFSYM_EXPORT(lwip_sendto),
ESP_ELFSYM_EXPORT(lwip_connect),
/* arpa/inet.h */
ESP_ELFSYM_EXPORT(ipaddr_addr),
ESP_ELFSYM_EXPORT(lwip_htons),
ESP_ELFSYM_EXPORT(lwip_htonl),
ESP_ELFSYM_EXPORT(ip4addr_ntoa),
/* ROM functions */
ESP_ELFSYM_EXPORT(ets_printf),
ESP_ELFSYM_END
};
/**
* @brief Find symbol address by name.
*
* @param sym_name - Symbol name
*
* @return Symbol address if success or 0 if failed.
*/
uintptr_t elf_find_sym_default(const char *sym_name)
{
if (!sym_name) {
ESP_LOGE(TAG, "Invalid parameter: sym_name is NULL");
return 0;
}
esp_elf_symbol_table_t *syms;
#ifdef CONFIG_ELF_LOADER_LIBC_SYMBOLS
syms = g_esp_libc_elfsyms;
while (syms->name) {
if (!strcmp(syms->name, sym_name)) {
return (uintptr_t)syms->sym;
}
syms++;
}
#else
syms = g_esp_libc_elfsyms;
(void)syms;
#endif
#ifdef CONFIG_ELF_LOADER_ESPIDF_SYMBOLS
syms = g_esp_espidf_elfsyms;
while (syms->name) {
if (!strcmp(syms->name, sym_name)) {
return (uintptr_t)syms->sym;
}
syms++;
}
#else
syms = g_esp_espidf_elfsyms;
(void)syms;
#endif
#ifdef CONFIG_ELF_LOADER_CUSTOMER_SYMBOLS
extern const struct esp_elfsym g_customer_elfsyms[];
syms = g_customer_elfsyms;
while (syms->name) {
if (!strcmp(syms->name, sym_name)) {
return (uintptr_t)syms->sym;
}
syms++;
}
#endif
uintptr_t sym_addr = esp_elf_find_symbol(sym_name);
if (sym_addr) {
return sym_addr;
}
#if CONFIG_ELF_DYNAMIC_LOAD_SHARED_OBJECT
return (uintptr_t)dlmod_getaddr(sym_name);
#else
return 0;
#endif
}
@@ -0,0 +1,133 @@
/*
* SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <assert.h>
#include <sys/errno.h>
#include "esp_idf_version.h"
#include "esp_attr.h"
#include "esp_heap_caps.h"
#include "esp32s2/rom/cache.h"
#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)
#include "esp32s2/spiram.h"
#endif
#include "soc/mmu.h"
#include "private/elf_platform.h"
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)
#define PSRAM_VADDR_START 0x3f800000
#else
#define PSRAM_VADDR_START (DRAM0_CACHE_ADDRESS_HIGH - esp_spiram_get_size())
#endif
#define MMU_INVALID BIT(14)
#define MMU_UNIT_SIZE 0x10000
#define MMU_REG ((volatile uint32_t *)DR_REG_MMU_TABLE)
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 2, 0)
#define IRAM0_ADDRESS_LOW SOC_IRAM0_ADDRESS_LOW
#define IRAM0_ADDRESS_HIGH SOC_IRAM0_ADDRESS_HIGH
#define MMU_ACCESS_SPIRAM SOC_MMU_ACCESS_SPIRAM
#endif
#define ESP_MMU_IBUS_BASE IRAM0_ADDRESS_LOW
#define ESP_MMU_IBUS_MAX ((IRAM0_ADDRESS_HIGH - IRAM0_ADDRESS_LOW) / \
MMU_UNIT_SIZE)
#define ESP_MMU_IBUS_OFF (8)
#define DADDR_2_SECS(v) ((v) / MMU_UNIT_SIZE)
#define IADDR_2_SECS(v) ((v) / MMU_UNIT_SIZE)
#define PSRAM_OFF(v) ((v) - PSRAM_VADDR_START)
#define PSRAM_SECS(v) DADDR_2_SECS(PSRAM_OFF((uintptr_t)(v)))
#define PSRAM_ALIGN(v) ((uintptr_t)(v) & (~(MMU_UNIT_SIZE - 1)))
#define ICACHE_ADDR(s) (ESP_MMU_IBUS_BASE + (s) * MMU_UNIT_SIZE)
extern void spi_flash_disable_interrupts_caches_and_other_cpu(void);
extern void spi_flash_enable_interrupts_caches_and_other_cpu(void);
/**
* @brief Initialize MMU hardware remapping function.
*
* @param elf - ELF object pointer
*
* @return 0 if success or a negative value if failed.
*/
int IRAM_ATTR esp_elf_arch_init_mmu(esp_elf_t *elf)
{
int ret;
int off;
uint32_t ibus_secs;
volatile uint32_t dbus_secs;
esp_elf_sec_t *sec = &elf->sec[ELF_SEC_TEXT];
volatile uint32_t *p = MMU_REG;
if (sec->size % MMU_UNIT_SIZE) {
ibus_secs = IADDR_2_SECS(sec->size) + 1;
} else {
ibus_secs = IADDR_2_SECS(sec->size);
}
dbus_secs = PSRAM_SECS(elf->ptext);
spi_flash_disable_interrupts_caches_and_other_cpu();
for (off = ESP_MMU_IBUS_OFF; off < ESP_MMU_IBUS_MAX; off++) {
if (p[off] == MMU_INVALID) {
int j;
for (j = 1; j < ibus_secs; j++) {
if (p[off + j] != MMU_INVALID) {
break;
}
}
if (j >= ibus_secs) {
for (int k = 0; k < ibus_secs; k++) {
p [off + k] = MMU_ACCESS_SPIRAM | (dbus_secs + k);
}
break;
}
}
}
spi_flash_enable_interrupts_caches_and_other_cpu();
if (off >= ESP_MMU_IBUS_MAX) {
ret = -EIO;
} else {
elf->mmu_off = off;
elf->mmu_num = ibus_secs;
elf->text_off = ICACHE_ADDR(off) - PSRAM_ALIGN(elf->ptext);
ret = 0;
}
return ret;
}
/**
* @brief De-initialize MMU hardware remapping function.
*
* @param elf - ELF object pointer
*
* @return None
*/
void IRAM_ATTR esp_elf_arch_deinit_mmu(esp_elf_t *elf)
{
volatile int num = elf->mmu_num;
volatile int off = elf->mmu_off;
volatile uint32_t *p = MMU_REG;
spi_flash_disable_interrupts_caches_and_other_cpu();
for (int i = 0; i < num; i++) {
p [off + i] = MMU_INVALID;
}
spi_flash_enable_interrupts_caches_and_other_cpu();
}
+268
View File
@@ -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()
@@ -0,0 +1,26 @@
59231c48ad41bff1ed67690b194ff5e1780d07d3cb194f9d9674d35accd1a1a4 ./CHANGELOG.md
f6db411fcc6bb9a02fa1f09919ddfb99374a11bc57942ac4df6f6188ef032c45 ./check_shared_object.cmake
0b942c88ecb16950bed4f418983014f6c9a25487fdfc621476ebefb51a3765af ./CMakeLists.txt
4e2b74ed77903be2b107dfe2c103deb5e76db4b3259179f8e17976a587dd79fa ./elf_loader.cmake
259f9e135559178b85ec6710ab6a17ab9a6a88c81187966eaa3ba614a455a7a9 ./idf_component.yml
3406d27e7ae6b1b443d27bb69ee7e862f60238a8d8b55e3e4bea76d66d328b6f ./include/esp_dlfcn.h
f4cef04b710e4863670a159040de4435a7fc19790a293a6223d2656ee98eb006 ./include/esp_elf.h
4dcdcb6a11aaf5156ea978019acc484f687234bedaa32fb2fececc652cac3cfe ./include/private/elf_platform.h
288b180445016fc889a1aec0ece5693c9ba99d923f7ec82bc87b0f85b72bb719 ./include/private/elf_symbol.h
b1e946cbb34dad91aa8913724022577154806ad32291d1ed4888e579d2897292 ./include/private/elf_types.h
1555b1e6a6db5c07150df6492d069d925f8a362a980f70956c8d731d03efde90 ./include/private/esp_dlmod.h
532cea3ef8cb7e9af97694c1f3bddec60a8453de6f7aabbbbcaca855168b3ca7 ./Kconfig
cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 ./license.txt
26e023b07668f37c812cad1b41217ee7f31e10683acb4cb5407daf6fd8d53565 ./linker.lf
f2fb6d2b5559ae8239a135b557aad3f147066f9a9c0afd0b72f28159ab106af5 ./project_include.cmake
dd33bb577b32f104f3e9f8b0650737cbb885b97b13ffab79c23b6d8057900524 ./README.md
f342b33cab7a66eb49bafc5f711f9c9ec53ccf2d81731b4719f4efa630c695a7 ./src/arch/esp_elf_riscv.c
5bdfb954bb1a4380b82897d460de2a08f4212d81d3221064ca83a028a31dc1e7 ./src/arch/esp_elf_xtensa.c
aa2a1d74a45726ac45cabf778a825b9328cf2c731b869de0e5dfe9523acd2ead ./src/dlso/dlfcn.c
02c9411d7993f7b6d13bca15094fbd58979e4fdb938a9470ef845d174a7f3bca ./src/dlso/dlmod.c
203376641eb31d39f5691865afbb6fab1eae2e8317e36e41f0a0192be206fb69 ./src/esp_all_symbol.c
76bc197b51844110e73962c4a0be98965a0ed9028f4a27725185eabb332dcb2c ./src/esp_elf_adapter.c
e3aecd2dccd963440b28cee811158e917825bd59683898df0815014c529df40c ./src/esp_elf.c
81407e3dbbe7705cf3666c97ed23b5b4b9eefa7b1337de2059be85d08d0a0f4d ./src/esp_elf_symbol.c
163857a64578cf8bfbed900ea5168cd43a1db6a51b7921b7dec1b588b989e03e ./src/soc/esp_elf_esp32s2.c
81398e6eeb1bd381e0a8a1cb36d81452f6ea8f2d69a577e3a9599619c5e54246 ./tool/symbols.py