Skip to content

feat(fspy): add userland ELF loader and freestanding target-none foundations - #1015

Merged
wan9chi merged 34 commits into
mainfrom
t3/0805c989
Nov 25, 2026
Merged

wan9chi merged 34 commits into
mainfrom
t3/0805c989

Conversation

@wan9chi

@wan9chi wan9chi commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

Note

Status: The userland ELF loader (fspy_elf_loader) is still unfinished and is not wired into fspy yet — it is currently unused outside of fspy_elf_loader_tests. vp run continues to spawn Linux processes using the existing LD_PRELOAD / seccomp_unotify path.

Motivation

On Linux, fspy currently splits process tracking between LD_PRELOAD (for dynamically linked binaries) and seccomp_unotify (for static binaries), because kernel execve resets in-process intercept state. The target Linux architecture replaces this split with a single path: kernel-exec a freestanding (target_os = "none") launcher that installs SECCOMP_RET_TRAP / SIGSYS interception and then maps and enters the target ELF in userland so intercept state survives into the target process.

This PR lands the freestanding target_os = "none" foundations and the initial userland ELF64 loader crate ahead of wiring interception and process spawning into fspy:

  • Freestanding foundations (fspy_nostd, fspy_shm, fspy_shared, vt_ipc_str): target_os = "none" entry point, initial stack views (argv/envp/auxv), raw stdio/panic handling, link-time global-allocator guard, and no_std shared-memory IPC sender support.
  • Userland ELF64 loader (fspy_elf_loader): Pure #![no_std], allocator-free loader for little-endian ELF64 on x86-64 and AArch64 covering all four image shapes (ET_DYN/ET_EXEC, with or without PT_INTERP), PT_LOAD mapping with shared-page/BSS padzero, fixed-address overlap rejection, rebuilt startup stack (argv/envp/auxv), and naked entry stubs.
  • Test launcher and integration suite (fspy_elf_loader_test_launcher, fspy_elf_loader_tests): Freestanding static high-address test launcher and differential integration tests comparing all four C runtime ELF cells against kernel execve, plus CI coverage for bare-metal clippy and release-mode loader tests.

Remaining work (follow-up PRs)

  • Userland PATH and shebang (#!) resolution above exec_elf and nested execve handling.
  • /proc/self/exe virtualization so targets observe their own executable path.
  • Installing SIGSYS interception in the launcher and wiring fspy to use it instead of the LD_PRELOAD / seccomp_unotify split.

Note

Medium Risk
New low-level process startup and memory-mapping code on Linux with extensive tests, but no change yet to live fspy spawn paths; workspace dependency/feature tweaks may affect cross-target builds.

Overview
Introduces a Linux userland ELF64 loader (fspy_elf_loader) that maps targets in-process and transfers control without kernel execve, plus freestanding plumbing so a future high-address launcher can keep intercept state across entry. The loader is not wired into fspy yet; production Linux spawning still uses LD_PRELOAD / seccomp_unotify.

fspy_elf_loader implements exec_elf for x86-64 and AArch64: PT_LOAD mapping (shared pages, BSS, Linux-style padzero), optional PT_INTERP, rebuilt startup stack (argv/envp/auxv), and naked entry stubs. Fixed ET_EXEC images that overlap existing mappings are rejected.

Freestanding support expands fspy_nostd (main!, InitialStack, panic/stderr handling, link-time no_global_alloc! guard) and teaches fspy_shm, fspy_shared, and vt_ipc_str to build under target_os = "none" where needed for launcher IPC writers.

Testing & CI: fspy_elf_loader_test_launcher plus fspy_elf_loader_tests differentially compare four C runtime ELF shapes against kernel execve; workflows add bare-metal clippy and release-mode loader tests on Linux (glibc/musl).

Reviewed by Cursor Bugbot for commit 3279a12. Bugbot is set up for automated code reviews on this repo. Configure here.

wan9chi and others added 30 commits November 25, 2026 18:23
Co-authored-by: GPT-5 Codex <codex@openai.com>
Co-authored-by: GPT-5 Codex <codex@openai.com>
Co-authored-by: GPT-6 <codex@openai.com>
Add borrowed stdout/stderr accessors, formatted descriptor writes, and an opt-in Linux panic handler. Define the thin C string layout and cover write retries and errors.

Co-authored-by: GPT-5 Codex <codex@openai.com>
Move InitialStack and AuxEntry into env and add main! with parsed stack input and the default panic handler. Preserve layout tests and the callback lifetime compile-fail test.

Co-authored-by: GPT-5 Codex <codex@openai.com>
Use fspy_nostd::env::AuxEntry for inherited auxv and restrict ELF execution to the Linux and none targets.

Co-authored-by: GPT-5 Codex <codex@openai.com>
Add a target-none launcher using fspy_nostd's entry point and panic handler to exercise exec_elf. Leave the separate host-side test crate for a later commit.

Co-authored-by: GPT-5 Codex <codex@openai.com>
Add the allocator registration macro and link regression tests. Expose MAP_FIXED on Linux/none and clarify the entry point's relocation requirements.

Co-authored-by: GPT-5 Codex <codex@openai.com>
Map executable and interpreter segments, build the initial stack using an explicit page-bump allocator, and enter the interpreter without a kernel exec. Add freestanding launcher integration tests with ntest timeouts for AArch64 and x86-64.

Co-authored-by: GPT-5 Codex <codex@openai.com>
Co-authored-by: GPT-5 Codex <codex@openai.com>
Load dynamic ET_EXEC images at their declared addresses without replacing existing mappings. Add fixed-address runtime and collision tests, plus an optional Node.js execution check.

Co-authored-by: GPT-6 <codex@openai.com>
Place the freestanding launcher inside sanitizer-friendly application regions while keeping low executable addresses available. Verify the static ELF layout and fixed-address execution; drop a unit test covered by integration coverage.

Co-authored-by: GPT-6 Codex <codex@openai.com>
Map zero-filesz loads like elf_map so a mid-page BSS segment does not
wipe the previous page. Padzero whenever filesz is not page-aligned,
including filesz==memsz. Accept padded PT_INTERP paths and unordered
non-overlapping PT_LOADs. Clear leftover GPRs in the enter stubs.

Co-authored-by: Cursor Grok 4.6 <cursoragent@cursor.com>
Co-authored-by: Charles Wang <wan9chi@users.noreply.github.com>
Treat PT_INTERP as optional. Map only the executable when it is absent,
set AT_BASE to 0, and enter e_entry. Add cc -static and -static-pie
runtime fixtures covering traditional static and static-PIE.

Co-authored-by: Cursor Grok 4.6 <cursoragent@cursor.com>
Co-authored-by: Charles Wang <wan9chi@users.noreply.github.com>
The undefined __fspy_global_allocator_must_not_be_used symbol is for
freestanding Linux/none binaries. Linking it into fspy_preload_windows
fails MSVC because the rlib object is retained.

Also align cargo-shear with the rustc-only allocator fixture and skip
lib doctests that rustdoc compiles with std.

Co-authored-by: Cursor Grok 4.6 <cursoragent@cursor.com>
Co-authored-by: Charles Wang <wan9chi@users.noreply.github.com>
Co-authored-by: Cursor Grok 4.6 <cursoragent@cursor.com>
Co-authored-by: Charles Wang <wan9chi@users.noreply.github.com>
…lamp shared pages

Avoid zeroing past filesz == memsz on read-only and executable segments,
which unnecessarily COW-dirtied shared pages and triggered RW -> RX
mprotect transitions under W^X policies. Clamp the padzero range to the
start of any higher-vaddr PT_LOAD sharing the same page so unordered
segments cannot wipe each other.

Co-authored-by: Gemini 4 Neon <gemini@google.com>
Expose fspy_nostd::param::seed_page_size on Linux/none and seed it from
AT_PAGESZ in fspy_elf_loader::exec_elf so temporary allocations in the
freestanding launcher do not trigger a redundant 2 MiB mmap/mprotect
page-size probe.

Co-authored-by: Gemini 4 Neon <gemini@google.com>
…room, and entry GPRs

- Reject fixed-address (ET_EXEC) PT_INTERP images instead of emitting AT_BASE = 0.
- Relax segment congruence to page granularity, matching Linux binfmt_elf so
  patchelf-modified binaries load cleanly.
- Break on AT_NULL in inherited auxv, guard against null AT_RANDOM / platform
  pointers, 16-byte align AT_RANDOM, and reserve 64 KiB of call-stack headroom.
- Zero all remaining GPRs in x86-64 and AArch64 enter stubs to match Linux
  process entry state.

Co-authored-by: Gemini 4 Neon <gemini@google.com>
…d leaks in static fixture

Do not hardcode that the host's /bin/echo is a dynamic PIE (which can fail
on Alpine/static-busybox or non-PIE distros; FIXTURE already asserts ET_DYN
with PT_INTERP), and add the /proc/self/fd leak check to static_runtime.c
to match fixture.rs.

Co-authored-by: Gemini 4 Neon <gemini@google.com>
Keep fspy_elf_loader as a pure no_std library without a test-only [[bin]],
build.rs, or dummy host main(). Put the freestanding test launcher in
crates/fspy_elf_loader_test_launcher and depend on it from
fspy_elf_loader_tests.

Co-authored-by: Gemini 4 Neon <gemini@google.com>
…re cc resolution

Compile one C runtime fixture (fixtures/runtime.c) across all four ELF64
cells with explicit PIE/non-PIE flags (-fPIE -pie, -fno-pie -no-pie,
-fno-pie -static, -fPIE -static-pie), eliminating protocol drift between
fixture.rs and static_runtime.c and removing the brittle rustc -no-pie
link-arg override in fixture_exec.rs. Keep fixture.rs as a dedicated Rust
std runtime check.

Use the cc crate for target-aware C compiler discovery (CC_<target>, CC)
with rerun-if-env-changed instead of hardcoding Command::new("cc").

Co-authored-by: Gemini 4 Neon <gemini@google.com>
…rnel exec

Execute each runtime fixture directly via kernel execve (with matching
arg0 and environment) before running it through the freestanding launcher
so fixture or toolchain regressions are separated from loader bugs.

Co-authored-by: Gemini 4 Neon <gemini@google.com>
cargo-zigbuild's gnu wrapper cannot link static glibc binaries, so detect
zigcc wrappers in build.rs and compile the static and static-PIE C fixtures
via `cargo-zigbuild zig cc` targeting `<arch>-linux-musl`.

Co-authored-by: Gemini 4 Neon <gemini@google.com>
… instead of /bin/echo

Replace raw ELF header/program-header byte offsets with `offset_of!` /
`size_of` over `libc::Elf64_Ehdr`/`Elf64_Phdr` in integration tests and a
typed `Phdr` builder in unit tests. Mutate our own `FIXTURE_DYN_PIE` binary
instead of host `/bin/echo` in malformed-image and section-header tests so
those cases no longer depend on host system binary layout.

Co-authored-by: Gemini 4 Neon <gemini@google.com>
The unified C fixture (`fixtures/runtime.c`) already covers the same
startup contract across all four ELF64 cells, making the extra dynamic-PIE
Rust `fixture` binary redundant. Move `libc` to Linux dev-dependencies.

Co-authored-by: Gemini 4 Neon <gemini@google.com>
Run `fspy_elf_loader_tests` in `--release` on both Linux glibc and musl CI
jobs, run `clippy` on `fspy_elf_loader` and `fspy_elf_loader_test_launcher`
for both bare-metal targets (`x86_64-unknown-none` and
`aarch64-unknown-none-softfloat`), and update `fspy_elf_loader_tests/README.md`.

Co-authored-by: Gemini 4 Neon <gemini@google.com>
…in, link args, and C ehdr read

- Share `EHDR_SIZE` and `PHDR_SIZE` constants from `image.rs` across `image/tests.rs` (and `stack.rs`).
- Simplify `Mapping::retain` to return `()` since no caller used the pointer.
- Use `cargo::rustc-link-arg=` in `fspy_elf_loader_test_launcher/build.rs`.
- Read `Elf64_Ehdr` fields directly in `fixtures/runtime.c` instead of raw offsets `64`/`32`.

Co-authored-by: Gemini 4 Neon <gemini@google.com>
…ng without allocator

Stage `argc`/`argv`/`envp`/`auxv` words directly at the bottom of the
reserved stack mapping and shift them up next to the payloads in `finish()`
via `ptr::copy` (zeroing the vacated scratch prefix below SP). This drops
the `allocator-api2` and `fspy_nostd_alloc` dependencies and an extra
`mmap`/`munmap` pair per `exec_elf`, gates the remaining `fspy_elf_loader`
dependencies to `linux`/`none`, and removes the now-unused
`fspy_nostd::param::seed_page_size`.

Co-authored-by: Gemini 4 Neon <gemini@google.com>
…ookup

Resolve the C compiler directly from `CC_<target>`, `CC`, or `cc` in
`fspy_elf_loader_tests/build.rs`, removing the `cc` build dependency and
eliminating the spurious `zig: error: version '.2.17' in target triple`
warning emitted by `cc`'s compiler probe under `cargo-zigbuild`.

Co-authored-by: Gemini 4 Neon <gemini@google.com>
wan9chi and others added 2 commits November 25, 2026 18:25
…fixture helper

Remove `echo_preserves_empty_and_non_utf8_arguments` (already verified
across all four runtime fixtures differentially against kernel `execve`
and in `stack::tests`) and share fixture setup between `check_runtime_image`
and `does_not_require_section_headers`.

Co-authored-by: Gemini 4 Neon <gemini@google.com>
Format `crates/fspy_elf_loader/README.md` with `vp fmt` and restore
`crates/fspy_nostd/src/param.rs` to eliminate the leftover refactor from
adding and removing `seed_page_size`.

Co-authored-by: Gemini 4 Neon <gemini@google.com>
@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

fspy benchmark

linux

dynamic/launch             change  +1.57%  [ -4.66% ..  +6.56%]  overhead   +64.09%
dynamic/access             change  +0.00%  [ -4.90% .. +10.27%]  overhead   +20.30%
dynamic/access-relative    change  +0.28%  [ -2.84% ..  +2.84%]  overhead   +70.11%
dynamic/access-contended   change  -0.48%  [-11.91% ..  +8.16%]  overhead    +0.30%
static/launch              change  +0.16%  [-11.34% ..  +7.89%]  overhead  +202.33%
static/access              change  +0.51%  [ -2.67% ..  +2.07%]  overhead +1333.30%
static/access-relative     change  -0.12%  [-13.34% .. +14.58%]  overhead +1659.80%
static/access-contended    change  -0.43%  [ -7.87% ..  +1.89%]  overhead  +934.46%

macos

dynamic/launch             change  -0.40%  [ -2.82% ..  +2.87%]  overhead  +223.96%
dynamic/access             change  +0.01%  [ -2.74% ..  +2.54%]  overhead    +4.73%
dynamic/access-relative    change  -0.31%  [ -2.25% ..  +2.23%]  overhead  +246.91%
dynamic/access-contended   change  +0.00%  [ -2.52% ..  +2.59%]  overhead    +3.35%

windows

dynamic/launch             change  +0.72%  [ -4.15% ..  +4.67%]  overhead   +27.41%
dynamic/access             change  +0.37%  [ -0.95% ..  +1.68%]  overhead    +1.48%
dynamic/access-relative    change  +0.18%  [ -1.73% ..  +1.96%]  overhead    +1.62%
dynamic/access-contended   change  -0.82%  [ -6.40% ..  +3.30%]  overhead    +0.69%

wan9chi and others added 2 commits November 25, 2026 18:34
Cross-compiled Windows nextest archives are built on Linux and extracted
on Windows runners where the compile-time `CARGO_BIN_FILE_*` Linux path
does not exist. Embed the freestanding launcher ELF with `include_bytes!`
so `launcher_image` works portably across archived test runs.

Co-authored-by: Gemini 4 Neon <gemini@google.com>
Cross-compiled Windows nextest archives remap the workspace at runtime
via `CARGO_MANIFEST_DIR`, whereas `env!("CARGO_MANIFEST_DIR")` baked
in the Linux build host path. Read `std::env::var_os("CARGO_MANIFEST_DIR")`
at runtime with a fallback to the compile-time path.

Co-authored-by: Gemini 4 Neon <gemini@google.com>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 3279a12. Configure here.

}
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shared-page remap undoes BSS zeros

Medium Severity

map_segment padzeros BSS (and writable tails) while walking PT_LOAD headers, then a later header that shares that page issues MAP_FIXED over the whole file page. That remap restores file bytes and wipes the zeros already written for the earlier segment. The clamp only stops padzero from touching a higher vaddr; it does not re-zero after a later remap. Standard page-aligned GNU ld images avoid this, but the loader claims to accept shared-page and unordered loads, and those layouts can start with a non-zero BSS.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 3279a12. Configure here.

@wan9chi
wan9chi merged commit e436112 into main Nov 25, 2026
22 of 23 checks passed
@wan9chi
wan9chi deleted the t3/0805c989 branch November 25, 2026 10:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants