From 589faf38c37cbea27ea2b63a63b8a7acab215b17 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Thu, 20 Aug 2026 16:06:56 +0800 Subject: [PATCH 01/34] feat(fspy): add target-none foundations Co-authored-by: GPT-5 Codex --- Cargo.lock | 1 + Cargo.toml | 4 ++-- crates/fspy_nostd/src/error.rs | 5 ++++- crates/fspy_nostd_alloc/src/c_string.rs | 2 +- crates/fspy_nostd_alloc/src/fs.rs | 6 ++--- crates/fspy_nostd_alloc/src/lib.rs | 6 ++--- crates/fspy_shm/Cargo.toml | 2 +- crates/fspy_shm/src/lib.rs | 4 ++-- crates/vt_ipc_shared/Cargo.toml | 2 +- crates/vt_ipc_str/Cargo.toml | 1 + crates/vt_ipc_str/src/lib.rs | 29 +++++++++++++++++++------ 11 files changed, 41 insertions(+), 21 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ec2ead5fd..91c1bc3b7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5161,6 +5161,7 @@ name = "vt_ipc_str" version = "0.0.0" dependencies = [ "allocator-api2", + "bstr", "bumpalo", "bytemuck", "fspy_nostd", diff --git a/Cargo.toml b/Cargo.toml index 267788b65..ce4b0b9de 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -48,7 +48,7 @@ async-trait = "0.1.89" base64 = "0.22.1" bytes = "1.11.1" url = "2.5.8" -wincode = "0.6.0" +wincode = { version = "0.6.0", default-features = false, features = ["alloc"] } bindgen = "0.72.1" bitflags = "2.10.0" brush-parser = "0.4.0" @@ -150,7 +150,7 @@ syscalls = { version = "0.8.0", default-features = false } tar = "0.4.45" tempfile = "3.14.0" test-log = "0.2.18" -thiserror = "2" +thiserror = { version = "2", default-features = false } tokio = "1.53.3" tokio-util = "0.7.17" toml = "1.0.0" diff --git a/crates/fspy_nostd/src/error.rs b/crates/fspy_nostd/src/error.rs index e6d3d9af4..a873ef62c 100644 --- a/crates/fspy_nostd/src/error.rs +++ b/crates/fspy_nostd/src/error.rs @@ -1,7 +1,7 @@ #[cfg(target_os = "macos")] use libc::__error; #[cfg(windows)] -use windows_sys::Win32::Foundation::GetLastError; +use windows_sys::Win32::Foundation::{ERROR_FILE_NOT_FOUND, GetLastError}; /// An operating-system error code. #[cfg(any(target_os = "linux", target_os = "none", target_os = "macos"))] @@ -51,6 +51,9 @@ impl Error { #[cfg(windows)] impl Error { + /// The requested file does not exist. + pub const NOENT: Self = Self(ERROR_FILE_NOT_FOUND); + /// Creates an error from a raw Windows error code. #[must_use] pub const fn from_raw_os_error(code: u32) -> Self { diff --git a/crates/fspy_nostd_alloc/src/c_string.rs b/crates/fspy_nostd_alloc/src/c_string.rs index b2e38e6d1..8db5c34eb 100644 --- a/crates/fspy_nostd_alloc/src/c_string.rs +++ b/crates/fspy_nostd_alloc/src/c_string.rs @@ -11,7 +11,7 @@ pub struct CString { /// An allocator-backed owned C string of the platform's native path code /// units: bytes on Unix and wide (`u16`) code units on Windows. -#[cfg(unix)] +#[cfg(any(unix, target_os = "none"))] pub type OsCString = CString; /// An allocator-backed owned C string of the platform's native path code /// units: bytes on Unix and wide (`u16`) code units on Windows. diff --git a/crates/fspy_nostd_alloc/src/fs.rs b/crates/fspy_nostd_alloc/src/fs.rs index 3295a1364..c348b6a48 100644 --- a/crates/fspy_nostd_alloc/src/fs.rs +++ b/crates/fspy_nostd_alloc/src/fs.rs @@ -3,9 +3,9 @@ #[cfg(target_os = "macos")] use allocator_api2::boxed::Box; use allocator_api2::{alloc::Allocator, vec::Vec}; -#[cfg(any(target_os = "linux", target_os = "macos"))] +#[cfg(any(target_os = "linux", target_os = "none", target_os = "macos"))] use fspy_nostd::Thin; -#[cfg(target_os = "linux")] +#[cfg(any(target_os = "linux", target_os = "none"))] use fspy_nostd::{BorrowedFd, CStr}; use fspy_nostd::{Error, Fat, Result}; @@ -43,7 +43,7 @@ pub fn getcwd(allocator: A) -> Result> { /// /// Returns [`Error::NOMEM`] if storage cannot be allocated, or the error from /// [`fspy_nostd::fs::readlinkat`]. -#[cfg(target_os = "linux")] +#[cfg(any(target_os = "linux", target_os = "none"))] pub fn readlinkat( allocator: A, dirfd: BorrowedFd<'_>, diff --git a/crates/fspy_nostd_alloc/src/lib.rs b/crates/fspy_nostd_alloc/src/lib.rs index fd2f9f6e4..bac25747e 100644 --- a/crates/fspy_nostd_alloc/src/lib.rs +++ b/crates/fspy_nostd_alloc/src/lib.rs @@ -15,9 +15,9 @@ #![cfg_attr(not(test), no_std)] mod c_string; -#[cfg(unix)] +#[cfg(any(unix, target_os = "none"))] pub mod fs; -#[cfg(unix)] +#[cfg(any(unix, target_os = "none"))] mod mmap; mod pool; #[cfg(windows)] @@ -34,7 +34,7 @@ use bump_scope::{ settings::{BumpAllocatorSettings, BumpSettings}, }; pub use c_string::{CString, OsCString}; -#[cfg(unix)] +#[cfg(any(unix, target_os = "none"))] pub use mmap::MmapAllocator as PageAllocator; use pool::ChunkPool; #[cfg(windows)] diff --git a/crates/fspy_shm/Cargo.toml b/crates/fspy_shm/Cargo.toml index 416f5a6c9..63a30d20c 100644 --- a/crates/fspy_shm/Cargo.toml +++ b/crates/fspy_shm/Cargo.toml @@ -7,7 +7,7 @@ license.workspace = true publish = false rust-version.workspace = true -[target.'cfg(any(unix, windows))'.dependencies] +[target.'cfg(any(unix, windows, target_os = "none"))'.dependencies] fspy_nostd = { workspace = true } [target.'cfg(target_os = "windows")'.dependencies] diff --git a/crates/fspy_shm/src/lib.rs b/crates/fspy_shm/src/lib.rs index bacf233f6..7329db8a3 100644 --- a/crates/fspy_shm/src/lib.rs +++ b/crates/fspy_shm/src/lib.rs @@ -1,13 +1,13 @@ #![doc = include_str!("../README.md")] #![cfg_attr(not(test), no_std)] -#[cfg(unix)] +#[cfg(any(unix, target_os = "none"))] mod unix; #[cfg(windows)] mod windows; pub use platform::{Mapping, ShmHandle, create, open, remove}; -#[cfg(unix)] +#[cfg(any(unix, target_os = "none"))] use unix as platform; #[cfg(windows)] use windows as platform; diff --git a/crates/vt_ipc_shared/Cargo.toml b/crates/vt_ipc_shared/Cargo.toml index 080dd6336..0691305ae 100644 --- a/crates/vt_ipc_shared/Cargo.toml +++ b/crates/vt_ipc_shared/Cargo.toml @@ -9,7 +9,7 @@ rust-version.workspace = true [dependencies] rustc-hash = { workspace = true } vt_ipc_str = { workspace = true } -wincode = { workspace = true, features = ["derive"] } +wincode = { workspace = true, features = ["derive", "std"] } [lints] workspace = true diff --git a/crates/vt_ipc_str/Cargo.toml b/crates/vt_ipc_str/Cargo.toml index e190b8deb..8750f0119 100644 --- a/crates/vt_ipc_str/Cargo.toml +++ b/crates/vt_ipc_str/Cargo.toml @@ -8,6 +8,7 @@ rust-version.workspace = true [dependencies] allocator-api2 = { workspace = true, features = ["alloc"], optional = true } +bstr = { workspace = true } bumpalo = { workspace = true } bytemuck = { workspace = true, features = ["derive", "extern_crate_alloc", "must_cast"] } fspy_nostd = { workspace = true, optional = true } diff --git a/crates/vt_ipc_str/src/lib.rs b/crates/vt_ipc_str/src/lib.rs index 6284e2393..766889b35 100644 --- a/crates/vt_ipc_str/src/lib.rs +++ b/crates/vt_ipc_str/src/lib.rs @@ -1,3 +1,6 @@ +#![cfg_attr(target_os = "none", no_std)] + +use core::{fmt::Debug, mem::MaybeUninit}; #[cfg(windows)] use std::ffi::OsString; #[cfg(unix)] @@ -6,14 +9,19 @@ use std::os::unix::ffi::OsStrExt as _; use std::os::windows::ffi::OsStrExt as _; #[cfg(windows)] use std::os::windows::ffi::OsStringExt as _; -use std::{borrow::Cow, ffi::OsStr, fmt::Debug, mem::MaybeUninit}; +#[cfg(any(unix, windows))] +use std::{borrow::Cow, ffi::OsStr}; #[cfg(feature = "fspy_nostd")] use allocator_api2::alloc::Allocator; +#[cfg(any(unix, target_os = "none"))] +use bstr::BStr; use bumpalo::Bump; +use bytemuck::TransparentWrapper; +#[cfg(any(unix, windows))] +use bytemuck::TransparentWrapperAlloc; #[cfg(windows)] use bytemuck::must_cast_slice; -use bytemuck::{TransparentWrapper, TransparentWrapperAlloc}; #[cfg(feature = "fspy_nostd")] use fspy_nostd::{Fat, OsCStr}; #[cfg(feature = "fspy_nostd")] @@ -53,7 +61,7 @@ pub struct IpcStr { } impl IpcStr { - #[cfg(unix)] + #[cfg(any(unix, target_os = "none"))] #[must_use] pub fn from_bytes(bytes: &[u8]) -> &Self { Self::wrap_ref(bytes) @@ -85,6 +93,7 @@ impl IpcStr { ) } + #[cfg(any(unix, windows))] #[must_use] pub fn to_cow_os_str(&self) -> Cow<'_, OsStr> { #[cfg(windows)] @@ -108,7 +117,7 @@ impl IpcStr { /// neither direction goes through [`OsStr`], so both work without std. #[must_use] pub fn from_os_c_str(path: OsCStr<'_, Fat>) -> &Self { - #[cfg(unix)] + #[cfg(any(unix, target_os = "none"))] return Self::wrap_ref(path.as_units()); #[cfg(windows)] return Self::wrap_ref(must_cast_slice(path.as_units())); @@ -121,7 +130,7 @@ impl IpcStr { /// length on Windows, or an interior NUL code unit. #[must_use] pub fn to_os_c_string_in(&self, allocator: A) -> Option> { - #[cfg(unix)] + #[cfg(any(unix, target_os = "none"))] { let mut units = allocator_api2::vec::Vec::with_capacity_in(self.data.len() + 1, allocator); @@ -148,8 +157,11 @@ impl IpcStr { } impl Debug for IpcStr { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - ::fmt(self.to_cow_os_str().as_ref(), f) + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + #[cfg(any(unix, target_os = "none"))] + return ::fmt(BStr::new(&self.data), f); + #[cfg(windows)] + return ::fmt(self.to_cow_os_str().as_ref(), f); } } @@ -180,6 +192,7 @@ unsafe impl<'de, C: Config> SchemaRead<'de, C> for &'de IpcStr { } // SAFETY: Delegates to `IpcStr`'s SchemaWrite impl, preserving its invariants. +#[cfg(any(unix, windows))] unsafe impl SchemaWrite for Box { type Src = Self; @@ -194,6 +207,7 @@ unsafe impl SchemaWrite for Box { // SchemaRead for Box: owned decode // SAFETY: Delegates to `&[u8]`'s SchemaRead impl; dst is initialized on Ok. +#[cfg(any(unix, windows))] unsafe impl<'de, C: Config> SchemaRead<'de, C> for Box { type Dst = Self; @@ -211,6 +225,7 @@ impl<'a, S: AsRef + ?Sized> From<&'a S> for &'a IpcStr { } } +#[cfg(any(unix, windows))] impl> From for Box { #[cfg(unix)] fn from(value: S) -> Self { From dd64546eb0d9ece49f2195ec96bcdf1b175c6737 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Thu, 20 Aug 2026 16:09:02 +0800 Subject: [PATCH 02/34] refactor(fspy-shared): make the shared-memory sender no-std Co-authored-by: GPT-5 Codex --- crates/fspy_shared/Cargo.toml | 10 +++--- crates/fspy_shared/src/ipc/channel/mod.rs | 32 +++++++++++++++---- .../src/ipc/channel/shm_io/layout.rs | 16 +++++++++- .../fspy_shared/src/ipc/channel/shm_io/mod.rs | 4 ++- .../src/ipc/channel/shm_io/writer.rs | 2 +- crates/fspy_shared/src/ipc/ipc_path.rs | 22 +++++++++---- crates/fspy_shared/src/ipc/mod.rs | 4 ++- crates/fspy_shared/src/lib.rs | 2 ++ 8 files changed, 71 insertions(+), 21 deletions(-) diff --git a/crates/fspy_shared/Cargo.toml b/crates/fspy_shared/Cargo.toml index 0f055799d..fcfff9ecd 100644 --- a/crates/fspy_shared/Cargo.toml +++ b/crates/fspy_shared/Cargo.toml @@ -6,17 +6,18 @@ license.workspace = true publish = false [dependencies] -wincode = { workspace = true, features = ["derive"] } allocator-api2 = { workspace = true, features = ["alloc"] } -bumpalo = { workspace = true } -bstr = { workspace = true, features = ["alloc", "std"] } bytemuck = { workspace = true, features = ["must_cast", "derive"] } fspy_nostd = { workspace = true } fspy_nostd_alloc = { workspace = true } fspy_shm = { workspace = true } thiserror = { workspace = true } -uuid = { workspace = true, features = ["v4"] } vt_ipc_str = { workspace = true, features = ["fspy_nostd"] } +wincode = { workspace = true, features = ["derive"] } + +[target.'cfg(not(target_os = "none"))'.dependencies] +bumpalo = { workspace = true } +uuid = { workspace = true, features = ["v4"] } vt_path = { workspace = true } [target.'cfg(target_os = "windows")'.dependencies] @@ -26,6 +27,7 @@ winapi = { workspace = true, features = ["std"] } [dev-dependencies] assert2 = { workspace = true } +bstr = { workspace = true, features = ["alloc", "std"] } ctor = { workspace = true } rustc-hash = { workspace = true } vt_subprocess_test = { workspace = true } diff --git a/crates/fspy_shared/src/ipc/channel/mod.rs b/crates/fspy_shared/src/ipc/channel/mod.rs index af874cd6c..14d0906a4 100644 --- a/crates/fspy_shared/src/ipc/channel/mod.rs +++ b/crates/fspy_shared/src/ipc/channel/mod.rs @@ -7,17 +7,27 @@ mod shm_io; -use std::{env::temp_dir, ffi::OsStr, io, num::NonZeroUsize, path::PathBuf}; +use core::num::NonZeroUsize; +#[cfg(not(target_os = "none"))] +use std::{env::temp_dir, ffi::OsStr, io, path::PathBuf}; use allocator_api2::alloc::Allocator; +#[cfg(not(target_os = "none"))] use fspy_nostd::Fat; +#[cfg(not(target_os = "none"))] use fspy_nostd_alloc::OsCString; -use fspy_shm::{Mapping, ShmHandle}; -use shm_io::{SealError, ShmReader, ShmWriter}; +use fspy_shm::Mapping; +#[cfg(not(target_os = "none"))] +use fspy_shm::ShmHandle; +use shm_io::ShmWriter; +#[cfg(not(target_os = "none"))] +use shm_io::{SealError, ShmReader}; /// Reads the committed frames of a sealed channel; borrows the shared /// mapping, which stays alive (and mapped) until this value drops. +#[cfg(not(target_os = "none"))] pub type FrameReader = shm_io::ShmReader; +#[cfg(not(target_os = "none"))] use uuid::Uuid; use wincode::{SchemaRead, SchemaWrite, Serialize as _, config::DefaultConfig}; @@ -29,6 +39,7 @@ use super::IpcStr; /// The files sit directly in the temporary directory. A shared subdirectory /// would belong to whichever user created it first and block everyone else; /// uniquely named `0o600` files in the sticky-bit temp directory avoid that. +#[cfg(not(target_os = "none"))] const SHM_BACKING_PREFIX: &str = "vite-task-fspy-"; /// Descriptor slots in every channel, one per record. @@ -54,6 +65,7 @@ pub struct ChannelConf<'a> { /// derives the serializable configuration that other processes use to create /// senders. #[expect(clippy::missing_errors_doc, reason = "non-vt crate: cannot use vt_str/vt_path types")] +#[cfg(not(target_os = "none"))] pub fn channel(capacity: usize, allocator: A) -> io::Result> { let shm_c_path = os_c_string(shm_backing_path()?.as_os_str(), allocator)?; let handle = @@ -78,6 +90,7 @@ pub fn channel(capacity: usize, allocator: A) -> io::Result(path: &OsStr, allocator: A) -> io::Result> { let mut units = os_units(path, allocator); units.push(0); @@ -116,6 +129,7 @@ fn shm_error_to_io(error: fspy_nostd::Error) -> io::Error { } /// Returns a fresh absolute path for a shared-memory backing file. +#[cfg(not(target_os = "none"))] fn shm_backing_path() -> io::Result { // `temp_dir` reflects `TMPDIR` verbatim, which may be relative. The path // travels to processes with other working directories, so resolve it @@ -152,10 +166,12 @@ fn to_verbatim_if_long(path: PathBuf) -> io::Result { /// /// Removal is cleanup, not a stop signal: later opens fail, but existing /// handles and mappings keep reading and writing; see [`fspy_shm::remove`]. +#[cfg(not(target_os = "none"))] struct ShmKeeper { path: OsCString, } +#[cfg(not(target_os = "none"))] impl Drop for ShmKeeper { fn drop(&mut self) { let _ = fspy_shm::remove(self.path.as_c_str().as_thin()); @@ -189,13 +205,12 @@ impl ChannelConf<'_> { let mapping = match fspy_shm::open(shm_path.as_c_str().as_thin()) { Ok(handle) => handle.map().expect("cannot map the shared-memory channel"), Err(error) => { - let error = shm_error_to_io(error); // The receiver removed the backing file, so it has already // stopped collecting. - if error.kind() == io::ErrorKind::NotFound { + if error == fspy_nostd::Error::NOENT { return None; } - panic!("cannot open the shared-memory channel: {error}"); + panic!("cannot open the shared-memory channel: {error:?}"); } }; // SAFETY: `mapping` is a freshly mapped shared memory region created @@ -271,6 +286,7 @@ unsafe impl Sync for Sender {} /// /// Holds the shared memory and its backing file alive for as long as senders /// may attach; [`Receiver::close`] (or dropping) removes the backing file. +#[cfg(not(target_os = "none"))] pub struct Receiver { /// Keeps the shared memory's backing file alive for as long as senders /// may attach. @@ -284,11 +300,14 @@ pub struct Receiver { // accesses the mapping exclusively through the `shm_io` protocol in `close`, // which synchronizes with senders via atomic operations. The mapping's // address is stable and independently owned. +#[cfg(not(target_os = "none"))] unsafe impl Send for Receiver {} // SAFETY: see the `Send` impl. +#[cfg(not(target_os = "none"))] unsafe impl Sync for Receiver {} +#[cfg(not(target_os = "none"))] impl Receiver { /// Returns the serializable configuration other processes pass to /// [`ChannelConf::sender`], borrowing this receiver's storage. @@ -376,6 +395,7 @@ impl Receiver { /// senders did wrong, and both leave the run untracked. #[derive(thiserror::Error, Clone, Copy, PartialEq, Eq, Debug)] #[error("a sender ran out of room in the shared-memory channel")] +#[cfg(not(target_os = "none"))] pub struct RecordsLost; #[cfg(test)] diff --git a/crates/fspy_shared/src/ipc/channel/shm_io/layout.rs b/crates/fspy_shared/src/ipc/channel/shm_io/layout.rs index 93e94d81c..7c15cd8c5 100644 --- a/crates/fspy_shared/src/ipc/channel/shm_io/layout.rs +++ b/crates/fspy_shared/src/ipc/channel/shm_io/layout.rs @@ -7,7 +7,7 @@ //! an offset and a length always fit a descriptor's 32-bit fields and //! bounds checks add them in 32 bits. -use std::{num::NonZeroU32, ptr::NonNull, sync::atomic::AtomicU64}; +use core::{num::NonZeroU32, ptr::NonNull, sync::atomic::AtomicU64}; /// The CLOSED gate bit of the claim counter. The receiver sets it when it /// seals, and so does a claim the region had no room for, which is how it @@ -147,6 +147,13 @@ pub enum SlotState { /// Nothing is published in the slot: the writer has not finished it /// yet, or died or gave it up before finishing. The receiver ignores /// such slots. + #[cfg_attr( + target_os = "none", + expect( + dead_code, + reason = "target-none builds only the writer; the hosted reader uses it" + ) + )] Unfinished, /// A payload is committed: the receiver may read its span, once /// checked against the payload area's bounds. @@ -163,6 +170,13 @@ pub enum SlotState { impl SlotState { /// Decodes a slot value into its state. The two processes sharing a /// value run on one machine, so native byte order is fine. + #[cfg_attr( + target_os = "none", + expect( + dead_code, + reason = "target-none builds only the writer; the hosted reader uses it" + ) + )] pub const fn decode(slot_value: u64) -> Self { let [offset, len] = bytemuck::must_cast::(slot_value); let Some(len) = NonZeroU32::new(len) else { diff --git a/crates/fspy_shared/src/ipc/channel/shm_io/mod.rs b/crates/fspy_shared/src/ipc/channel/shm_io/mod.rs index 9bc6586a5..b542a447b 100644 --- a/crates/fspy_shared/src/ipc/channel/shm_io/mod.rs +++ b/crates/fspy_shared/src/ipc/channel/shm_io/mod.rs @@ -19,12 +19,14 @@ //! number. mod layout; +#[cfg(not(target_os = "none"))] mod reader; mod writer; -use std::ptr::slice_from_raw_parts_mut; +use core::ptr::slice_from_raw_parts_mut; use fspy_shm::Mapping; +#[cfg(not(target_os = "none"))] pub use reader::{SealError, ShmReader}; // Only tests name a claim's failure; a sender skips the record either // way, so production matches on `Ok`/`Err` alone. diff --git a/crates/fspy_shared/src/ipc/channel/shm_io/writer.rs b/crates/fspy_shared/src/ipc/channel/shm_io/writer.rs index 4b7eb1b9b..7187540ea 100644 --- a/crates/fspy_shared/src/ipc/channel/shm_io/writer.rs +++ b/crates/fspy_shared/src/ipc/channel/shm_io/writer.rs @@ -1,6 +1,6 @@ //! The writer side: claim a frame, fill it, finish it. -use std::{ +use core::{ num::{NonZeroU32, NonZeroUsize}, ops::{Deref, DerefMut}, slice, diff --git a/crates/fspy_shared/src/ipc/ipc_path.rs b/crates/fspy_shared/src/ipc/ipc_path.rs index 255c09009..ccc22fc10 100644 --- a/crates/fspy_shared/src/ipc/ipc_path.rs +++ b/crates/fspy_shared/src/ipc/ipc_path.rs @@ -1,13 +1,12 @@ +use core::{fmt::Debug, mem::MaybeUninit}; #[cfg(unix)] use std::ffi::OsStr; #[cfg(unix)] use std::os::unix::ffi::OsStrExt as _; -use std::{ - fmt::Debug, - mem::MaybeUninit, - path::{Path, PathBuf, StripPrefixError}, -}; +#[cfg(not(target_os = "none"))] +use std::path::{Path, PathBuf, StripPrefixError}; +#[cfg(not(target_os = "none"))] use bumpalo::Bump; use bytemuck::TransparentWrapper; use vt_ipc_str::IpcStr; @@ -57,16 +56,24 @@ unsafe impl<'de, C: Config> SchemaRead<'de, C> for &'de IpcPath { } impl IpcPath { + #[cfg(any(unix, target_os = "none"))] + #[must_use] + pub fn from_bytes(bytes: &[u8]) -> &Self { + Self::wrap_ref(IpcStr::from_bytes(bytes)) + } + #[cfg(windows)] #[must_use] pub fn from_wide(wide: &[u16]) -> &Self { Self::wrap_ref(IpcStr::from_wide(wide)) } + #[cfg(not(target_os = "none"))] pub fn clone_in<'bump>(&self, bump: &'bump Bump) -> &'bump Self { Self::wrap_ref(self.inner.clone_in(bump)) } + #[cfg(not(target_os = "none"))] pub fn strip_path_prefix, R, F: FnOnce(Result<&Path, StripPrefixError>) -> R>( &self, base: P, @@ -87,6 +94,7 @@ impl IpcPath { /// # Errors /// /// Returns an error if `base` is not a path prefix of the cleaned path. + #[cfg(not(target_os = "none"))] pub fn clean_and_strip_path_prefix>( &self, base: P, @@ -97,7 +105,7 @@ impl IpcPath { } impl Debug for IpcPath { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { ::fmt(&self.inner, f) } } @@ -105,6 +113,6 @@ impl Debug for IpcPath { #[cfg(unix)] impl<'a, S: AsRef + ?Sized> From<&'a S> for &'a IpcPath { fn from(value: &'a S) -> Self { - IpcPath::wrap_ref(IpcStr::from_bytes(value.as_ref().as_bytes())) + IpcPath::from_bytes(value.as_ref().as_bytes()) } } diff --git a/crates/fspy_shared/src/ipc/mod.rs b/crates/fspy_shared/src/ipc/mod.rs index 39a8c1ef4..1983fe200 100644 --- a/crates/fspy_shared/src/ipc/mod.rs +++ b/crates/fspy_shared/src/ipc/mod.rs @@ -1,7 +1,8 @@ pub mod channel; mod ipc_path; -use std::iter; +use core::iter; +#[cfg(not(target_os = "none"))] use bumpalo::Bump; pub use ipc_path::IpcPath; pub use vt_ipc_str::IpcStr; @@ -68,6 +69,7 @@ impl<'a> PathAccess<'a> { } } + #[cfg(not(target_os = "none"))] #[must_use] pub fn clone_in<'bump>(&self, bump: &'bump Bump) -> PathAccess<'bump> { match self { diff --git a/crates/fspy_shared/src/lib.rs b/crates/fspy_shared/src/lib.rs index e44d2b7ea..0cb88e9cf 100644 --- a/crates/fspy_shared/src/lib.rs +++ b/crates/fspy_shared/src/lib.rs @@ -1,3 +1,5 @@ +#![cfg_attr(target_os = "none", no_std)] + pub mod ipc; #[cfg(windows)] From fda100cc4bb942dec226ba1131b180acbbcccbc6 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sun, 6 Sep 2026 11:27:25 +0800 Subject: [PATCH 03/34] feat(fspy-elf-loader): define ELF execution API Co-authored-by: GPT-6 --- Cargo.lock | 7 +++++ crates/fspy_elf_loader/Cargo.toml | 14 ++++++++++ crates/fspy_elf_loader/src/lib.rs | 45 +++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+) create mode 100644 crates/fspy_elf_loader/Cargo.toml create mode 100644 crates/fspy_elf_loader/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 91c1bc3b7..e8d7a6ba6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1468,6 +1468,13 @@ dependencies = [ "toml", ] +[[package]] +name = "fspy_elf_loader" +version = "0.1.0" +dependencies = [ + "fspy_nostd", +] + [[package]] name = "fspy_nostd" version = "0.0.0" diff --git a/crates/fspy_elf_loader/Cargo.toml b/crates/fspy_elf_loader/Cargo.toml new file mode 100644 index 000000000..a337a3e23 --- /dev/null +++ b/crates/fspy_elf_loader/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "fspy_elf_loader" +version = "0.1.0" +authors.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true +rust-version.workspace = true + +[dependencies] +fspy_nostd = { workspace = true } + +[lints] +workspace = true diff --git a/crates/fspy_elf_loader/src/lib.rs b/crates/fspy_elf_loader/src/lib.rs new file mode 100644 index 000000000..bf02579c3 --- /dev/null +++ b/crates/fspy_elf_loader/src/lib.rs @@ -0,0 +1,45 @@ +#![no_std] + +use fspy_nostd::{CStr, OwnedFd, Thin}; + +/// Loads an ELF executable into the current process and enters it. +/// +/// Takes ownership of a private executable descriptor and closes it after +/// mapping. Loads the executable and its `PT_INTERP`, builds an initial stack, +/// and transfers control to the interpreter or executable entry point. +/// +/// `execfn` is the original execution name used for `AT_EXECFN`; it need not +/// match `argv[0]`. Arguments and environment entries are copied to the new +/// stack. `inherited_auxv` comes from the loader's kernel exec: image-specific +/// entries are replaced, reusable entries are preserved, and referenced data +/// is copied where needed. The resulting vector ends with `AT_NULL`. +/// +/// Path resolution, shebang handling, and execution-policy checks belong to +/// the caller. This function does not perform kernel exec cleanup: installed +/// signal handlers and their resident code and state must remain usable. +/// Loading failures terminate the process; they cannot return to the program +/// that executed the loader. +/// +/// # Safety +/// +/// Call only from a fresh, single-threaded loader process. The executable and +/// interpreter must be trusted to run with the process's current privileges. +/// Auxiliary entries must describe this process; any referenced memory must +/// remain readable and unchanged until copied or retained for the target. +/// The caller must permit execution to abandon its stack without running +/// destructors. Any retained handlers, mappings, or other process state must +/// remain valid while the target runs. +/// +/// # Panics +/// +/// Not implemented yet; currently always panics. +pub unsafe fn exec_elf<'a>( + elf_file: OwnedFd, + execfn: CStr<'a, Thin>, + argv: impl Iterator>, + envp: impl Iterator>, + inherited_auxv: impl Iterator, +) -> ! { + let _ = (elf_file, execfn, argv, envp, inherited_auxv); + unimplemented!() +} From ba9c3311ab15b741237cd373e9c1c65c23c0e8da Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sun, 6 Sep 2026 15:32:44 +0800 Subject: [PATCH 04/34] feat(fspy-nostd): add stdio and panic handling 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 --- crates/fspy_nostd/src/c_str.rs | 15 +++++ crates/fspy_nostd/src/error.rs | 3 + crates/fspy_nostd/src/fd.rs | 32 +++++++++- crates/fspy_nostd/src/fd/tests.rs | 98 +++++++++++++++++++++++++++++++ crates/fspy_nostd/src/io.rs | 25 ++++---- crates/fspy_nostd/src/lib.rs | 9 ++- crates/fspy_nostd/src/panic.rs | 45 ++++++++++++++ crates/fspy_nostd/src/stdio.rs | 38 ++++++++++++ 8 files changed, 252 insertions(+), 13 deletions(-) create mode 100644 crates/fspy_nostd/src/fd/tests.rs create mode 100644 crates/fspy_nostd/src/panic.rs create mode 100644 crates/fspy_nostd/src/stdio.rs diff --git a/crates/fspy_nostd/src/c_str.rs b/crates/fspy_nostd/src/c_str.rs index bf36cdf86..a012386ea 100644 --- a/crates/fspy_nostd/src/c_str.rs +++ b/crates/fspy_nostd/src/c_str.rs @@ -22,6 +22,7 @@ impl CStrUnit for u16 {} /// Marks a [`CStr`] whose length is not known. #[derive(Clone, Copy)] +#[repr(C)] pub struct Thin { _private: (), } @@ -36,13 +37,27 @@ pub struct Fat { /// /// [`CStr<'_, Thin>`] stores only the string pointer, while /// [`CStr<'_, Fat>`] also stores the length including the terminating NUL. +/// A thin view has the memory layout of a non-null code-unit pointer. #[derive(Clone, Copy)] +#[repr(C)] pub struct CStr<'a, R, U: CStrUnit = u8> { ptr: NonNull, repr: R, lifetime: PhantomData<&'a U>, } +const _: () = { + use core::mem::{align_of, offset_of, size_of}; + assert!(size_of::() == 0); + assert!(align_of::() == 1); + assert!(size_of::>() == size_of::<*const u8>()); + assert!(align_of::>() == align_of::<*const u8>()); + assert!(offset_of!(CStr<'_, Thin>, ptr) == 0); + assert!(size_of::>() == size_of::<*const u16>()); + assert!(align_of::>() == align_of::<*const u16>()); + assert!(offset_of!(CStr<'_, Thin, u16>, ptr) == 0); +}; + /// A borrowed NUL-terminated string of `u16` code units. pub type WideCStr<'a, R> = CStr<'a, R, u16>; diff --git a/crates/fspy_nostd/src/error.rs b/crates/fspy_nostd/src/error.rs index a873ef62c..08db08466 100644 --- a/crates/fspy_nostd/src/error.rs +++ b/crates/fspy_nostd/src/error.rs @@ -18,6 +18,7 @@ pub struct Error(u32); #[cfg(any(target_os = "linux", target_os = "none", target_os = "macos"))] impl Error { pub const BADF: Self = Self(errno::BADF); + pub const INTR: Self = Self(errno::INTR); pub const INVAL: Self = Self(errno::INVAL); pub const NOENT: Self = Self(errno::NOENT); pub const NOMEM: Self = Self(errno::NOMEM); @@ -87,6 +88,7 @@ impl From for Error { #[cfg(any(target_os = "linux", target_os = "none"))] mod errno { pub const BADF: i32 = linux_raw_sys::errno::EBADF.cast_signed(); + pub const INTR: i32 = linux_raw_sys::errno::EINTR.cast_signed(); pub const INVAL: i32 = linux_raw_sys::errno::EINVAL.cast_signed(); pub const NOMEM: i32 = linux_raw_sys::errno::ENOMEM.cast_signed(); pub const NOENT: i32 = linux_raw_sys::errno::ENOENT.cast_signed(); @@ -97,6 +99,7 @@ mod errno { #[cfg(target_os = "macos")] mod errno { pub const BADF: i32 = libc::EBADF; + pub const INTR: i32 = libc::EINTR; pub const INVAL: i32 = libc::EINVAL; pub const NOMEM: i32 = libc::ENOMEM; pub const NOENT: i32 = libc::ENOENT; diff --git a/crates/fspy_nostd/src/fd.rs b/crates/fspy_nostd/src/fd.rs index c7b894850..46a2818c6 100644 --- a/crates/fspy_nostd/src/fd.rs +++ b/crates/fspy_nostd/src/fd.rs @@ -1,4 +1,9 @@ -use core::marker::PhantomData; +use core::{fmt, marker::PhantomData}; + +use crate::{Error, Result}; + +#[cfg(test)] +mod tests; /// A raw Unix file descriptor. pub type RawFd = i32; @@ -64,6 +69,31 @@ impl BorrowedFd<'_> { } } +/// Writes UTF-8 directly, retrying interrupted and partial writes. +/// +/// Zero progress and other write errors return [`fmt::Error`]. Output may +/// already have been written when an error is returned. Writes may block, +/// interleave with other writers, or raise `SIGPIPE` on a broken pipe. +/// This implementation adds no locks or allocation; formatting arguments +/// may have their own runtime requirements. +impl fmt::Write for BorrowedFd<'_> { + fn write_str(&mut self, text: &str) -> fmt::Result { + write_all(text.as_bytes(), |bytes| crate::io::write(*self, bytes)) + } +} + +fn write_all(mut bytes: &[u8], mut write: impl FnMut(&[u8]) -> Result) -> fmt::Result { + while !bytes.is_empty() { + match write(bytes) { + Ok(0) => return Err(fmt::Error), + Ok(count) => bytes = bytes.get(count..).ok_or(fmt::Error)?, + Err(error) if error == Error::INTR => {} + Err(_) => return Err(fmt::Error), + } + } + Ok(()) +} + impl OwnedFd { /// Takes ownership of a raw descriptor returned by the operating system. /// diff --git a/crates/fspy_nostd/src/fd/tests.rs b/crates/fspy_nostd/src/fd/tests.rs new file mode 100644 index 000000000..ad6c6a74d --- /dev/null +++ b/crates/fspy_nostd/src/fd/tests.rs @@ -0,0 +1,98 @@ +use core::fmt::Write as _; +use std::{ + io::Read as _, + os::{fd::AsRawFd as _, unix::net::UnixStream}, + time::Duration, +}; + +use super::*; + +#[test] +fn formats_into_a_borrowed_descriptor() { + let (writer, mut reader) = UnixStream::pair().unwrap(); + reader.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + // SAFETY: writer owns the descriptor throughout this borrow. + let mut fd = unsafe { BorrowedFd::borrow_raw(writer.as_raw_fd()) }; + write!(fd, "value={} ", 42).unwrap(); + fd.write_char('é').unwrap(); + fd.write_str("\n").unwrap(); + + let expected = "value=42 é\n".as_bytes(); + let mut actual = vec![0; expected.len()]; + reader.read_exact(&mut actual).unwrap(); + assert_eq!(actual, expected); +} + +#[test] +fn writing_a_read_only_descriptor_returns_an_error() { + let file = std::fs::File::open("/dev/null").unwrap(); + // SAFETY: file owns the descriptor throughout this borrow. Write access + // is not required to borrow it; the kernel rejects the write below. + let mut fd = unsafe { BorrowedFd::borrow_raw(file.as_raw_fd()) }; + assert_eq!(fd.write_str("test"), Err(fmt::Error)); +} + +#[test] +fn retries_interrupted_and_partial_writes() { + let expected = "éxyz".as_bytes(); + let mut results = [Err(Error::INTR), Ok(1), Err(Error::INTR), Ok(1), Ok(3)].into_iter(); + let mut output = Vec::new(); + write_all(expected, |bytes| { + let result = results.next().unwrap(); + if let Ok(count) = result { + output.extend_from_slice(&bytes[..count]); + } + result + }) + .unwrap(); + assert_eq!(output, expected); + assert!(results.next().is_none()); +} + +#[test] +fn empty_text_needs_no_write() { + let mut calls = 0; + assert_eq!( + write_all(b"", |_| { + calls += 1; + Err(Error::BADF) + }), + Ok(()) + ); + assert_eq!(calls, 0); +} + +#[test] +fn zero_progress_and_errors_do_not_retry() { + #[cfg(any(target_os = "linux", target_os = "none"))] + let again = Error::from_raw_os_error(linux_raw_sys::errno::EAGAIN.cast_signed()); + #[cfg(target_os = "macos")] + let again = Error::from_raw_os_error(libc::EAGAIN); + + for result in [Ok(0), Ok(4), Err(Error::BADF), Err(again)] { + let mut calls = 0; + assert_eq!( + write_all(b"abc", |_| { + calls += 1; + result + }), + Err(fmt::Error) + ); + assert_eq!(calls, 1); + } +} + +#[test] +fn reports_an_error_after_a_partial_write() { + let mut results = [Ok(1), Err(Error::BADF)].into_iter(); + assert_eq!(write_all(b"abc", |_| results.next().unwrap()), Err(fmt::Error)); + assert!(results.next().is_none()); +} + +#[test] +fn standard_descriptors_have_the_expected_numbers() { + // SAFETY: the std test process keeps its standard descriptors open. + let (stdout, stderr) = unsafe { (crate::stdio::stdout(), crate::stdio::stderr()) }; + assert_eq!(stdout.as_raw_fd(), 1); + assert_eq!(stderr.as_raw_fd(), 2); +} diff --git a/crates/fspy_nostd/src/io.rs b/crates/fspy_nostd/src/io.rs index abad39b91..bba554c2e 100644 --- a/crates/fspy_nostd/src/io.rs +++ b/crates/fspy_nostd/src/io.rs @@ -1,8 +1,4 @@ //! I/O calls with caller-owned buffers. -//! -//! Linux only: these go straight to the kernel with no libc wrapper, so they -//! are usable from a signal handler, a post-`fork()` child, or freestanding -//! injected code. use crate::{BorrowedFd, Error, Result}; @@ -12,6 +8,7 @@ use crate::{BorrowedFd, Error, Result}; /// # Errors /// /// Returns the error reported by `read`. +#[cfg(any(target_os = "linux", target_os = "none"))] pub fn read(fd: BorrowedFd<'_>, buf: &mut [u8]) -> Result { // SAFETY: `fd` stays borrowed and `buf` is writable for its whole length. unsafe { @@ -30,12 +27,18 @@ pub fn read(fd: BorrowedFd<'_>, buf: &mut [u8]) -> Result { /// /// Returns the error reported by `write`. pub fn write(fd: BorrowedFd<'_>, buf: &[u8]) -> Result { - // SAFETY: `fd` stays borrowed for the call and `buf` is readable for its - // whole length. The kernel receives the descriptor, buffer pointer, and - // length explicitly and returns the accepted byte count. - let written = unsafe { - syscalls::syscall!(syscalls::Sysno::write, fd.as_raw_fd(), buf.as_ptr(), buf.len()) + #[cfg(any(target_os = "linux", target_os = "none"))] + { + // SAFETY: `fd` stays borrowed and `buf` is readable for its full length. + unsafe { + syscalls::syscall!(syscalls::Sysno::write, fd.as_raw_fd(), buf.as_ptr(), buf.len()) + } + .map_err(Error::from) + } + #[cfg(target_os = "macos")] + { + // SAFETY: `fd` stays borrowed and `buf` is readable for its full length. + let written = unsafe { libc::write(fd.as_raw_fd(), buf.as_ptr().cast(), buf.len()) }; + if written == -1 { Err(Error::last_os_error()) } else { Ok(written.cast_unsigned()) } } - .map_err(Error::from)?; - Ok(written) } diff --git a/crates/fspy_nostd/src/lib.rs b/crates/fspy_nostd/src/lib.rs index 8a0ec38cb..7f22fce55 100644 --- a/crates/fspy_nostd/src/lib.rs +++ b/crates/fspy_nostd/src/lib.rs @@ -11,6 +11,8 @@ mod c_str; mod error; #[cfg(any(target_os = "linux", target_os = "none", target_os = "macos"))] mod fd; +#[cfg(any(target_os = "linux", target_os = "none"))] +mod panic; #[cfg(windows)] mod windows; @@ -18,17 +20,22 @@ mod windows; pub mod env; #[cfg(any(target_os = "linux", target_os = "none", target_os = "macos", windows))] pub mod fs; -#[cfg(any(target_os = "linux", target_os = "none"))] +#[cfg(any(target_os = "linux", target_os = "none", target_os = "macos"))] pub mod io; #[cfg(any(target_os = "linux", target_os = "none", target_os = "macos", windows))] pub mod mm; #[cfg(any(target_os = "linux", target_os = "none", target_os = "macos"))] pub mod param; +#[cfg(any(target_os = "linux", target_os = "none", target_os = "macos"))] +pub mod stdio; pub use c_str::{CStr, CStrUnit, Fat, OsCStr, Thin, Units, WideCStr}; pub use error::{Error, Result}; #[cfg(any(target_os = "linux", target_os = "none", target_os = "macos"))] pub use fd::{BorrowedFd, CWD, OwnedFd, RawFd}; +#[cfg(any(target_os = "linux", target_os = "none"))] +#[doc(hidden)] +pub use panic::handle as __panic_handler; #[cfg(windows)] pub use windows::{ BorrowedHandle, OwnedHandle, RawHandle, SecurityAttributes, bool_result, get_module_handle, diff --git a/crates/fspy_nostd/src/panic.rs b/crates/fspy_nostd/src/panic.rs new file mode 100644 index 000000000..45dd951cb --- /dev/null +++ b/crates/fspy_nostd/src/panic.rs @@ -0,0 +1,45 @@ +use core::{ + fmt::Write as _, + panic::PanicInfo, + sync::atomic::{AtomicBool, Ordering}, +}; + +/// Installs a Linux panic handler in a freestanding executable. +/// +/// Invoke once as `fspy_nostd::panic_handler!()`. Do not combine it with `std` +/// or another panic handler. +/// The executable must keep stderr open and unreplaced until termination. +/// +/// Prints the panic to descriptor 2, then calls `exit_group(101)` without +/// unwinding or running destructors. Output errors are ignored. Recursive or +/// concurrent panics skip printing and terminate immediately. +/// +/// This uses no libc, allocation, or locks. Formatting the panic message may +/// invoke user code, and writing may block or raise `SIGPIPE`. The process's +/// syscall policy must allow the writes and process termination. +#[macro_export] +macro_rules! panic_handler { + () => { + const _: () = { + #[panic_handler] + fn panic(info: &::core::panic::PanicInfo<'_>) -> ! { + $crate::__panic_handler(info) + } + }; + }; +} + +pub fn handle(info: &PanicInfo<'_>) -> ! { + static PANICKING: AtomicBool = AtomicBool::new(false); + // This only elects the first printer; there is no shared payload to order. + if !PANICKING.swap(true, Ordering::Relaxed) { + // SAFETY: the executable keeps stderr open until termination, as + // required by panic_handler!'s contract. + let mut stderr = unsafe { crate::stdio::stderr() }; + let _ = writeln!(stderr, "{info}"); + } + loop { + // SAFETY: terminates the process without accessing userspace memory. + let _ = unsafe { syscalls::syscall!(syscalls::Sysno::exit_group, 101) }; + } +} diff --git a/crates/fspy_nostd/src/stdio.rs b/crates/fspy_nostd/src/stdio.rs new file mode 100644 index 000000000..6a83faf9a --- /dev/null +++ b/crates/fspy_nostd/src/stdio.rs @@ -0,0 +1,38 @@ +//! Borrowed standard output and standard error descriptors. +//! +//! These do not buffer output or coordinate with other writers. + +use crate::BorrowedFd; + +#[cfg(any(target_os = "linux", target_os = "none"))] +const STDOUT_FILENO: crate::RawFd = linux_raw_sys::general::STDOUT_FILENO.cast_signed(); +#[cfg(any(target_os = "linux", target_os = "none"))] +const STDERR_FILENO: crate::RawFd = linux_raw_sys::general::STDERR_FILENO.cast_signed(); +#[cfg(target_os = "macos")] +use libc::{STDERR_FILENO, STDOUT_FILENO}; + +/// Borrows the standard output descriptor without taking ownership. +/// +/// # Safety +/// +/// The descriptor must remain open for the returned borrow's lifetime; no +/// thread may close or replace it during that time. +#[inline] +#[must_use] +pub const unsafe fn stdout() -> BorrowedFd<'static> { + // SAFETY: the caller keeps the standard output descriptor open. + unsafe { BorrowedFd::borrow_raw(STDOUT_FILENO) } +} + +/// Borrows the standard error descriptor without taking ownership. +/// +/// # Safety +/// +/// The descriptor must remain open for the returned borrow's lifetime; no +/// thread may close or replace it during that time. +#[inline] +#[must_use] +pub const unsafe fn stderr() -> BorrowedFd<'static> { + // SAFETY: the caller keeps the standard error descriptor open. + unsafe { BorrowedFd::borrow_raw(STDERR_FILENO) } +} From 1ffd188c60fcd2053c242c3dd85d31f105c977f8 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sun, 6 Sep 2026 15:48:10 +0800 Subject: [PATCH 05/34] feat(fspy-nostd): add Linux entry point and initial stack views 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 --- crates/fspy_nostd/Cargo.toml | 3 - crates/fspy_nostd/src/entry.rs | 60 ++++++ crates/fspy_nostd/src/env/initial_stack.rs | 204 +++++++++++++++++++++ crates/fspy_nostd/src/env/mod.rs | 10 +- crates/fspy_nostd/src/lib.rs | 2 + crates/fspy_nostd/src/panic.rs | 2 +- 6 files changed, 276 insertions(+), 5 deletions(-) create mode 100644 crates/fspy_nostd/src/entry.rs create mode 100644 crates/fspy_nostd/src/env/initial_stack.rs diff --git a/crates/fspy_nostd/Cargo.toml b/crates/fspy_nostd/Cargo.toml index 6ad5ef3b0..1e46062bb 100644 --- a/crates/fspy_nostd/Cargo.toml +++ b/crates/fspy_nostd/Cargo.toml @@ -4,9 +4,6 @@ edition = "2024" license.workspace = true publish = false -[lib] -doctest = false - [dependencies] # Only the borrowed `BStr` type is used. Keeping every feature disabled makes # the environment iterator usable without `alloc` or `std`. diff --git a/crates/fspy_nostd/src/entry.rs b/crates/fspy_nostd/src/entry.rs new file mode 100644 index 000000000..bf0f9b839 --- /dev/null +++ b/crates/fspy_nostd/src/entry.rs @@ -0,0 +1,60 @@ +/// Defines the entry point for a freestanding Linux executable. +/// +/// Invoke once as `fspy_nostd::main!(run)`, where `run` has signature +/// `fn(fspy_nostd::env::InitialStack<'_>) -> !`. The macro parses the original +/// Linux stack before calling this safe Rust function. The callback must +/// accept any stack lifetime; it cannot require `InitialStack<'static>`. +/// +/// ```compile_fail,E0308 +/// #![no_std] +/// #![no_main] +/// +/// fn run(_: fspy_nostd::env::InitialStack<'static>) -> ! { +/// loop {} +/// } +/// fspy_nostd::main!(run); +/// ``` +/// +/// Supports `AArch64` and x86-64. The executable must use `#![no_main]` and +/// must not link `std`, another entry point, or another panic handler. +/// This installs [`crate::panic_handler`], which prints panics and terminates +/// with status 101. Stderr must remain open and unreplaced until termination. +/// This does not initialize libc, TLS, or Rust's standard runtime. +#[macro_export] +macro_rules! main { + ($run:path $(,)?) => { + $crate::panic_handler!(); + + const _: () = { + unsafe extern "C" fn __fspy_entry(sp: *const usize) -> ! { + let run: for<'a> fn($crate::env::InitialStack<'a>) -> ! = $run; + // SAFETY: `_start` passes the untouched Linux entry stack. + // The callback borrows it immutably; unsafe code that replaces + // its storage must preserve the validity of these borrows. + let stack = unsafe { $crate::env::InitialStack::from_ptr(sp) }; + run(stack) + } + + #[cfg(target_arch = "aarch64")] + #[unsafe(naked)] + #[unsafe(no_mangle)] + unsafe extern "C" fn _start() -> ! { + // Capture SP before any stack frame is created. BL keeps its + // alignment and puts the return address in the link register. + ::core::arch::naked_asm!("mov x0, sp", "bl {entry}", "brk #0", entry = sym __fspy_entry) + } + + #[cfg(target_arch = "x86_64")] + #[unsafe(naked)] + #[unsafe(no_mangle)] + unsafe extern "C" fn _start() -> ! { + // Linux enters with RSP aligned to 16 bytes. CALL pushes the + // return address, giving the bridge normal C entry alignment. + ::core::arch::naked_asm!("mov rdi, rsp", "call {entry}", "ud2", entry = sym __fspy_entry) + } + + #[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))] + compile_error!("fspy_nostd::main! supports only AArch64 and x86-64"); + }; + }; +} diff --git a/crates/fspy_nostd/src/env/initial_stack.rs b/crates/fspy_nostd/src/env/initial_stack.rs new file mode 100644 index 000000000..fb1107646 --- /dev/null +++ b/crates/fspy_nostd/src/env/initial_stack.rs @@ -0,0 +1,204 @@ +use core::slice; + +use crate::{CStr, Thin}; + +/// A native-word entry in the Linux auxiliary vector. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[repr(C)] +pub struct AuxEntry { + pub key: usize, + pub value: usize, +} + +const _: () = { + use core::mem::{align_of, offset_of, size_of}; + assert!(size_of::() == 2 * size_of::()); + assert!(align_of::() == align_of::()); + assert!(offset_of!(AuxEntry, key) == 0); + assert!(offset_of!(AuxEntry, value) == size_of::()); +}; + +/// An immutable view of the stack supplied at Linux executable entry. +/// +/// Locates argument pointers, environment pointers, and auxiliary entries +/// without allocating or counting string lengths. The slices borrow the stack +/// directly. Dropping the view does not release the stack or its contents. +pub struct InitialStack<'a> { + arguments: &'a [CStr<'a, Thin>], + environment: &'a [CStr<'a, Thin>], + auxiliary: &'a [AuxEntry], +} + +impl<'a> InitialStack<'a> { + /// Borrows the original stack captured by the executable's entry trampoline. + /// + /// # Safety + /// + /// `sp` must be aligned and point to a readable Linux initial stack in one + /// allocation: argc, argc non-null argument pointers, a null pointer, + /// environment pointers ending in null, and auxiliary pairs ending in + /// `AT_NULL`. The complete region must fit in `isize::MAX` bytes. + /// + /// Every string pointer must name an immutable NUL-terminated string. + /// Stack storage, strings, and memory referenced by auxiliary entries must + /// remain valid and unchanged for `'a`. String pointers must carry valid + /// provenance for their strings. + /// This reads the entry stack, not the current stack of a Rust function. + #[must_use] + pub const unsafe fn from_ptr(sp: *const usize) -> Self { + // SAFETY: the caller supplies argc followed by that many pointers and + // a terminator, all within the initial-stack allocation. Thin CStr + // has pointer layout; the counted entries are non-null valid strings. + let (arguments, environment) = unsafe { + let count = sp.read(); + let start = sp.add(1).cast::<*const u8>(); + (slice::from_raw_parts(start.cast::>(), count), start.add(count).add(1)) + }; + let mut count = 0; + // SAFETY: environment pointers are readable through their terminator. + while !unsafe { environment.add(count).read() }.is_null() { + count += 1; + } + // SAFETY: the scan found the entire environment region; auxiliary + // pairs follow its terminator and have the same word alignment. The + // terminator is excluded before borrowing entries as non-null CStrs. + let (environment, auxiliary) = unsafe { + ( + slice::from_raw_parts(environment.cast::>(), count), + environment.add(count).add(1).cast::(), + ) + }; + let mut count = 0; + // SAFETY: auxiliary pairs are readable through AT_NULL, whose key is 0. + while unsafe { auxiliary.add(count).read().key } != 0 { + count += 1; + } + // SAFETY: the scan found all non-terminating pairs in the allocation. + let auxiliary = unsafe { slice::from_raw_parts(auxiliary, count) }; + Self { arguments, environment, auxiliary } + } + + /// Borrows arguments, including argv[0], without the null terminator. + #[must_use] + pub const fn args(&self) -> &'a [CStr<'a, Thin>] { + self.arguments + } + + /// Borrows complete environment strings without the null terminator. + /// + /// Entries are preserved verbatim, including entries without `=`. + #[must_use] + pub const fn envs(&self) -> &'a [CStr<'a, Thin>] { + self.environment + } + + /// Borrows auxiliary key/value pairs, excluding `AT_NULL`. + /// + /// Values are unchanged and may contain pointers into the original stack. + #[must_use] + pub const fn auxv(&self) -> &'a [AuxEntry] { + self.auxiliary + } +} + +#[cfg(test)] +mod tests { + use core::ptr; + + use super::*; + + #[repr(C)] + struct Stack { + count: usize, + arguments: [*const u8; A], + arguments_end: *const u8, + environment: [*const u8; E], + environment_end: *const u8, + auxiliary: [AuxEntry; V], + } + + #[test] + fn preserves_strings_and_auxiliary_values() { + let random = [42_u8; 16]; + let raw = Stack { + count: 3, + arguments: [ + c"custom-argv-zero".as_ptr().cast(), + c"".as_ptr().cast(), + c"\xff".as_ptr().cast(), + ], + arguments_end: ptr::null(), + environment: [ + c"KEY=value=tail".as_ptr().cast(), + c"EMPTY=".as_ptr().cast(), + c"NO_EQUALS".as_ptr().cast(), + c"".as_ptr().cast(), + ], + environment_end: ptr::null(), + auxiliary: [ + AuxEntry { key: 6, value: 4096 }, + AuxEntry { key: 25, value: random.as_ptr().expose_provenance() }, + AuxEntry { key: 0x1234, value: 0 }, + AuxEntry { key: 0, value: 0 }, + AuxEntry { key: 99, value: 99 }, + ], + }; + // SAFETY: raw models the Linux layout; all strings and auxiliary + // data remain readable and immutable until the view is discarded. + let stack = unsafe { InitialStack::from_ptr(ptr::from_ref(&raw).cast()) }; + assert_eq!(stack.args().len(), 3); + for (arg, expected) in + stack.args().iter().zip([b"custom-argv-zero".as_slice(), b"", b"\xff"]) + { + assert_eq!(arg.count().as_units(), expected); + } + assert_eq!(stack.envs().len(), 4); + for (env, expected) in + stack.envs().iter().zip([b"KEY=value=tail".as_slice(), b"EMPTY=", b"NO_EQUALS", b""]) + { + assert_eq!(env.count().as_units(), expected); + } + assert_eq!(stack.auxv(), &raw.auxiliary[..3]); + // The arrays and their strings are borrowed, not copied. + assert_eq!(stack.args()[0].as_ptr(), raw.arguments[0]); + assert_eq!(stack.args().as_ptr().cast(), raw.arguments.as_ptr()); + assert_eq!(stack.envs().as_ptr().cast(), raw.environment.as_ptr()); + assert_eq!(stack.auxv().as_ptr(), raw.auxiliary.as_ptr()); + } + + #[test] + fn accepts_empty_regions() { + let raw = Stack { + count: 0, + arguments: [], + arguments_end: ptr::null(), + environment: [], + environment_end: ptr::null(), + auxiliary: [AuxEntry { key: 0, value: 0 }], + }; + // SAFETY: argc is zero, both pointer arrays and auxv end immediately. + let stack = unsafe { InitialStack::from_ptr(ptr::from_ref(&raw).cast()) }; + assert!(stack.args().is_empty()); + assert!(stack.envs().is_empty()); + assert!(stack.auxv().is_empty()); + } + + #[test] + fn slices_borrow_storage_independently_of_view() { + let raw = Stack { + count: 1, + arguments: [c"arg".as_ptr().cast()], + arguments_end: ptr::null(), + environment: [], + environment_end: ptr::null(), + auxiliary: [AuxEntry { key: 0, value: 0 }], + }; + let args = { + // SAFETY: backing storage and literal outlive the returned slice. + let stack = unsafe { InitialStack::from_ptr(ptr::from_ref(&raw).cast()) }; + stack.args() + }; + assert_eq!(args.len(), 1); + assert_eq!(args[0].count().as_units(), b"arg"); + } +} diff --git a/crates/fspy_nostd/src/env/mod.rs b/crates/fspy_nostd/src/env/mod.rs index ff7ffd2b3..b36a255b5 100644 --- a/crates/fspy_nostd/src/env/mod.rs +++ b/crates/fspy_nostd/src/env/mod.rs @@ -5,19 +5,27 @@ //! arrays exposed by `_NSGetArgv` and `_NSGetEnviron`. //! //! macOS additionally exposes `args` and `envs` as direct thin C-string -//! views. Neither platform interface can attach a lifetime to its +//! views. Neither platform's `current` interface can attach a lifetime to its //! process-global storage, so construction is unsafe and yielded views //! deliberately carry a `'static` lifetime. +//! +//! On Linux, `InitialStack` instead borrows the original entry stack supplied +//! by the caller, without querying `/proc`. Its views retain that lifetime. use bstr::BStr; use crate::{CStr, Fat}; +// The parser is portable Rust; also exercise its synthetic layouts on macOS. +#[cfg(any(target_os = "linux", target_os = "none", test))] +mod initial_stack; #[cfg(any(target_os = "linux", target_os = "none"))] mod linux; #[cfg(target_os = "macos")] mod mac; +#[cfg(any(target_os = "linux", target_os = "none"))] +pub use initial_stack::{AuxEntry, InitialStack}; #[cfg(any(target_os = "linux", target_os = "none"))] pub use linux::{Current, FatArgs, FatEnvs, current}; #[cfg(target_os = "macos")] diff --git a/crates/fspy_nostd/src/lib.rs b/crates/fspy_nostd/src/lib.rs index 7f22fce55..c6a6ce6aa 100644 --- a/crates/fspy_nostd/src/lib.rs +++ b/crates/fspy_nostd/src/lib.rs @@ -8,6 +8,8 @@ #![cfg_attr(not(test), no_std)] mod c_str; +#[cfg(any(target_os = "linux", target_os = "none"))] +mod entry; mod error; #[cfg(any(target_os = "linux", target_os = "none", target_os = "macos"))] mod fd; diff --git a/crates/fspy_nostd/src/panic.rs b/crates/fspy_nostd/src/panic.rs index 45dd951cb..07b3e89e9 100644 --- a/crates/fspy_nostd/src/panic.rs +++ b/crates/fspy_nostd/src/panic.rs @@ -7,7 +7,7 @@ use core::{ /// Installs a Linux panic handler in a freestanding executable. /// /// Invoke once as `fspy_nostd::panic_handler!()`. Do not combine it with `std` -/// or another panic handler. +/// or another panic handler. [`crate::main`] already installs this handler. /// The executable must keep stderr open and unreplaced until termination. /// /// Prints the panic to descriptor 2, then calls `exit_group(101)` without From 4e3f3ee8147e78b5133c8341403e5b481a9ecf7c Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sun, 6 Sep 2026 15:58:44 +0800 Subject: [PATCH 06/34] refactor(fspy-elf-loader): use shared auxiliary vector entries Use fspy_nostd::env::AuxEntry for inherited auxv and restrict ELF execution to the Linux and none targets. Co-authored-by: GPT-5 Codex --- crates/fspy_elf_loader/src/lib.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/crates/fspy_elf_loader/src/lib.rs b/crates/fspy_elf_loader/src/lib.rs index bf02579c3..b039fcb32 100644 --- a/crates/fspy_elf_loader/src/lib.rs +++ b/crates/fspy_elf_loader/src/lib.rs @@ -1,6 +1,8 @@ +// ELF execution uses the Linux process ABI. +#![cfg(any(target_os = "linux", target_os = "none"))] #![no_std] -use fspy_nostd::{CStr, OwnedFd, Thin}; +use fspy_nostd::{CStr, OwnedFd, Thin, env::AuxEntry}; /// Loads an ELF executable into the current process and enters it. /// @@ -10,9 +12,10 @@ use fspy_nostd::{CStr, OwnedFd, Thin}; /// /// `execfn` is the original execution name used for `AT_EXECFN`; it need not /// match `argv[0]`. Arguments and environment entries are copied to the new -/// stack. `inherited_auxv` comes from the loader's kernel exec: image-specific -/// entries are replaced, reusable entries are preserved, and referenced data -/// is copied where needed. The resulting vector ends with `AT_NULL`. +/// stack. `inherited_auxv` supplies [`AuxEntry`] values from the loader's kernel +/// exec, excluding `AT_NULL`. Image-specific entries are replaced, reusable +/// entries are preserved, and referenced data is copied where needed. The +/// resulting vector ends with `AT_NULL`. /// /// Path resolution, shebang handling, and execution-policy checks belong to /// the caller. This function does not perform kernel exec cleanup: installed @@ -38,7 +41,7 @@ pub unsafe fn exec_elf<'a>( execfn: CStr<'a, Thin>, argv: impl Iterator>, envp: impl Iterator>, - inherited_auxv: impl Iterator, + inherited_auxv: impl Iterator, ) -> ! { let _ = (elf_file, execfn, argv, envp, inherited_auxv); unimplemented!() From 6131d2be0d22cedc4dd9f6d265e2b1e1cec52aa6 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sun, 6 Sep 2026 15:59:54 +0800 Subject: [PATCH 07/34] test(fspy-elf-loader): add freestanding launcher 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 --- crates/fspy_elf_loader/Cargo.toml | 6 +++ .../fspy_elf_loader/tests/support/launcher.rs | 38 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 crates/fspy_elf_loader/tests/support/launcher.rs diff --git a/crates/fspy_elf_loader/Cargo.toml b/crates/fspy_elf_loader/Cargo.toml index a337a3e23..b3b52216d 100644 --- a/crates/fspy_elf_loader/Cargo.toml +++ b/crates/fspy_elf_loader/Cargo.toml @@ -10,5 +10,11 @@ rust-version.workspace = true [dependencies] fspy_nostd = { workspace = true } +[[bin]] +name = "fspy_elf_loader_test_launcher" +path = "tests/support/launcher.rs" +test = false +bench = false + [lints] workspace = true diff --git a/crates/fspy_elf_loader/tests/support/launcher.rs b/crates/fspy_elf_loader/tests/support/launcher.rs new file mode 100644 index 000000000..53e13c6f1 --- /dev/null +++ b/crates/fspy_elf_loader/tests/support/launcher.rs @@ -0,0 +1,38 @@ +#![cfg_attr(target_os = "none", no_std)] +#![cfg_attr(target_os = "none", no_main)] + +#[cfg(not(target_os = "none"))] +fn main() {} + +#[cfg(target_os = "none")] +mod freestanding { + use fspy_nostd::{ + CWD, + fs::{Mode, OFlags, openat}, + }; + + fspy_nostd::main!(run); + + // The kernel enters with argc, argv, envp, and auxv on the initial stack. + // Consume those views before exec_elf replaces the stack. + #[expect(clippy::needless_pass_by_value, reason = "signature required by main!")] + fn run(stack: fspy_nostd::env::InitialStack<'_>) -> ! { + let mut args = stack.args().iter().copied(); + let _launcher = args.next().expect("missing launcher argv[0]"); + let path = args.next().expect("missing target path"); + let file = openat(CWD, path, OFlags::RDONLY | OFlags::CLOEXEC, Mode::empty()) + .expect("cannot open target"); + // SAFETY: this is a fresh single-threaded freestanding process. The + // parent selects a trusted fixture and kernel auxv references stay + // valid until copied. There is no runtime requiring stack cleanup. + unsafe { + fspy_elf_loader::exec_elf( + file, + path, + args, + stack.envs().iter().copied(), + stack.auxv().iter().copied(), + ) + } + } +} From 0d0f3ee2d976bf9f66b9542c3e1e9e1871c6c721 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Thu, 10 Sep 2026 22:20:49 +0800 Subject: [PATCH 08/34] feat(fspy-nostd): add link-time global allocator guard 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 --- Cargo.lock | 1 + .../fspy_elf_loader/tests/support/launcher.rs | 1 + crates/fspy_nostd/Cargo.toml | 3 + crates/fspy_nostd/src/entry.rs | 2 + crates/fspy_nostd/src/lib.rs | 2 + crates/fspy_nostd/src/mm.rs | 3 + crates/fspy_nostd/src/no_global_alloc.rs | 57 +++++++++++++++++++ crates/fspy_nostd/tests/no_global_alloc.rs | 46 +++++++++++++++ .../tests/support/no_global_alloc.rs | 42 ++++++++++++++ 9 files changed, 157 insertions(+) create mode 100644 crates/fspy_nostd/src/no_global_alloc.rs create mode 100644 crates/fspy_nostd/tests/no_global_alloc.rs create mode 100644 crates/fspy_nostd/tests/support/no_global_alloc.rs diff --git a/Cargo.lock b/Cargo.lock index e8d7a6ba6..9c76cf1a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1485,6 +1485,7 @@ dependencies = [ "libc", "linux-raw-sys 0.12.1", "syscalls", + "tempfile", "windows-sys 0.61.2", ] diff --git a/crates/fspy_elf_loader/tests/support/launcher.rs b/crates/fspy_elf_loader/tests/support/launcher.rs index 53e13c6f1..b72793b8f 100644 --- a/crates/fspy_elf_loader/tests/support/launcher.rs +++ b/crates/fspy_elf_loader/tests/support/launcher.rs @@ -12,6 +12,7 @@ mod freestanding { }; fspy_nostd::main!(run); + fspy_nostd::no_global_alloc!(); // The kernel enters with argc, argv, envp, and auxv on the initial stack. // Consume those views before exec_elf replaces the stack. diff --git a/crates/fspy_nostd/Cargo.toml b/crates/fspy_nostd/Cargo.toml index 1e46062bb..d11fe81a1 100644 --- a/crates/fspy_nostd/Cargo.toml +++ b/crates/fspy_nostd/Cargo.toml @@ -32,3 +32,6 @@ windows-sys = { workspace = true, features = [ [lints] workspace = true + +[dev-dependencies] +tempfile = { workspace = true } diff --git a/crates/fspy_nostd/src/entry.rs b/crates/fspy_nostd/src/entry.rs index bf0f9b839..2879e3ebd 100644 --- a/crates/fspy_nostd/src/entry.rs +++ b/crates/fspy_nostd/src/entry.rs @@ -20,6 +20,8 @@ /// This installs [`crate::panic_handler`], which prints panics and terminates /// with status 101. Stderr must remain open and unreplaced until termination. /// This does not initialize libc, TLS, or Rust's standard runtime. +/// It does not apply dynamic relocations; link a fixed-address executable +/// unless relocation has already been handled before entering `_start`. #[macro_export] macro_rules! main { ($run:path $(,)?) => { diff --git a/crates/fspy_nostd/src/lib.rs b/crates/fspy_nostd/src/lib.rs index c6a6ce6aa..e10fda1ca 100644 --- a/crates/fspy_nostd/src/lib.rs +++ b/crates/fspy_nostd/src/lib.rs @@ -13,6 +13,8 @@ mod entry; mod error; #[cfg(any(target_os = "linux", target_os = "none", target_os = "macos"))] mod fd; +#[doc(hidden)] +pub mod no_global_alloc; #[cfg(any(target_os = "linux", target_os = "none"))] mod panic; #[cfg(windows)] diff --git a/crates/fspy_nostd/src/mm.rs b/crates/fspy_nostd/src/mm.rs index 4c5acc8c7..b84b75a09 100644 --- a/crates/fspy_nostd/src/mm.rs +++ b/crates/fspy_nostd/src/mm.rs @@ -53,6 +53,9 @@ mod unix { const SHARED = imp::MAP_SHARED; /// Changes are private to this mapping. const PRIVATE = imp::MAP_PRIVATE; + /// Replace mappings at the requested address instead of using it as a hint. + #[cfg(any(target_os = "linux", target_os = "none"))] + const FIXED = linux_raw_sys::general::MAP_FIXED; } } diff --git a/crates/fspy_nostd/src/no_global_alloc.rs b/crates/fspy_nostd/src/no_global_alloc.rs new file mode 100644 index 000000000..6ef0be127 --- /dev/null +++ b/crates/fspy_nostd/src/no_global_alloc.rs @@ -0,0 +1,57 @@ +use core::alloc::{GlobalAlloc, Layout}; + +#[doc(hidden)] +pub struct ForbiddenGlobalAllocator; + +unsafe extern "C" { + // Do not return `!`: allocator calls carry optimizer attributes + // that can erase calls to a known non-returning implementation. + fn __fspy_global_allocator_must_not_be_used() -> *mut u8; +} + +// SAFETY: no operation can execute: any retained call fails to link +// because the referenced symbol has no definition. +unsafe impl GlobalAlloc for ForbiddenGlobalAllocator { + unsafe fn alloc(&self, _: Layout) -> *mut u8 { + // SAFETY: this symbol must remain undefined; see above. + unsafe { __fspy_global_allocator_must_not_be_used() } + } + + unsafe fn dealloc(&self, _: *mut u8, _: Layout) { + // SAFETY: this symbol must remain undefined; see above. + unsafe { __fspy_global_allocator_must_not_be_used() }; + } + + unsafe fn alloc_zeroed(&self, _: Layout) -> *mut u8 { + // SAFETY: this symbol must remain undefined; see above. + unsafe { __fspy_global_allocator_must_not_be_used() } + } + + unsafe fn realloc(&self, _: *mut u8, _: Layout, _: usize) -> *mut u8 { + // SAFETY: this symbol must remain undefined; see above. + unsafe { __fspy_global_allocator_must_not_be_used() } + } +} + +/// Registers a global allocator that fails to link if used. +/// +/// Invoke once in the final binary as `fspy_nostd::no_global_alloc!()`. +/// This satisfies `alloc`'s allocator requirement while allowing collections +/// backed by explicit allocators. Every global allocation, deallocation, +/// zeroed allocation, or reallocation calls an intentionally undefined symbol. +/// +/// The final linker must discard unused code and reject unresolved symbols. +/// This checks code retained after optimization, not every source-level call. +/// Shared libraries that allow unresolved symbols need stricter linker flags. +/// Do not define `__fspy_global_allocator_must_not_be_used` or register another +/// global allocator alongside this one. +#[macro_export] +macro_rules! no_global_alloc { + () => { + const _: () = { + #[::core::prelude::v1::global_allocator] + static ALLOCATOR: $crate::no_global_alloc::ForbiddenGlobalAllocator = + $crate::no_global_alloc::ForbiddenGlobalAllocator; + }; + }; +} diff --git a/crates/fspy_nostd/tests/no_global_alloc.rs b/crates/fspy_nostd/tests/no_global_alloc.rs new file mode 100644 index 000000000..122d72c2f --- /dev/null +++ b/crates/fspy_nostd/tests/no_global_alloc.rs @@ -0,0 +1,46 @@ +use std::process::Command; + +#[test] +fn global_allocator_is_checked_at_link_time() { + let source = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/support/no_global_alloc.rs"); + // Compile and link freestanding fixtures, but never execute them. Both + // targets are installed by rust-toolchain.toml; no Linux VM is needed. + for target in ["aarch64-unknown-none-softfloat", "x86_64-unknown-none"] { + // Optimization once erased a forbidden allocation when the undefined + // function returned `!`. Check both optimized and unoptimized builds. + for optimization in ["0", "3"] { + for operation in ["unused", "alloc", "alloc_zeroed", "dealloc", "realloc", "global_vec"] + { + let directory = tempfile::tempdir().unwrap(); + // Run a full link: cargo check cannot detect undefined symbols. + // --cfg selects the fixture's operation. Abort avoids an unwind + // runtime, and --no-pie matches our fixed-address launcher. + let output = Command::new("rustc") + .args([source, "--edition=2024", "--target", target]) + .args(["--cfg", operation, "-C", "panic=abort", "-C"]) + .arg(["opt-level=", optimization].concat()) + .args(["-C", "link-arg=--no-pie", "-o"]) + .arg(directory.path().join("probe")) + .output() + .expect("cannot run rustc"); + let stderr = std::str::from_utf8(&output.stderr).unwrap(); + if operation == "unused" { + // Linking alloc alone must work when its global allocator + // is unused and the linker can discard the forbidden calls. + assert!(output.status.success(), "{target}, opt={optimization}: {stderr}"); + } else { + assert!( + !output.status.success(), + "{target}, opt={optimization}: {operation} unexpectedly linked" + ); + // An unrelated compiler or linker error is not a pass. + assert!( + stderr + .contains("undefined symbol: __fspy_global_allocator_must_not_be_used"), + "{target}, opt={optimization}, {operation}: {stderr}" + ); + } + } + } + } +} diff --git a/crates/fspy_nostd/tests/support/no_global_alloc.rs b/crates/fspy_nostd/tests/support/no_global_alloc.rs new file mode 100644 index 000000000..a6ee51cdb --- /dev/null +++ b/crates/fspy_nostd/tests/support/no_global_alloc.rs @@ -0,0 +1,42 @@ +#![no_std] +#![no_main] + +extern crate alloc; + +// Compile the actual module without needing a separate cross-built rlib. +#[path = "../../src/no_global_alloc.rs"] +mod no_global_alloc; +no_global_alloc!(); + +#[panic_handler] +fn panic(_: &core::panic::PanicInfo<'_>) -> ! { + loop {} +} + +// This is a link-only fixture, never executed. Negative cases each retain +// exactly one global allocator operation; the caller must supply a valid +// allocation for dealloc/realloc, just as for those APIs themselves. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn _start(pointer: *mut u8) -> ! { + let _ = pointer; + #[cfg(any(alloc, alloc_zeroed, dealloc, realloc))] + let layout = core::alloc::Layout::new::(); + #[cfg(alloc)] + core::hint::black_box(unsafe { alloc::alloc::alloc(layout) }); + #[cfg(alloc_zeroed)] + core::hint::black_box(unsafe { alloc::alloc::alloc_zeroed(layout) }); + #[cfg(dealloc)] + unsafe { + alloc::alloc::dealloc(pointer, layout) + }; + #[cfg(realloc)] + core::hint::black_box(unsafe { alloc::alloc::realloc(pointer, layout, 16) }); + #[cfg(global_vec)] + { + let mut values = alloc::vec::Vec::with_capacity(core::hint::black_box(16)); + values.push(core::hint::black_box(42_usize)); + core::hint::black_box(&mut values); + drop(values); + } + loop {} +} From fc4bc299ebbec42c9d05b10a1762b63c831165ad Mon Sep 17 00:00:00 2001 From: wan9chi Date: Tue, 15 Sep 2026 15:31:14 +0800 Subject: [PATCH 09/34] feat(fspy-elf-loader): load dynamic ELF images in process 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 --- Cargo.lock | 16 + crates/fspy_elf_loader/Cargo.toml | 9 + crates/fspy_elf_loader/build.rs | 9 + crates/fspy_elf_loader/src/image.rs | 295 ++++++++++++++++++ crates/fspy_elf_loader/src/image/tests.rs | 100 ++++++ crates/fspy_elf_loader/src/lib.rs | 116 ++++++- crates/fspy_elf_loader/src/mapping.rs | 96 ++++++ crates/fspy_elf_loader/src/stack.rs | 270 ++++++++++++++++ .../fspy_elf_loader/tests/support/launcher.rs | 11 +- crates/fspy_elf_loader_tests/Cargo.toml | 28 ++ .../fspy_elf_loader_tests/src/bin/fixture.rs | 84 +++++ .../fspy_elf_loader_tests/tests/exec_elf.rs | 145 +++++++++ rust-toolchain.toml | 1 + 13 files changed, 1164 insertions(+), 16 deletions(-) create mode 100644 crates/fspy_elf_loader/build.rs create mode 100644 crates/fspy_elf_loader/src/image.rs create mode 100644 crates/fspy_elf_loader/src/image/tests.rs create mode 100644 crates/fspy_elf_loader/src/mapping.rs create mode 100644 crates/fspy_elf_loader/src/stack.rs create mode 100644 crates/fspy_elf_loader_tests/Cargo.toml create mode 100644 crates/fspy_elf_loader_tests/src/bin/fixture.rs create mode 100644 crates/fspy_elf_loader_tests/tests/exec_elf.rs diff --git a/Cargo.lock b/Cargo.lock index 9c76cf1a4..385b2218d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1472,7 +1472,23 @@ dependencies = [ name = "fspy_elf_loader" version = "0.1.0" dependencies = [ + "allocator-api2", + "elf", "fspy_nostd", + "fspy_nostd_alloc", + "linux-raw-sys 0.12.1", + "tempfile", +] + +[[package]] +name = "fspy_elf_loader_tests" +version = "0.0.0" +dependencies = [ + "elf", + "fspy_elf_loader", + "libc", + "ntest", + "tempfile", ] [[package]] diff --git a/crates/fspy_elf_loader/Cargo.toml b/crates/fspy_elf_loader/Cargo.toml index b3b52216d..4d2395d4e 100644 --- a/crates/fspy_elf_loader/Cargo.toml +++ b/crates/fspy_elf_loader/Cargo.toml @@ -8,7 +8,16 @@ publish.workspace = true rust-version.workspace = true [dependencies] +allocator-api2 = { workspace = true, features = ["alloc"] } +elf = { workspace = true } fspy_nostd = { workspace = true } +fspy_nostd_alloc = { workspace = true } + +[target.'cfg(any(target_os = "linux", target_os = "none"))'.dependencies] +linux-raw-sys = { workspace = true, features = ["auxvec", "no_std"] } + +[target.'cfg(target_os = "linux")'.dev-dependencies] +tempfile = { workspace = true } [[bin]] name = "fspy_elf_loader_test_launcher" diff --git a/crates/fspy_elf_loader/build.rs b/crates/fspy_elf_loader/build.rs new file mode 100644 index 000000000..d47ab4cc1 --- /dev/null +++ b/crates/fspy_elf_loader/build.rs @@ -0,0 +1,9 @@ +fn main() { + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("none") { + // main! has no self-relocator. x86_64-unknown-none otherwise links a + // static PIE with unresolved load-bias relocations, even for panics. + // The kernel maps PT_LOAD segments but does not fix up pointers in a + // static PIE. With --no-pie, the linker resolves them for fixed addresses. + println!("cargo::rustc-link-arg-bin=fspy_elf_loader_test_launcher=--no-pie"); + } +} diff --git a/crates/fspy_elf_loader/src/image.rs b/crates/fspy_elf_loader/src/image.rs new file mode 100644 index 000000000..b6f1c5dd1 --- /dev/null +++ b/crates/fspy_elf_loader/src/image.rs @@ -0,0 +1,295 @@ +//! Map the regions described by an ELF file's program headers. +//! +//! Each `PT_LOAD` header describes a segment: `p_offset` locates its bytes in +//! the file, `p_vaddr` gives its link-time virtual address, `p_filesz` counts +//! file bytes, and `p_memsz` counts memory bytes. The extra memory is zero-filled +//! storage (BSS), used for objects such as zero-initialized global variables. +//! `p_flags` gives read/write/execute permissions; `p_align` constrains placement. +//! +//! See ELF's program-header definitions in . + +use core::{ops::Range, ptr}; + +use elf::{ + abi, + endian::LittleEndian, + file::{self, Class, FileHeader}, + segment::{ProgramHeader, SegmentTable}, +}; +use fspy_nostd::{ + CStr, Fat, OwnedFd, fs, + mm::{self, MapFlags, MprotectFlags, ProtFlags}, +}; + +use crate::mapping::{Mapping, add, align_up, sub, word}; + +#[cfg(test)] +mod tests; + +#[cfg(target_arch = "aarch64")] +const MACHINE: u16 = abi::EM_AARCH64; +#[cfg(target_arch = "x86_64")] +const MACHINE: u16 = abi::EM_X86_64; + +/// A temporary read-only view used to parse file offsets, not to execute code. +pub struct File { + fd: OwnedFd, + view: Mapping, + header: FileHeader, + headers: Range, +} + +/// The final memory layout, with addresses the target can use at runtime. +pub struct Image { + mapping: Mapping, + /// Add this load bias to an ELF virtual address to get its runtime address. + pub bias: usize, + pub entry: usize, + /// Address of the program-header table inside the mapped image, if present. + pub phdr: Option, + pub phnum: usize, +} + +impl Image { + pub fn retain(self) { + self.mapping.retain(); + } +} + +impl File { + pub fn new(fd: OwnedFd) -> Self { + let len = usize::try_from(fs::fstat(fd.as_fd()).expect("cannot stat ELF").st_size) + .expect("invalid ELF file size"); + assert!(len >= 64, "truncated ELF header"); + let view = Mapping::file(fd.as_fd(), len); + // SAFETY: this is the unchanged, read-only file view. + let bytes = unsafe { view.bytes() }; + // The 16-byte identity tells us how to decode the rest of the 64-byte + // ELF64 header. Section headers describe linker/debugger information; + // loading these images needs only the separate program-header table. + let ident = file::parse_ident::(&bytes[..16]).expect("invalid ELF identity"); + assert_eq!(ident.1, Class::ELF64, "only ELF64 is supported"); + let header = FileHeader::parse_tail(ident, &bytes[16..64]).expect("invalid ELF header"); + assert_eq!(header.e_machine, MACHINE, "ELF architecture mismatch"); + // ET_DYN permits a load bias chosen for the available address space. + // Position-independent executables (PIE) and their interpreters use it. + // ET_EXEC requires fixed addresses, which could overlap our loader. + assert_eq!(header.e_type, abi::ET_DYN, "only ET_DYN images are supported"); + assert_eq!(header.version, u32::from(abi::EV_CURRENT), "invalid ELF version"); + assert_eq!(header.e_phentsize, 56, "invalid program-header size"); + // 0xffff is an escape to a count stored in section metadata. This MVP + // accepts only counts carried in the ELF header itself. + assert!( + header.e_phnum != 0 && header.e_phnum != 0xffff, + "unsupported program-header count" + ); + let start = word(header.e_phoff); + let end = add(start, usize::from(header.e_phnum) * 56); + assert!(bytes.get(start..end).is_some(), "truncated program headers"); + Self { fd, view, header, headers: start..end } + } + + fn segments(&self) -> SegmentTable<'_, LittleEndian> { + // SAFETY: the file remains unchanged and mapped read-only. + SegmentTable::new( + LittleEndian, + Class::ELF64, + &unsafe { self.view.bytes() }[self.headers.clone()], + ) + } + + pub fn interpreter(&self) -> Option> { + let mut result = None; + for segment in self.segments().iter() { + if segment.p_type == abi::PT_INTERP { + assert!(result.is_none(), "multiple PT_INTERP entries"); + let start = word(segment.p_offset); + let end = add(start, word(segment.p_filesz)); + // SAFETY: the file remains unchanged and mapped read-only. + let bytes = + unsafe { self.view.bytes() }.get(start..end).expect("truncated PT_INTERP"); + let path = CStr::from_units_with_nul(bytes).expect("invalid PT_INTERP path"); + assert!(!path.as_units().is_empty(), "empty PT_INTERP path"); + result = Some(path); + } + } + result + } + + pub fn map(&self, page: usize) -> Image { + // First validate the segments and find their page-rounded span. + // mmap operates on whole pages, even when ELF segments do not. + let mut low = usize::MAX; + let mut high = 0; + let mut alignment = page; + let mut previous_end = 0; + for segment in self.segments().iter() { + if segment.p_type == abi::PT_GNU_STACK { + assert!(segment.p_flags & abi::PF_X == 0, "executable stacks are unsupported"); + } + if segment.p_type != abi::PT_LOAD { + continue; + } + let start = word(segment.p_vaddr); + let end = add(start, word(segment.p_memsz)); + let file_end = add(word(segment.p_offset), word(segment.p_filesz)); + assert!(segment.p_filesz <= segment.p_memsz, "ELF filesz exceeds memsz"); + assert!(file_end <= self.view.len, "truncated ELF segment"); + // Our MVP rejects overlapping byte ranges. Page-rounded ranges + // can still overlap, so mapping below must preserve header order. + assert!(start >= previous_end, "overlapping or unordered ELF segments"); + previous_end = end; + // ELF treats alignment 0 and 1 as no extra constraint. File and + // memory offsets must agree within a page for file-backed mmap. + let align = word(segment.p_align).max(1); + assert!(align.is_power_of_two(), "invalid segment alignment"); + assert_eq!(start % align, word(segment.p_offset) % align, "incongruent ELF alignment"); + assert_eq!(start % page, word(segment.p_offset) % page, "incongruent ELF page offsets"); + alignment = alignment.max(align); + if segment.p_memsz == 0 { + continue; + } + low = low.min(start & !sub(page, 1)); + high = high.max(align_up(end, page)); + } + let span = high.checked_sub(low).expect("ELF has no loadable memory"); + // Reserve the whole image, including holes, before replacing pages + // with MAP_FIXED. That flag discards existing mappings at its address; + // restricting it to our reservation protects the loader and old stack. + // Extra space lets us align the bias, even if p_align exceeds a page. + let mapping = Mapping::reserve(add(span, alignment)); + let base = mapping.ptr.as_ptr().expose_provenance(); + let bias = + align_up(base.checked_sub(low).expect("unsupported ELF address range"), alignment); + assert!(add(bias, high) <= add(base, mapping.len), "ELF exceeds reservation"); + let mut phdr = None; + let mut executable_entry = false; + // All segments share one bias, preserving their relative addresses. + // The executable and interpreter each get their own reservation/bias. + for segment in + self.segments().iter().filter(|ph| ph.p_type == abi::PT_LOAD && ph.p_memsz != 0) + { + let file_start = word(segment.p_offset); + // AT_PHDR must point into the final image, not our temporary file + // view. Find the LOAD covering the table and translate its offset. + // This also works when the ELF has no explicit PT_PHDR header. + if self.headers.start >= file_start + && self.headers.end <= add(file_start, word(segment.p_filesz)) + { + phdr = Some(add( + add(bias, word(segment.p_vaddr)), + sub(self.headers.start, file_start), + )); + } + executable_entry |= segment.p_flags & abi::PF_X != 0 + && self.header.e_entry >= segment.p_vaddr + && self.header.e_entry + < segment + .p_vaddr + .checked_add(segment.p_memsz) + .expect("ELF entry range overflow"); + // SAFETY: validation and reservation cover every page this + // segment replaces. No references to those pages exist yet. + unsafe { self.map_segment(segment, bias, page) }; + } + assert!(executable_entry, "ELF entry is not in an executable segment"); + Image { + mapping, + bias, + entry: add(bias, word(self.header.e_entry)), + phdr, + phnum: usize::from(self.header.e_phnum), + } + } + + unsafe fn map_segment(&self, segment: ProgramHeader, bias: usize, page: usize) { + let start = add(bias, word(segment.p_vaddr)); + let end = add(start, word(segment.p_memsz)); + let file_end = add(start, word(segment.p_filesz)); + let page_start = start & !sub(page, 1); + let mut protection = ProtFlags::empty(); + if segment.p_flags & abi::PF_R != 0 { + protection |= ProtFlags::READ; + } + if segment.p_flags & abi::PF_W != 0 { + protection |= ProtFlags::WRITE; + } + if segment.p_flags & abi::PF_X != 0 { + protection |= ProtFlags::EXEC; + } + let fixed = MapFlags::PRIVATE | MapFlags::FIXED; + if segment.p_filesz != 0 { + // Round both the file offset and address down by the same amount. + // For example, an offset ending in 0x340 needs those first 0x340 + // bytes of its page mapped too. Round the end up to cover the tail. + // PRIVATE keeps BSS writes and later relocations out of the file. + let len = sub(align_up(file_end, page), page_start); + // SAFETY: caller owns the entire reservation being replaced. + unsafe { + mm::mmap( + ptr::with_exposed_provenance_mut(page_start), + len, + protection, + fixed, + self.fd.as_fd(), + segment.p_offset & !u64::try_from(sub(page, 1)).unwrap(), + ) + } + .expect("cannot map ELF segment"); + if file_end < end && !file_end.is_multiple_of(page) { + let tail_page = file_end & !sub(page, 1); + // Writable, non-executable pages can be zeroed directly. + // Otherwise temporarily make the last file page writable, + // without X, and restore its original protection afterwards. + let change_protection = + !protection.contains(ProtFlags::WRITE) || protection.contains(ProtFlags::EXEC); + // Clear through the page boundary, not just p_memsz: glibc's + // early allocator uses the spare bytes after the interpreter's + // _end and expects them to be zero (Linux padzero behavior). + // Stopping at p_memsz crashed /bin/echo's interpreter in the + // ARM64 smoke test. image/tests.rs checks the entire page tail. + // SAFETY: this private page was mapped above; it has no live references. + unsafe { + if change_protection { + mm::mprotect( + ptr::with_exposed_provenance_mut(tail_page), + page, + MprotectFlags::READ | MprotectFlags::WRITE, + ) + .expect("cannot zero ELF BSS"); + } + ptr::write_bytes( + ptr::with_exposed_provenance_mut::(file_end), + 0, + sub(align_up(file_end, page), file_end), + ); + if change_protection { + mm::mprotect( + ptr::with_exposed_provenance_mut(tail_page), + page, + MprotectFlags::from_bits_retain(protection.bits()), + ) + .expect("cannot restore ELF protection"); + } + } + } + } + let anonymous_start = + if segment.p_filesz == 0 { page_start } else { align_up(file_end, page) }; + let anonymous_end = align_up(end, page); + if anonymous_start < anonymous_end { + // The remaining BSS has no file bytes. Anonymous pages start at + // zero; mapping the file past its end could instead cause SIGBUS. + // SAFETY: these pages lie inside the reservation and have no live references. + unsafe { + mm::mmap_anonymous( + ptr::with_exposed_provenance_mut(anonymous_start), + sub(anonymous_end, anonymous_start), + protection, + fixed, + ) + } + .expect("cannot map ELF BSS"); + } + } +} diff --git a/crates/fspy_elf_loader/src/image/tests.rs b/crates/fspy_elf_loader/src/image/tests.rs new file mode 100644 index 000000000..15d43b1d0 --- /dev/null +++ b/crates/fspy_elf_loader/src/image/tests.rs @@ -0,0 +1,100 @@ +use super::*; + +#[test] +fn zeroes_the_entire_last_file_page_and_anonymous_bss() { + let page = fspy_nostd::param::page_size(); + // Exercise both direct writes and temporarily writable pages. The final + // protections must match the ELF in either case. + for (flags, protection) in + [(abi::PF_R | abi::PF_W, "rw-p"), (abi::PF_R, "r--p"), (abi::PF_R | abi::PF_X, "r-xp")] + { + check_bss(page, flags, protection); + } +} + +fn check_bss(page: usize, flags: u32, expected_protection: &str) { + for memory_size in [0x180, page + 0x180] { + let bytes = fixture(page, memory_size, flags); + let file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(file.path(), bytes).unwrap(); + let path = std::ffi::CString::new(file.path().as_os_str().as_encoded_bytes()).unwrap(); + let path = CStr::from_units_with_nul(path.as_bytes_with_nul()).unwrap(); + let image = File::new( + fs::openat(fspy_nostd::CWD, path, fs::OFlags::RDONLY, fs::Mode::empty()).unwrap(), + ); + let image = image.map(page); + assert_eq!(image.bias % (2 * page), 0); + assert_eq!(image.phdr, Some(image.bias + 64)); + let maps = std::fs::read_to_string("/proc/self/maps").unwrap(); + let protection = |address| { + maps.lines() + .find_map(|line| { + let mut fields = line.split_whitespace(); + let (start, end) = fields.next()?.split_once('-')?; + let range = usize::from_str_radix(start, 16).ok()? + ..usize::from_str_radix(end, 16).ok()?; + range.contains(&address).then(|| fields.next().unwrap()) + }) + .unwrap() + }; + assert_eq!(protection(image.entry), "r-xp"); + assert_eq!(protection(image.bias + page + 0x200), expected_protection); + assert_eq!(protection(image.mapping.ptr.as_ptr().addr() + image.mapping.len - 1), "---p"); + let zero_start = image.bias + page + 0x300; + let zero_end = align_up(image.bias + page + 0x200 + memory_size, page); + // SAFETY: the synthetic second LOAD is readable throughout + // this range, including the file tail and anonymous BSS pages. + let zeroed = unsafe { + core::slice::from_raw_parts( + ptr::with_exposed_provenance::(zero_start), + zero_end - zero_start, + ) + }; + assert!(zeroed.iter().all(|byte| *byte == 0)); + // The two segments share a rounded page. Its earlier segment bytes + // must survive mapping the later segment at a non-page-aligned vaddr. + // SAFETY: both addresses are inside mapped readable LOAD pages. + unsafe { + assert_eq!(ptr::with_exposed_provenance::(image.bias + page + 0x80).read(), 0xa5); + assert_eq!(ptr::with_exposed_provenance::(image.bias + page + 0x200).read(), 0xa5); + } + } +} + +fn fixture(page: usize, memory_size: usize, flags: u32) -> std::vec::Vec { + let mut bytes = std::vec![0xa5; 3 * page]; + bytes[..64].fill(0); + bytes[..7].copy_from_slice(b"\x7fELF\x02\x01\x01"); + bytes[16..18].copy_from_slice(&abi::ET_DYN.to_le_bytes()); + bytes[18..20].copy_from_slice(&MACHINE.to_le_bytes()); + bytes[20..24].copy_from_slice(&1_u32.to_le_bytes()); + bytes[24..32].copy_from_slice(&0x200_u64.to_le_bytes()); + bytes[32..40].copy_from_slice(&64_u64.to_le_bytes()); + bytes[52..54].copy_from_slice(&64_u16.to_le_bytes()); + bytes[54..56].copy_from_slice(&56_u16.to_le_bytes()); + bytes[56..58].copy_from_slice(&2_u16.to_le_bytes()); + segment(&mut bytes, 0, 0, page + 0x100, page + 0x100, abi::PF_R | abi::PF_X, page); + segment(&mut bytes, 1, page + 0x200, 0x100, memory_size, flags, page); + bytes +} + +fn segment( + bytes: &mut [u8], + index: usize, + start: usize, + file_size: usize, + memory_size: usize, + flags: u32, + page: usize, +) { + let offset = 64 + index * 56; + let header = &mut bytes[offset..offset + 56]; + header.fill(0); + header[..4].copy_from_slice(&abi::PT_LOAD.to_le_bytes()); + header[4..8].copy_from_slice(&flags.to_le_bytes()); + for (offset, value) in + [(8, start), (16, start), (32, file_size), (40, memory_size), (48, 2 * page)] + { + header[offset..offset + 8].copy_from_slice(&u64::try_from(value).unwrap().to_le_bytes()); + } +} diff --git a/crates/fspy_elf_loader/src/lib.rs b/crates/fspy_elf_loader/src/lib.rs index b039fcb32..12c07bf14 100644 --- a/crates/fspy_elf_loader/src/lib.rs +++ b/crates/fspy_elf_loader/src/lib.rs @@ -1,8 +1,26 @@ -// ELF execution uses the Linux process ABI. +//! Load a Linux ELF executable inside an existing process. +//! +//! For a dynamic executable, the kernel maps the executable and its ELF +//! interpreter, writes startup data onto a new stack, and enters the +//! interpreter. The interpreter (such as `ld-linux`) loads shared libraries, +//! fixes addresses through relocations, and enters the executable's startup +//! code. That startup code eventually calls the application's `main`. +//! +//! We implement the mapping, stack, and entry steps after the kernel has +//! already executed our freestanding loader. We leave its mappings and signal +//! handlers in place. Calling another kernel exec here would discard them. #![cfg(any(target_os = "linux", target_os = "none"))] #![no_std] +#[cfg(test)] +extern crate std; + use fspy_nostd::{CStr, OwnedFd, Thin, env::AuxEntry}; +use linux_raw_sys::auxvec::AT_PAGESZ; + +mod image; +mod mapping; +mod stack; /// Loads an ELF executable into the current process and enters it. /// @@ -12,10 +30,11 @@ use fspy_nostd::{CStr, OwnedFd, Thin, env::AuxEntry}; /// /// `execfn` is the original execution name used for `AT_EXECFN`; it need not /// match `argv[0]`. Arguments and environment entries are copied to the new -/// stack. `inherited_auxv` supplies [`AuxEntry`] values from the loader's kernel -/// exec, excluding `AT_NULL`. Image-specific entries are replaced, reusable -/// entries are preserved, and referenced data is copied where needed. The -/// resulting vector ends with `AT_NULL`. +/// stack. `inherited_auxv` borrows entries from the loader's original kernel +/// stack, excluding `AT_NULL`. Its `AT_PAGESZ` supplies the page size used for +/// mapping. Image-specific entries are replaced, reusable entries are +/// preserved, and referenced data is copied where needed. The resulting +/// vector ends with `AT_NULL`. /// /// Path resolution, shebang handling, and execution-policy checks belong to /// the caller. This function does not perform kernel exec cleanup: installed @@ -23,10 +42,19 @@ use fspy_nostd::{CStr, OwnedFd, Thin, env::AuxEntry}; /// Loading failures terminate the process; they cannot return to the program /// that executed the loader. /// +/// Currently supports native little-endian ELF64 dynamic PIE executables on +/// `AArch64` and x86-64, with an ELF interpreter and a non-executable stack. +/// The new stack has a fixed 8 MiB capacity and a guard page. Existing loader +/// mappings, the old stack, and kernel process metadata (including `/proc` +/// identity and `brk`) are retained. This does not emulate a complete exec. +/// Processor-specific GNU properties are not applied. +/// /// # Safety /// /// Call only from a fresh, single-threaded loader process. The executable and /// interpreter must be trusted to run with the process's current privileges. +/// Their backing files must remain unchanged throughout loading. The loader +/// must not have initialized libc or thread-local runtime state. /// Auxiliary entries must describe this process; any referenced memory must /// remain readable and unchanged until copied or retained for the target. /// The caller must permit execution to abandon its stack without running @@ -35,14 +63,84 @@ use fspy_nostd::{CStr, OwnedFd, Thin, env::AuxEntry}; /// /// # Panics /// -/// Not implemented yet; currently always panics. +/// Panics when `AT_PAGESZ` is missing or invalid, loading detects an unsupported +/// or malformed image, runs out of stack capacity, or fails to map or open a +/// file. The freestanding panic handler must terminate the process. Faults +/// after entering the interpreter or executable are not converted into panics. pub unsafe fn exec_elf<'a>( elf_file: OwnedFd, execfn: CStr<'a, Thin>, argv: impl Iterator>, envp: impl Iterator>, - inherited_auxv: impl Iterator, + inherited_auxv: &[AuxEntry], ) -> ! { - let _ = (elf_file, execfn, argv, envp, inherited_auxv); - unimplemented!() + let page_size = inherited_auxv + .iter() + .find(|entry| entry.key == usize::try_from(AT_PAGESZ).unwrap()) + .expect("missing AT_PAGESZ") + .value; + assert!(page_size.is_power_of_two(), "invalid AT_PAGESZ"); + let executable = image::File::new(elf_file); + // PT_INTERP names a second ELF file. Loading it here lets us delegate + // dynamic linking and libc startup to the program's own interpreter. + let interpreter = executable.interpreter().expect("executable has no PT_INTERP"); + let interpreter = fspy_nostd::fs::openat( + fspy_nostd::CWD, + interpreter, + fspy_nostd::fs::OFlags::RDONLY | fspy_nostd::fs::OFlags::CLOEXEC, + fspy_nostd::fs::Mode::empty(), + ) + .expect("cannot open ELF interpreter"); + let interpreter = image::File::new(interpreter); + assert!(interpreter.interpreter().is_none(), "nested PT_INTERP is unsupported"); + let executable_image = executable.map(page_size); + let interpreter_image = interpreter.map(page_size); + // SAFETY: the caller supplies live auxiliary payloads from this process. + let stack = unsafe { + stack::build( + execfn, + argv, + envp, + inherited_auxv.iter().copied(), + &executable_image, + &interpreter_image, + page_size, + ) + }; + // The interpreter must run first, even though AT_ENTRY on the new stack + // points at the executable. The interpreter uses that value to hand off + // after dynamic linking; it does not call the application's main itself. + let entry = interpreter_image.entry; + // File mappings keep their backing storage alive after close. Release + // only our parsing views and descriptors, then retain the execution maps + // so Rust destructors cannot unmap code the target is about to use. + drop(interpreter); + drop(executable); + executable_image.retain(); + interpreter_image.retain(); + // SAFETY: the images and stack are initialized and retained. The caller + // permits abandoning the current stack and entering the trusted image. + unsafe { enter(entry, stack) } +} + +// No Rust code may execute after replacing SP. The dynamic interpreter is +// entered like a program, not called like a function with a return address. +// #[naked] prevents a compiler-generated stack frame. Each stub starts with +// C function arguments in registers, installs the process-entry stack, and +// jumps. A normal call would put an unwanted return address on x86-64's stack. +#[cfg(target_arch = "aarch64")] +#[unsafe(naked)] +unsafe extern "C" fn enter(_entry: usize, _stack: *mut usize) -> ! { + // X0 holds entry and X1 holds the new SP. Save entry in scratch register + // X16 before clearing X0; clear X30 because there is no caller to return to. + core::arch::naked_asm!("mov x16, x0", "mov sp, x1", "mov x0, xzr", "mov x30, xzr", "br x16"); +} + +#[cfg(target_arch = "x86_64")] +#[unsafe(naked)] +unsafe extern "C" fn enter(_entry: usize, _stack: *mut usize) -> ! { + // RDI holds entry and RSI holds the new RSP. RDX is the optional + // dynamic-linker finalizer (an exit callback); there is none yet. + // Clear RBP to mark the end of the frame-pointer chain. + core::arch::naked_asm!("mov rsp, rsi", "xor edx, edx", "xor ebp, ebp", "jmp rdi"); } diff --git a/crates/fspy_elf_loader/src/mapping.rs b/crates/fspy_elf_loader/src/mapping.rs new file mode 100644 index 000000000..e997fa359 --- /dev/null +++ b/crates/fspy_elf_loader/src/mapping.rs @@ -0,0 +1,96 @@ +use core::{ptr, ptr::NonNull, slice}; + +use fspy_nostd::{ + BorrowedFd, + mm::{self, MapFlags, ProtFlags}, +}; + +pub const fn add(left: usize, right: usize) -> usize { + left.checked_add(right).expect("ELF address overflow") +} + +pub const fn sub(left: usize, right: usize) -> usize { + left.checked_sub(right).expect("invalid ELF address range") +} + +pub const fn align_up(value: usize, alignment: usize) -> usize { + assert!(alignment.is_power_of_two(), "invalid ELF alignment"); + let mask = sub(alignment, 1); + add(value, mask) & !mask +} + +pub fn word(value: u64) -> usize { + usize::try_from(value).expect("ELF value exceeds native word") +} + +/// An owned address range: a parsing view, image reservation, or new stack. +/// +/// Drop releases the range during loading or unwinding. Retain hands its +/// lifetime to the target; the kernel reclaims it on a later exec or exit. +pub struct Mapping { + pub ptr: NonNull, + pub len: usize, +} + +impl Mapping { + pub fn reserve(len: usize) -> Self { + Self::check_len(len); + // PROT_NONE reserves addresses but permits no access. Image segments + // later replace its pages; the stack makes its usable pages writable. + // SAFETY: no fixed address is requested and no references exist yet. + let ptr = unsafe { + mm::mmap_anonymous(ptr::null_mut(), len, ProtFlags::empty(), MapFlags::PRIVATE) + } + .expect("cannot reserve address space"); + Self::new(ptr.cast(), len) + } + + pub fn file(fd: BorrowedFd<'_>, len: usize) -> Self { + Self::check_len(len); + // One contiguous view makes file-offset parsing possible. This is + // separate from the segments mapped at their final execution addresses. + // SAFETY: private read-only view at a kernel-selected address. The + // exec_elf contract keeps the file unchanged while this view is used. + let ptr = + unsafe { mm::mmap(ptr::null_mut(), len, ProtFlags::READ, MapFlags::PRIVATE, fd, 0) } + .expect("cannot map ELF metadata"); + Self::new(ptr.cast(), len) + } + + fn check_len(len: usize) { + assert!(len != 0 && isize::try_from(len).is_ok(), "invalid mapping length"); + } + + fn new(ptr: *mut u8, len: usize) -> Self { + let Some(ptr) = NonNull::new(ptr) else { + // SAFETY: this successful mapping is owned here, but address zero + // cannot back Rust references, so release it before failing. + let _ = unsafe { mm::munmap(ptr.cast(), len) }; + panic!("mapping returned address zero"); + }; + Self { ptr, len } + } + + /// Only called on immutable, fully readable file mappings. + pub const unsafe fn bytes(&self) -> &[u8] { + // SAFETY: caller establishes readability; length and non-nullness + // were checked when creating the mapping. + unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len) } + } + + pub const fn retain(self) -> *mut u8 { + // Switching SP or jumping does not transfer Rust ownership. Suppress + // Drop here so it cannot release memory needed after the handoff. + let ptr = self.ptr.as_ptr(); + core::mem::forget(self); + ptr + } +} + +impl Drop for Mapping { + fn drop(&mut self) { + // SAFETY: this object owns the whole mapping, including any segment + // mappings replacing its reserved pages. No target has entered it. + let _ = unsafe { mm::munmap(self.ptr.as_ptr().cast(), self.len) }; + } +} diff --git a/crates/fspy_elf_loader/src/stack.rs b/crates/fspy_elf_loader/src/stack.rs new file mode 100644 index 000000000..c27d485e5 --- /dev/null +++ b/crates/fspy_elf_loader/src/stack.rs @@ -0,0 +1,270 @@ +//! Recreate the startup stack normally supplied by Linux exec. +//! +//! At entry, the stack pointer (SP) points to argc (the argument count), then +//! argv (argument pointers) and NULL, envp (environment pointers) and NULL, +//! then auxiliary-vector (key, value) pairs through `AT_NULL`. +//! The auxiliary vector lets the interpreter and libc +//! discover image addresses and process properties before runtime startup. +//! +//! We copy strings and known auxiliary payloads into the same mapping. Build +//! the pointer table in a temporary vector and payloads downward, then copy +//! the table next to the payloads. Argument and environment pointers are +//! collected first so their strings can be copied in reverse order, preserving +//! Linux's ascending, contiguous string layout. This consumes iterators once. + +use core::{mem::size_of, ptr}; + +use allocator_api2::vec::Vec; +use fspy_nostd::{ + CStr, Thin, + env::AuxEntry, + mm::{self, MprotectFlags}, +}; +use fspy_nostd_alloc::{PageBump, page_bump}; +use linux_raw_sys::auxvec as abi; + +use crate::{ + image::Image, + mapping::{Mapping, add}, +}; + +// Includes startup data and room for the target's downward-growing call stack. +// This MVP uses a fixed mapping rather than Linux's growable initial stack. +const CAPACITY: usize = 8 * 1024 * 1024; + +struct Builder { + mapping: Mapping, + // Offsets from mapping.ptr: first usable byte and payload start. + start: usize, + words: Vec, + strings: usize, +} + +impl Builder { + fn new(page: usize) -> Self { + let mapping = Mapping::reserve(add(CAPACITY, page)); + // Keep the low page inaccessible so an overflow reaching it faults + // instead of writing into a neighboring mapping. + // SAFETY: the first page remains a guard; the remaining pages are + // exclusively owned and do not have live references. + unsafe { + mm::mprotect( + mapping.ptr.as_ptr().add(page).cast(), + CAPACITY, + MprotectFlags::READ | MprotectFlags::WRITE, + ) + } + .expect("cannot map target stack"); + Self { strings: mapping.len, mapping, start: page, words: Vec::new_in(page_bump()) } + } + + fn push(&mut self, value: usize) { + let end = add(self.table_end(), size_of::()); + assert!(end <= self.strings, "initial stack exceeds capacity"); + self.words.push(value); + } + + fn table_end(&self) -> usize { + add(self.start, size_of_val(self.words.as_slice())) + } + + fn copy(&mut self, bytes: &[u8]) -> usize { + let start = self.strings.checked_sub(bytes.len()).expect("initial stack exceeds capacity"); + assert!(start >= self.table_end(), "initial stack exceeds capacity"); + // SAFETY: bytes come from the old process image, not this fresh + // mapping. The destination is writable and outside the pointer table. + let target = unsafe { self.mapping.ptr.as_ptr().add(start) }; + // SAFETY: source and destination are valid, disjoint byte ranges. + unsafe { ptr::copy_nonoverlapping(bytes.as_ptr(), target, bytes.len()) }; + self.strings = start; + target.expose_provenance() + } + + fn string(&mut self, value: CStr<'_, Thin>) -> usize { + self.copy(value.count().as_units_with_nul()) + } + + fn args_envs<'a>( + &mut self, + argv: impl Iterator>, + envp: impl Iterator>, + ) { + let argc_slot = self.words.len(); + self.push(0); + let pointers_start = self.words.len(); + let mut argument_count = 0_usize; + for arg in argv { + self.push(arg.as_ptr().expose_provenance()); + argument_count = add(argument_count, 1); + } + self.words[argc_slot] = argument_count; + self.push(0); + for env in envp { + self.push(env.as_ptr().expose_provenance()); + } + self.push(0); + + // These slots temporarily point into the original strings. Copy from + // the last environment entry back to argv[0], because allocation grows + // downward. The result is contiguous argv strings followed by envp. + // libuv relies on this layout when updating the process title. + for index in (pointers_start..self.words.len()).rev() { + let source = self.words[index]; + if source == 0 { + continue; + } + // SAFETY: nonzero slots came from the CStr values above, whose + // original storage remains valid for 'a while we copy it. + let string = unsafe { CStr::from_ptr(ptr::with_exposed_provenance(source)) }; + self.words[index] = self.string(string); + } + } + + fn aux(&mut self, key: u32, value: usize) { + self.push(usize::try_from(key).unwrap()); + self.push(value); + } + + fn finish(self) -> *mut usize { + // Final layout, from low to high addresses: + // guard | free stack space | argc/argv/envp/auxv | padding | payloads + // ^ new SP, aligned to 16 bytes + // Keeping the table near the top leaves room below SP for calls. Only + // table bytes move: its pointers already name the final payloads. + let len = size_of_val(self.words.as_slice()); + let start = self.strings.checked_sub(len).expect("initial stack exceeds capacity") & !15; + assert!(start >= self.start, "initial stack exceeds capacity"); + // The temporary vector and its owned bump are dropped before handoff. + // SAFETY: the initialized vector and writable destination are disjoint. + // The checked destination fits below the strings. The result is + // aligned to the process-entry ABI and retains the complete mapping. + unsafe { + let base = self.mapping.ptr.as_ptr(); + let target = base.add(start); + ptr::copy_nonoverlapping(self.words.as_ptr().cast::(), target, len); + self.mapping.retain(); + target.cast() + } + } +} + +pub unsafe fn build<'a>( + execfn: CStr<'a, Thin>, + argv: impl Iterator>, + envp: impl Iterator>, + inherited: impl Iterator, + image: &Image, + interpreter: &Image, + page: usize, +) -> *mut usize { + let mut stack = Builder::new(page); + stack.args_envs(argv, envp); + for mut entry in inherited { + let Ok(key) = u32::try_from(entry.key) else { + stack.push(entry.key); + stack.push(entry.value); + continue; + }; + match key { + // Replace loader-image addresses below. AT_EXECFD would refer to + // an old execution descriptor; omit it. Emit our own end marker. + abi::AT_NULL + | abi::AT_PHDR + | abi::AT_PHENT + | abi::AT_PHNUM + | abi::AT_ENTRY + | abi::AT_BASE + | abi::AT_EXECFN + | abi::AT_EXECFD + | abi::AT_FLAGS => continue, + abi::AT_RANDOM => { + // The value is a pointer, not the random number itself. Copy + // the kernel-provided bytes used by libc for stack canaries. + // SAFETY: the exec_elf caller supplies the kernel's readable + // 16-byte random payload, kept immutable while copying. + let bytes = unsafe { + core::slice::from_raw_parts(ptr::with_exposed_provenance(entry.value), 16) + }; + entry.value = stack.copy(bytes); + } + abi::AT_PLATFORM | abi::AT_BASE_PLATFORM => { + // SAFETY: the caller supplies a live NUL-terminated auxiliary string. + let string = unsafe { CStr::from_ptr(ptr::with_exposed_provenance(entry.value)) }; + entry.value = stack.string(string); + } + // Scalars such as page size and hardware capabilities still apply. + // Unknown pointers remain usable only while their old mappings + // survive. This includes the vDSO, kernel-provided userspace code. + _ => {} // Old mappings, including the vDSO, remain resident. + } + stack.aux(key, entry.value); + } + // Describe the main executable even though we enter the interpreter first: + // PHDR/PHENT/PHNUM locate and size its header table; ENTRY is its startup + // address. BASE identifies the interpreter's load bias for its own linking. + stack.aux(abi::AT_PHDR, image.phdr.expect("program headers are not mapped by PT_LOAD")); + stack.aux(abi::AT_PHENT, 56); + stack.aux(abi::AT_PHNUM, image.phnum); + stack.aux(abi::AT_ENTRY, image.entry); + stack.aux(abi::AT_BASE, interpreter.bias); + stack.aux(abi::AT_FLAGS, 0); + let execfn = stack.string(execfn); + // Execution name and argv[0] are independent: callers can choose a custom + // argv[0] without changing which pathname AT_EXECFN reports. + stack.aux(abi::AT_EXECFN, execfn); + stack.aux(abi::AT_NULL, 0); + stack.finish() +} + +#[cfg(test)] +mod tests { + use fspy_nostd::env::InitialStack; + + use super::*; + + #[test] + fn args_and_envs_are_contiguous_in_forward_order() { + let args = [c"program", c"", c"\xff", c"longer-argument"]; + let envs = [c"EMPTY=", c"BYTES=\xff", c"A=B=C"]; + let page = fspy_nostd::param::page_size(); + for argc in 0..=args.len() { + for envc in 0..=envs.len() { + let mut builder = Builder::new(page); + let thin = |value: &'static core::ffi::CStr| { + CStr::from_units_with_nul(value.to_bytes_with_nul()).unwrap().as_thin() + }; + builder.args_envs( + args[..argc].iter().copied().map(thin), + envs[..envc].iter().copied().map(thin), + ); + builder.aux(abi::AT_NULL, 0); + let ptr = builder.mapping.ptr; + let len = builder.mapping.len; + let sp = builder.finish(); + // Reclaim the mapping retained by finish after all views expire. + let _mapping = Mapping { ptr, len }; + assert!(sp.addr().is_multiple_of(16)); + // SAFETY: the builder initialized a complete initial stack; + // its mapping stays readable and unchanged throughout this scope. + let stack = unsafe { InitialStack::from_ptr(sp) }; + assert_eq!(stack.args().len(), argc); + assert_eq!(stack.envs().len(), envc); + let mut previous_end = None; + for (actual, expected) in stack + .args() + .iter() + .chain(stack.envs()) + .zip(args[..argc].iter().chain(&envs[..envc])) + { + let actual = actual.count(); + assert_eq!(actual.as_units_with_nul(), expected.to_bytes_with_nul()); + let start = actual.as_ptr().addr(); + if let Some(end) = previous_end { + assert_eq!(start, end, "argv and envp strings must be contiguous"); + } + previous_end = Some(add(start, actual.as_units_with_nul().len())); + } + } + } + } +} diff --git a/crates/fspy_elf_loader/tests/support/launcher.rs b/crates/fspy_elf_loader/tests/support/launcher.rs index b72793b8f..60c99a59b 100644 --- a/crates/fspy_elf_loader/tests/support/launcher.rs +++ b/crates/fspy_elf_loader/tests/support/launcher.rs @@ -18,6 +18,9 @@ mod freestanding { // Consume those views before exec_elf replaces the stack. #[expect(clippy::needless_pass_by_value, reason = "signature required by main!")] fn run(stack: fspy_nostd::env::InitialStack<'_>) -> ! { + // Invocation: launcher ELF_PATH TARGET_ARGV0 [TARGET_ARGS...]. + // The kernel supplied this stack for the launcher; exec_elf will build + // another one for the target, with the first two arguments removed. let mut args = stack.args().iter().copied(); let _launcher = args.next().expect("missing launcher argv[0]"); let path = args.next().expect("missing target path"); @@ -27,13 +30,7 @@ mod freestanding { // parent selects a trusted fixture and kernel auxv references stay // valid until copied. There is no runtime requiring stack cleanup. unsafe { - fspy_elf_loader::exec_elf( - file, - path, - args, - stack.envs().iter().copied(), - stack.auxv().iter().copied(), - ) + fspy_elf_loader::exec_elf(file, path, args, stack.envs().iter().copied(), stack.auxv()) } } } diff --git a/crates/fspy_elf_loader_tests/Cargo.toml b/crates/fspy_elf_loader_tests/Cargo.toml new file mode 100644 index 000000000..a0851fa9f --- /dev/null +++ b/crates/fspy_elf_loader_tests/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "fspy_elf_loader_tests" +version = "0.0.0" +authors.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true +rust-version.workspace = true + +[target.'cfg(target_os = "linux")'.dev-dependencies] +ntest = { workspace = true } +elf = { workspace = true } +tempfile = { workspace = true } + +[target.'cfg(target_os = "linux")'.dependencies] +libc = { workspace = true } + +[target.'cfg(target_arch = "aarch64")'.dev-dependencies] +fspy_elf_loader = { path = "../fspy_elf_loader", artifact = "bin:fspy_elf_loader_test_launcher", target = "aarch64-unknown-none-softfloat" } + +[target.'cfg(target_arch = "x86_64")'.dev-dependencies] +fspy_elf_loader = { path = "../fspy_elf_loader", artifact = "bin:fspy_elf_loader_test_launcher", target = "x86_64-unknown-none" } + +[lints] +workspace = true + +[package.metadata.cargo-shear] +ignored = ["fspy_elf_loader"] diff --git a/crates/fspy_elf_loader_tests/src/bin/fixture.rs b/crates/fspy_elf_loader_tests/src/bin/fixture.rs new file mode 100644 index 000000000..974b35602 --- /dev/null +++ b/crates/fspy_elf_loader_tests/src/bin/fixture.rs @@ -0,0 +1,84 @@ +#[cfg(not(target_os = "linux"))] +const fn main() {} + +#[cfg(target_os = "linux")] +fn main() { + use std::{ + cell::Cell, + io::Write as _, + os::unix::ffi::OsStrExt as _, + sync::atomic::{AtomicU8, Ordering}, + }; + + static BSS: [AtomicU8; 128 * 1024] = [const { AtomicU8::new(0) }; 128 * 1024]; + static DATA: AtomicU8 = AtomicU8::new(42); + thread_local! { static TLS: Cell = const { Cell::new(17) }; } + + let args: Vec<_> = std::env::args_os().collect(); + assert_eq!(args.len(), 3); + assert_eq!(args[0], "custom-argv-zero"); + assert_eq!(args[1], ""); + assert_eq!(args[2].as_bytes(), b"\xff"); + assert_eq!(std::env::var_os("EMPTY").unwrap(), ""); + assert_eq!(std::env::var_os("BYTES").unwrap().as_bytes(), b"\xff"); + for byte in &BSS { + assert_eq!(byte.load(Ordering::Relaxed), 0); + } + BSS[BSS.len() - 1].store(9, Ordering::Relaxed); + assert_eq!(DATA.swap(43, Ordering::Relaxed), 42); + TLS.set(23); + let values = std::thread::spawn(|| { + assert_eq!(TLS.get(), 17); + vec![7_u8; 128 * 1024] + }) + .join() + .unwrap(); + assert!(values.iter().all(|value| *value == 7)); + assert_eq!(TLS.get(), 23); + + // SAFETY: successful runtime startup supplies readable auxiliary data. + unsafe { + let execfn = aux(libc::AT_EXECFN); + let execfn = std::ffi::CStr::from_ptr(std::ptr::with_exposed_provenance(execfn)); + assert_eq!(execfn.to_bytes(), std::env::var_os("FIXTURE_IMAGE").unwrap().as_bytes()); + assert_eq!(aux(libc::AT_PHENT), size_of::()); + let headers = std::slice::from_raw_parts( + std::ptr::with_exposed_provenance::(aux(libc::AT_PHDR)), + aux(libc::AT_PHNUM), + ); + let phdr = headers.iter().find(|ph| ph.p_type == libc::PT_PHDR).unwrap(); + let bias = aux(libc::AT_PHDR).checked_sub(usize::try_from(phdr.p_vaddr).unwrap()).unwrap(); + let entry = aux(libc::AT_ENTRY); + assert!(headers.iter().any(|ph| { + ph.p_type == libc::PT_LOAD + && ph.p_flags & libc::PF_X != 0 + && (bias + usize::try_from(ph.p_vaddr).unwrap() + ..bias + usize::try_from(ph.p_vaddr + ph.p_memsz).unwrap()) + .contains(&entry) + })); + let interpreter = std::slice::from_raw_parts( + std::ptr::with_exposed_provenance::(aux(libc::AT_BASE)), + 4, + ); + assert_eq!(interpreter, b"\x7fELF"); + let random = std::slice::from_raw_parts( + std::ptr::with_exposed_provenance::(aux(libc::AT_RANDOM)), + 16, + ); + assert!(random.iter().any(|byte| *byte != 0)); + } + let image = std::env::var_os("FIXTURE_IMAGE").unwrap(); + for entry in std::fs::read_dir("/proc/self/fd").unwrap() { + if let Ok(path) = std::fs::read_link(entry.unwrap().path()) { + assert_ne!(path.as_os_str(), image, "executable fd leaked"); + } + } + std::io::stdout().write_all(b"runtime-ok\n").unwrap(); + std::process::exit(37); +} + +#[cfg(target_os = "linux")] +fn aux(key: libc::c_ulong) -> usize { + // SAFETY: libc is initialized and getauxval only reads its startup data. + usize::try_from(unsafe { libc::getauxval(key) }).unwrap() +} diff --git a/crates/fspy_elf_loader_tests/tests/exec_elf.rs b/crates/fspy_elf_loader_tests/tests/exec_elf.rs new file mode 100644 index 000000000..c384c9eb5 --- /dev/null +++ b/crates/fspy_elf_loader_tests/tests/exec_elf.rs @@ -0,0 +1,145 @@ +// exec_elf implements the Linux process ABI. Its execution tests need Linux, +// even though Cargo can cross-compile the freestanding artifact on other hosts. +#![cfg(target_os = "linux")] + +use std::{ + ffi::OsStr, + os::unix::ffi::OsStrExt as _, + process::{Command, Output, Stdio}, +}; + +use ntest::timeout; + +const LAUNCHER: &str = env!("CARGO_BIN_FILE_FSPY_ELF_LOADER_fspy_elf_loader_test_launcher"); +const FIXTURE: &str = env!("CARGO_BIN_EXE_fixture"); + +#[test] +#[timeout(10_000)] +fn echo_matches_kernel_exec() { + assert_dynamic_pie("/bin/echo"); + let mut direct = Command::new("/bin/echo"); + direct.args(["hello", "world"]); + let mut loaded = launcher(); + loaded.args(["/bin/echo", "custom-argv-zero", "hello", "world"]); + let direct = output(direct); + let loaded = output(loaded); + assert_eq!(loaded.status.code(), Some(0), "{loaded:?}"); + assert_eq!(loaded.stdout, b"hello world\n"); + assert_eq!(loaded.stdout, direct.stdout); + assert_eq!(loaded.stderr, direct.stderr); +} + +#[test] +#[timeout(10_000)] +fn echo_preserves_empty_and_non_utf8_arguments() { + let mut command = launcher(); + command.args(["/bin/echo", "echo", ""]); + command.arg(OsStr::from_bytes(b"\xff")); + let output = output(command); + assert_eq!(output.status.code(), Some(0), "{output:?}"); + assert_eq!(output.stdout, b" \xff\n"); + assert!(output.stderr.is_empty()); +} + +#[test] +#[timeout(10_000)] +fn initializes_runtime_bss_tls_and_auxiliary_vector() { + assert_dynamic_pie(FIXTURE); + let mut command = launcher(); + command.args([FIXTURE, "custom-argv-zero", ""]); + command.arg(OsStr::from_bytes(b"\xff")); + command.env_clear().env("FIXTURE_IMAGE", FIXTURE).env("EMPTY", ""); + command.env("BYTES", OsStr::from_bytes(b"\xff")); + let output = output(command); + assert_eq!(output.status.code(), Some(37), "{output:?}"); + assert_eq!(output.stdout, b"runtime-ok\n"); + assert!(output.stderr.is_empty(), "{output:?}"); +} + +#[test] +#[timeout(10_000)] +fn rejects_unsupported_static_image() { + let mut command = launcher(); + command.args([LAUNCHER, "target-argv-zero"]); + let output = output(command); + assert_eq!(output.status.code(), Some(101), "{output:?}"); + assert!(str::from_utf8(&output.stderr).unwrap().contains("only ET_DYN")); +} + +#[test] +#[timeout(10_000)] +fn rejects_malformed_images() { + let echo = std::fs::read("/bin/echo").unwrap(); + let mut overflow = echo.clone(); + overflow[32..40].copy_from_slice(&u64::MAX.to_le_bytes()); + let mut wrong_machine = echo.clone(); + wrong_machine[18..20].copy_from_slice(&0_u16.to_le_bytes()); + let parsed = elf::ElfBytes::::minimal_parse(&echo).unwrap(); + let load = + parsed.segments().unwrap().iter().position(|ph| ph.p_type == elf::abi::PT_LOAD).unwrap(); + let header = usize::try_from(parsed.ehdr.e_phoff).unwrap() + load * 56; + let mut invalid_size = echo.clone(); + invalid_size[header + 32..header + 40].copy_from_slice(&u64::MAX.to_le_bytes()); + let mut invalid_alignment = echo.clone(); + invalid_alignment[header + 48..header + 56].copy_from_slice(&3_u64.to_le_bytes()); + for bytes in [ + b"not ELF".to_vec(), + echo[..64].to_vec(), + overflow, + wrong_machine, + invalid_size, + invalid_alignment, + ] { + let file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(file.path(), bytes).unwrap(); + let mut command = launcher(); + command.arg(file.path()).arg("invalid-image"); + let output = output(command); + assert_eq!(output.status.code(), Some(101), "{output:?}"); + assert!(str::from_utf8(&output.stderr).unwrap().contains("panicked at")); + } +} + +#[test] +#[timeout(10_000)] +fn does_not_require_section_headers() { + let mut bytes = std::fs::read("/bin/echo").unwrap(); + // The ELF loader must not use section metadata, even if it is unusable. + bytes[40..48].copy_from_slice(&u64::MAX.to_le_bytes()); + let file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(file.path(), bytes).unwrap(); + let mut command = launcher(); + command.arg(file.path()).args(["echo", "without-sections"]); + let output = output(command); + assert_eq!(output.status.code(), Some(0), "{output:?}"); + assert_eq!(output.stdout, b"without-sections\n"); +} + +#[test] +#[timeout(10_000)] +fn panic_terminates_with_read_only_stderr() { + let mut command = launcher(); + // Keep the descriptor valid, but make writes fail with EBADF. + command.stderr(std::fs::File::open("/dev/null").unwrap()); + // No target argument: the launcher panics while reading its arguments. + let output = output(command); + assert_eq!(output.status.code(), Some(101)); + assert!(output.stderr.is_empty()); +} + +fn launcher() -> Command { + let mut command = Command::new(LAUNCHER); + command.stderr(Stdio::piped()); + command +} + +fn assert_dynamic_pie(path: &str) { + let bytes = std::fs::read(path).unwrap(); + let elf = elf::ElfBytes::::minimal_parse(&bytes).unwrap(); + assert_eq!(elf.ehdr.e_type, elf::abi::ET_DYN, "fixture must be a dynamic PIE: {path}"); + assert!(elf.segments().unwrap().iter().any(|ph| ph.p_type == elf::abi::PT_INTERP)); +} + +fn output(mut command: Command) -> Output { + command.stdin(Stdio::null()).output().expect("cannot run freestanding launcher") +} diff --git a/rust-toolchain.toml b/rust-toolchain.toml index b39fe511d..569d02bce 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -3,3 +3,4 @@ # - cargo `Z-bindeps` to build and embed preload shared libraries as dependencies of fspy channel = "nightly-2026-08-02" profile = "default" +targets = ["aarch64-unknown-none-softfloat", "x86_64-unknown-none"] From cfdd317f352f1b7dd05f8d77cccb8e06c0aa6f5c Mon Sep 17 00:00:00 2001 From: wan9chi Date: Tue, 15 Sep 2026 15:39:03 +0800 Subject: [PATCH 10/34] docs(fspy-elf-loader): explain crate motivations and scope Co-authored-by: GPT-5 Codex --- crates/fspy_elf_loader/README.md | 13 +++++++++++++ crates/fspy_elf_loader_tests/README.md | 11 +++++++++++ 2 files changed, 24 insertions(+) create mode 100644 crates/fspy_elf_loader/README.md create mode 100644 crates/fspy_elf_loader_tests/README.md diff --git a/crates/fspy_elf_loader/README.md b/crates/fspy_elf_loader/README.md new file mode 100644 index 000000000..2fb8fd42d --- /dev/null +++ b/crates/fspy_elf_loader/README.md @@ -0,0 +1,13 @@ +# fspy_elf_loader + +An experimental Linux program loader for fspy's custom-loader approach. + +fspy needs to set up interception before a target program starts and keep that setup intact as the program takes over. This crate explores loading the program within the existing process, preserving the signal handlers that a normal exec would reset. + +## Scope + +This crate handles loading an ELF program and transferring execution to it. The caller owns execution-policy checks and interception setup. Integration with fspy remains separate work. + +The current implementation is a proof of concept for evaluating compatibility. It does not yet provide a complete replacement for Linux exec. + +[`fspy_elf_loader_tests`](../fspy_elf_loader_tests/README.md) covers program execution through the loader. diff --git a/crates/fspy_elf_loader_tests/README.md b/crates/fspy_elf_loader_tests/README.md new file mode 100644 index 000000000..6f1d6e6e8 --- /dev/null +++ b/crates/fspy_elf_loader_tests/README.md @@ -0,0 +1,11 @@ +# fspy_elf_loader_tests + +Integration tests for [`fspy_elf_loader`](../fspy_elf_loader/README.md). + +The tests check whether programs start and behave as expected through the custom loader. They help catch compatibility regressions as its scope grows. + +## Scope + +This crate covers program execution and loading failures in Linux processes. Unit tests for individual loader components stay in `fspy_elf_loader`. + +Keeping integration tests in a separate crate lets us use the normal Rust test runtime without adding it to the loader. The tests validate the loader itself; full fspy interception remains outside their scope. From 5e3d97165afb73693e1dd222446b9ded8973ae59 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sun, 20 Sep 2026 00:24:18 +0800 Subject: [PATCH 11/34] feat(fspy-elf-loader): support fixed-address executables 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 --- crates/fspy_elf_loader/README.md | 2 + crates/fspy_elf_loader/src/image.rs | 26 ++-- crates/fspy_elf_loader/src/image/tests.rs | 36 +++++ crates/fspy_elf_loader/src/lib.rs | 6 +- crates/fspy_elf_loader/src/mapping.rs | 27 ++++ crates/fspy_elf_loader_tests/README.md | 2 + crates/fspy_elf_loader_tests/build.rs | 7 + .../fspy_elf_loader_tests/src/bin/fixture.rs | 3 + .../src/bin/fixture_exec.rs | 2 + .../fspy_elf_loader_tests/tests/exec_elf.rs | 123 +++++++++++++++--- crates/fspy_nostd/src/env/initial_stack.rs | 2 +- crates/fspy_nostd/src/mm.rs | 5 + 12 files changed, 213 insertions(+), 28 deletions(-) create mode 100644 crates/fspy_elf_loader_tests/build.rs create mode 100644 crates/fspy_elf_loader_tests/src/bin/fixture_exec.rs diff --git a/crates/fspy_elf_loader/README.md b/crates/fspy_elf_loader/README.md index 2fb8fd42d..a80de534e 100644 --- a/crates/fspy_elf_loader/README.md +++ b/crates/fspy_elf_loader/README.md @@ -10,4 +10,6 @@ This crate handles loading an ELF program and transferring execution to it. The The current implementation is a proof of concept for evaluating compatibility. It does not yet provide a complete replacement for Linux exec. +It loads native ELF64 dynamic executables on AArch64 and x86-64, including PIE (`ET_DYN`) and fixed-address (`ET_EXEC`) images. Fixed-address images are rejected if their address range overlaps any existing mapping. Static executables remain unsupported. + [`fspy_elf_loader_tests`](../fspy_elf_loader_tests/README.md) covers program execution through the loader. diff --git a/crates/fspy_elf_loader/src/image.rs b/crates/fspy_elf_loader/src/image.rs index b6f1c5dd1..eebf5fc34 100644 --- a/crates/fspy_elf_loader/src/image.rs +++ b/crates/fspy_elf_loader/src/image.rs @@ -73,8 +73,11 @@ impl File { assert_eq!(header.e_machine, MACHINE, "ELF architecture mismatch"); // ET_DYN permits a load bias chosen for the available address space. // Position-independent executables (PIE) and their interpreters use it. - // ET_EXEC requires fixed addresses, which could overlap our loader. - assert_eq!(header.e_type, abi::ET_DYN, "only ET_DYN images are supported"); + // ET_EXEC instead uses its declared addresses with no load bias. + assert!( + matches!(header.e_type, abi::ET_DYN | abi::ET_EXEC), + "only ET_DYN and ET_EXEC images are supported" + ); assert_eq!(header.version, u32::from(abi::EV_CURRENT), "invalid ELF version"); assert_eq!(header.e_phentsize, 56, "invalid program-header size"); // 0xffff is an escape to a count stored in section metadata. This MVP @@ -156,12 +159,19 @@ impl File { // Reserve the whole image, including holes, before replacing pages // with MAP_FIXED. That flag discards existing mappings at its address; // restricting it to our reservation protects the loader and old stack. - // Extra space lets us align the bias, even if p_align exceeds a page. - let mapping = Mapping::reserve(add(span, alignment)); - let base = mapping.ptr.as_ptr().expose_provenance(); - let bias = - align_up(base.checked_sub(low).expect("unsupported ELF address range"), alignment); - assert!(add(bias, high) <= add(base, mapping.len), "ELF exceeds reservation"); + let (mapping, bias) = if self.header.e_type == abi::ET_EXEC { + // Fixed-address executables cannot move. Refuse collisions rather + // than replacing resident loader code or other process state. + (Mapping::reserve_at(low, span), 0) + } else { + // Extra space aligns the bias even when p_align exceeds a page. + let mapping = Mapping::reserve(add(span, alignment)); + let base = mapping.ptr.as_ptr().expose_provenance(); + let bias = + align_up(base.checked_sub(low).expect("unsupported ELF address range"), alignment); + assert!(add(bias, high) <= add(base, mapping.len), "ELF exceeds reservation"); + (mapping, bias) + }; let mut phdr = None; let mut executable_entry = false; // All segments share one bias, preserving their relative addresses. diff --git a/crates/fspy_elf_loader/src/image/tests.rs b/crates/fspy_elf_loader/src/image/tests.rs index 15d43b1d0..e6567a8d3 100644 --- a/crates/fspy_elf_loader/src/image/tests.rs +++ b/crates/fspy_elf_loader/src/image/tests.rs @@ -1,5 +1,41 @@ use super::*; +#[test] +fn fixed_image_collision_preserves_existing_memory() { + let page = fspy_nostd::param::page_size(); + let occupied = Mapping::reserve(4 * page); + // SAFETY: this reservation is exclusively owned here with no references. + unsafe { + mm::mprotect( + occupied.ptr.as_ptr().cast(), + occupied.len, + MprotectFlags::READ | MprotectFlags::WRITE, + ) + .unwrap(); + ptr::write_bytes(occupied.ptr.as_ptr(), 0x5a, occupied.len); + } + let base = align_up(occupied.ptr.as_ptr().addr(), 2 * page); + let mut bytes = fixture(page, page + 0x180, abi::PF_R | abi::PF_W); + bytes[16..18].copy_from_slice(&abi::ET_EXEC.to_le_bytes()); + bytes[24..32].copy_from_slice(&u64::try_from(base + 0x200).unwrap().to_le_bytes()); + for (index, start) in [(0, base), (1, base + page + 0x200)] { + let offset = 64 + index * 56 + 16; + bytes[offset..offset + 8].copy_from_slice(&u64::try_from(start).unwrap().to_le_bytes()); + } + let file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(file.path(), bytes).unwrap(); + let path = std::ffi::CString::new(file.path().as_os_str().as_encoded_bytes()).unwrap(); + let path = CStr::from_units_with_nul(path.as_bytes_with_nul()).unwrap(); + let image = File::new( + fs::openat(fspy_nostd::CWD, path, fs::OFlags::RDONLY, fs::Mode::empty()).unwrap(), + ); + assert!(std::panic::catch_unwind(|| image.map(page)).is_err()); + // SAFETY: a failed reservation must leave the original readable mapping + // intact, including the pages later LOAD segments would have replaced. + let bytes = unsafe { core::slice::from_raw_parts(occupied.ptr.as_ptr(), occupied.len) }; + assert!(bytes.iter().all(|byte| *byte == 0x5a)); +} + #[test] fn zeroes_the_entire_last_file_page_and_anonymous_bss() { let page = fspy_nostd::param::page_size(); diff --git a/crates/fspy_elf_loader/src/lib.rs b/crates/fspy_elf_loader/src/lib.rs index 12c07bf14..fa6a373ca 100644 --- a/crates/fspy_elf_loader/src/lib.rs +++ b/crates/fspy_elf_loader/src/lib.rs @@ -26,7 +26,7 @@ mod stack; /// /// Takes ownership of a private executable descriptor and closes it after /// mapping. Loads the executable and its `PT_INTERP`, builds an initial stack, -/// and transfers control to the interpreter or executable entry point. +/// and transfers control to the interpreter entry point. /// /// `execfn` is the original execution name used for `AT_EXECFN`; it need not /// match `argv[0]`. Arguments and environment entries are copied to the new @@ -42,8 +42,10 @@ mod stack; /// Loading failures terminate the process; they cannot return to the program /// that executed the loader. /// -/// Currently supports native little-endian ELF64 dynamic PIE executables on +/// Currently supports native little-endian ELF64 dynamic executables on /// `AArch64` and x86-64, with an ELF interpreter and a non-executable stack. +/// Both PIE (`ET_DYN`) and fixed-address (`ET_EXEC`) executables are supported. +/// Fixed-address images must not overlap any existing process mappings. /// The new stack has a fixed 8 MiB capacity and a guard page. Existing loader /// mappings, the old stack, and kernel process metadata (including `/proc` /// identity and `brk`) are retained. This does not emulate a complete exec. diff --git a/crates/fspy_elf_loader/src/mapping.rs b/crates/fspy_elf_loader/src/mapping.rs index e997fa359..f592af0d1 100644 --- a/crates/fspy_elf_loader/src/mapping.rs +++ b/crates/fspy_elf_loader/src/mapping.rs @@ -45,6 +45,33 @@ impl Mapping { Self::new(ptr.cast(), len) } + pub fn reserve_at(address: usize, len: usize) -> Self { + Self::check_len(len); + // Reserve the complete fixed-address image before replacing any of + // its pages. A collision with the loader, stack, or another mapping + // must fail without changing that mapping. + // SAFETY: FIXED_NOREPLACE never replaces existing mappings, and the + // fresh reservation has no references or accessible pages. + let ptr = unsafe { + mm::mmap_anonymous( + ptr::with_exposed_provenance_mut(address), + len, + ProtFlags::empty(), + MapFlags::PRIVATE | MapFlags::FIXED_NOREPLACE, + ) + } + .expect("cannot reserve fixed ELF address range"); + let mapping = Self::new(ptr.cast(), len); + // Older kernels can ignore FIXED_NOREPLACE and choose another address. + // Release that reservation before failing; MAP_FIXED below must never + // run unless we own the exact requested range. + if mapping.ptr.as_ptr().addr() != address { + drop(mapping); + panic!("cannot reserve fixed ELF address range at the requested address"); + } + mapping + } + pub fn file(fd: BorrowedFd<'_>, len: usize) -> Self { Self::check_len(len); // One contiguous view makes file-offset parsing possible. This is diff --git a/crates/fspy_elf_loader_tests/README.md b/crates/fspy_elf_loader_tests/README.md index 6f1d6e6e8..5d66c31e9 100644 --- a/crates/fspy_elf_loader_tests/README.md +++ b/crates/fspy_elf_loader_tests/README.md @@ -4,6 +4,8 @@ Integration tests for [`fspy_elf_loader`](../fspy_elf_loader/README.md). The tests check whether programs start and behave as expected through the custom loader. They help catch compatibility regressions as its scope grows. +The default suite covers dynamic PIE and fixed-address executables, including address collisions. With Node.js on `PATH`, run `cargo test -p fspy_elf_loader_tests -- --include-ignored` on Linux to also compare a real Node program with normal execution. + ## Scope This crate covers program execution and loading failures in Linux processes. Unit tests for individual loader components stay in `fspy_elf_loader`. diff --git a/crates/fspy_elf_loader_tests/build.rs b/crates/fspy_elf_loader_tests/build.rs new file mode 100644 index 000000000..3cd8b7487 --- /dev/null +++ b/crates/fspy_elf_loader_tests/build.rs @@ -0,0 +1,7 @@ +fn main() { + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("linux") { + // Keep the same runtime checks in PIE and fixed-address executables. + // The linker driver must retain dynamic linking while disabling PIE. + println!("cargo::rustc-link-arg-bin=fixture_exec=-no-pie"); + } +} diff --git a/crates/fspy_elf_loader_tests/src/bin/fixture.rs b/crates/fspy_elf_loader_tests/src/bin/fixture.rs index 974b35602..eb8a594e3 100644 --- a/crates/fspy_elf_loader_tests/src/bin/fixture.rs +++ b/crates/fspy_elf_loader_tests/src/bin/fixture.rs @@ -48,6 +48,9 @@ fn main() { ); let phdr = headers.iter().find(|ph| ph.p_type == libc::PT_PHDR).unwrap(); let bias = aux(libc::AT_PHDR).checked_sub(usize::try_from(phdr.p_vaddr).unwrap()).unwrap(); + if std::env::var_os("EXPECT_FIXED_ADDRESS").is_some() { + assert_eq!(bias, 0, "fixed-address executable was relocated"); + } let entry = aux(libc::AT_ENTRY); assert!(headers.iter().any(|ph| { ph.p_type == libc::PT_LOAD diff --git a/crates/fspy_elf_loader_tests/src/bin/fixture_exec.rs b/crates/fspy_elf_loader_tests/src/bin/fixture_exec.rs new file mode 100644 index 000000000..8fb726c2f --- /dev/null +++ b/crates/fspy_elf_loader_tests/src/bin/fixture_exec.rs @@ -0,0 +1,2 @@ +// build.rs links these runtime checks as a dynamic ET_EXEC executable. +include!("fixture.rs"); diff --git a/crates/fspy_elf_loader_tests/tests/exec_elf.rs b/crates/fspy_elf_loader_tests/tests/exec_elf.rs index c384c9eb5..ce3bd3775 100644 --- a/crates/fspy_elf_loader_tests/tests/exec_elf.rs +++ b/crates/fspy_elf_loader_tests/tests/exec_elf.rs @@ -12,15 +12,18 @@ use ntest::timeout; const LAUNCHER: &str = env!("CARGO_BIN_FILE_FSPY_ELF_LOADER_fspy_elf_loader_test_launcher"); const FIXTURE: &str = env!("CARGO_BIN_EXE_fixture"); +const FIXTURE_EXEC: &str = env!("CARGO_BIN_EXE_fixture_exec"); #[test] #[timeout(10_000)] fn echo_matches_kernel_exec() { - assert_dynamic_pie("/bin/echo"); + assert_dynamic_image("/bin/echo", elf::abi::ET_DYN); let mut direct = Command::new("/bin/echo"); direct.args(["hello", "world"]); let mut loaded = launcher(); - loaded.args(["/bin/echo", "custom-argv-zero", "hello", "world"]); + // BusyBox selects its applet through argv[0]. The runtime fixtures below + // exercise custom argv[0] independently of the host's echo implementation. + loaded.args(["/bin/echo", "echo", "hello", "world"]); let direct = output(direct); let loaded = output(loaded); assert_eq!(loaded.status.code(), Some(0), "{loaded:?}"); @@ -44,12 +47,25 @@ fn echo_preserves_empty_and_non_utf8_arguments() { #[test] #[timeout(10_000)] fn initializes_runtime_bss_tls_and_auxiliary_vector() { - assert_dynamic_pie(FIXTURE); + check_runtime(FIXTURE, elf::abi::ET_DYN); +} + +#[test] +#[timeout(10_000)] +fn initializes_runtime_in_fixed_address_executable() { + check_runtime(FIXTURE_EXEC, elf::abi::ET_EXEC); +} + +fn check_runtime(fixture: &str, image_type: u16) { + assert_dynamic_image(fixture, image_type); let mut command = launcher(); - command.args([FIXTURE, "custom-argv-zero", ""]); + command.args([fixture, "custom-argv-zero", ""]); command.arg(OsStr::from_bytes(b"\xff")); - command.env_clear().env("FIXTURE_IMAGE", FIXTURE).env("EMPTY", ""); + command.env_clear().env("FIXTURE_IMAGE", fixture).env("EMPTY", ""); command.env("BYTES", OsStr::from_bytes(b"\xff")); + if image_type == elf::abi::ET_EXEC { + command.env("EXPECT_FIXED_ADDRESS", "1"); + } let output = output(command); assert_eq!(output.status.code(), Some(37), "{output:?}"); assert_eq!(output.stdout, b"runtime-ok\n"); @@ -63,7 +79,74 @@ fn rejects_unsupported_static_image() { command.args([LAUNCHER, "target-argv-zero"]); let output = output(command); assert_eq!(output.status.code(), Some(101), "{output:?}"); - assert!(str::from_utf8(&output.stderr).unwrap().contains("only ET_DYN")); + assert!(str::from_utf8(&output.stderr).unwrap().contains("executable has no PT_INTERP")); +} + +#[test] +#[timeout(10_000)] +fn rejects_fixed_image_overlapping_launcher() { + let launcher_bytes = std::fs::read(LAUNCHER).unwrap(); + let launcher_elf = + elf::ElfBytes::::minimal_parse(&launcher_bytes).unwrap(); + let launcher_base = launcher_elf + .segments() + .unwrap() + .iter() + .find(|ph| ph.p_type == elf::abi::PT_LOAD) + .unwrap() + .p_vaddr; + let mut bytes = std::fs::read(FIXTURE_EXEC).unwrap(); + let parsed = elf::ElfBytes::::minimal_parse(&bytes).unwrap(); + let table = usize::try_from(parsed.ehdr.e_phoff).unwrap(); + let loads: Vec<_> = parsed + .segments() + .unwrap() + .iter() + .enumerate() + .filter(|(_, ph)| ph.p_type == elf::abi::PT_LOAD) + .collect(); + let base = loads[0].1.p_vaddr; + let entry = parsed.ehdr.e_entry - base + launcher_base; + bytes[24..32].copy_from_slice(&entry.to_le_bytes()); + for (index, ph) in loads { + let offset = table + index * 56 + 16; + bytes[offset..offset + 8] + .copy_from_slice(&(ph.p_vaddr - base + launcher_base).to_le_bytes()); + } + let file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(file.path(), bytes).unwrap(); + let mut command = launcher(); + command.arg(file.path()).arg("overlapping-image"); + let output = output(command); + assert_eq!(output.status.code(), Some(101), "{output:?}"); + assert!( + str::from_utf8(&output.stderr).unwrap().contains("cannot reserve fixed ELF address range"), + "{output:?}" + ); +} + +#[test] +#[ignore = "requires Node.js"] +#[timeout(10_000)] +fn node_runs_javascript() { + // Resolve the actual executable even when PATH contains a Node wrapper. + let mut resolve = Command::new("node"); + resolve.args(["-p", "process.execPath"]); + let resolved = output(resolve); + assert!(resolved.status.success(), "{resolved:?}"); + let node = OsStr::from_bytes(resolved.stdout.strip_suffix(b"\n").unwrap()); + let script = + "console.log(require('node:crypto').createHash('sha256').update('loader').digest('hex'))"; + let mut direct = Command::new(node); + direct.args(["-e", script]); + let mut loaded = launcher(); + loaded.arg(node).args(["node", "-e", script]); + let direct = output(direct); + let loaded = output(loaded); + assert_eq!(direct.status.code(), Some(0), "{direct:?}"); + assert_eq!(loaded.status.code(), Some(0), "{loaded:?}"); + assert_eq!(loaded.stdout, direct.stdout); + assert_eq!(loaded.stderr, direct.stderr); } #[test] @@ -74,6 +157,8 @@ fn rejects_malformed_images() { overflow[32..40].copy_from_slice(&u64::MAX.to_le_bytes()); let mut wrong_machine = echo.clone(); wrong_machine[18..20].copy_from_slice(&0_u16.to_le_bytes()); + let mut unsupported_type = echo.clone(); + unsupported_type[16..18].copy_from_slice(&elf::abi::ET_REL.to_le_bytes()); let parsed = elf::ElfBytes::::minimal_parse(&echo).unwrap(); let load = parsed.segments().unwrap().iter().position(|ph| ph.p_type == elf::abi::PT_LOAD).unwrap(); @@ -82,21 +167,25 @@ fn rejects_malformed_images() { invalid_size[header + 32..header + 40].copy_from_slice(&u64::MAX.to_le_bytes()); let mut invalid_alignment = echo.clone(); invalid_alignment[header + 48..header + 56].copy_from_slice(&3_u64.to_le_bytes()); - for bytes in [ - b"not ELF".to_vec(), - echo[..64].to_vec(), - overflow, - wrong_machine, - invalid_size, - invalid_alignment, + for (case, bytes) in [ + ("truncated header", b"not ELF".to_vec()), + ("truncated program headers", echo[..64].to_vec()), + ("overflowing program-header offset", overflow), + ("wrong architecture", wrong_machine), + ("unsupported type", unsupported_type), + ("invalid size", invalid_size), + ("invalid alignment", invalid_alignment), ] { let file = tempfile::NamedTempFile::new().unwrap(); std::fs::write(file.path(), bytes).unwrap(); let mut command = launcher(); command.arg(file.path()).arg("invalid-image"); let output = output(command); - assert_eq!(output.status.code(), Some(101), "{output:?}"); - assert!(str::from_utf8(&output.stderr).unwrap().contains("panicked at")); + assert_eq!(output.status.code(), Some(101), "{case}: {output:?}"); + assert!( + str::from_utf8(&output.stderr).unwrap().contains("panicked at"), + "{case}: {output:?}" + ); } } @@ -133,10 +222,10 @@ fn launcher() -> Command { command } -fn assert_dynamic_pie(path: &str) { +fn assert_dynamic_image(path: &str, image_type: u16) { let bytes = std::fs::read(path).unwrap(); let elf = elf::ElfBytes::::minimal_parse(&bytes).unwrap(); - assert_eq!(elf.ehdr.e_type, elf::abi::ET_DYN, "fixture must be a dynamic PIE: {path}"); + assert_eq!(elf.ehdr.e_type, image_type, "unexpected fixture image type: {path}"); assert!(elf.segments().unwrap().iter().any(|ph| ph.p_type == elf::abi::PT_INTERP)); } diff --git a/crates/fspy_nostd/src/env/initial_stack.rs b/crates/fspy_nostd/src/env/initial_stack.rs index fb1107646..a3d7d5b7a 100644 --- a/crates/fspy_nostd/src/env/initial_stack.rs +++ b/crates/fspy_nostd/src/env/initial_stack.rs @@ -78,7 +78,7 @@ impl<'a> InitialStack<'a> { Self { arguments, environment, auxiliary } } - /// Borrows arguments, including argv[0], without the null terminator. + /// Borrows arguments, including `argv[0]`, without the null terminator. #[must_use] pub const fn args(&self) -> &'a [CStr<'a, Thin>] { self.arguments diff --git a/crates/fspy_nostd/src/mm.rs b/crates/fspy_nostd/src/mm.rs index b84b75a09..37a8a036f 100644 --- a/crates/fspy_nostd/src/mm.rs +++ b/crates/fspy_nostd/src/mm.rs @@ -56,6 +56,11 @@ mod unix { /// Replace mappings at the requested address instead of using it as a hint. #[cfg(any(target_os = "linux", target_os = "none"))] const FIXED = linux_raw_sys::general::MAP_FIXED; + /// Request an exact address without replacing existing mappings. + /// Kernels before Linux 4.17 may treat the address as a hint; + /// callers must check the returned address. + #[cfg(any(target_os = "linux", target_os = "none"))] + const FIXED_NOREPLACE = linux_raw_sys::general::MAP_FIXED_NOREPLACE; } } From ac6514ff7a9d3602788c523116ffe2dffdf5a2e5 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Tue, 3 Nov 2026 23:03:02 +0800 Subject: [PATCH 12/34] test(fspy-elf-loader): select high fixed launcher addresses 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 --- .gitignore | 1 + crates/fspy_elf_loader/README.md | 19 +++++++++ crates/fspy_elf_loader/build.rs | 19 ++++++--- crates/fspy_elf_loader/src/image/tests.rs | 36 ----------------- crates/fspy_elf_loader_tests/Cargo.toml | 4 +- crates/fspy_elf_loader_tests/README.md | 8 +++- .../fspy_elf_loader_tests/tests/exec_elf.rs | 2 +- .../tests/launcher_image.rs | 39 +++++++++++++++++++ 8 files changed, 84 insertions(+), 44 deletions(-) create mode 100644 crates/fspy_elf_loader_tests/tests/launcher_image.rs diff --git a/.gitignore b/.gitignore index 881b4e1ad..38e1b824f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ /target +/crates/fspy_elf_loader_tests/compat/ node_modules # Fixture node_modules that stand in for real npm installs in snapshot tests. # `**` covers nested monorepo layouts (e.g. packages/foo/node_modules/.bin). diff --git a/crates/fspy_elf_loader/README.md b/crates/fspy_elf_loader/README.md index a80de534e..16af9b929 100644 --- a/crates/fspy_elf_loader/README.md +++ b/crates/fspy_elf_loader/README.md @@ -12,4 +12,23 @@ The current implementation is a proof of concept for evaluating compatibility. I It loads native ELF64 dynamic executables on AArch64 and x86-64, including PIE (`ET_DYN`) and fixed-address (`ET_EXEC`) images. Fixed-address images are rejected if their address range overlaps any existing mapping. Static executables remain unsupported. +The freestanding launcher is a static fixed-address executable with no startup relocation: + +| Architecture | Base address | Base in binary units | +| ------------ | ------------------ | -------------------- | +| x86-64 | `0x5500_0000_0000` | 85 TiB | +| AArch64 | `0x0002_0000_0000` | 8 GiB | + +These bases leave the low 4 GiB available and sit in application regions of +the current LLVM Linux [AddressSanitizer](https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/asan/asan_mapping.h) +and [C/C++ ThreadSanitizer](https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/tsan/rtl/tsan_platform.h) +layouts. AArch64 uses a lower base to fit smaller virtual address spaces, +including 39-bit configurations, and remains below their 20 GiB TSan low +application-region limit. These placement choices do not establish complete +sanitizer compatibility: GCC 12's AArch64 TSan runtime rejects the 8 GiB +launcher mapping. Its [older layout](https://github.com/gcc-mirror/gcc/blob/releases/gcc-12.2.0/libsanitizer/tsan/tsan_platform.h) +limits low application memory to below 4 GiB on 39-bit systems and below +8 GiB on 48-bit systems. The addresses are conventions, not reserved ranges: +fixed-address targets that overlap retained mappings are still rejected. + [`fspy_elf_loader_tests`](../fspy_elf_loader_tests/README.md) covers program execution through the loader. diff --git a/crates/fspy_elf_loader/build.rs b/crates/fspy_elf_loader/build.rs index d47ab4cc1..368cac7ba 100644 --- a/crates/fspy_elf_loader/build.rs +++ b/crates/fspy_elf_loader/build.rs @@ -1,9 +1,18 @@ fn main() { if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("none") { - // main! has no self-relocator. x86_64-unknown-none otherwise links a - // static PIE with unresolved load-bias relocations, even for panics. - // The kernel maps PT_LOAD segments but does not fix up pointers in a - // static PIE. With --no-pie, the linker resolves them for fixed addresses. - println!("cargo::rustc-link-arg-bin=fspy_elf_loader_test_launcher=--no-pie"); + // Leave the low 4 GiB available while staying in application regions + // of the current LLVM Linux ASan and C/C++ TSan layouts. AArch64's + // base also fits smaller virtual address spaces, including 39-bit. + // Older AArch64 TSan runtimes can reject 8 GiB; see the README. + // This is a placement convention; fixed targets can still overlap it. + let image_base = match std::env::var("CARGO_CFG_TARGET_ARCH").as_deref() { + Ok("x86_64") => "--image-base=0x550000000000", // 85 TiB + Ok("aarch64") => "--image-base=0x200000000", // 8 GiB + _ => panic!("unsupported launcher architecture"), + }; + // Fixed linking resolves pointers without a startup self-relocator. + for argument in ["--no-pie", image_base] { + println!("cargo::rustc-link-arg-bin=fspy_elf_loader_test_launcher={argument}"); + } } } diff --git a/crates/fspy_elf_loader/src/image/tests.rs b/crates/fspy_elf_loader/src/image/tests.rs index e6567a8d3..15d43b1d0 100644 --- a/crates/fspy_elf_loader/src/image/tests.rs +++ b/crates/fspy_elf_loader/src/image/tests.rs @@ -1,41 +1,5 @@ use super::*; -#[test] -fn fixed_image_collision_preserves_existing_memory() { - let page = fspy_nostd::param::page_size(); - let occupied = Mapping::reserve(4 * page); - // SAFETY: this reservation is exclusively owned here with no references. - unsafe { - mm::mprotect( - occupied.ptr.as_ptr().cast(), - occupied.len, - MprotectFlags::READ | MprotectFlags::WRITE, - ) - .unwrap(); - ptr::write_bytes(occupied.ptr.as_ptr(), 0x5a, occupied.len); - } - let base = align_up(occupied.ptr.as_ptr().addr(), 2 * page); - let mut bytes = fixture(page, page + 0x180, abi::PF_R | abi::PF_W); - bytes[16..18].copy_from_slice(&abi::ET_EXEC.to_le_bytes()); - bytes[24..32].copy_from_slice(&u64::try_from(base + 0x200).unwrap().to_le_bytes()); - for (index, start) in [(0, base), (1, base + page + 0x200)] { - let offset = 64 + index * 56 + 16; - bytes[offset..offset + 8].copy_from_slice(&u64::try_from(start).unwrap().to_le_bytes()); - } - let file = tempfile::NamedTempFile::new().unwrap(); - std::fs::write(file.path(), bytes).unwrap(); - let path = std::ffi::CString::new(file.path().as_os_str().as_encoded_bytes()).unwrap(); - let path = CStr::from_units_with_nul(path.as_bytes_with_nul()).unwrap(); - let image = File::new( - fs::openat(fspy_nostd::CWD, path, fs::OFlags::RDONLY, fs::Mode::empty()).unwrap(), - ); - assert!(std::panic::catch_unwind(|| image.map(page)).is_err()); - // SAFETY: a failed reservation must leave the original readable mapping - // intact, including the pages later LOAD segments would have replaced. - let bytes = unsafe { core::slice::from_raw_parts(occupied.ptr.as_ptr(), occupied.len) }; - assert!(bytes.iter().all(|byte| *byte == 0x5a)); -} - #[test] fn zeroes_the_entire_last_file_page_and_anonymous_bss() { let page = fspy_nostd::param::page_size(); diff --git a/crates/fspy_elf_loader_tests/Cargo.toml b/crates/fspy_elf_loader_tests/Cargo.toml index a0851fa9f..0def1608d 100644 --- a/crates/fspy_elf_loader_tests/Cargo.toml +++ b/crates/fspy_elf_loader_tests/Cargo.toml @@ -7,9 +7,11 @@ license.workspace = true publish.workspace = true rust-version.workspace = true +[dev-dependencies] +elf = { workspace = true } + [target.'cfg(target_os = "linux")'.dev-dependencies] ntest = { workspace = true } -elf = { workspace = true } tempfile = { workspace = true } [target.'cfg(target_os = "linux")'.dependencies] diff --git a/crates/fspy_elf_loader_tests/README.md b/crates/fspy_elf_loader_tests/README.md index 5d66c31e9..10f208f77 100644 --- a/crates/fspy_elf_loader_tests/README.md +++ b/crates/fspy_elf_loader_tests/README.md @@ -4,7 +4,13 @@ Integration tests for [`fspy_elf_loader`](../fspy_elf_loader/README.md). The tests check whether programs start and behave as expected through the custom loader. They help catch compatibility regressions as its scope grows. -The default suite covers dynamic PIE and fixed-address executables, including address collisions. With Node.js on `PATH`, run `cargo test -p fspy_elf_loader_tests -- --include-ignored` on Linux to also compare a real Node program with normal execution. +The default suite covers dynamic PIE and fixed-address executables, including rejection of a target overlapping the launcher. With Node.js on `PATH`, run `cargo test -p fspy_elf_loader_tests -- --include-ignored` on Linux to also compare a real Node program with normal execution. + +The launcher artifact is checked on every host for a static fixed-address +layout at 85 TiB on x86-64 or 8 GiB on AArch64, with no dynamic relocation +requirements. The collision test checks that the launcher still reports the +expected error after rejecting an overlapping target. Run the Linux suite in +both debug and release profiles. ## Scope diff --git a/crates/fspy_elf_loader_tests/tests/exec_elf.rs b/crates/fspy_elf_loader_tests/tests/exec_elf.rs index ce3bd3775..1f77b4625 100644 --- a/crates/fspy_elf_loader_tests/tests/exec_elf.rs +++ b/crates/fspy_elf_loader_tests/tests/exec_elf.rs @@ -52,7 +52,7 @@ fn initializes_runtime_bss_tls_and_auxiliary_vector() { #[test] #[timeout(10_000)] -fn initializes_runtime_in_fixed_address_executable() { +fn initializes_fixed_runtime() { check_runtime(FIXTURE_EXEC, elf::abi::ET_EXEC); } diff --git a/crates/fspy_elf_loader_tests/tests/launcher_image.rs b/crates/fspy_elf_loader_tests/tests/launcher_image.rs new file mode 100644 index 000000000..c4077aab0 --- /dev/null +++ b/crates/fspy_elf_loader_tests/tests/launcher_image.rs @@ -0,0 +1,39 @@ +use elf::{ElfBytes, abi, endian::LittleEndian, file::Class}; + +const LAUNCHER: &str = env!("CARGO_BIN_FILE_FSPY_ELF_LOADER_fspy_elf_loader_test_launcher"); + +// Inspect the real artifact on every host, including macOS and Windows. +// Linux execution tests separately check startup and fixed-address collisions. +#[test] +fn launcher_uses_high_fixed_addresses_without_runtime_relocations() { + let bytes = std::fs::read(LAUNCHER).unwrap(); + let image = ElfBytes::::minimal_parse(&bytes).unwrap(); + assert_eq!(image.ehdr.class, Class::ELF64); + assert_eq!(image.ehdr.e_type, abi::ET_EXEC); + // Keep the entire image inside a sanitizer application region: x86-64 + // C/C++ TSan's 85–90 TiB region, or AArch64 39-bit TSan's low 20 GiB. + let (base, limit) = match image.ehdr.e_machine { + abi::EM_X86_64 => (0x5500_0000_0000, 0x5a00_0000_0000), + abi::EM_AARCH64 => (0x0002_0000_0000, 0x0005_0000_0000), + machine => panic!("unsupported launcher machine: {machine}"), + }; + let segments: Vec<_> = image.segments().unwrap().iter().collect(); + assert!( + !segments + .iter() + .any(|ph| { matches!(ph.p_type, abi::PT_INTERP | abi::PT_DYNAMIC | abi::PT_TLS) }) + ); + let first_load = segments.iter().find(|ph| ph.p_type == abi::PT_LOAD).unwrap(); + assert_eq!((first_load.p_vaddr, first_load.p_offset), (base, 0)); + for segment in segments.iter().filter(|ph| ph.p_type == abi::PT_LOAD) { + assert!(segment.p_vaddr >= base); + assert!(segment.p_vaddr.checked_add(segment.p_memsz).unwrap() <= limit); + } + assert!(segments.iter().any(|ph| { + ph.p_type == abi::PT_LOAD + && ph.p_flags & abi::PF_X != 0 + && ph.p_vaddr <= image.ehdr.e_entry + && image.ehdr.e_entry < ph.p_vaddr + ph.p_memsz + })); + assert!(image.dynamic().unwrap().is_none()); +} From e76921e3fc6f22b1ff2bc44d3223d963834af43a Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 18 Nov 2026 03:47:40 +0000 Subject: [PATCH 13/34] fix(fspy-elf-loader): match Linux PT_LOAD and PT_INTERP loading 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 Co-authored-by: Charles Wang --- crates/fspy_elf_loader/src/image.rs | 101 ++++++++------ crates/fspy_elf_loader/src/image/tests.rs | 157 +++++++++++++++++++--- crates/fspy_elf_loader/src/lib.rs | 25 +++- 3 files changed, 221 insertions(+), 62 deletions(-) diff --git a/crates/fspy_elf_loader/src/image.rs b/crates/fspy_elf_loader/src/image.rs index eebf5fc34..e9e8f9d90 100644 --- a/crates/fspy_elf_loader/src/image.rs +++ b/crates/fspy_elf_loader/src/image.rs @@ -111,7 +111,12 @@ impl File { // SAFETY: the file remains unchanged and mapped read-only. let bytes = unsafe { self.view.bytes() }.get(start..end).expect("truncated PT_INTERP"); - let path = CStr::from_units_with_nul(bytes).expect("invalid PT_INTERP path"); + // Linux requires only that the last byte is NUL, then treats + // the slice as a C string. Linkers may pad with extra NULs. + assert!(bytes.last() == Some(&0), "unterminated PT_INTERP"); + let len = bytes.iter().position(|byte| *byte == 0).unwrap() + 1; + let path = + CStr::from_units_with_nul(&bytes[..len]).expect("invalid PT_INTERP path"); assert!(!path.as_units().is_empty(), "empty PT_INTERP path"); result = Some(path); } @@ -119,41 +124,56 @@ impl File { result } + fn assert_disjoint_load(&self, index: usize, start: usize, end: usize) { + for (other_index, other) in self.segments().iter().enumerate() { + if other_index > index && other.p_type == abi::PT_LOAD && other.p_memsz != 0 { + let other_start = word(other.p_vaddr); + let other_end = add(other_start, word(other.p_memsz)); + assert!(end <= other_start || other_end <= start, "overlapping ELF segments"); + } + } + } + pub fn map(&self, page: usize) -> Image { // First validate the segments and find their page-rounded span. // mmap operates on whole pages, even when ELF segments do not. let mut low = usize::MAX; let mut high = 0; let mut alignment = page; - let mut previous_end = 0; - for segment in self.segments().iter() { + for (index, segment) in self.segments().iter().enumerate() { if segment.p_type == abi::PT_GNU_STACK { assert!(segment.p_flags & abi::PF_X == 0, "executable stacks are unsupported"); } - if segment.p_type != abi::PT_LOAD { - continue; - } - let start = word(segment.p_vaddr); - let end = add(start, word(segment.p_memsz)); - let file_end = add(word(segment.p_offset), word(segment.p_filesz)); - assert!(segment.p_filesz <= segment.p_memsz, "ELF filesz exceeds memsz"); - assert!(file_end <= self.view.len, "truncated ELF segment"); - // Our MVP rejects overlapping byte ranges. Page-rounded ranges - // can still overlap, so mapping below must preserve header order. - assert!(start >= previous_end, "overlapping or unordered ELF segments"); - previous_end = end; - // ELF treats alignment 0 and 1 as no extra constraint. File and - // memory offsets must agree within a page for file-backed mmap. - let align = word(segment.p_align).max(1); - assert!(align.is_power_of_two(), "invalid segment alignment"); - assert_eq!(start % align, word(segment.p_offset) % align, "incongruent ELF alignment"); - assert_eq!(start % page, word(segment.p_offset) % page, "incongruent ELF page offsets"); - alignment = alignment.max(align); - if segment.p_memsz == 0 { - continue; + if segment.p_type == abi::PT_LOAD { + let start = word(segment.p_vaddr); + let end = add(start, word(segment.p_memsz)); + let file_end = add(word(segment.p_offset), word(segment.p_filesz)); + assert!(segment.p_filesz <= segment.p_memsz, "ELF filesz exceeds memsz"); + assert!(file_end <= self.view.len, "truncated ELF segment"); + // Byte ranges must not overlap. Header order need not match + // vaddr order; mapping below still walks headers so a later + // MAP_FIXED can share a page with an earlier load. + if segment.p_memsz != 0 { + self.assert_disjoint_load(index, start, end); + low = low.min(start & !sub(page, 1)); + high = high.max(align_up(end, page)); + } + // ELF treats alignment 0 and 1 as no extra constraint. File + // and memory offsets must agree within a page for mmap. + let align = word(segment.p_align).max(1); + assert!(align.is_power_of_two(), "invalid segment alignment"); + assert_eq!( + start % align, + word(segment.p_offset) % align, + "incongruent ELF alignment" + ); + assert_eq!( + start % page, + word(segment.p_offset) % page, + "incongruent ELF page offsets" + ); + alignment = alignment.max(align); } - low = low.min(start & !sub(page, 1)); - high = high.max(align_up(end, page)); } let span = high.checked_sub(low).expect("ELF has no loadable memory"); // Reserve the whole image, including holes, before replacing pages @@ -228,17 +248,21 @@ impl File { protection |= ProtFlags::EXEC; } let fixed = MapFlags::PRIVATE | MapFlags::FIXED; - if segment.p_filesz != 0 { + // Linux elf_map skips a zero-length mapping, which happens only when + // filesz is 0 and vaddr is page-aligned. A zero-filesz load that + // starts mid-page still maps that shared page from the file so a + // later MAP_FIXED does not anonymous-wipe the previous load's bytes. + let file_len = sub(align_up(file_end, page), page_start); + if file_len != 0 { // Round both the file offset and address down by the same amount. // For example, an offset ending in 0x340 needs those first 0x340 // bytes of its page mapped too. Round the end up to cover the tail. // PRIVATE keeps BSS writes and later relocations out of the file. - let len = sub(align_up(file_end, page), page_start); // SAFETY: caller owns the entire reservation being replaced. unsafe { mm::mmap( ptr::with_exposed_provenance_mut(page_start), - len, + file_len, protection, fixed, self.fd.as_fd(), @@ -246,18 +270,18 @@ impl File { ) } .expect("cannot map ELF segment"); - if file_end < end && !file_end.is_multiple_of(page) { + // Zero through the page boundary, not just p_memsz: leftover file + // bytes after filesz==memsz, and the BSS tail of filesz(image.bias + page + 0x100).read(), 0xa5); + assert_eq!(ptr::with_exposed_provenance::(image.bias + page + 0x2ff).read(), 0xa5); + let tail = core::slice::from_raw_parts( + ptr::with_exposed_provenance::(image.bias + page + 0x300), + page - 0x300, + ); + assert!(tail.iter().all(|byte| *byte == 0), "filesz==memsz must still padzero"); + } + } +} + +#[test] +fn preserves_previous_load_when_bss_only_starts_mid_page() { + let page = fspy_nostd::param::page_size(); + for memory_size in [0x180, page + 0x180] { + let mut bytes = std::vec![0xa5; 3 * page]; + write_header(&mut bytes, 2, 0x200); + load(&mut bytes, 0, 0, page + 0x200, page + 0x200, abi::PF_R | abi::PF_X, page); + load(&mut bytes, 1, page + 0x200, 0, memory_size, abi::PF_R | abi::PF_W, page); + let image = map_bytes(&bytes); + // SAFETY: both LOADs are mapped readable; the first occupies the + // shared page below the BSS-only vaddr. + unsafe { + assert_eq!( + ptr::with_exposed_provenance::(image.bias + page + 0x80).read(), + 0xa5, + "anonymous MAP_FIXED of a filesz==0 LOAD must not wipe the previous segment" + ); + assert_eq!(ptr::with_exposed_provenance::(image.bias + page + 0x1ff).read(), 0xa5); + let zero_start = image.bias + page + 0x200; + let zero_end = align_up(zero_start + memory_size, page); + let zeroed = core::slice::from_raw_parts( + ptr::with_exposed_provenance::(zero_start), + zero_end - zero_start, + ); + assert!(zeroed.iter().all(|byte| *byte == 0)); + } + } +} + +#[test] +fn maps_unordered_non_overlapping_loads() { + let page = fspy_nostd::param::page_size(); + let mut bytes = std::vec![0; 3 * page]; + write_header(&mut bytes, 2, 0x200); + // Higher vaddr first: Linux still loads in header order. + load(&mut bytes, 0, 2 * page, 0x40, 0x40, abi::PF_R | abi::PF_W, page); + load(&mut bytes, 1, 0, page, page, abi::PF_R | abi::PF_X, page); + bytes[2 * page] = 0x11; + bytes[0x200] = 0x22; + let image = map_bytes(&bytes); + assert_eq!(image.entry, image.bias + 0x200); + // SAFETY: both disjoint LOADs are mapped readable. + unsafe { + assert_eq!(ptr::with_exposed_provenance::(image.bias + 2 * page).read(), 0x11); + assert_eq!(ptr::with_exposed_provenance::(image.entry).read(), 0x22); + } +} + +#[test] +#[should_panic(expected = "overlapping ELF segments")] +fn rejects_overlapping_load_segments() { + let page = fspy_nostd::param::page_size(); + let mut bytes = std::vec![0xa5; 2 * page]; + write_header(&mut bytes, 2, 0x80); + load(&mut bytes, 0, 0, 0x200, 0x200, abi::PF_R | abi::PF_X, page); + load(&mut bytes, 1, 0x100, 0x200, 0x200, abi::PF_R | abi::PF_W, page); + map_bytes(&bytes); +} + +#[test] +fn accepts_pt_interp_padded_with_extra_nuls() { + let file = File::new(open_bytes(&interp_image(b"ld.so\0\0\0"))); + let path = file.interpreter().unwrap(); + assert_eq!(path.as_units(), b"ld.so"); +} + +#[test] +#[should_panic(expected = "unterminated PT_INTERP")] +fn rejects_unterminated_pt_interp() { + let _ = File::new(open_bytes(&interp_image(b"ld.so"))).interpreter(); +} + +#[test] +#[should_panic(expected = "empty PT_INTERP path")] +fn rejects_empty_pt_interp() { + let _ = File::new(open_bytes(&interp_image(b"\0\0\0"))).interpreter(); +} + fn fixture(page: usize, memory_size: usize, flags: u32) -> std::vec::Vec { let mut bytes = std::vec![0xa5; 3 * page]; + write_header(&mut bytes, 2, 0x200); + load(&mut bytes, 0, 0, page + 0x100, page + 0x100, abi::PF_R | abi::PF_X, page); + load(&mut bytes, 1, page + 0x200, 0x100, memory_size, flags, page); + bytes +} + +fn interp_image(path: &[u8]) -> std::vec::Vec { + let start = 64 + 56; + let mut bytes = std::vec![0; start + path.len()]; + write_header(&mut bytes, 1, 0); + let header = &mut bytes[64..120]; + header[..4].copy_from_slice(&abi::PT_INTERP.to_le_bytes()); + for (field, value) in [(8, start), (32, path.len()), (40, path.len()), (48, 1)] { + header[field..field + 8].copy_from_slice(&u64::try_from(value).unwrap().to_le_bytes()); + } + bytes[start..start + path.len()].copy_from_slice(path); + bytes +} + +fn write_header(bytes: &mut [u8], phnum: u16, entry: u64) { bytes[..64].fill(0); bytes[..7].copy_from_slice(b"\x7fELF\x02\x01\x01"); bytes[16..18].copy_from_slice(&abi::ET_DYN.to_le_bytes()); bytes[18..20].copy_from_slice(&MACHINE.to_le_bytes()); bytes[20..24].copy_from_slice(&1_u32.to_le_bytes()); - bytes[24..32].copy_from_slice(&0x200_u64.to_le_bytes()); + bytes[24..32].copy_from_slice(&entry.to_le_bytes()); bytes[32..40].copy_from_slice(&64_u64.to_le_bytes()); bytes[52..54].copy_from_slice(&64_u16.to_le_bytes()); bytes[54..56].copy_from_slice(&56_u16.to_le_bytes()); - bytes[56..58].copy_from_slice(&2_u16.to_le_bytes()); - segment(&mut bytes, 0, 0, page + 0x100, page + 0x100, abi::PF_R | abi::PF_X, page); - segment(&mut bytes, 1, page + 0x200, 0x100, memory_size, flags, page); - bytes + bytes[56..58].copy_from_slice(&phnum.to_le_bytes()); } -fn segment( +fn load( bytes: &mut [u8], index: usize, start: usize, @@ -87,14 +197,25 @@ fn segment( flags: u32, page: usize, ) { - let offset = 64 + index * 56; - let header = &mut bytes[offset..offset + 56]; + let header = &mut bytes[64 + index * 56..64 + index * 56 + 56]; header.fill(0); header[..4].copy_from_slice(&abi::PT_LOAD.to_le_bytes()); header[4..8].copy_from_slice(&flags.to_le_bytes()); - for (offset, value) in + for (field, value) in [(8, start), (16, start), (32, file_size), (40, memory_size), (48, 2 * page)] { - header[offset..offset + 8].copy_from_slice(&u64::try_from(value).unwrap().to_le_bytes()); + header[field..field + 8].copy_from_slice(&u64::try_from(value).unwrap().to_le_bytes()); } } + +fn map_bytes(bytes: &[u8]) -> Image { + File::new(open_bytes(bytes)).map(fspy_nostd::param::page_size()) +} + +fn open_bytes(bytes: &[u8]) -> OwnedFd { + let file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(file.path(), bytes).unwrap(); + let path = std::ffi::CString::new(file.path().as_os_str().as_encoded_bytes()).unwrap(); + let path = CStr::from_units_with_nul(path.as_bytes_with_nul()).unwrap(); + fs::openat(fspy_nostd::CWD, path, fs::OFlags::RDONLY, fs::Mode::empty()).unwrap() +} diff --git a/crates/fspy_elf_loader/src/lib.rs b/crates/fspy_elf_loader/src/lib.rs index fa6a373ca..05e18df95 100644 --- a/crates/fspy_elf_loader/src/lib.rs +++ b/crates/fspy_elf_loader/src/lib.rs @@ -133,9 +133,17 @@ pub unsafe fn exec_elf<'a>( #[cfg(target_arch = "aarch64")] #[unsafe(naked)] unsafe extern "C" fn enter(_entry: usize, _stack: *mut usize) -> ! { - // X0 holds entry and X1 holds the new SP. Save entry in scratch register - // X16 before clearing X0; clear X30 because there is no caller to return to. - core::arch::naked_asm!("mov x16, x0", "mov sp, x1", "mov x0, xzr", "mov x30, xzr", "br x16"); + // X0 holds entry and X1 holds the new SP. Linux start_thread zeros GPRs; + // clear the ones this stub dirties. X16 must keep the entry for BR. + core::arch::naked_asm!( + "mov x16, x0", + "mov sp, x1", + "mov x0, xzr", + "mov x1, xzr", + "mov x29, xzr", + "mov x30, xzr", + "br x16", + ); } #[cfg(target_arch = "x86_64")] @@ -143,6 +151,13 @@ unsafe extern "C" fn enter(_entry: usize, _stack: *mut usize) -> ! { unsafe extern "C" fn enter(_entry: usize, _stack: *mut usize) -> ! { // RDI holds entry and RSI holds the new RSP. RDX is the optional // dynamic-linker finalizer (an exit callback); there is none yet. - // Clear RBP to mark the end of the frame-pointer chain. - core::arch::naked_asm!("mov rsp, rsi", "xor edx, edx", "xor ebp, ebp", "jmp rdi"); + // Clear RBP to mark the end of the frame-pointer chain. RSI held SP. + // RDI must keep the entry for JMP. + core::arch::naked_asm!( + "mov rsp, rsi", + "xor esi, esi", + "xor edx, edx", + "xor ebp, ebp", + "jmp rdi" + ); } From 22c450d5e002e5c571bbaca135ee7272180a6477 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 20 Nov 2026 01:41:07 +0000 Subject: [PATCH 14/34] feat(fspy-elf-loader): load static ELF images without PT_INTERP 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 Co-authored-by: Charles Wang --- crates/fspy_elf_loader/README.md | 6 +- crates/fspy_elf_loader/src/image/tests.rs | 7 + crates/fspy_elf_loader/src/lib.rs | 54 ++--- crates/fspy_elf_loader/src/stack.rs | 10 +- crates/fspy_elf_loader_tests/README.md | 2 +- crates/fspy_elf_loader_tests/build.rs | 49 ++++- .../fixtures/static_runtime.c | 186 ++++++++++++++++++ .../fspy_elf_loader_tests/src/bin/fixture.rs | 11 +- .../fspy_elf_loader_tests/tests/exec_elf.rs | 29 ++- 9 files changed, 306 insertions(+), 48 deletions(-) create mode 100644 crates/fspy_elf_loader_tests/fixtures/static_runtime.c diff --git a/crates/fspy_elf_loader/README.md b/crates/fspy_elf_loader/README.md index 16af9b929..b57756ded 100644 --- a/crates/fspy_elf_loader/README.md +++ b/crates/fspy_elf_loader/README.md @@ -10,7 +10,11 @@ This crate handles loading an ELF program and transferring execution to it. The The current implementation is a proof of concept for evaluating compatibility. It does not yet provide a complete replacement for Linux exec. -It loads native ELF64 dynamic executables on AArch64 and x86-64, including PIE (`ET_DYN`) and fixed-address (`ET_EXEC`) images. Fixed-address images are rejected if their address range overlaps any existing mapping. Static executables remain unsupported. +It loads native ELF64 executables on AArch64 and x86-64, including PIE +(`ET_DYN`) and fixed-address (`ET_EXEC`) images, with or without `PT_INTERP`. +Fixed-address images are rejected if their address range overlaps any existing +mapping. Images with `PT_INTERP` enter the dynamic linker; images without it +enter the executable and receive `AT_BASE` 0. The freestanding launcher is a static fixed-address executable with no startup relocation: diff --git a/crates/fspy_elf_loader/src/image/tests.rs b/crates/fspy_elf_loader/src/image/tests.rs index 8460ff5a7..58c48ca0d 100644 --- a/crates/fspy_elf_loader/src/image/tests.rs +++ b/crates/fspy_elf_loader/src/image/tests.rs @@ -135,6 +135,13 @@ fn rejects_overlapping_load_segments() { map_bytes(&bytes); } +#[test] +fn reports_no_interpreter_when_pt_interp_is_absent() { + let page = fspy_nostd::param::page_size(); + let file = File::new(open_bytes(&fixture(page, 0x180, abi::PF_R | abi::PF_W))); + assert!(file.interpreter().is_none()); +} + #[test] fn accepts_pt_interp_padded_with_extra_nuls() { let file = File::new(open_bytes(&interp_image(b"ld.so\0\0\0"))); diff --git a/crates/fspy_elf_loader/src/lib.rs b/crates/fspy_elf_loader/src/lib.rs index 05e18df95..c2c55f259 100644 --- a/crates/fspy_elf_loader/src/lib.rs +++ b/crates/fspy_elf_loader/src/lib.rs @@ -6,6 +6,10 @@ //! fixes addresses through relocations, and enters the executable's startup //! code. That startup code eventually calls the application's `main`. //! +//! For a static executable there is no `PT_INTERP`. The kernel maps only the +//! executable and enters its `e_entry`. `AT_BASE` is 0. Static-PIE images are +//! `ET_DYN` without an interpreter; their CRT applies `RELATIVE` relocations. +//! //! We implement the mapping, stack, and entry steps after the kernel has //! already executed our freestanding loader. We leave its mappings and signal //! handlers in place. Calling another kernel exec here would discard them. @@ -25,8 +29,9 @@ mod stack; /// Loads an ELF executable into the current process and enters it. /// /// Takes ownership of a private executable descriptor and closes it after -/// mapping. Loads the executable and its `PT_INTERP`, builds an initial stack, -/// and transfers control to the interpreter entry point. +/// mapping. Loads the executable and, when present, its `PT_INTERP`. Builds an +/// initial stack and transfers control to the interpreter, or to the +/// executable when there is no interpreter. /// /// `execfn` is the original execution name used for `AT_EXECFN`; it need not /// match `argv[0]`. Arguments and environment entries are copied to the new @@ -42,9 +47,9 @@ mod stack; /// Loading failures terminate the process; they cannot return to the program /// that executed the loader. /// -/// Currently supports native little-endian ELF64 dynamic executables on -/// `AArch64` and x86-64, with an ELF interpreter and a non-executable stack. -/// Both PIE (`ET_DYN`) and fixed-address (`ET_EXEC`) executables are supported. +/// Currently supports native little-endian ELF64 executables on `AArch64` and +/// x86-64, with a non-executable stack. Both PIE (`ET_DYN`) and fixed-address +/// (`ET_EXEC`) images are supported, with or without `PT_INTERP`. /// Fixed-address images must not overlap any existing process mappings. /// The new stack has a fixed 8 MiB capacity and a guard page. Existing loader /// mappings, the old stack, and kernel process metadata (including `/proc` @@ -85,18 +90,21 @@ pub unsafe fn exec_elf<'a>( let executable = image::File::new(elf_file); // PT_INTERP names a second ELF file. Loading it here lets us delegate // dynamic linking and libc startup to the program's own interpreter. - let interpreter = executable.interpreter().expect("executable has no PT_INTERP"); - let interpreter = fspy_nostd::fs::openat( - fspy_nostd::CWD, - interpreter, - fspy_nostd::fs::OFlags::RDONLY | fspy_nostd::fs::OFlags::CLOEXEC, - fspy_nostd::fs::Mode::empty(), - ) - .expect("cannot open ELF interpreter"); - let interpreter = image::File::new(interpreter); - assert!(interpreter.interpreter().is_none(), "nested PT_INTERP is unsupported"); + // Static and static-PIE images omit it; the executable is the startup image. + let interpreter = executable.interpreter().map(|path| { + let fd = fspy_nostd::fs::openat( + fspy_nostd::CWD, + path, + fspy_nostd::fs::OFlags::RDONLY | fspy_nostd::fs::OFlags::CLOEXEC, + fspy_nostd::fs::Mode::empty(), + ) + .expect("cannot open ELF interpreter"); + let file = image::File::new(fd); + assert!(file.interpreter().is_none(), "nested PT_INTERP is unsupported"); + file + }); let executable_image = executable.map(page_size); - let interpreter_image = interpreter.map(page_size); + let interpreter_image = interpreter.as_ref().map(|file| file.map(page_size)); // SAFETY: the caller supplies live auxiliary payloads from this process. let stack = unsafe { stack::build( @@ -105,21 +113,23 @@ pub unsafe fn exec_elf<'a>( envp, inherited_auxv.iter().copied(), &executable_image, - &interpreter_image, + interpreter_image.as_ref(), page_size, ) }; - // The interpreter must run first, even though AT_ENTRY on the new stack - // points at the executable. The interpreter uses that value to hand off - // after dynamic linking; it does not call the application's main itself. - let entry = interpreter_image.entry; + // With PT_INTERP, the interpreter runs first even though AT_ENTRY points + // at the executable. It uses that value to hand off after linking. + // Without PT_INTERP, AT_BASE is 0 and the executable's e_entry starts. + let entry = interpreter_image.as_ref().map_or(executable_image.entry, |image| image.entry); // File mappings keep their backing storage alive after close. Release // only our parsing views and descriptors, then retain the execution maps // so Rust destructors cannot unmap code the target is about to use. drop(interpreter); drop(executable); executable_image.retain(); - interpreter_image.retain(); + if let Some(image) = interpreter_image { + image.retain(); + } // SAFETY: the images and stack are initialized and retained. The caller // permits abandoning the current stack and entering the trusted image. unsafe { enter(entry, stack) } diff --git a/crates/fspy_elf_loader/src/stack.rs b/crates/fspy_elf_loader/src/stack.rs index c27d485e5..39b7adc77 100644 --- a/crates/fspy_elf_loader/src/stack.rs +++ b/crates/fspy_elf_loader/src/stack.rs @@ -154,7 +154,7 @@ pub unsafe fn build<'a>( envp: impl Iterator>, inherited: impl Iterator, image: &Image, - interpreter: &Image, + interpreter: Option<&Image>, page: usize, ) -> *mut usize { let mut stack = Builder::new(page); @@ -199,14 +199,14 @@ pub unsafe fn build<'a>( } stack.aux(key, entry.value); } - // Describe the main executable even though we enter the interpreter first: - // PHDR/PHENT/PHNUM locate and size its header table; ENTRY is its startup - // address. BASE identifies the interpreter's load bias for its own linking. + // PHDR/PHENT/PHNUM locate and size the executable's header table; ENTRY + // is its startup address. With PT_INTERP we enter the interpreter first + // and BASE is that image's load bias. Without one, BASE is 0 as on Linux. stack.aux(abi::AT_PHDR, image.phdr.expect("program headers are not mapped by PT_LOAD")); stack.aux(abi::AT_PHENT, 56); stack.aux(abi::AT_PHNUM, image.phnum); stack.aux(abi::AT_ENTRY, image.entry); - stack.aux(abi::AT_BASE, interpreter.bias); + stack.aux(abi::AT_BASE, interpreter.map_or(0, |image| image.bias)); stack.aux(abi::AT_FLAGS, 0); let execfn = stack.string(execfn); // Execution name and argv[0] are independent: callers can choose a custom diff --git a/crates/fspy_elf_loader_tests/README.md b/crates/fspy_elf_loader_tests/README.md index 10f208f77..33db4fc0f 100644 --- a/crates/fspy_elf_loader_tests/README.md +++ b/crates/fspy_elf_loader_tests/README.md @@ -4,7 +4,7 @@ Integration tests for [`fspy_elf_loader`](../fspy_elf_loader/README.md). The tests check whether programs start and behave as expected through the custom loader. They help catch compatibility regressions as its scope grows. -The default suite covers dynamic PIE and fixed-address executables, including rejection of a target overlapping the launcher. With Node.js on `PATH`, run `cargo test -p fspy_elf_loader_tests -- --include-ignored` on Linux to also compare a real Node program with normal execution. +The default suite covers dynamic and static PIE and fixed-address executables, including rejection of a target overlapping the launcher. Static fixtures are compiled with `cc -static` and `cc -static-pie`. With Node.js on `PATH`, run `cargo test -p fspy_elf_loader_tests -- --include-ignored` on Linux to also compare a real Node program with normal execution. The launcher artifact is checked on every host for a static fixed-address layout at 85 TiB on x86-64 or 8 GiB on AArch64, with no dynamic relocation diff --git a/crates/fspy_elf_loader_tests/build.rs b/crates/fspy_elf_loader_tests/build.rs index 3cd8b7487..7fdfa6ec7 100644 --- a/crates/fspy_elf_loader_tests/build.rs +++ b/crates/fspy_elf_loader_tests/build.rs @@ -1,7 +1,48 @@ +use std::{ + env, + ffi::OsString, + process::{Command, Stdio}, +}; + fn main() { - if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("linux") { - // Keep the same runtime checks in PIE and fixed-address executables. - // The linker driver must retain dynamic linking while disabling PIE. - println!("cargo::rustc-link-arg-bin=fixture_exec=-no-pie"); + if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("linux") { + return; } + // Keep the same runtime checks in PIE and fixed-address executables. + // The linker driver must retain dynamic linking while disabling PIE. + println!("cargo::rustc-link-arg-bin=fixture_exec=-no-pie"); + println!("cargo::rerun-if-changed=fixtures/static_runtime.c"); + + let out = env::var_os("OUT_DIR").unwrap(); + let mut source = env::var_os("CARGO_MANIFEST_DIR").unwrap(); + source.push("/fixtures/static_runtime.c"); + let static_bin = join_out(&out, "/fixture_static"); + let static_pie = join_out(&out, "/fixture_static_pie"); + compile(&source, &static_bin, &["-static"]); + compile(&source, &static_pie, &["-static-pie"]); + println!("cargo::rustc-env=FIXTURE_STATIC={}", static_bin.to_str().unwrap()); + println!("cargo::rustc-env=FIXTURE_STATIC_PIE={}", static_pie.to_str().unwrap()); +} + +fn join_out(out: &OsString, name: &str) -> OsString { + let mut path = out.clone(); + path.push(name); + path +} + +fn compile(source: &OsString, dest: &OsString, extra: &[&str]) { + let output = Command::new("cc") + .args(["-O1", "-pthread"]) + .args(extra) + .arg("-o") + .arg(dest) + .arg(source) + .stderr(Stdio::piped()) + .output() + .expect("cannot invoke cc"); + assert!( + output.status.success(), + "cannot compile static runtime fixture: {}", + str::from_utf8(&output.stderr).unwrap_or("non-utf8 cc diagnostics") + ); } diff --git a/crates/fspy_elf_loader_tests/fixtures/static_runtime.c b/crates/fspy_elf_loader_tests/fixtures/static_runtime.c new file mode 100644 index 000000000..95c6a6ae9 --- /dev/null +++ b/crates/fspy_elf_loader_tests/fixtures/static_runtime.c @@ -0,0 +1,186 @@ +/* Runtime checks for static and static-PIE images loaded by exec_elf. + * + * Protocol matches src/bin/fixture.rs: argv[0]="custom-argv-zero", argv[1]="", + * argv[2]=0xff, EMPTY="", BYTES=0xff, FIXTURE_IMAGE=AT_EXECFN, stdout + * "runtime-ok\n", exit 37. AT_BASE must be 0 (no interpreter). + */ + +#define _GNU_SOURCE + +#include +#include +#include +#include +#include +#include + +static char bss[128 * 1024]; +static int data = 42; +static __thread int tls = 17; + +static void fail(const char *message) { + write(STDERR_FILENO, message, strlen(message)); + write(STDERR_FILENO, "\n", 1); + _exit(2); +} + +static void *thread_main(void *argument) { + if (tls != 17) { + fail("thread tls"); + } + *(int *)argument = 1; + return NULL; +} + +static unsigned long load_bias(unsigned long at_phdr, unsigned long phnum, const Elf64_Phdr *ph) { + unsigned long i; + for (i = 0; i < phnum; i++) { + if (ph[i].p_type == PT_PHDR) { + return at_phdr - (unsigned long)ph[i].p_vaddr; + } + } + /* GNU ld omits PT_PHDR on some static images. ELF64 headers start at 0. */ + unsigned char *ehdr = (unsigned char *)(at_phdr - 64); + if (ehdr[0] != 0x7f || ehdr[1] != 'E' || ehdr[2] != 'L' || ehdr[3] != 'F') { + fail("elf header"); + } + unsigned long e_phoff; + memcpy(&e_phoff, ehdr + 32, sizeof e_phoff); + if (e_phoff != 64) { + fail("e_phoff"); + } + for (i = 0; i < phnum; i++) { + if (ph[i].p_type == PT_LOAD && ph[i].p_offset == 0) { + return at_phdr - e_phoff - (unsigned long)ph[i].p_vaddr; + } + } + fail("no load at file start"); + return 0; +} + +int main(int argc, char **argv) { + unsigned long i; + pthread_t thread; + int started = 0; + char *heap; + unsigned long at_phdr; + unsigned long phnum; + unsigned long phent; + unsigned long entry; + unsigned long bias; + const Elf64_Phdr *ph; + const char *image; + + if (argc != 3) { + fail("argc"); + } + if (strcmp(argv[0], "custom-argv-zero") != 0) { + fail("argv0"); + } + if (argv[1][0] != '\0') { + fail("argv1"); + } + if ((unsigned char)argv[2][0] != 0xff || argv[2][1] != '\0') { + fail("argv2"); + } + if (getenv("EMPTY") == NULL || getenv("EMPTY")[0] != '\0') { + fail("EMPTY"); + } + { + const char *bytes = getenv("BYTES"); + if (bytes == NULL || (unsigned char)bytes[0] != 0xff || bytes[1] != '\0') { + fail("BYTES"); + } + } + for (i = 0; i < sizeof bss; i++) { + if (bss[i] != 0) { + fail("bss"); + } + } + bss[sizeof bss - 1] = 9; + if (data != 42) { + fail("data"); + } + data = 43; + if (tls != 17) { + fail("tls"); + } + tls = 23; + if (pthread_create(&thread, NULL, thread_main, &started) != 0) { + fail("pthread_create"); + } + if (pthread_join(thread, NULL) != 0 || started != 1) { + fail("pthread_join"); + } + if (tls != 23) { + fail("tls after join"); + } + + heap = malloc(128 * 1024); + if (heap == NULL) { + fail("malloc"); + } + memset(heap, 7, 128 * 1024); + for (i = 0; i < 128 * 1024; i++) { + if ((unsigned char)heap[i] != 7) { + fail("heap"); + } + } + free(heap); + + if (getauxval(AT_BASE) != 0) { + fail("AT_BASE"); + } + at_phdr = getauxval(AT_PHDR); + phnum = getauxval(AT_PHNUM); + phent = getauxval(AT_PHENT); + entry = getauxval(AT_ENTRY); + if (phent != sizeof(Elf64_Phdr) || at_phdr == 0 || phnum == 0 || entry == 0) { + fail("auxv"); + } + ph = (const Elf64_Phdr *)at_phdr; + bias = load_bias(at_phdr, phnum, ph); + if (getenv("EXPECT_FIXED_ADDRESS") != NULL && bias != 0) { + fail("relocated fixed image"); + } + { + int found_entry = 0; + for (i = 0; i < phnum; i++) { + unsigned long start; + unsigned long end; + if (ph[i].p_type != PT_LOAD || (ph[i].p_flags & PF_X) == 0) { + continue; + } + start = bias + (unsigned long)ph[i].p_vaddr; + end = start + (unsigned long)ph[i].p_memsz; + if (entry >= start && entry < end) { + found_entry = 1; + } + } + if (!found_entry) { + fail("AT_ENTRY"); + } + } + image = getenv("FIXTURE_IMAGE"); + if (image == NULL || strcmp((const char *)getauxval(AT_EXECFN), image) != 0) { + fail("AT_EXECFN"); + } + { + const unsigned char *random = (const unsigned char *)getauxval(AT_RANDOM); + int nonzero = 0; + if (random == NULL) { + fail("AT_RANDOM"); + } + for (i = 0; i < 16; i++) { + if (random[i] != 0) { + nonzero = 1; + } + } + if (!nonzero) { + fail("AT_RANDOM zero"); + } + } + + write(STDOUT_FILENO, "runtime-ok\n", 11); + _exit(37); +} diff --git a/crates/fspy_elf_loader_tests/src/bin/fixture.rs b/crates/fspy_elf_loader_tests/src/bin/fixture.rs index eb8a594e3..6b99288e2 100644 --- a/crates/fspy_elf_loader_tests/src/bin/fixture.rs +++ b/crates/fspy_elf_loader_tests/src/bin/fixture.rs @@ -59,11 +59,12 @@ fn main() { ..bias + usize::try_from(ph.p_vaddr + ph.p_memsz).unwrap()) .contains(&entry) })); - let interpreter = std::slice::from_raw_parts( - std::ptr::with_exposed_provenance::(aux(libc::AT_BASE)), - 4, - ); - assert_eq!(interpreter, b"\x7fELF"); + let base = aux(libc::AT_BASE); + if base != 0 { + let interpreter = + std::slice::from_raw_parts(std::ptr::with_exposed_provenance::(base), 4); + assert_eq!(interpreter, b"\x7fELF"); + } let random = std::slice::from_raw_parts( std::ptr::with_exposed_provenance::(aux(libc::AT_RANDOM)), 16, diff --git a/crates/fspy_elf_loader_tests/tests/exec_elf.rs b/crates/fspy_elf_loader_tests/tests/exec_elf.rs index 1f77b4625..bcb31f8f9 100644 --- a/crates/fspy_elf_loader_tests/tests/exec_elf.rs +++ b/crates/fspy_elf_loader_tests/tests/exec_elf.rs @@ -13,11 +13,13 @@ use ntest::timeout; const LAUNCHER: &str = env!("CARGO_BIN_FILE_FSPY_ELF_LOADER_fspy_elf_loader_test_launcher"); const FIXTURE: &str = env!("CARGO_BIN_EXE_fixture"); const FIXTURE_EXEC: &str = env!("CARGO_BIN_EXE_fixture_exec"); +const FIXTURE_STATIC: &str = env!("FIXTURE_STATIC"); +const FIXTURE_STATIC_PIE: &str = env!("FIXTURE_STATIC_PIE"); #[test] #[timeout(10_000)] fn echo_matches_kernel_exec() { - assert_dynamic_image("/bin/echo", elf::abi::ET_DYN); + assert_image("/bin/echo", elf::abi::ET_DYN, true); let mut direct = Command::new("/bin/echo"); direct.args(["hello", "world"]); let mut loaded = launcher(); @@ -57,7 +59,11 @@ fn initializes_fixed_runtime() { } fn check_runtime(fixture: &str, image_type: u16) { - assert_dynamic_image(fixture, image_type); + check_runtime_image(fixture, image_type, true); +} + +fn check_runtime_image(fixture: &str, image_type: u16, interpreter: bool) { + assert_image(fixture, image_type, interpreter); let mut command = launcher(); command.args([fixture, "custom-argv-zero", ""]); command.arg(OsStr::from_bytes(b"\xff")); @@ -74,12 +80,14 @@ fn check_runtime(fixture: &str, image_type: u16) { #[test] #[timeout(10_000)] -fn rejects_unsupported_static_image() { - let mut command = launcher(); - command.args([LAUNCHER, "target-argv-zero"]); - let output = output(command); - assert_eq!(output.status.code(), Some(101), "{output:?}"); - assert!(str::from_utf8(&output.stderr).unwrap().contains("executable has no PT_INTERP")); +fn initializes_static_runtime() { + check_runtime_image(FIXTURE_STATIC, elf::abi::ET_EXEC, false); +} + +#[test] +#[timeout(10_000)] +fn initializes_static_pie_runtime() { + check_runtime_image(FIXTURE_STATIC_PIE, elf::abi::ET_DYN, false); } #[test] @@ -222,11 +230,12 @@ fn launcher() -> Command { command } -fn assert_dynamic_image(path: &str, image_type: u16) { +fn assert_image(path: &str, image_type: u16, interpreter: bool) { let bytes = std::fs::read(path).unwrap(); let elf = elf::ElfBytes::::minimal_parse(&bytes).unwrap(); assert_eq!(elf.ehdr.e_type, image_type, "unexpected fixture image type: {path}"); - assert!(elf.segments().unwrap().iter().any(|ph| ph.p_type == elf::abi::PT_INTERP)); + let has_interp = elf.segments().unwrap().iter().any(|ph| ph.p_type == elf::abi::PT_INTERP); + assert_eq!(has_interp, interpreter, "unexpected PT_INTERP: {path}"); } fn output(mut command: Command) -> Output { From fb8cc71284562d9bd6ad609a4be837c832c05c5f Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 20 Nov 2026 01:54:02 +0000 Subject: [PATCH 15/34] fix(fspy-nostd): keep allocator guard off Windows std links 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 Co-authored-by: Charles Wang --- crates/fspy_elf_loader/Cargo.toml | 3 +++ crates/fspy_nostd/Cargo.toml | 7 +++++++ crates/fspy_nostd/src/entry.rs | 5 +---- crates/fspy_nostd/src/lib.rs | 1 + 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/crates/fspy_elf_loader/Cargo.toml b/crates/fspy_elf_loader/Cargo.toml index 4d2395d4e..62551f55c 100644 --- a/crates/fspy_elf_loader/Cargo.toml +++ b/crates/fspy_elf_loader/Cargo.toml @@ -25,5 +25,8 @@ path = "tests/support/launcher.rs" test = false bench = false +[lib] +doctest = false + [lints] workspace = true diff --git a/crates/fspy_nostd/Cargo.toml b/crates/fspy_nostd/Cargo.toml index d11fe81a1..0c6af81ff 100644 --- a/crates/fspy_nostd/Cargo.toml +++ b/crates/fspy_nostd/Cargo.toml @@ -30,8 +30,15 @@ windows-sys = { workspace = true, features = [ "Win32_System_Threading", ] } +[lib] +doctest = false + [lints] workspace = true [dev-dependencies] tempfile = { workspace = true } + +[package.metadata.cargo-shear] +# Compiled by rustc from tests/no_global_alloc.rs, not as a crate module. +ignored-paths = ["tests/support/no_global_alloc.rs"] diff --git a/crates/fspy_nostd/src/entry.rs b/crates/fspy_nostd/src/entry.rs index 2879e3ebd..e741e7acd 100644 --- a/crates/fspy_nostd/src/entry.rs +++ b/crates/fspy_nostd/src/entry.rs @@ -6,13 +6,10 @@ /// accept any stack lifetime; it cannot require `InitialStack<'static>`. /// /// ```compile_fail,E0308 -/// #![no_std] -/// #![no_main] -/// /// fn run(_: fspy_nostd::env::InitialStack<'static>) -> ! { /// loop {} /// } -/// fspy_nostd::main!(run); +/// const _: for<'a> fn(fspy_nostd::env::InitialStack<'a>) -> ! = run; /// ``` /// /// Supports `AArch64` and x86-64. The executable must use `#![no_main]` and diff --git a/crates/fspy_nostd/src/lib.rs b/crates/fspy_nostd/src/lib.rs index e10fda1ca..fbd6b36f8 100644 --- a/crates/fspy_nostd/src/lib.rs +++ b/crates/fspy_nostd/src/lib.rs @@ -13,6 +13,7 @@ mod entry; mod error; #[cfg(any(target_os = "linux", target_os = "none", target_os = "macos"))] mod fd; +#[cfg(any(target_os = "linux", target_os = "none"))] #[doc(hidden)] pub mod no_global_alloc; #[cfg(any(target_os = "linux", target_os = "none"))] From b771e1b17b677a7549bd82ca8f82fb2497fbfa3f Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Tue, 24 Nov 2026 01:24:27 +0000 Subject: [PATCH 16/34] docs(fspy-elf-loader): record userland-exec scope and remaining work Co-authored-by: Cursor Grok 4.6 Co-authored-by: Charles Wang --- crates/fspy_elf_loader/README.md | 100 ++++++++++++++++++++++--------- 1 file changed, 73 insertions(+), 27 deletions(-) diff --git a/crates/fspy_elf_loader/README.md b/crates/fspy_elf_loader/README.md index b57756ded..af63ac7dd 100644 --- a/crates/fspy_elf_loader/README.md +++ b/crates/fspy_elf_loader/README.md @@ -1,38 +1,84 @@ # fspy_elf_loader -An experimental Linux program loader for fspy's custom-loader approach. +Linux userland exec for fspy, the file tracker behind `vp run`: map a target +ELF into the current process and jump to it, so intercept state installed +before entry (SIGSYS, handlers, mappings) survives. -fspy needs to set up interception before a target program starts and keep that setup intact as the program takes over. This crate explores loading the program within the existing process, preserving the signal handlers that a normal exec would reset. +The **Linux end state** is this path alone. Kernel `execve` of the target +would reset intercept state, so fspy must not exec the target. Resolve PATH +and shebang in userland, kernel-exec a freestanding launcher, then +[`exec_elf`](src/lib.rs). That replaces today's `LD_PRELOAD` vs +`seccomp_unotify` split (chosen from `PT_INTERP`). SIGSYS stays as the +intercept; it is not a second spawn backend. -## Scope +This is a **compatibility contract**, not a complete `execve`. This crate +only maps and enters an ELF. PATH, shebang, policy, nested exec, and fspy +wiring belong above it. fspy already parses shebang in `fspy_shared_unix`; +the kernel will not, once it never sees the target. -This crate handles loading an ELF program and transferring execution to it. The caller owns execution-policy checks and interception setup. Integration with fspy remains separate work. +## Support -The current implementation is a proof of concept for evaluating compatibility. It does not yet provide a complete replacement for Linux exec. +Native little-endian ELF64 on x86-64 and AArch64. `PT_GNU_STACK` must be +non-executable. `ET_EXEC` that overlaps any retained mapping is rejected. -It loads native ELF64 executables on AArch64 and x86-64, including PIE -(`ET_DYN`) and fixed-address (`ET_EXEC`) images, with or without `PT_INTERP`. -Fixed-address images are rejected if their address range overlaps any existing -mapping. Images with `PT_INTERP` enter the dynamic linker; images without it -enter the executable and receive `AT_BASE` 0. +| | `PT_INTERP` | no `PT_INTERP` | +| --- | --- | --- | +| `ET_DYN` | dynamic PIE: enter ld.so, `AT_BASE` = interp bias | static-PIE / ld.so: enter `e_entry`, `AT_BASE` = 0 | +| `ET_EXEC` | dynamic non-PIE: same as dynamic PIE | traditional static: enter `e_entry`, `AT_BASE` = 0 | -The freestanding launcher is a static fixed-address executable with no startup relocation: +All four cells load. With an interpreter, map both images and enter the +interpreter even though `AT_ENTRY` names the executable. Without one, map only +the executable. -| Architecture | Base address | Base in binary units | -| ------------ | ------------------ | -------------------- | -| x86-64 | `0x5500_0000_0000` | 85 TiB | -| AArch64 | `0x0002_0000_0000` | 8 GiB | +The launcher is itself a static `ET_EXEC` at a high fixed address so the low +4 GiB stays free for non-PIE targets: -These bases leave the low 4 GiB available and sit in application regions of -the current LLVM Linux [AddressSanitizer](https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/asan/asan_mapping.h) -and [C/C++ ThreadSanitizer](https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/tsan/rtl/tsan_platform.h) -layouts. AArch64 uses a lower base to fit smaller virtual address spaces, -including 39-bit configurations, and remains below their 20 GiB TSan low -application-region limit. These placement choices do not establish complete -sanitizer compatibility: GCC 12's AArch64 TSan runtime rejects the 8 GiB -launcher mapping. Its [older layout](https://github.com/gcc-mirror/gcc/blob/releases/gcc-12.2.0/libsanitizer/tsan/tsan_platform.h) -limits low application memory to below 4 GiB on 39-bit systems and below -8 GiB on 48-bit systems. The addresses are conventions, not reserved ranges: -fixed-address targets that overlap retained mappings are still rejected. +| Arch | Base | +| --- | --- | +| x86-64 | `0x5500_0000_0000` (85 TiB) | +| AArch64 | `0x0002_0000_0000` (8 GiB) | -[`fspy_elf_loader_tests`](../fspy_elf_loader_tests/README.md) covers program execution through the loader. +These sit in current LLVM Linux ASan/TSan application regions; GCC 12's AArch64 +TSan still rejects the 8 GiB mapping. The addresses are conventions, not +reserved ranges. + +## Done + +- `PT_LOAD` mapping in the Linux `elf_map` shape (shared pages, BSS, padzero). +- Optional `PT_INTERP`, including padded interpreter paths. +- Startup stack: contiguous argv/envp strings, rebuilt auxv, copied + `AT_RANDOM` / platform strings, inherited scalars and resident vDSO. +- Naked enter stubs: install SP, clear dirty GPRs, jump (no return address). +- [`fspy_elf_loader_tests`](../fspy_elf_loader_tests/README.md): dynamic and + static PIE/`ET_EXEC` runtimes, overlap rejection, malformed images. An + ignored Node test exists (`--include-ignored` on Linux with Node on `PATH`). + +## Not a complete exec + +Do not try to close these in this crate unless a real target requires it: + +- **`brk` / `start_brk`.** The kernel's brk belongs to the high launcher + mapping. It cannot be moved to a Linux-faithful image end. glibc malloc + still works via mmap; leave brk alone. +- **`/proc` identity.** `/proc/self/exe` and parent-visible `/proc//exe` + still name the launcher. Parent `/proc//exe` is not a JS/Chromium + identity gate. `/proc/self/exe` is, and needs virtualization later. +- GNU properties, executable stacks, ELF32, other arches, growable stack + (fixed 8 MiB + guard), fd/signal/personality cleanup. + +Load failures panic and terminate. `exec_elf` is for a fresh single-threaded +process with no libc or TLS init. Trusted images only; this is not a sandbox. + +## Product work (elsewhere) + +fspy still spawns with `LD_PRELOAD` or `seccomp_unotify`. The loader is not +wired in. Remaining work is to make launcher + userland shebang + `exec_elf` +the only Linux spawn: + +1. Shebang and PATH above `exec_elf`, then load the resulting ELF. Scripts + never hit kernel `binfmt_script`. Nested `execve` must re-enter this path + instead of kernel-execing the child image. +2. Virtualize `/proc/self/exe` so the target sees its own path (`process.execPath` + / `fs.realpath`). The ignored Node test does not do this. +3. Drop the Linux preload/seccomp spawn split. One intercept setup in the + launcher covers dynamic glibc, musl, and static images. From 0462a940ef5b40e567904c3ac8ebb3c0a7e7b15f Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 12:31:14 +0800 Subject: [PATCH 17/34] fix(fspy-elf-loader): scope padzero to writable or BSS segments and clamp 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 --- crates/fspy_elf_loader/src/image.rs | 80 ++++++++++++++--------- crates/fspy_elf_loader/src/image/tests.rs | 60 ++++++++++++++--- 2 files changed, 99 insertions(+), 41 deletions(-) diff --git a/crates/fspy_elf_loader/src/image.rs b/crates/fspy_elf_loader/src/image.rs index e9e8f9d90..869433bd7 100644 --- a/crates/fspy_elf_loader/src/image.rs +++ b/crates/fspy_elf_loader/src/image.rs @@ -270,40 +270,56 @@ impl File { ) } .expect("cannot map ELF segment"); - // Zero through the page boundary, not just p_memsz: leftover file - // bytes after filesz==memsz, and the BSS tail of filesz filesz) or is writable (glibc's early allocator + // reads spare bytes after the interpreter's _end even when + // filesz == memsz). Skip filesz == memsz on read-only/executable + // segments so we do not COW-dirty code/rodata pages or trigger + // RW -> RX mprotect transitions under W^X policies. + // + // Clamp the zeroed range to the start of any higher-vaddr LOAD + // sharing this page so unordered segments cannot wipe each other. + let pad_zero = segment.p_memsz > segment.p_filesz || segment.p_flags & abi::PF_W != 0; + if pad_zero && !file_end.is_multiple_of(page) { let tail_page = file_end & !sub(page, 1); - // Writable, non-executable pages can be zeroed directly. - // Otherwise temporarily make the last file page writable, - // without X, and restore its original protection afterwards. - let change_protection = - !protection.contains(ProtFlags::WRITE) || protection.contains(ProtFlags::EXEC); - // SAFETY: this private page was mapped above; it has no live references. - unsafe { - if change_protection { - mm::mprotect( - ptr::with_exposed_provenance_mut(tail_page), - page, - MprotectFlags::READ | MprotectFlags::WRITE, - ) - .expect("cannot zero ELF BSS"); + let mut zero_end = align_up(file_end, page); + for other in self.segments().iter() { + if other.p_type == abi::PT_LOAD && other.p_memsz != 0 { + let other_start = add(bias, word(other.p_vaddr)); + if other_start >= end && other_start < zero_end { + zero_end = other_start; + } } - ptr::write_bytes( - ptr::with_exposed_provenance_mut::(file_end), - 0, - sub(align_up(file_end, page), file_end), - ); - if change_protection { - mm::mprotect( - ptr::with_exposed_provenance_mut(tail_page), - page, - MprotectFlags::from_bits_retain(protection.bits()), - ) - .expect("cannot restore ELF protection"); + } + if zero_end > file_end { + // Writable, non-executable pages can be zeroed directly. + // Otherwise temporarily make the last file page writable, + // without X, and restore its original protection afterwards. + let change_protection = !protection.contains(ProtFlags::WRITE) + || protection.contains(ProtFlags::EXEC); + // SAFETY: this private page was mapped above; it has no live references. + unsafe { + if change_protection { + mm::mprotect( + ptr::with_exposed_provenance_mut(tail_page), + page, + MprotectFlags::READ | MprotectFlags::WRITE, + ) + .expect("cannot zero ELF BSS"); + } + ptr::write_bytes( + ptr::with_exposed_provenance_mut::(file_end), + 0, + sub(zero_end, file_end), + ); + if change_protection { + mm::mprotect( + ptr::with_exposed_provenance_mut(tail_page), + page, + MprotectFlags::from_bits_retain(protection.bits()), + ) + .expect("cannot restore ELF protection"); + } } } } diff --git a/crates/fspy_elf_loader/src/image/tests.rs b/crates/fspy_elf_loader/src/image/tests.rs index 58c48ca0d..cb94ca64b 100644 --- a/crates/fspy_elf_loader/src/image/tests.rs +++ b/crates/fspy_elf_loader/src/image/tests.rs @@ -55,27 +55,69 @@ fn check_bss(page: usize, flags: u32, expected_protection: &str) { } #[test] -fn zeroes_spare_file_bytes_when_filesz_equals_memsz() { +fn zeroes_spare_file_bytes_on_writable_segment_when_filesz_equals_memsz() { let page = fspy_nostd::param::page_size(); - for flags in [abi::PF_R | abi::PF_W, abi::PF_R, abi::PF_R | abi::PF_X] { + let mut bytes = std::vec![0xa5; 2 * page]; + write_header(&mut bytes, 2, 0x200); + load(&mut bytes, 0, 0, page, page, abi::PF_R | abi::PF_X, page); + load(&mut bytes, 1, page + 0x100, 0x200, 0x200, abi::PF_R | abi::PF_W, page); + let image = map_bytes(&bytes); + // SAFETY: the second LOAD and its padzero tail are mapped readable. + unsafe { + assert_eq!(ptr::with_exposed_provenance::(image.bias + page + 0x100).read(), 0xa5); + assert_eq!(ptr::with_exposed_provenance::(image.bias + page + 0x2ff).read(), 0xa5); + let tail = core::slice::from_raw_parts( + ptr::with_exposed_provenance::(image.bias + page + 0x300), + page - 0x300, + ); + assert!(tail.iter().all(|byte| *byte == 0), "writable filesz==memsz must still padzero"); + } +} + +#[test] +fn does_not_dirty_readonly_or_exec_tail_when_filesz_equals_memsz() { + let page = fspy_nostd::param::page_size(); + for flags in [abi::PF_R, abi::PF_R | abi::PF_X] { let mut bytes = std::vec![0xa5; 2 * page]; write_header(&mut bytes, 2, 0x200); load(&mut bytes, 0, 0, page, page, abi::PF_R | abi::PF_X, page); load(&mut bytes, 1, page + 0x100, 0x200, 0x200, flags, page); let image = map_bytes(&bytes); - // SAFETY: the second LOAD and its padzero tail are mapped readable. + // SAFETY: the second LOAD's page is mapped readable directly from the file. unsafe { - assert_eq!(ptr::with_exposed_provenance::(image.bias + page + 0x100).read(), 0xa5); - assert_eq!(ptr::with_exposed_provenance::(image.bias + page + 0x2ff).read(), 0xa5); - let tail = core::slice::from_raw_parts( - ptr::with_exposed_provenance::(image.bias + page + 0x300), - page - 0x300, + assert_eq!( + ptr::with_exposed_provenance::(image.bias + page + 0x300).read(), + 0xa5, + "non-writable filesz==memsz must not COW-zero its tail page" ); - assert!(tail.iter().all(|byte| *byte == 0), "filesz==memsz must still padzero"); } } } +#[test] +fn unordered_shared_page_does_not_wipe_higher_segment() { + let page = fspy_nostd::param::page_size(); + let mut bytes = std::vec![0xa5; 3 * page]; + write_header(&mut bytes, 3, 0x200); + load(&mut bytes, 0, 0, page, page, abi::PF_R | abi::PF_X, page); + // Higher vaddr first, lower vaddr second on the same page. + load(&mut bytes, 1, page + 0x300, 0x100, 0x100, abi::PF_R | abi::PF_W, page); + load(&mut bytes, 2, page + 0x100, 0x100, 0x100, abi::PF_R | abi::PF_W, page); + bytes[page + 0x300] = 0x11; + bytes[page + 0x100] = 0x22; + let image = map_bytes(&bytes); + // SAFETY: both segments on the shared page are mapped readable. + unsafe { + assert_eq!(ptr::with_exposed_provenance::(image.bias + page + 0x100).read(), 0x22); + assert_eq!(ptr::with_exposed_provenance::(image.bias + page + 0x200).read(), 0); + assert_eq!( + ptr::with_exposed_provenance::(image.bias + page + 0x300).read(), + 0x11, + "padzero on a lower segment must not wipe a higher segment on the same page" + ); + } +} + #[test] fn preserves_previous_load_when_bss_only_starts_mid_page() { let page = fspy_nostd::param::page_size(); From 06f49fbb3f98a6f23ec590da9b9d7671fe3b5cb0 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 12:31:49 +0800 Subject: [PATCH 18/34] perf(fspy-nostd): allow seeding cached page size from AT_PAGESZ 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 --- crates/fspy_elf_loader/src/lib.rs | 3 +++ crates/fspy_nostd/src/param.rs | 24 +++++++++++++++++++++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/crates/fspy_elf_loader/src/lib.rs b/crates/fspy_elf_loader/src/lib.rs index c2c55f259..1c9fc298b 100644 --- a/crates/fspy_elf_loader/src/lib.rs +++ b/crates/fspy_elf_loader/src/lib.rs @@ -87,6 +87,9 @@ pub unsafe fn exec_elf<'a>( .expect("missing AT_PAGESZ") .value; assert!(page_size.is_power_of_two(), "invalid AT_PAGESZ"); + // Seed fspy_nostd's page-size cache from AT_PAGESZ so temporary stack + // allocations via PageBump do not trigger a redundant 2 MiB probe mapping. + fspy_nostd::param::seed_page_size(page_size); let executable = image::File::new(elf_file); // PT_INTERP names a second ELF file. Loading it here lets us delegate // dynamic linking and libc startup to the program's own interpreter. diff --git a/crates/fspy_nostd/src/param.rs b/crates/fspy_nostd/src/param.rs index 8272e0a50..c8c2fc45c 100644 --- a/crates/fspy_nostd/src/param.rs +++ b/crates/fspy_nostd/src/param.rs @@ -13,7 +13,7 @@ //! anyway, it calls `sysconf` directly. #[cfg(any(target_os = "linux", target_os = "none"))] -pub use linux::page_size; +pub use linux::{page_size, seed_page_size}; #[cfg(target_os = "macos")] pub use mac::page_size; @@ -33,6 +33,20 @@ mod linux { /// larger pages. const MAX_PROBE_PAGE: usize = 1 << 20; + static CACHE: AtomicUsize = AtomicUsize::new(0); + + /// Seeds the cached page size when the caller already knows it (for + /// example, from `AT_PAGESZ` in the Linux auxiliary vector). + /// + /// Ignores zero or non-power-of-two values, and never overwrites an + /// already-cached page size. Once seeded, [`page_size`] returns the cached + /// value without running the `mmap`/`mprotect` probe. + pub fn seed_page_size(page: usize) { + if page.is_power_of_two() { + let _ = CACHE.compare_exchange(0, page, Ordering::Relaxed, Ordering::Relaxed); + } + } + /// Returns the size of a memory page, or 0 if it cannot be determined. /// /// Discovered from the kernel with a handful of raw syscalls, once per @@ -46,7 +60,6 @@ mod linux { /// this operation" (an allocator refuses the allocation). #[must_use] pub fn page_size() -> usize { - static CACHE: AtomicUsize = AtomicUsize::new(0); let cached = CACHE.load(Ordering::Relaxed); if cached != 0 { return cached; @@ -126,7 +139,12 @@ mod linux { #[test] fn probe_is_stable_and_cached() { - assert_eq!(probe_page_size(), page_size()); + let probed = probe_page_size(); + seed_page_size(0); + seed_page_size(3); + seed_page_size(probed); + seed_page_size(probed * 2); + assert_eq!(probed, page_size()); assert_eq!(page_size(), page_size()); #[cfg(target_arch = "x86_64")] assert_eq!(page_size(), 4096); From 45d7fef0ae15eee3f6851f061b79a387ce09aec0 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 12:33:55 +0800 Subject: [PATCH 19/34] fix(fspy-elf-loader): harden interpreter, alignment, auxv, stack headroom, 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 --- crates/fspy_elf_loader/src/image.rs | 18 ++++-- crates/fspy_elf_loader/src/image/tests.rs | 22 +++++++ crates/fspy_elf_loader/src/lib.rs | 47 ++++++++++++-- crates/fspy_elf_loader/src/stack.rs | 77 +++++++++++++++++++++-- 4 files changed, 148 insertions(+), 16 deletions(-) diff --git a/crates/fspy_elf_loader/src/image.rs b/crates/fspy_elf_loader/src/image.rs index 869433bd7..870f2ad7f 100644 --- a/crates/fspy_elf_loader/src/image.rs +++ b/crates/fspy_elf_loader/src/image.rs @@ -54,6 +54,11 @@ impl Image { pub fn retain(self) { self.mapping.retain(); } + + #[cfg(test)] + pub fn test_stub(page: usize) -> Self { + Self { mapping: Mapping::reserve(page), bias: 0, entry: 0x1000, phdr: Some(0x40), phnum: 1 } + } } impl File { @@ -101,6 +106,10 @@ impl File { ) } + pub const fn is_dynamic(&self) -> bool { + self.header.e_type == abi::ET_DYN + } + pub fn interpreter(&self) -> Option> { let mut result = None; for segment in self.segments().iter() { @@ -159,14 +168,11 @@ impl File { high = high.max(align_up(end, page)); } // ELF treats alignment 0 and 1 as no extra constraint. File - // and memory offsets must agree within a page for mmap. + // and memory offsets must agree within a page for mmap; like + // Linux binfmt_elf, do not reject binaries (e.g. patchelf + // output) that are page-congruent but incongruent mod p_align. let align = word(segment.p_align).max(1); assert!(align.is_power_of_two(), "invalid segment alignment"); - assert_eq!( - start % align, - word(segment.p_offset) % align, - "incongruent ELF alignment" - ); assert_eq!( start % page, word(segment.p_offset) % page, diff --git a/crates/fspy_elf_loader/src/image/tests.rs b/crates/fspy_elf_loader/src/image/tests.rs index cb94ca64b..6a1f8314f 100644 --- a/crates/fspy_elf_loader/src/image/tests.rs +++ b/crates/fspy_elf_loader/src/image/tests.rs @@ -166,6 +166,28 @@ fn maps_unordered_non_overlapping_loads() { } } +#[test] +fn accepts_page_congruent_segment_incongruent_with_large_p_align() { + let page = fspy_nostd::param::page_size(); + let mut bytes = std::vec![0; 3 * page]; + write_header(&mut bytes, 2, 0x200); + load(&mut bytes, 0, 0, page, page, abi::PF_R | abi::PF_X, page); + // Offset = page, vaddr = 2 * page: congruent mod page, incongruent mod 2 * page. + let header = &mut bytes[64 + 56..64 + 2 * 56]; + header.fill(0); + header[..4].copy_from_slice(&abi::PT_LOAD.to_le_bytes()); + header[4..8].copy_from_slice(&(abi::PF_R | abi::PF_W).to_le_bytes()); + for (field, value) in [(8, page), (16, 2 * page), (32, 0x40), (40, 0x40), (48, 2 * page)] { + header[field..field + 8].copy_from_slice(&u64::try_from(value).unwrap().to_le_bytes()); + } + bytes[page] = 0x77; + let image = map_bytes(&bytes); + // SAFETY: mapped readable segment. + unsafe { + assert_eq!(ptr::with_exposed_provenance::(image.bias + 2 * page).read(), 0x77); + } +} + #[test] #[should_panic(expected = "overlapping ELF segments")] fn rejects_overlapping_load_segments() { diff --git a/crates/fspy_elf_loader/src/lib.rs b/crates/fspy_elf_loader/src/lib.rs index 1c9fc298b..2870e13d5 100644 --- a/crates/fspy_elf_loader/src/lib.rs +++ b/crates/fspy_elf_loader/src/lib.rs @@ -103,6 +103,7 @@ pub unsafe fn exec_elf<'a>( ) .expect("cannot open ELF interpreter"); let file = image::File::new(fd); + assert!(file.is_dynamic(), "fixed-address PT_INTERP is unsupported"); assert!(file.interpreter().is_none(), "nested PT_INTERP is unsupported"); file }); @@ -146,13 +147,39 @@ pub unsafe fn exec_elf<'a>( #[cfg(target_arch = "aarch64")] #[unsafe(naked)] unsafe extern "C" fn enter(_entry: usize, _stack: *mut usize) -> ! { - // X0 holds entry and X1 holds the new SP. Linux start_thread zeros GPRs; - // clear the ones this stub dirties. X16 must keep the entry for BR. + // X0 holds entry and X1 holds the new SP. Match Linux start_thread by + // zeroing GPRs before entry. X16 keeps the entry for BTI-compatible BR. core::arch::naked_asm!( "mov x16, x0", "mov sp, x1", "mov x0, xzr", "mov x1, xzr", + "mov x2, xzr", + "mov x3, xzr", + "mov x4, xzr", + "mov x5, xzr", + "mov x6, xzr", + "mov x7, xzr", + "mov x8, xzr", + "mov x9, xzr", + "mov x10, xzr", + "mov x11, xzr", + "mov x12, xzr", + "mov x13, xzr", + "mov x14, xzr", + "mov x15, xzr", + "mov x17, xzr", + "mov x18, xzr", + "mov x19, xzr", + "mov x20, xzr", + "mov x21, xzr", + "mov x22, xzr", + "mov x23, xzr", + "mov x24, xzr", + "mov x25, xzr", + "mov x26, xzr", + "mov x27, xzr", + "mov x28, xzr", "mov x29, xzr", "mov x30, xzr", "br x16", @@ -164,13 +191,23 @@ unsafe extern "C" fn enter(_entry: usize, _stack: *mut usize) -> ! { unsafe extern "C" fn enter(_entry: usize, _stack: *mut usize) -> ! { // RDI holds entry and RSI holds the new RSP. RDX is the optional // dynamic-linker finalizer (an exit callback); there is none yet. - // Clear RBP to mark the end of the frame-pointer chain. RSI held SP. - // RDI must keep the entry for JMP. + // Match Linux ELF_PLAT_INIT by zeroing GPRs; RDI keeps the entry for JMP. core::arch::naked_asm!( "mov rsp, rsi", - "xor esi, esi", + "xor eax, eax", + "xor ebx, ebx", + "xor ecx, ecx", "xor edx, edx", + "xor esi, esi", "xor ebp, ebp", + "xor r8d, r8d", + "xor r9d, r9d", + "xor r10d, r10d", + "xor r11d, r11d", + "xor r12d, r12d", + "xor r13d, r13d", + "xor r14d, r14d", + "xor r15d, r15d", "jmp rdi" ); } diff --git a/crates/fspy_elf_loader/src/stack.rs b/crates/fspy_elf_loader/src/stack.rs index 39b7adc77..52f9252a2 100644 --- a/crates/fspy_elf_loader/src/stack.rs +++ b/crates/fspy_elf_loader/src/stack.rs @@ -31,6 +31,10 @@ use crate::{ // Includes startup data and room for the target's downward-growing call stack. // This MVP uses a fixed mapping rather than Linux's growable initial stack. const CAPACITY: usize = 8 * 1024 * 1024; +// Reserve at least 64 KiB below the initial SP above the guard page so a huge +// argv/envp fails loudly during loading instead of immediately SIGSEGVing at +// process entry. +const MIN_STACK_HEADROOM: usize = 64 * 1024; struct Builder { mapping: Mapping, @@ -69,7 +73,13 @@ impl Builder { } fn copy(&mut self, bytes: &[u8]) -> usize { - let start = self.strings.checked_sub(bytes.len()).expect("initial stack exceeds capacity"); + self.copy_aligned(bytes, 1) + } + + fn copy_aligned(&mut self, bytes: &[u8], align: usize) -> usize { + assert!(align.is_power_of_two(), "invalid stack payload alignment"); + let start = self.strings.checked_sub(bytes.len()).expect("initial stack exceeds capacity") + & !(align - 1); assert!(start >= self.table_end(), "initial stack exceeds capacity"); // SAFETY: bytes come from the old process image, not this fresh // mapping. The destination is writable and outside the pointer table. @@ -133,7 +143,7 @@ impl Builder { // table bytes move: its pointers already name the final payloads. let len = size_of_val(self.words.as_slice()); let start = self.strings.checked_sub(len).expect("initial stack exceeds capacity") & !15; - assert!(start >= self.start, "initial stack exceeds capacity"); + assert!(start >= add(self.start, MIN_STACK_HEADROOM), "initial stack exceeds capacity"); // The temporary vector and its owned bump are dropped before handoff. // SAFETY: the initialized vector and writable destination are disjoint. // The checked destination fits below the strings. The result is @@ -166,10 +176,10 @@ pub unsafe fn build<'a>( continue; }; match key { + abi::AT_NULL => break, // Replace loader-image addresses below. AT_EXECFD would refer to // an old execution descriptor; omit it. Emit our own end marker. - abi::AT_NULL - | abi::AT_PHDR + abi::AT_PHDR | abi::AT_PHENT | abi::AT_PHNUM | abi::AT_ENTRY @@ -178,6 +188,7 @@ pub unsafe fn build<'a>( | abi::AT_EXECFD | abi::AT_FLAGS => continue, abi::AT_RANDOM => { + assert!(entry.value != 0, "null AT_RANDOM"); // The value is a pointer, not the random number itself. Copy // the kernel-provided bytes used by libc for stack canaries. // SAFETY: the exec_elf caller supplies the kernel's readable @@ -185,9 +196,10 @@ pub unsafe fn build<'a>( let bytes = unsafe { core::slice::from_raw_parts(ptr::with_exposed_provenance(entry.value), 16) }; - entry.value = stack.copy(bytes); + entry.value = stack.copy_aligned(bytes, 16); } abi::AT_PLATFORM | abi::AT_BASE_PLATFORM => { + assert!(entry.value != 0, "null auxiliary string"); // SAFETY: the caller supplies a live NUL-terminated auxiliary string. let string = unsafe { CStr::from_ptr(ptr::with_exposed_provenance(entry.value)) }; entry.value = stack.string(string); @@ -267,4 +279,59 @@ mod tests { } } } + + #[test] + fn stops_at_at_null_and_aligns_at_random() { + let page = fspy_nostd::param::page_size(); + let random = [0x5a_u8; 16]; + let image = Image::test_stub(page); + let thin = |value: &'static core::ffi::CStr| { + CStr::from_units_with_nul(value.to_bytes_with_nul()).unwrap().as_thin() + }; + let inherited = [ + AuxEntry { key: usize::try_from(abi::AT_PAGESZ).unwrap(), value: page }, + AuxEntry { + key: usize::try_from(abi::AT_RANDOM).unwrap(), + value: random.as_ptr().expose_provenance(), + }, + AuxEntry { key: usize::try_from(abi::AT_NULL).unwrap(), value: 0 }, + // Trailing entry past AT_NULL must not be emitted. + AuxEntry { key: 0x1234, value: 0xdead }, + ]; + // SAFETY: synthetic image/auxv pointers stay valid throughout build. + let sp = unsafe { + build( + thin(c"prog"), + [thin(c"a")].into_iter(), + core::iter::empty(), + inherited.into_iter(), + &image, + None, + page, + ) + }; + // SAFETY: build returned a complete initial stack. + let stack = unsafe { InitialStack::from_ptr(sp) }; + let aux_random = stack + .auxv() + .iter() + .find(|entry| entry.key == usize::try_from(abi::AT_RANDOM).unwrap()) + .unwrap() + .value; + assert_eq!(aux_random % 16, 0, "AT_RANDOM should be 16-byte aligned"); + assert!( + !stack.auxv().iter().any(|entry| entry.key == 0x1234), + "entries after AT_NULL must not be emitted" + ); + } + + #[test] + #[should_panic(expected = "initial stack exceeds capacity")] + fn rejects_stack_without_call_headroom() { + let page = fspy_nostd::param::page_size(); + let mut builder = Builder::new(page); + let huge = std::vec![b'x'; CAPACITY - MIN_STACK_HEADROOM / 2]; + let _ = builder.copy(&huge); + let _ = builder.finish(); + } } From fa5ae590ae33bc288d692a14bcba2a6ef5987a33 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 12:35:28 +0800 Subject: [PATCH 20/34] test(fspy-elf-loader): avoid assuming /bin/echo is ET_DYN and check fd 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 --- .../fixtures/static_runtime.c | 28 +++++++++++++++++++ .../fspy_elf_loader_tests/tests/exec_elf.rs | 1 - 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/fspy_elf_loader_tests/fixtures/static_runtime.c b/crates/fspy_elf_loader_tests/fixtures/static_runtime.c index 95c6a6ae9..7b9e29411 100644 --- a/crates/fspy_elf_loader_tests/fixtures/static_runtime.c +++ b/crates/fspy_elf_loader_tests/fixtures/static_runtime.c @@ -7,8 +7,11 @@ #define _GNU_SOURCE +#include #include +#include #include +#include #include #include #include @@ -181,6 +184,31 @@ int main(int argc, char **argv) { } } + { + DIR *dir = opendir("/proc/self/fd"); + struct dirent *entry; + if (dir == NULL) { + fail("opendir /proc/self/fd"); + } + while ((entry = readdir(dir)) != NULL) { + char link_path[PATH_MAX]; + char target[PATH_MAX]; + ssize_t len; + if (entry->d_name[0] == '.') { + continue; + } + snprintf(link_path, sizeof link_path, "/proc/self/fd/%s", entry->d_name); + len = readlink(link_path, target, sizeof target - 1); + if (len >= 0) { + target[len] = '\0'; + if (strcmp(target, image) == 0) { + fail("executable fd leaked"); + } + } + } + closedir(dir); + } + write(STDOUT_FILENO, "runtime-ok\n", 11); _exit(37); } diff --git a/crates/fspy_elf_loader_tests/tests/exec_elf.rs b/crates/fspy_elf_loader_tests/tests/exec_elf.rs index bcb31f8f9..22c3c4630 100644 --- a/crates/fspy_elf_loader_tests/tests/exec_elf.rs +++ b/crates/fspy_elf_loader_tests/tests/exec_elf.rs @@ -19,7 +19,6 @@ const FIXTURE_STATIC_PIE: &str = env!("FIXTURE_STATIC_PIE"); #[test] #[timeout(10_000)] fn echo_matches_kernel_exec() { - assert_image("/bin/echo", elf::abi::ET_DYN, true); let mut direct = Command::new("/bin/echo"); direct.args(["hello", "world"]); let mut loaded = launcher(); From 5056f554d32315a0fc41ea3cb42554e5085bcc46 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 17:34:51 +0800 Subject: [PATCH 21/34] refactor(fspy-elf-loader): move test launcher binary to its own crate 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 --- Cargo.lock | 10 ++++++++- crates/fspy_elf_loader/Cargo.toml | 6 ------ .../fspy_elf_loader_test_launcher/Cargo.toml | 21 +++++++++++++++++++ .../build.rs | 0 .../src/main.rs} | 2 +- crates/fspy_elf_loader_tests/Cargo.toml | 6 +++--- .../fspy_elf_loader_tests/tests/exec_elf.rs | 2 +- .../tests/launcher_image.rs | 2 +- 8 files changed, 36 insertions(+), 13 deletions(-) create mode 100644 crates/fspy_elf_loader_test_launcher/Cargo.toml rename crates/{fspy_elf_loader => fspy_elf_loader_test_launcher}/build.rs (100%) rename crates/{fspy_elf_loader/tests/support/launcher.rs => fspy_elf_loader_test_launcher/src/main.rs} (98%) diff --git a/Cargo.lock b/Cargo.lock index 385b2218d..73b3490d0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1480,12 +1480,20 @@ dependencies = [ "tempfile", ] +[[package]] +name = "fspy_elf_loader_test_launcher" +version = "0.0.0" +dependencies = [ + "fspy_elf_loader", + "fspy_nostd", +] + [[package]] name = "fspy_elf_loader_tests" version = "0.0.0" dependencies = [ "elf", - "fspy_elf_loader", + "fspy_elf_loader_test_launcher", "libc", "ntest", "tempfile", diff --git a/crates/fspy_elf_loader/Cargo.toml b/crates/fspy_elf_loader/Cargo.toml index 62551f55c..1d6f14a93 100644 --- a/crates/fspy_elf_loader/Cargo.toml +++ b/crates/fspy_elf_loader/Cargo.toml @@ -19,12 +19,6 @@ linux-raw-sys = { workspace = true, features = ["auxvec", "no_std"] } [target.'cfg(target_os = "linux")'.dev-dependencies] tempfile = { workspace = true } -[[bin]] -name = "fspy_elf_loader_test_launcher" -path = "tests/support/launcher.rs" -test = false -bench = false - [lib] doctest = false diff --git a/crates/fspy_elf_loader_test_launcher/Cargo.toml b/crates/fspy_elf_loader_test_launcher/Cargo.toml new file mode 100644 index 000000000..eadaf1072 --- /dev/null +++ b/crates/fspy_elf_loader_test_launcher/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "fspy_elf_loader_test_launcher" +version = "0.0.0" +authors.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true +rust-version.workspace = true + +[target.'cfg(target_os = "none")'.dependencies] +fspy_elf_loader = { path = "../fspy_elf_loader" } +fspy_nostd = { workspace = true } + +[[bin]] +name = "fspy_elf_loader_test_launcher" +path = "src/main.rs" +test = false +bench = false + +[lints] +workspace = true diff --git a/crates/fspy_elf_loader/build.rs b/crates/fspy_elf_loader_test_launcher/build.rs similarity index 100% rename from crates/fspy_elf_loader/build.rs rename to crates/fspy_elf_loader_test_launcher/build.rs diff --git a/crates/fspy_elf_loader/tests/support/launcher.rs b/crates/fspy_elf_loader_test_launcher/src/main.rs similarity index 98% rename from crates/fspy_elf_loader/tests/support/launcher.rs rename to crates/fspy_elf_loader_test_launcher/src/main.rs index 60c99a59b..29cde1486 100644 --- a/crates/fspy_elf_loader/tests/support/launcher.rs +++ b/crates/fspy_elf_loader_test_launcher/src/main.rs @@ -2,7 +2,7 @@ #![cfg_attr(target_os = "none", no_main)] #[cfg(not(target_os = "none"))] -fn main() {} +const fn main() {} #[cfg(target_os = "none")] mod freestanding { diff --git a/crates/fspy_elf_loader_tests/Cargo.toml b/crates/fspy_elf_loader_tests/Cargo.toml index 0def1608d..3a843cce3 100644 --- a/crates/fspy_elf_loader_tests/Cargo.toml +++ b/crates/fspy_elf_loader_tests/Cargo.toml @@ -18,13 +18,13 @@ tempfile = { workspace = true } libc = { workspace = true } [target.'cfg(target_arch = "aarch64")'.dev-dependencies] -fspy_elf_loader = { path = "../fspy_elf_loader", artifact = "bin:fspy_elf_loader_test_launcher", target = "aarch64-unknown-none-softfloat" } +fspy_elf_loader_test_launcher = { path = "../fspy_elf_loader_test_launcher", artifact = "bin", target = "aarch64-unknown-none-softfloat" } [target.'cfg(target_arch = "x86_64")'.dev-dependencies] -fspy_elf_loader = { path = "../fspy_elf_loader", artifact = "bin:fspy_elf_loader_test_launcher", target = "x86_64-unknown-none" } +fspy_elf_loader_test_launcher = { path = "../fspy_elf_loader_test_launcher", artifact = "bin", target = "x86_64-unknown-none" } [lints] workspace = true [package.metadata.cargo-shear] -ignored = ["fspy_elf_loader"] +ignored = ["fspy_elf_loader_test_launcher"] diff --git a/crates/fspy_elf_loader_tests/tests/exec_elf.rs b/crates/fspy_elf_loader_tests/tests/exec_elf.rs index 22c3c4630..9cab12a31 100644 --- a/crates/fspy_elf_loader_tests/tests/exec_elf.rs +++ b/crates/fspy_elf_loader_tests/tests/exec_elf.rs @@ -10,7 +10,7 @@ use std::{ use ntest::timeout; -const LAUNCHER: &str = env!("CARGO_BIN_FILE_FSPY_ELF_LOADER_fspy_elf_loader_test_launcher"); +const LAUNCHER: &str = env!("CARGO_BIN_FILE_FSPY_ELF_LOADER_TEST_LAUNCHER"); const FIXTURE: &str = env!("CARGO_BIN_EXE_fixture"); const FIXTURE_EXEC: &str = env!("CARGO_BIN_EXE_fixture_exec"); const FIXTURE_STATIC: &str = env!("FIXTURE_STATIC"); diff --git a/crates/fspy_elf_loader_tests/tests/launcher_image.rs b/crates/fspy_elf_loader_tests/tests/launcher_image.rs index c4077aab0..dc447c436 100644 --- a/crates/fspy_elf_loader_tests/tests/launcher_image.rs +++ b/crates/fspy_elf_loader_tests/tests/launcher_image.rs @@ -1,6 +1,6 @@ use elf::{ElfBytes, abi, endian::LittleEndian, file::Class}; -const LAUNCHER: &str = env!("CARGO_BIN_FILE_FSPY_ELF_LOADER_fspy_elf_loader_test_launcher"); +const LAUNCHER: &str = env!("CARGO_BIN_FILE_FSPY_ELF_LOADER_TEST_LAUNCHER"); // Inspect the real artifact on every host, including macOS and Windows. // Linux execution tests separately check startup and fixed-address collisions. From fb3bb181bd242aea631e249612ae6eade6e788ab Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 17:37:40 +0800 Subject: [PATCH 22/34] test(fspy-elf-loader): unify 4-cell ELF fixtures in C with target-aware 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_, CC) with rerun-if-env-changed instead of hardcoding Command::new("cc"). Co-authored-by: Gemini 4 Neon --- Cargo.lock | 1 + crates/fspy_elf_loader_tests/Cargo.toml | 3 + crates/fspy_elf_loader_tests/build.rs | 56 +++++++++++++------ .../fixtures/{static_runtime.c => runtime.c} | 37 +++++++++--- .../src/bin/fixture_exec.rs | 2 - .../fspy_elf_loader_tests/tests/exec_elf.rs | 28 ++++++---- 6 files changed, 90 insertions(+), 37 deletions(-) rename crates/fspy_elf_loader_tests/fixtures/{static_runtime.c => runtime.c} (82%) delete mode 100644 crates/fspy_elf_loader_tests/src/bin/fixture_exec.rs diff --git a/Cargo.lock b/Cargo.lock index 73b3490d0..8b368cd9e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1492,6 +1492,7 @@ dependencies = [ name = "fspy_elf_loader_tests" version = "0.0.0" dependencies = [ + "cc", "elf", "fspy_elf_loader_test_launcher", "libc", diff --git a/crates/fspy_elf_loader_tests/Cargo.toml b/crates/fspy_elf_loader_tests/Cargo.toml index 3a843cce3..bc9a71b1f 100644 --- a/crates/fspy_elf_loader_tests/Cargo.toml +++ b/crates/fspy_elf_loader_tests/Cargo.toml @@ -7,6 +7,9 @@ license.workspace = true publish.workspace = true rust-version.workspace = true +[build-dependencies] +cc = { workspace = true } + [dev-dependencies] elf = { workspace = true } diff --git a/crates/fspy_elf_loader_tests/build.rs b/crates/fspy_elf_loader_tests/build.rs index 7fdfa6ec7..6eadc8955 100644 --- a/crates/fspy_elf_loader_tests/build.rs +++ b/crates/fspy_elf_loader_tests/build.rs @@ -8,20 +8,40 @@ fn main() { if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("linux") { return; } - // Keep the same runtime checks in PIE and fixed-address executables. - // The linker driver must retain dynamic linking while disabling PIE. - println!("cargo::rustc-link-arg-bin=fixture_exec=-no-pie"); - println!("cargo::rerun-if-changed=fixtures/static_runtime.c"); + println!("cargo::rerun-if-changed=fixtures/runtime.c"); + println!("cargo::rerun-if-env-changed=CC"); + if let Ok(mut target) = env::var("TARGET") { + // SAFETY: replacing ASCII '-' with ASCII '_' preserves UTF-8 validity. + for byte in unsafe { target.as_bytes_mut() } { + if *byte == b'-' { + *byte = b'_'; + } + } + println!("cargo::rerun-if-env-changed=CC_{target}"); + } + + // Use cc's target-aware compiler discovery (respects CC_, CC, and + // cross toolchains) without inheriting its library-oriented default flags. + let compiler = cc::Build::new().cargo_metadata(false).get_compiler(); let out = env::var_os("OUT_DIR").unwrap(); let mut source = env::var_os("CARGO_MANIFEST_DIR").unwrap(); - source.push("/fixtures/static_runtime.c"); - let static_bin = join_out(&out, "/fixture_static"); - let static_pie = join_out(&out, "/fixture_static_pie"); - compile(&source, &static_bin, &["-static"]); - compile(&source, &static_pie, &["-static-pie"]); - println!("cargo::rustc-env=FIXTURE_STATIC={}", static_bin.to_str().unwrap()); - println!("cargo::rustc-env=FIXTURE_STATIC_PIE={}", static_pie.to_str().unwrap()); + source.push("/fixtures/runtime.c"); + + // Compile the single C runtime fixture across all four ELF64 cells with + // explicit PIE/non-PIE flags so GCC, Clang, and zig cc emit identical shapes. + let cells = [ + ("FIXTURE_DYN_PIE", "/fixture_dyn_pie", &["-fPIE", "-pie"][..]), + ("FIXTURE_DYN_EXEC", "/fixture_dyn_exec", &["-fno-pie", "-no-pie"][..]), + ("FIXTURE_STATIC_EXEC", "/fixture_static_exec", &["-fno-pie", "-static"][..]), + ("FIXTURE_STATIC_PIE", "/fixture_static_pie", &["-fPIE", "-static-pie"][..]), + ]; + + for (env_name, file_name, flags) in cells { + let dest = join_out(&out, file_name); + compile(&compiler, &source, &dest, flags); + println!("cargo::rustc-env={env_name}={}", dest.to_str().unwrap()); + } } fn join_out(out: &OsString, name: &str) -> OsString { @@ -30,8 +50,12 @@ fn join_out(out: &OsString, name: &str) -> OsString { path } -fn compile(source: &OsString, dest: &OsString, extra: &[&str]) { - let output = Command::new("cc") +fn compile(compiler: &cc::Tool, source: &OsString, dest: &OsString, extra: &[&str]) { + let mut command = Command::new(compiler.path()); + for (key, value) in compiler.env() { + command.env(key, value); + } + let output = command .args(["-O1", "-pthread"]) .args(extra) .arg("-o") @@ -39,10 +63,10 @@ fn compile(source: &OsString, dest: &OsString, extra: &[&str]) { .arg(source) .stderr(Stdio::piped()) .output() - .expect("cannot invoke cc"); + .expect("cannot invoke C compiler"); assert!( output.status.success(), - "cannot compile static runtime fixture: {}", - str::from_utf8(&output.stderr).unwrap_or("non-utf8 cc diagnostics") + "cannot compile runtime fixture ({extra:?}): {}", + str::from_utf8(&output.stderr).unwrap_or("non-utf8 C compiler diagnostics") ); } diff --git a/crates/fspy_elf_loader_tests/fixtures/static_runtime.c b/crates/fspy_elf_loader_tests/fixtures/runtime.c similarity index 82% rename from crates/fspy_elf_loader_tests/fixtures/static_runtime.c rename to crates/fspy_elf_loader_tests/fixtures/runtime.c index 7b9e29411..f20b0fc14 100644 --- a/crates/fspy_elf_loader_tests/fixtures/static_runtime.c +++ b/crates/fspy_elf_loader_tests/fixtures/runtime.c @@ -1,8 +1,10 @@ -/* Runtime checks for static and static-PIE images loaded by exec_elf. +/* Runtime checks for all four Linux ELF64 cells loaded by exec_elf: + * dynamic PIE, dynamic ET_EXEC, traditional static, and static-PIE. * - * Protocol matches src/bin/fixture.rs: argv[0]="custom-argv-zero", argv[1]="", - * argv[2]=0xff, EMPTY="", BYTES=0xff, FIXTURE_IMAGE=AT_EXECFN, stdout - * "runtime-ok\n", exit 37. AT_BASE must be 0 (no interpreter). + * Protocol: argv[0]="custom-argv-zero", argv[1]="", argv[2]=0xff, + * EMPTY="", BYTES=0xff, FIXTURE_IMAGE=AT_EXECFN, stdout "runtime-ok\n", + * exit 37. Set EXPECT_INTERPRETER=1 when PT_INTERP is present (AT_BASE != 0) + * and EXPECT_FIXED_ADDRESS=1 for ET_EXEC images (load bias == 0). */ #define _GNU_SOURCE @@ -21,9 +23,20 @@ static char bss[128 * 1024]; static int data = 42; static __thread int tls = 17; +static void write_all(int fd, const char *buf, size_t len) { + while (len > 0) { + ssize_t written = write(fd, buf, len); + if (written <= 0) { + return; + } + buf += written; + len -= (size_t)written; + } +} + static void fail(const char *message) { - write(STDERR_FILENO, message, strlen(message)); - write(STDERR_FILENO, "\n", 1); + write_all(STDERR_FILENO, message, strlen(message)); + write_all(STDERR_FILENO, "\n", 1); _exit(2); } @@ -66,6 +79,7 @@ int main(int argc, char **argv) { pthread_t thread; int started = 0; char *heap; + unsigned long at_base; unsigned long at_phdr; unsigned long phnum; unsigned long phent; @@ -131,9 +145,16 @@ int main(int argc, char **argv) { } free(heap); - if (getauxval(AT_BASE) != 0) { + at_base = getauxval(AT_BASE); + if (getenv("EXPECT_INTERPRETER") != NULL) { + const unsigned char *interp = (const unsigned char *)at_base; + if (at_base == 0 || memcmp(interp, "\x7f" "ELF", 4) != 0) { + fail("AT_BASE interpreter"); + } + } else if (at_base != 0) { fail("AT_BASE"); } + at_phdr = getauxval(AT_PHDR); phnum = getauxval(AT_PHNUM); phent = getauxval(AT_PHENT); @@ -209,6 +230,6 @@ int main(int argc, char **argv) { closedir(dir); } - write(STDOUT_FILENO, "runtime-ok\n", 11); + write_all(STDOUT_FILENO, "runtime-ok\n", 11); _exit(37); } diff --git a/crates/fspy_elf_loader_tests/src/bin/fixture_exec.rs b/crates/fspy_elf_loader_tests/src/bin/fixture_exec.rs deleted file mode 100644 index 8fb726c2f..000000000 --- a/crates/fspy_elf_loader_tests/src/bin/fixture_exec.rs +++ /dev/null @@ -1,2 +0,0 @@ -// build.rs links these runtime checks as a dynamic ET_EXEC executable. -include!("fixture.rs"); diff --git a/crates/fspy_elf_loader_tests/tests/exec_elf.rs b/crates/fspy_elf_loader_tests/tests/exec_elf.rs index 9cab12a31..1e9fabe50 100644 --- a/crates/fspy_elf_loader_tests/tests/exec_elf.rs +++ b/crates/fspy_elf_loader_tests/tests/exec_elf.rs @@ -11,9 +11,10 @@ use std::{ use ntest::timeout; const LAUNCHER: &str = env!("CARGO_BIN_FILE_FSPY_ELF_LOADER_TEST_LAUNCHER"); -const FIXTURE: &str = env!("CARGO_BIN_EXE_fixture"); -const FIXTURE_EXEC: &str = env!("CARGO_BIN_EXE_fixture_exec"); -const FIXTURE_STATIC: &str = env!("FIXTURE_STATIC"); +const FIXTURE_RUST: &str = env!("CARGO_BIN_EXE_fixture"); +const FIXTURE_DYN_PIE: &str = env!("FIXTURE_DYN_PIE"); +const FIXTURE_DYN_EXEC: &str = env!("FIXTURE_DYN_EXEC"); +const FIXTURE_STATIC_EXEC: &str = env!("FIXTURE_STATIC_EXEC"); const FIXTURE_STATIC_PIE: &str = env!("FIXTURE_STATIC_PIE"); #[test] @@ -47,18 +48,20 @@ fn echo_preserves_empty_and_non_utf8_arguments() { #[test] #[timeout(10_000)] -fn initializes_runtime_bss_tls_and_auxiliary_vector() { - check_runtime(FIXTURE, elf::abi::ET_DYN); +fn initializes_rust_std_runtime() { + check_runtime_image(FIXTURE_RUST, elf::abi::ET_DYN, true); } #[test] #[timeout(10_000)] -fn initializes_fixed_runtime() { - check_runtime(FIXTURE_EXEC, elf::abi::ET_EXEC); +fn initializes_dynamic_pie_runtime() { + check_runtime_image(FIXTURE_DYN_PIE, elf::abi::ET_DYN, true); } -fn check_runtime(fixture: &str, image_type: u16) { - check_runtime_image(fixture, image_type, true); +#[test] +#[timeout(10_000)] +fn initializes_fixed_runtime() { + check_runtime_image(FIXTURE_DYN_EXEC, elf::abi::ET_EXEC, true); } fn check_runtime_image(fixture: &str, image_type: u16, interpreter: bool) { @@ -68,6 +71,9 @@ fn check_runtime_image(fixture: &str, image_type: u16, interpreter: bool) { command.arg(OsStr::from_bytes(b"\xff")); command.env_clear().env("FIXTURE_IMAGE", fixture).env("EMPTY", ""); command.env("BYTES", OsStr::from_bytes(b"\xff")); + if interpreter { + command.env("EXPECT_INTERPRETER", "1"); + } if image_type == elf::abi::ET_EXEC { command.env("EXPECT_FIXED_ADDRESS", "1"); } @@ -80,7 +86,7 @@ fn check_runtime_image(fixture: &str, image_type: u16, interpreter: bool) { #[test] #[timeout(10_000)] fn initializes_static_runtime() { - check_runtime_image(FIXTURE_STATIC, elf::abi::ET_EXEC, false); + check_runtime_image(FIXTURE_STATIC_EXEC, elf::abi::ET_EXEC, false); } #[test] @@ -102,7 +108,7 @@ fn rejects_fixed_image_overlapping_launcher() { .find(|ph| ph.p_type == elf::abi::PT_LOAD) .unwrap() .p_vaddr; - let mut bytes = std::fs::read(FIXTURE_EXEC).unwrap(); + let mut bytes = std::fs::read(FIXTURE_DYN_EXEC).unwrap(); let parsed = elf::ElfBytes::::minimal_parse(&bytes).unwrap(); let table = usize::try_from(parsed.ehdr.e_phoff).unwrap(); let loads: Vec<_> = parsed From a49faa39e11b969a16e2ee22b78d59d7ec1646db Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 17:38:12 +0800 Subject: [PATCH 23/34] test(fspy-elf-loader): run runtime fixtures differentially against kernel 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 --- .../fspy_elf_loader_tests/tests/exec_elf.rs | 46 ++++++++++++------- 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/crates/fspy_elf_loader_tests/tests/exec_elf.rs b/crates/fspy_elf_loader_tests/tests/exec_elf.rs index 1e9fabe50..80f7c7ca2 100644 --- a/crates/fspy_elf_loader_tests/tests/exec_elf.rs +++ b/crates/fspy_elf_loader_tests/tests/exec_elf.rs @@ -4,7 +4,7 @@ use std::{ ffi::OsStr, - os::unix::ffi::OsStrExt as _, + os::unix::{ffi::OsStrExt as _, process::CommandExt as _}, process::{Command, Output, Stdio}, }; @@ -66,21 +66,35 @@ fn initializes_fixed_runtime() { fn check_runtime_image(fixture: &str, image_type: u16, interpreter: bool) { assert_image(fixture, image_type, interpreter); - let mut command = launcher(); - command.args([fixture, "custom-argv-zero", ""]); - command.arg(OsStr::from_bytes(b"\xff")); - command.env_clear().env("FIXTURE_IMAGE", fixture).env("EMPTY", ""); - command.env("BYTES", OsStr::from_bytes(b"\xff")); - if interpreter { - command.env("EXPECT_INTERPRETER", "1"); - } - if image_type == elf::abi::ET_EXEC { - command.env("EXPECT_FIXED_ADDRESS", "1"); - } - let output = output(command); - assert_eq!(output.status.code(), Some(37), "{output:?}"); - assert_eq!(output.stdout, b"runtime-ok\n"); - assert!(output.stderr.is_empty(), "{output:?}"); + let configure = |command: &mut Command| { + command.arg("").arg(OsStr::from_bytes(b"\xff")); + command.env_clear().env("FIXTURE_IMAGE", fixture).env("EMPTY", ""); + command.env("BYTES", OsStr::from_bytes(b"\xff")); + if interpreter { + command.env("EXPECT_INTERPRETER", "1"); + } + if image_type == elf::abi::ET_EXEC { + command.env("EXPECT_FIXED_ADDRESS", "1"); + } + }; + + // Run each fixture through kernel execve first so fixture/toolchain issues + // are distinguished from loader regressions. + let mut direct = Command::new(fixture); + direct.arg0("custom-argv-zero").stderr(Stdio::piped()); + configure(&mut direct); + let direct = output(direct); + assert_eq!(direct.status.code(), Some(37), "kernel exec: {direct:?}"); + assert_eq!(direct.stdout, b"runtime-ok\n"); + assert!(direct.stderr.is_empty(), "kernel exec: {direct:?}"); + + let mut loaded = launcher(); + loaded.args([fixture, "custom-argv-zero"]); + configure(&mut loaded); + let loaded = output(loaded); + assert_eq!(loaded.status.code(), Some(37), "loader exec: {loaded:?}"); + assert_eq!(loaded.stdout, direct.stdout); + assert_eq!(loaded.stderr, direct.stderr); } #[test] From bfdb806e0427ce15aadbbae4c252f00ae6e0ec2c Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 17:45:48 +0800 Subject: [PATCH 24/34] fix(fspy-elf-loader): support cargo-zigbuild for static C test fixtures 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 `-linux-musl`. Co-authored-by: Gemini 4 Neon --- crates/fspy_elf_loader_tests/build.rs | 52 ++++++++++++++++++++++----- 1 file changed, 43 insertions(+), 9 deletions(-) diff --git a/crates/fspy_elf_loader_tests/build.rs b/crates/fspy_elf_loader_tests/build.rs index 6eadc8955..86740cfea 100644 --- a/crates/fspy_elf_loader_tests/build.rs +++ b/crates/fspy_elf_loader_tests/build.rs @@ -1,6 +1,6 @@ use std::{ env, - ffi::OsString, + ffi::{OsStr, OsString}, process::{Command, Stdio}, }; @@ -23,6 +23,11 @@ fn main() { // Use cc's target-aware compiler discovery (respects CC_, CC, and // cross toolchains) without inheriting its library-oriented default flags. let compiler = cc::Build::new().cargo_metadata(false).get_compiler(); + let is_zigcc = compiler + .path() + .file_name() + .and_then(OsStr::to_str) + .is_some_and(|name| name.starts_with("zigcc-")); let out = env::var_os("OUT_DIR").unwrap(); let mut source = env::var_os("CARGO_MANIFEST_DIR").unwrap(); @@ -30,16 +35,35 @@ fn main() { // Compile the single C runtime fixture across all four ELF64 cells with // explicit PIE/non-PIE flags so GCC, Clang, and zig cc emit identical shapes. - let cells = [ - ("FIXTURE_DYN_PIE", "/fixture_dyn_pie", &["-fPIE", "-pie"][..]), - ("FIXTURE_DYN_EXEC", "/fixture_dyn_exec", &["-fno-pie", "-no-pie"][..]), - ("FIXTURE_STATIC_EXEC", "/fixture_static_exec", &["-fno-pie", "-static"][..]), - ("FIXTURE_STATIC_PIE", "/fixture_static_pie", &["-fPIE", "-static-pie"][..]), - ]; + // cargo-zigbuild's gnu wrapper cannot link static glibc executables, so use + // `cargo-zigbuild zig cc` targeting musl for the two static cells. + let musl_target = if is_zigcc { + Some(match env::var("CARGO_CFG_TARGET_ARCH").as_deref() { + Ok("x86_64") => "x86_64-linux-musl", + Ok("aarch64") => "aarch64-linux-musl", + other => panic!("unsupported Linux target arch for zig cc static fixtures: {other:?}"), + }) + } else { + None + }; - for (env_name, file_name, flags) in cells { + for (env_name, file_name, flags, is_static) in [ + ("FIXTURE_DYN_PIE", "/fixture_dyn_pie", &["-fPIE", "-pie"][..], false), + ("FIXTURE_DYN_EXEC", "/fixture_dyn_exec", &["-fno-pie", "-no-pie"][..], false), + ("FIXTURE_STATIC_EXEC", "/fixture_static_exec", &["-fno-pie", "-static"][..], true), + ( + "FIXTURE_STATIC_PIE", + "/fixture_static_pie", + if is_zigcc { &["-fPIE", "-static", "-pie"][..] } else { &["-fPIE", "-static-pie"] }, + true, + ), + ] { let dest = join_out(&out, file_name); - compile(&compiler, &source, &dest, flags); + if is_static && let Some(musl_target) = musl_target { + compile_zig_musl(musl_target, &source, &dest, flags); + } else { + compile(&compiler, &source, &dest, flags); + } println!("cargo::rustc-env={env_name}={}", dest.to_str().unwrap()); } } @@ -50,11 +74,21 @@ fn join_out(out: &OsString, name: &str) -> OsString { path } +fn compile_zig_musl(musl_target: &str, source: &OsString, dest: &OsString, extra: &[&str]) { + let mut command = Command::new("cargo-zigbuild"); + command.args(["zig", "cc", "--", "-target", musl_target]); + run_compile(command, source, dest, extra); +} + fn compile(compiler: &cc::Tool, source: &OsString, dest: &OsString, extra: &[&str]) { let mut command = Command::new(compiler.path()); for (key, value) in compiler.env() { command.env(key, value); } + run_compile(command, source, dest, extra); +} + +fn run_compile(mut command: Command, source: &OsString, dest: &OsString, extra: &[&str]) { let output = command .args(["-O1", "-pthread"]) .args(extra) From 8acc878ac062b10e107cdea956ef38207d322e16 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 17:45:48 +0800 Subject: [PATCH 25/34] test(fspy-elf-loader): use typed ELF64 helpers and mutate own fixture 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 --- crates/fspy_elf_loader/src/image/tests.rs | 99 +++++++++++++------ .../fspy_elf_loader_tests/tests/exec_elf.rs | 66 ++++++++----- 2 files changed, 113 insertions(+), 52 deletions(-) diff --git a/crates/fspy_elf_loader/src/image/tests.rs b/crates/fspy_elf_loader/src/image/tests.rs index 6a1f8314f..3b57d8157 100644 --- a/crates/fspy_elf_loader/src/image/tests.rs +++ b/crates/fspy_elf_loader/src/image/tests.rs @@ -173,13 +173,16 @@ fn accepts_page_congruent_segment_incongruent_with_large_p_align() { write_header(&mut bytes, 2, 0x200); load(&mut bytes, 0, 0, page, page, abi::PF_R | abi::PF_X, page); // Offset = page, vaddr = 2 * page: congruent mod page, incongruent mod 2 * page. - let header = &mut bytes[64 + 56..64 + 2 * 56]; - header.fill(0); - header[..4].copy_from_slice(&abi::PT_LOAD.to_le_bytes()); - header[4..8].copy_from_slice(&(abi::PF_R | abi::PF_W).to_le_bytes()); - for (field, value) in [(8, page), (16, 2 * page), (32, 0x40), (40, 0x40), (48, 2 * page)] { - header[field..field + 8].copy_from_slice(&u64::try_from(value).unwrap().to_le_bytes()); + Phdr { + p_type: abi::PT_LOAD, + p_flags: abi::PF_R | abi::PF_W, + p_offset: u64::try_from(page).unwrap(), + p_vaddr: u64::try_from(2 * page).unwrap(), + p_filesz: 0x40, + p_memsz: 0x40, + p_align: u64::try_from(2 * page).unwrap(), } + .write_to(&mut bytes, 1); bytes[page] = 0x77; let image = map_bytes(&bytes); // SAFETY: mapped readable segment. @@ -233,30 +236,66 @@ fn fixture(page: usize, memory_size: usize, flags: u32) -> std::vec::Vec { bytes } +const EHDR_SIZE: usize = 64; +const PHDR_SIZE: usize = 56; + +#[expect(clippy::struct_field_names, reason = "matches ELF64 Elf64_Phdr field names")] +struct Phdr { + p_type: u32, + p_flags: u32, + p_offset: u64, + p_vaddr: u64, + p_filesz: u64, + p_memsz: u64, + p_align: u64, +} + +impl Phdr { + fn write_to(&self, bytes: &mut [u8], index: usize) { + let start = EHDR_SIZE + index * PHDR_SIZE; + let out = &mut bytes[start..start + PHDR_SIZE]; + out.fill(0); + out[0..4].copy_from_slice(&self.p_type.to_le_bytes()); + out[4..8].copy_from_slice(&self.p_flags.to_le_bytes()); + out[8..16].copy_from_slice(&self.p_offset.to_le_bytes()); + out[16..24].copy_from_slice(&self.p_vaddr.to_le_bytes()); + out[32..40].copy_from_slice(&self.p_filesz.to_le_bytes()); + out[40..48].copy_from_slice(&self.p_memsz.to_le_bytes()); + out[48..56].copy_from_slice(&self.p_align.to_le_bytes()); + } +} + fn interp_image(path: &[u8]) -> std::vec::Vec { - let start = 64 + 56; + let start = EHDR_SIZE + PHDR_SIZE; let mut bytes = std::vec![0; start + path.len()]; write_header(&mut bytes, 1, 0); - let header = &mut bytes[64..120]; - header[..4].copy_from_slice(&abi::PT_INTERP.to_le_bytes()); - for (field, value) in [(8, start), (32, path.len()), (40, path.len()), (48, 1)] { - header[field..field + 8].copy_from_slice(&u64::try_from(value).unwrap().to_le_bytes()); + let len = u64::try_from(path.len()).unwrap(); + Phdr { + p_type: abi::PT_INTERP, + p_flags: 0, + p_offset: u64::try_from(start).unwrap(), + p_vaddr: 0, + p_filesz: len, + p_memsz: len, + p_align: 1, } + .write_to(&mut bytes, 0); bytes[start..start + path.len()].copy_from_slice(path); bytes } fn write_header(bytes: &mut [u8], phnum: u16, entry: u64) { - bytes[..64].fill(0); - bytes[..7].copy_from_slice(b"\x7fELF\x02\x01\x01"); - bytes[16..18].copy_from_slice(&abi::ET_DYN.to_le_bytes()); - bytes[18..20].copy_from_slice(&MACHINE.to_le_bytes()); - bytes[20..24].copy_from_slice(&1_u32.to_le_bytes()); - bytes[24..32].copy_from_slice(&entry.to_le_bytes()); - bytes[32..40].copy_from_slice(&64_u64.to_le_bytes()); - bytes[52..54].copy_from_slice(&64_u16.to_le_bytes()); - bytes[54..56].copy_from_slice(&56_u16.to_le_bytes()); - bytes[56..58].copy_from_slice(&phnum.to_le_bytes()); + let out = &mut bytes[..EHDR_SIZE]; + out.fill(0); + out[0..7].copy_from_slice(b"\x7fELF\x02\x01\x01"); + out[16..18].copy_from_slice(&abi::ET_DYN.to_le_bytes()); + out[18..20].copy_from_slice(&MACHINE.to_le_bytes()); + out[20..24].copy_from_slice(&1_u32.to_le_bytes()); + out[24..32].copy_from_slice(&entry.to_le_bytes()); + out[32..40].copy_from_slice(&u64::try_from(EHDR_SIZE).unwrap().to_le_bytes()); + out[52..54].copy_from_slice(&u16::try_from(EHDR_SIZE).unwrap().to_le_bytes()); + out[54..56].copy_from_slice(&u16::try_from(PHDR_SIZE).unwrap().to_le_bytes()); + out[56..58].copy_from_slice(&phnum.to_le_bytes()); } fn load( @@ -268,15 +307,17 @@ fn load( flags: u32, page: usize, ) { - let header = &mut bytes[64 + index * 56..64 + index * 56 + 56]; - header.fill(0); - header[..4].copy_from_slice(&abi::PT_LOAD.to_le_bytes()); - header[4..8].copy_from_slice(&flags.to_le_bytes()); - for (field, value) in - [(8, start), (16, start), (32, file_size), (40, memory_size), (48, 2 * page)] - { - header[field..field + 8].copy_from_slice(&u64::try_from(value).unwrap().to_le_bytes()); + let addr = u64::try_from(start).unwrap(); + Phdr { + p_type: abi::PT_LOAD, + p_flags: flags, + p_offset: addr, + p_vaddr: addr, + p_filesz: u64::try_from(file_size).unwrap(), + p_memsz: u64::try_from(memory_size).unwrap(), + p_align: u64::try_from(2 * page).unwrap(), } + .write_to(bytes, index); } fn map_bytes(bytes: &[u8]) -> Image { diff --git a/crates/fspy_elf_loader_tests/tests/exec_elf.rs b/crates/fspy_elf_loader_tests/tests/exec_elf.rs index 80f7c7ca2..0b95b4e19 100644 --- a/crates/fspy_elf_loader_tests/tests/exec_elf.rs +++ b/crates/fspy_elf_loader_tests/tests/exec_elf.rs @@ -4,6 +4,7 @@ use std::{ ffi::OsStr, + mem::{offset_of, size_of}, os::unix::{ffi::OsStrExt as _, process::CommandExt as _}, process::{Command, Output, Stdio}, }; @@ -134,11 +135,14 @@ fn rejects_fixed_image_overlapping_launcher() { .collect(); let base = loads[0].1.p_vaddr; let entry = parsed.ehdr.e_entry - base + launcher_base; - bytes[24..32].copy_from_slice(&entry.to_le_bytes()); + write_u64(&mut bytes, offset_of!(libc::Elf64_Ehdr, e_entry), entry); for (index, ph) in loads { - let offset = table + index * 56 + 16; - bytes[offset..offset + 8] - .copy_from_slice(&(ph.p_vaddr - base + launcher_base).to_le_bytes()); + let phdr_offset = table + index * size_of::(); + write_u64( + &mut bytes, + phdr_offset + offset_of!(libc::Elf64_Phdr, p_vaddr), + ph.p_vaddr - base + launcher_base, + ); } let file = tempfile::NamedTempFile::new().unwrap(); std::fs::write(file.path(), bytes).unwrap(); @@ -179,24 +183,24 @@ fn node_runs_javascript() { #[test] #[timeout(10_000)] fn rejects_malformed_images() { - let echo = std::fs::read("/bin/echo").unwrap(); - let mut overflow = echo.clone(); - overflow[32..40].copy_from_slice(&u64::MAX.to_le_bytes()); - let mut wrong_machine = echo.clone(); - wrong_machine[18..20].copy_from_slice(&0_u16.to_le_bytes()); - let mut unsupported_type = echo.clone(); - unsupported_type[16..18].copy_from_slice(&elf::abi::ET_REL.to_le_bytes()); - let parsed = elf::ElfBytes::::minimal_parse(&echo).unwrap(); + let base = std::fs::read(FIXTURE_DYN_PIE).unwrap(); + let mut overflow = base.clone(); + write_u64(&mut overflow, offset_of!(libc::Elf64_Ehdr, e_phoff), u64::MAX); + let mut wrong_machine = base.clone(); + write_u16(&mut wrong_machine, offset_of!(libc::Elf64_Ehdr, e_machine), 0); + let mut unsupported_type = base.clone(); + write_u16(&mut unsupported_type, offset_of!(libc::Elf64_Ehdr, e_type), elf::abi::ET_REL); + let parsed = elf::ElfBytes::::minimal_parse(&base).unwrap(); let load = parsed.segments().unwrap().iter().position(|ph| ph.p_type == elf::abi::PT_LOAD).unwrap(); - let header = usize::try_from(parsed.ehdr.e_phoff).unwrap() + load * 56; - let mut invalid_size = echo.clone(); - invalid_size[header + 32..header + 40].copy_from_slice(&u64::MAX.to_le_bytes()); - let mut invalid_alignment = echo.clone(); - invalid_alignment[header + 48..header + 56].copy_from_slice(&3_u64.to_le_bytes()); + let phdr = usize::try_from(parsed.ehdr.e_phoff).unwrap() + load * size_of::(); + let mut invalid_size = base.clone(); + write_u64(&mut invalid_size, phdr + offset_of!(libc::Elf64_Phdr, p_filesz), u64::MAX); + let mut invalid_alignment = base.clone(); + write_u64(&mut invalid_alignment, phdr + offset_of!(libc::Elf64_Phdr, p_align), 3); for (case, bytes) in [ ("truncated header", b"not ELF".to_vec()), - ("truncated program headers", echo[..64].to_vec()), + ("truncated program headers", base[..size_of::()].to_vec()), ("overflowing program-header offset", overflow), ("wrong architecture", wrong_machine), ("unsupported type", unsupported_type), @@ -219,16 +223,24 @@ fn rejects_malformed_images() { #[test] #[timeout(10_000)] fn does_not_require_section_headers() { - let mut bytes = std::fs::read("/bin/echo").unwrap(); + let mut bytes = std::fs::read(FIXTURE_DYN_PIE).unwrap(); // The ELF loader must not use section metadata, even if it is unusable. - bytes[40..48].copy_from_slice(&u64::MAX.to_le_bytes()); + write_u64(&mut bytes, offset_of!(libc::Elf64_Ehdr, e_shoff), u64::MAX); let file = tempfile::NamedTempFile::new().unwrap(); std::fs::write(file.path(), bytes).unwrap(); + let path = file.path().to_str().unwrap(); let mut command = launcher(); - command.arg(file.path()).args(["echo", "without-sections"]); + command.args([path, "custom-argv-zero", ""]).arg(OsStr::from_bytes(b"\xff")); + command + .env_clear() + .env("FIXTURE_IMAGE", path) + .env("EMPTY", "") + .env("BYTES", OsStr::from_bytes(b"\xff")) + .env("EXPECT_INTERPRETER", "1"); let output = output(command); - assert_eq!(output.status.code(), Some(0), "{output:?}"); - assert_eq!(output.stdout, b"without-sections\n"); + assert_eq!(output.status.code(), Some(37), "{output:?}"); + assert_eq!(output.stdout, b"runtime-ok\n"); + assert!(output.stderr.is_empty(), "{output:?}"); } #[test] @@ -257,6 +269,14 @@ fn assert_image(path: &str, image_type: u16, interpreter: bool) { assert_eq!(has_interp, interpreter, "unexpected PT_INTERP: {path}"); } +fn write_u16(bytes: &mut [u8], offset: usize, value: u16) { + bytes[offset..offset + size_of::()].copy_from_slice(&value.to_le_bytes()); +} + +fn write_u64(bytes: &mut [u8], offset: usize, value: u64) { + bytes[offset..offset + size_of::()].copy_from_slice(&value.to_le_bytes()); +} + fn output(mut command: Command) -> Output { command.stdin(Stdio::null()).output().expect("cannot run freestanding launcher") } From 1453b7bec597b64b10d7d35083466f8ed2308bb9 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 17:55:06 +0800 Subject: [PATCH 26/34] test(fspy-elf-loader): remove redundant Rust runtime fixture binary 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 --- crates/fspy_elf_loader_tests/Cargo.toml | 4 +- .../fspy_elf_loader_tests/src/bin/fixture.rs | 88 ------------------- .../fspy_elf_loader_tests/tests/exec_elf.rs | 7 -- 3 files changed, 1 insertion(+), 98 deletions(-) delete mode 100644 crates/fspy_elf_loader_tests/src/bin/fixture.rs diff --git a/crates/fspy_elf_loader_tests/Cargo.toml b/crates/fspy_elf_loader_tests/Cargo.toml index bc9a71b1f..11eace9f5 100644 --- a/crates/fspy_elf_loader_tests/Cargo.toml +++ b/crates/fspy_elf_loader_tests/Cargo.toml @@ -14,12 +14,10 @@ cc = { workspace = true } elf = { workspace = true } [target.'cfg(target_os = "linux")'.dev-dependencies] +libc = { workspace = true } ntest = { workspace = true } tempfile = { workspace = true } -[target.'cfg(target_os = "linux")'.dependencies] -libc = { workspace = true } - [target.'cfg(target_arch = "aarch64")'.dev-dependencies] fspy_elf_loader_test_launcher = { path = "../fspy_elf_loader_test_launcher", artifact = "bin", target = "aarch64-unknown-none-softfloat" } diff --git a/crates/fspy_elf_loader_tests/src/bin/fixture.rs b/crates/fspy_elf_loader_tests/src/bin/fixture.rs deleted file mode 100644 index 6b99288e2..000000000 --- a/crates/fspy_elf_loader_tests/src/bin/fixture.rs +++ /dev/null @@ -1,88 +0,0 @@ -#[cfg(not(target_os = "linux"))] -const fn main() {} - -#[cfg(target_os = "linux")] -fn main() { - use std::{ - cell::Cell, - io::Write as _, - os::unix::ffi::OsStrExt as _, - sync::atomic::{AtomicU8, Ordering}, - }; - - static BSS: [AtomicU8; 128 * 1024] = [const { AtomicU8::new(0) }; 128 * 1024]; - static DATA: AtomicU8 = AtomicU8::new(42); - thread_local! { static TLS: Cell = const { Cell::new(17) }; } - - let args: Vec<_> = std::env::args_os().collect(); - assert_eq!(args.len(), 3); - assert_eq!(args[0], "custom-argv-zero"); - assert_eq!(args[1], ""); - assert_eq!(args[2].as_bytes(), b"\xff"); - assert_eq!(std::env::var_os("EMPTY").unwrap(), ""); - assert_eq!(std::env::var_os("BYTES").unwrap().as_bytes(), b"\xff"); - for byte in &BSS { - assert_eq!(byte.load(Ordering::Relaxed), 0); - } - BSS[BSS.len() - 1].store(9, Ordering::Relaxed); - assert_eq!(DATA.swap(43, Ordering::Relaxed), 42); - TLS.set(23); - let values = std::thread::spawn(|| { - assert_eq!(TLS.get(), 17); - vec![7_u8; 128 * 1024] - }) - .join() - .unwrap(); - assert!(values.iter().all(|value| *value == 7)); - assert_eq!(TLS.get(), 23); - - // SAFETY: successful runtime startup supplies readable auxiliary data. - unsafe { - let execfn = aux(libc::AT_EXECFN); - let execfn = std::ffi::CStr::from_ptr(std::ptr::with_exposed_provenance(execfn)); - assert_eq!(execfn.to_bytes(), std::env::var_os("FIXTURE_IMAGE").unwrap().as_bytes()); - assert_eq!(aux(libc::AT_PHENT), size_of::()); - let headers = std::slice::from_raw_parts( - std::ptr::with_exposed_provenance::(aux(libc::AT_PHDR)), - aux(libc::AT_PHNUM), - ); - let phdr = headers.iter().find(|ph| ph.p_type == libc::PT_PHDR).unwrap(); - let bias = aux(libc::AT_PHDR).checked_sub(usize::try_from(phdr.p_vaddr).unwrap()).unwrap(); - if std::env::var_os("EXPECT_FIXED_ADDRESS").is_some() { - assert_eq!(bias, 0, "fixed-address executable was relocated"); - } - let entry = aux(libc::AT_ENTRY); - assert!(headers.iter().any(|ph| { - ph.p_type == libc::PT_LOAD - && ph.p_flags & libc::PF_X != 0 - && (bias + usize::try_from(ph.p_vaddr).unwrap() - ..bias + usize::try_from(ph.p_vaddr + ph.p_memsz).unwrap()) - .contains(&entry) - })); - let base = aux(libc::AT_BASE); - if base != 0 { - let interpreter = - std::slice::from_raw_parts(std::ptr::with_exposed_provenance::(base), 4); - assert_eq!(interpreter, b"\x7fELF"); - } - let random = std::slice::from_raw_parts( - std::ptr::with_exposed_provenance::(aux(libc::AT_RANDOM)), - 16, - ); - assert!(random.iter().any(|byte| *byte != 0)); - } - let image = std::env::var_os("FIXTURE_IMAGE").unwrap(); - for entry in std::fs::read_dir("/proc/self/fd").unwrap() { - if let Ok(path) = std::fs::read_link(entry.unwrap().path()) { - assert_ne!(path.as_os_str(), image, "executable fd leaked"); - } - } - std::io::stdout().write_all(b"runtime-ok\n").unwrap(); - std::process::exit(37); -} - -#[cfg(target_os = "linux")] -fn aux(key: libc::c_ulong) -> usize { - // SAFETY: libc is initialized and getauxval only reads its startup data. - usize::try_from(unsafe { libc::getauxval(key) }).unwrap() -} diff --git a/crates/fspy_elf_loader_tests/tests/exec_elf.rs b/crates/fspy_elf_loader_tests/tests/exec_elf.rs index 0b95b4e19..8c6bd84f9 100644 --- a/crates/fspy_elf_loader_tests/tests/exec_elf.rs +++ b/crates/fspy_elf_loader_tests/tests/exec_elf.rs @@ -12,7 +12,6 @@ use std::{ use ntest::timeout; const LAUNCHER: &str = env!("CARGO_BIN_FILE_FSPY_ELF_LOADER_TEST_LAUNCHER"); -const FIXTURE_RUST: &str = env!("CARGO_BIN_EXE_fixture"); const FIXTURE_DYN_PIE: &str = env!("FIXTURE_DYN_PIE"); const FIXTURE_DYN_EXEC: &str = env!("FIXTURE_DYN_EXEC"); const FIXTURE_STATIC_EXEC: &str = env!("FIXTURE_STATIC_EXEC"); @@ -47,12 +46,6 @@ fn echo_preserves_empty_and_non_utf8_arguments() { assert!(output.stderr.is_empty()); } -#[test] -#[timeout(10_000)] -fn initializes_rust_std_runtime() { - check_runtime_image(FIXTURE_RUST, elf::abi::ET_DYN, true); -} - #[test] #[timeout(10_000)] fn initializes_dynamic_pie_runtime() { From f3573f4bc73cb3b8f3dc2743e85a5cb60c111698 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 17:55:07 +0800 Subject: [PATCH 27/34] ci(fspy-elf-loader): run release loader tests and bare-metal clippy 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 --- .github/workflows/ci.yml | 10 ++++++++++ crates/fspy_elf_loader_tests/README.md | 10 +++++----- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f46d41f44..e7d508cca 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -66,6 +66,9 @@ jobs: # --locked: verify Cargo.lock is up to date (replaces the removed `cargo check --locked`) - run: cargo clippy --locked --all-targets --all-features -- -D warnings + - run: | + cargo clippy --locked -p fspy_elf_loader -p fspy_elf_loader_test_launcher --target x86_64-unknown-none -- -D warnings + cargo clippy --locked -p fspy_elf_loader -p fspy_elf_loader_test_launcher --target aarch64-unknown-none-softfloat -- -D warnings # fspy builds only on Windows, macOS, and Linux, but vp must still build # without it on other platforms. Cross-building `vt_bin` for FreeBSD catches @@ -149,6 +152,10 @@ jobs: - name: Run tests run: $TEST_CARGO_CMD test --target $TEST_BUILD_TARGET + - name: Run ELF loader tests (release) + if: ${{ env.TEST_TARGET == 'x86_64-unknown-linux-gnu' }} + run: $TEST_CARGO_CMD test --release -p fspy_elf_loader_tests --target $TEST_BUILD_TARGET + # x86_64-apple-darwin runs on arm64 runner under Rosetta; install x64 Node # so fspy's x86_64 preload dylib can be injected into spawned node procs. - uses: oxc-project/setup-node@f46a72f95efdc55273fcd042d61c84e723b2892c # v1.4.1 @@ -378,6 +385,9 @@ jobs: - name: Run tests run: cargo test + - name: Run ELF loader tests (release) + run: cargo test --release -p fspy_elf_loader_tests + - uses: oxc-project/setup-node@f46a72f95efdc55273fcd042d61c84e723b2892c # v1.4.1 - name: Run ignored tests diff --git a/crates/fspy_elf_loader_tests/README.md b/crates/fspy_elf_loader_tests/README.md index 33db4fc0f..7401bebe8 100644 --- a/crates/fspy_elf_loader_tests/README.md +++ b/crates/fspy_elf_loader_tests/README.md @@ -1,19 +1,19 @@ # fspy_elf_loader_tests -Integration tests for [`fspy_elf_loader`](../fspy_elf_loader/README.md). +Integration tests for [`fspy_elf_loader`](../fspy_elf_loader/README.md), executed via the freestanding [`fspy_elf_loader_test_launcher`](../fspy_elf_loader_test_launcher/src/main.rs) binary. The tests check whether programs start and behave as expected through the custom loader. They help catch compatibility regressions as its scope grows. -The default suite covers dynamic and static PIE and fixed-address executables, including rejection of a target overlapping the launcher. Static fixtures are compiled with `cc -static` and `cc -static-pie`. With Node.js on `PATH`, run `cargo test -p fspy_elf_loader_tests -- --include-ignored` on Linux to also compare a real Node program with normal execution. +The default suite compiles a unified C runtime fixture (`fixtures/runtime.c`) across all four ELF64 cells — dynamic PIE, dynamic fixed-address (`ET_EXEC`), static fixed-address, and static-PIE — and compares each fixture differentially against direct kernel `execve`. It also covers rejection of a target overlapping the launcher, malformed ELF images, and stripped section headers. With Node.js on `PATH`, run `cargo test -p fspy_elf_loader_tests -- --include-ignored` on Linux to also compare a real Node program with normal execution. The launcher artifact is checked on every host for a static fixed-address layout at 85 TiB on x86-64 or 8 GiB on AArch64, with no dynamic relocation requirements. The collision test checks that the launcher still reports the -expected error after rejecting an overlapping target. Run the Linux suite in -both debug and release profiles. +expected error after rejecting an overlapping target. CI runs the Linux suite +in both debug and release profiles (glibc and musl). ## Scope This crate covers program execution and loading failures in Linux processes. Unit tests for individual loader components stay in `fspy_elf_loader`. -Keeping integration tests in a separate crate lets us use the normal Rust test runtime without adding it to the loader. The tests validate the loader itself; full fspy interception remains outside their scope. +Keeping the freestanding test launcher and integration tests in separate crates keeps `fspy_elf_loader` a pure `#![no_std]` library while letting integration tests use the normal Rust test runtime. The tests validate the loader itself; full fspy interception remains outside their scope. From 8fbfe09f39931866707a9176fd2ee94a5de60095 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 18:11:42 +0800 Subject: [PATCH 28/34] refactor(fspy-elf-loader): share ELF size constants and simplify retain, 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 --- crates/fspy_elf_loader/src/image.rs | 12 ++++++++---- crates/fspy_elf_loader/src/image/tests.rs | 5 +---- crates/fspy_elf_loader/src/mapping.rs | 4 +--- crates/fspy_elf_loader_test_launcher/build.rs | 2 +- crates/fspy_elf_loader_tests/fixtures/runtime.c | 10 ++++------ 5 files changed, 15 insertions(+), 18 deletions(-) diff --git a/crates/fspy_elf_loader/src/image.rs b/crates/fspy_elf_loader/src/image.rs index 870f2ad7f..d5c844d75 100644 --- a/crates/fspy_elf_loader/src/image.rs +++ b/crates/fspy_elf_loader/src/image.rs @@ -26,6 +26,9 @@ use crate::mapping::{Mapping, add, align_up, sub, word}; #[cfg(test)] mod tests; +pub const EHDR_SIZE: usize = 64; +pub const PHDR_SIZE: usize = 56; + #[cfg(target_arch = "aarch64")] const MACHINE: u16 = abi::EM_AARCH64; #[cfg(target_arch = "x86_64")] @@ -65,7 +68,7 @@ impl File { pub fn new(fd: OwnedFd) -> Self { let len = usize::try_from(fs::fstat(fd.as_fd()).expect("cannot stat ELF").st_size) .expect("invalid ELF file size"); - assert!(len >= 64, "truncated ELF header"); + assert!(len >= EHDR_SIZE, "truncated ELF header"); let view = Mapping::file(fd.as_fd(), len); // SAFETY: this is the unchanged, read-only file view. let bytes = unsafe { view.bytes() }; @@ -74,7 +77,8 @@ impl File { // loading these images needs only the separate program-header table. let ident = file::parse_ident::(&bytes[..16]).expect("invalid ELF identity"); assert_eq!(ident.1, Class::ELF64, "only ELF64 is supported"); - let header = FileHeader::parse_tail(ident, &bytes[16..64]).expect("invalid ELF header"); + let header = + FileHeader::parse_tail(ident, &bytes[16..EHDR_SIZE]).expect("invalid ELF header"); assert_eq!(header.e_machine, MACHINE, "ELF architecture mismatch"); // ET_DYN permits a load bias chosen for the available address space. // Position-independent executables (PIE) and their interpreters use it. @@ -84,7 +88,7 @@ impl File { "only ET_DYN and ET_EXEC images are supported" ); assert_eq!(header.version, u32::from(abi::EV_CURRENT), "invalid ELF version"); - assert_eq!(header.e_phentsize, 56, "invalid program-header size"); + assert_eq!(usize::from(header.e_phentsize), PHDR_SIZE, "invalid program-header size"); // 0xffff is an escape to a count stored in section metadata. This MVP // accepts only counts carried in the ELF header itself. assert!( @@ -92,7 +96,7 @@ impl File { "unsupported program-header count" ); let start = word(header.e_phoff); - let end = add(start, usize::from(header.e_phnum) * 56); + let end = add(start, usize::from(header.e_phnum) * PHDR_SIZE); assert!(bytes.get(start..end).is_some(), "truncated program headers"); Self { fd, view, header, headers: start..end } } diff --git a/crates/fspy_elf_loader/src/image/tests.rs b/crates/fspy_elf_loader/src/image/tests.rs index 3b57d8157..42d0d5673 100644 --- a/crates/fspy_elf_loader/src/image/tests.rs +++ b/crates/fspy_elf_loader/src/image/tests.rs @@ -17,7 +17,7 @@ fn check_bss(page: usize, flags: u32, expected_protection: &str) { let bytes = fixture(page, memory_size, flags); let image = map_bytes(&bytes); assert_eq!(image.bias % (2 * page), 0); - assert_eq!(image.phdr, Some(image.bias + 64)); + assert_eq!(image.phdr, Some(image.bias + EHDR_SIZE)); let maps = std::fs::read_to_string("/proc/self/maps").unwrap(); let protection = |address| { maps.lines() @@ -236,9 +236,6 @@ fn fixture(page: usize, memory_size: usize, flags: u32) -> std::vec::Vec { bytes } -const EHDR_SIZE: usize = 64; -const PHDR_SIZE: usize = 56; - #[expect(clippy::struct_field_names, reason = "matches ELF64 Elf64_Phdr field names")] struct Phdr { p_type: u32, diff --git a/crates/fspy_elf_loader/src/mapping.rs b/crates/fspy_elf_loader/src/mapping.rs index f592af0d1..9d63f8d0e 100644 --- a/crates/fspy_elf_loader/src/mapping.rs +++ b/crates/fspy_elf_loader/src/mapping.rs @@ -105,12 +105,10 @@ impl Mapping { unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len) } } - pub const fn retain(self) -> *mut u8 { + pub const fn retain(self) { // Switching SP or jumping does not transfer Rust ownership. Suppress // Drop here so it cannot release memory needed after the handoff. - let ptr = self.ptr.as_ptr(); core::mem::forget(self); - ptr } } diff --git a/crates/fspy_elf_loader_test_launcher/build.rs b/crates/fspy_elf_loader_test_launcher/build.rs index 368cac7ba..99b5bec3c 100644 --- a/crates/fspy_elf_loader_test_launcher/build.rs +++ b/crates/fspy_elf_loader_test_launcher/build.rs @@ -12,7 +12,7 @@ fn main() { }; // Fixed linking resolves pointers without a startup self-relocator. for argument in ["--no-pie", image_base] { - println!("cargo::rustc-link-arg-bin=fspy_elf_loader_test_launcher={argument}"); + println!("cargo::rustc-link-arg={argument}"); } } } diff --git a/crates/fspy_elf_loader_tests/fixtures/runtime.c b/crates/fspy_elf_loader_tests/fixtures/runtime.c index f20b0fc14..167282321 100644 --- a/crates/fspy_elf_loader_tests/fixtures/runtime.c +++ b/crates/fspy_elf_loader_tests/fixtures/runtime.c @@ -56,18 +56,16 @@ static unsigned long load_bias(unsigned long at_phdr, unsigned long phnum, const } } /* GNU ld omits PT_PHDR on some static images. ELF64 headers start at 0. */ - unsigned char *ehdr = (unsigned char *)(at_phdr - 64); - if (ehdr[0] != 0x7f || ehdr[1] != 'E' || ehdr[2] != 'L' || ehdr[3] != 'F') { + const Elf64_Ehdr *ehdr = (const Elf64_Ehdr *)(at_phdr - sizeof *ehdr); + if (memcmp(ehdr->e_ident, ELFMAG, SELFMAG) != 0) { fail("elf header"); } - unsigned long e_phoff; - memcpy(&e_phoff, ehdr + 32, sizeof e_phoff); - if (e_phoff != 64) { + if (ehdr->e_phoff != sizeof *ehdr) { fail("e_phoff"); } for (i = 0; i < phnum; i++) { if (ph[i].p_type == PT_LOAD && ph[i].p_offset == 0) { - return at_phdr - e_phoff - (unsigned long)ph[i].p_vaddr; + return at_phdr - (unsigned long)ehdr->e_phoff - (unsigned long)ph[i].p_vaddr; } } fail("no load at file start"); From 3e278861664b86351c783c9b9d0492edfb48ff11 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 18:11:42 +0800 Subject: [PATCH 29/34] refactor(fspy-elf-loader): stage startup pointer table in stack mapping 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 --- crates/fspy_elf_loader/Cargo.toml | 6 +- crates/fspy_elf_loader/src/lib.rs | 3 - crates/fspy_elf_loader/src/stack.rs | 86 ++++++++++++++++++----------- crates/fspy_nostd/src/param.rs | 18 +----- 4 files changed, 57 insertions(+), 56 deletions(-) diff --git a/crates/fspy_elf_loader/Cargo.toml b/crates/fspy_elf_loader/Cargo.toml index 1d6f14a93..154943b2f 100644 --- a/crates/fspy_elf_loader/Cargo.toml +++ b/crates/fspy_elf_loader/Cargo.toml @@ -7,13 +7,9 @@ license.workspace = true publish.workspace = true rust-version.workspace = true -[dependencies] -allocator-api2 = { workspace = true, features = ["alloc"] } +[target.'cfg(any(target_os = "linux", target_os = "none"))'.dependencies] elf = { workspace = true } fspy_nostd = { workspace = true } -fspy_nostd_alloc = { workspace = true } - -[target.'cfg(any(target_os = "linux", target_os = "none"))'.dependencies] linux-raw-sys = { workspace = true, features = ["auxvec", "no_std"] } [target.'cfg(target_os = "linux")'.dev-dependencies] diff --git a/crates/fspy_elf_loader/src/lib.rs b/crates/fspy_elf_loader/src/lib.rs index 2870e13d5..8125f6919 100644 --- a/crates/fspy_elf_loader/src/lib.rs +++ b/crates/fspy_elf_loader/src/lib.rs @@ -87,9 +87,6 @@ pub unsafe fn exec_elf<'a>( .expect("missing AT_PAGESZ") .value; assert!(page_size.is_power_of_two(), "invalid AT_PAGESZ"); - // Seed fspy_nostd's page-size cache from AT_PAGESZ so temporary stack - // allocations via PageBump do not trigger a redundant 2 MiB probe mapping. - fspy_nostd::param::seed_page_size(page_size); let executable = image::File::new(elf_file); // PT_INTERP names a second ELF file. Loading it here lets us delegate // dynamic linking and libc startup to the program's own interpreter. diff --git a/crates/fspy_elf_loader/src/stack.rs b/crates/fspy_elf_loader/src/stack.rs index 52f9252a2..67752906d 100644 --- a/crates/fspy_elf_loader/src/stack.rs +++ b/crates/fspy_elf_loader/src/stack.rs @@ -6,26 +6,28 @@ //! The auxiliary vector lets the interpreter and libc //! discover image addresses and process properties before runtime startup. //! -//! We copy strings and known auxiliary payloads into the same mapping. Build -//! the pointer table in a temporary vector and payloads downward, then copy -//! the table next to the payloads. Argument and environment pointers are -//! collected first so their strings can be copied in reverse order, preserving -//! Linux's ascending, contiguous string layout. This consumes iterators once. +//! We copy strings and known auxiliary payloads into the same mapping. Stage +//! the pointer table upward from the bottom of the writable region and payloads +//! downward from the top, then shift the table up next to the payloads. +//! Argument and environment pointers are collected first so their strings can +//! be copied in reverse order, preserving Linux's ascending, contiguous string +//! layout. This consumes iterators once without any heap allocator. -use core::{mem::size_of, ptr}; +use core::{ + mem::{align_of, size_of}, + ptr, +}; -use allocator_api2::vec::Vec; use fspy_nostd::{ CStr, Thin, env::AuxEntry, mm::{self, MprotectFlags}, }; -use fspy_nostd_alloc::{PageBump, page_bump}; use linux_raw_sys::auxvec as abi; use crate::{ - image::Image, - mapping::{Mapping, add}, + image::{Image, PHDR_SIZE}, + mapping::{Mapping, add, sub}, }; // Includes startup data and room for the target's downward-growing call stack. @@ -38,14 +40,15 @@ const MIN_STACK_HEADROOM: usize = 64 * 1024; struct Builder { mapping: Mapping, - // Offsets from mapping.ptr: first usable byte and payload start. + // Offsets from mapping.ptr: first usable byte, staged word count, and payload start. start: usize, - words: Vec, + word_count: usize, strings: usize, } impl Builder { fn new(page: usize) -> Self { + assert!(page.is_multiple_of(align_of::()), "invalid page size"); let mapping = Mapping::reserve(add(CAPACITY, page)); // Keep the low page inaccessible so an overflow reaching it faults // instead of writing into a neighboring mapping. @@ -59,17 +62,37 @@ impl Builder { ) } .expect("cannot map target stack"); - Self { strings: mapping.len, mapping, start: page, words: Vec::new_in(page_bump()) } + Self { strings: mapping.len, mapping, start: page, word_count: 0 } + } + + const fn table_len(&self) -> usize { + self.word_count.checked_mul(size_of::()).expect("initial stack exceeds capacity") + } + + const fn table_end(&self) -> usize { + add(self.start, self.table_len()) + } + + #[expect(clippy::cast_ptr_alignment, reason = "mapping base and start offset are page-aligned")] + const unsafe fn words_ptr(&self) -> *mut usize { + // SAFETY: `self.start` is a page boundary inside `self.mapping`, + // which is strictly aligned for `usize`. + unsafe { self.mapping.ptr.as_ptr().add(self.start).cast::() } + } + + const fn words_mut(&mut self) -> &mut [usize] { + // SAFETY: `self.words_ptr()` is `usize`-aligned, and the staged words + // were exclusively written by `push`, disjoint from `[self.strings, mapping.len)`. + unsafe { core::slice::from_raw_parts_mut(self.words_ptr(), self.word_count) } } fn push(&mut self, value: usize) { let end = add(self.table_end(), size_of::()); assert!(end <= self.strings, "initial stack exceeds capacity"); - self.words.push(value); - } - - fn table_end(&self) -> usize { - add(self.start, size_of_val(self.words.as_slice())) + // SAFETY: `self.word_count` lies inside the writable staged region + // below `self.strings` and is unaliased. + unsafe { self.words_ptr().add(self.word_count).write(value) }; + self.word_count = add(self.word_count, 1); } fn copy(&mut self, bytes: &[u8]) -> usize { @@ -99,15 +122,15 @@ impl Builder { argv: impl Iterator>, envp: impl Iterator>, ) { - let argc_slot = self.words.len(); + let argc_slot = self.word_count; self.push(0); - let pointers_start = self.words.len(); + let pointers_start = self.word_count; let mut argument_count = 0_usize; for arg in argv { self.push(arg.as_ptr().expose_provenance()); argument_count = add(argument_count, 1); } - self.words[argc_slot] = argument_count; + self.words_mut()[argc_slot] = argument_count; self.push(0); for env in envp { self.push(env.as_ptr().expose_provenance()); @@ -118,15 +141,15 @@ impl Builder { // the last environment entry back to argv[0], because allocation grows // downward. The result is contiguous argv strings followed by envp. // libuv relies on this layout when updating the process title. - for index in (pointers_start..self.words.len()).rev() { - let source = self.words[index]; + for index in (pointers_start..self.word_count).rev() { + let source = self.words_mut()[index]; if source == 0 { continue; } // SAFETY: nonzero slots came from the CStr values above, whose // original storage remains valid for 'a while we copy it. let string = unsafe { CStr::from_ptr(ptr::with_exposed_provenance(source)) }; - self.words[index] = self.string(string); + self.words_mut()[index] = self.string(string); } } @@ -141,17 +164,18 @@ impl Builder { // ^ new SP, aligned to 16 bytes // Keeping the table near the top leaves room below SP for calls. Only // table bytes move: its pointers already name the final payloads. - let len = size_of_val(self.words.as_slice()); + let len = self.table_len(); let start = self.strings.checked_sub(len).expect("initial stack exceeds capacity") & !15; assert!(start >= add(self.start, MIN_STACK_HEADROOM), "initial stack exceeds capacity"); - // The temporary vector and its owned bump are dropped before handoff. - // SAFETY: the initialized vector and writable destination are disjoint. - // The checked destination fits below the strings. The result is - // aligned to the process-entry ABI and retains the complete mapping. + // SAFETY: both staged source and final destination lie inside the + // writable region of `self.mapping` below `self.strings`; `ptr::copy` + // handles any overlap. Zero the vacated staging prefix below SP. unsafe { let base = self.mapping.ptr.as_ptr(); + let source = base.add(self.start); let target = base.add(start); - ptr::copy_nonoverlapping(self.words.as_ptr().cast::(), target, len); + ptr::copy(source, target, len); + ptr::write_bytes(source, 0, len.min(sub(start, self.start))); self.mapping.retain(); target.cast() } @@ -215,7 +239,7 @@ pub unsafe fn build<'a>( // is its startup address. With PT_INTERP we enter the interpreter first // and BASE is that image's load bias. Without one, BASE is 0 as on Linux. stack.aux(abi::AT_PHDR, image.phdr.expect("program headers are not mapped by PT_LOAD")); - stack.aux(abi::AT_PHENT, 56); + stack.aux(abi::AT_PHENT, PHDR_SIZE); stack.aux(abi::AT_PHNUM, image.phnum); stack.aux(abi::AT_ENTRY, image.entry); stack.aux(abi::AT_BASE, interpreter.map_or(0, |image| image.bias)); diff --git a/crates/fspy_nostd/src/param.rs b/crates/fspy_nostd/src/param.rs index c8c2fc45c..c94709a81 100644 --- a/crates/fspy_nostd/src/param.rs +++ b/crates/fspy_nostd/src/param.rs @@ -13,7 +13,7 @@ //! anyway, it calls `sysconf` directly. #[cfg(any(target_os = "linux", target_os = "none"))] -pub use linux::{page_size, seed_page_size}; +pub use linux::page_size; #[cfg(target_os = "macos")] pub use mac::page_size; @@ -35,18 +35,6 @@ mod linux { static CACHE: AtomicUsize = AtomicUsize::new(0); - /// Seeds the cached page size when the caller already knows it (for - /// example, from `AT_PAGESZ` in the Linux auxiliary vector). - /// - /// Ignores zero or non-power-of-two values, and never overwrites an - /// already-cached page size. Once seeded, [`page_size`] returns the cached - /// value without running the `mmap`/`mprotect` probe. - pub fn seed_page_size(page: usize) { - if page.is_power_of_two() { - let _ = CACHE.compare_exchange(0, page, Ordering::Relaxed, Ordering::Relaxed); - } - } - /// Returns the size of a memory page, or 0 if it cannot be determined. /// /// Discovered from the kernel with a handful of raw syscalls, once per @@ -140,10 +128,6 @@ mod linux { #[test] fn probe_is_stable_and_cached() { let probed = probe_page_size(); - seed_page_size(0); - seed_page_size(3); - seed_page_size(probed); - seed_page_size(probed * 2); assert_eq!(probed, page_size()); assert_eq!(page_size(), page_size()); #[cfg(target_arch = "x86_64")] From 5788cfbad351259a0fd87632669e5e4bf0a967bb Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 18:11:43 +0800 Subject: [PATCH 30/34] refactor(fspy-elf-loader): drop cc build-dep in favor of direct env lookup Resolve the C compiler directly from `CC_`, `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 --- Cargo.lock | 3 -- crates/fspy_elf_loader_tests/Cargo.toml | 3 -- crates/fspy_elf_loader_tests/build.rs | 49 ++++++++++++------------- 3 files changed, 23 insertions(+), 32 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8b368cd9e..6a5597c97 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1472,10 +1472,8 @@ dependencies = [ name = "fspy_elf_loader" version = "0.1.0" dependencies = [ - "allocator-api2", "elf", "fspy_nostd", - "fspy_nostd_alloc", "linux-raw-sys 0.12.1", "tempfile", ] @@ -1492,7 +1490,6 @@ dependencies = [ name = "fspy_elf_loader_tests" version = "0.0.0" dependencies = [ - "cc", "elf", "fspy_elf_loader_test_launcher", "libc", diff --git a/crates/fspy_elf_loader_tests/Cargo.toml b/crates/fspy_elf_loader_tests/Cargo.toml index 11eace9f5..0e7c174bb 100644 --- a/crates/fspy_elf_loader_tests/Cargo.toml +++ b/crates/fspy_elf_loader_tests/Cargo.toml @@ -7,9 +7,6 @@ license.workspace = true publish.workspace = true rust-version.workspace = true -[build-dependencies] -cc = { workspace = true } - [dev-dependencies] elf = { workspace = true } diff --git a/crates/fspy_elf_loader_tests/build.rs b/crates/fspy_elf_loader_tests/build.rs index 86740cfea..994ad4197 100644 --- a/crates/fspy_elf_loader_tests/build.rs +++ b/crates/fspy_elf_loader_tests/build.rs @@ -1,6 +1,6 @@ use std::{ env, - ffi::{OsStr, OsString}, + ffi::OsString, process::{Command, Stdio}, }; @@ -10,24 +10,11 @@ fn main() { } println!("cargo::rerun-if-changed=fixtures/runtime.c"); println!("cargo::rerun-if-env-changed=CC"); - if let Ok(mut target) = env::var("TARGET") { - // SAFETY: replacing ASCII '-' with ASCII '_' preserves UTF-8 validity. - for byte in unsafe { target.as_bytes_mut() } { - if *byte == b'-' { - *byte = b'_'; - } - } - println!("cargo::rerun-if-env-changed=CC_{target}"); - } - // Use cc's target-aware compiler discovery (respects CC_, CC, and - // cross toolchains) without inheriting its library-oriented default flags. - let compiler = cc::Build::new().cargo_metadata(false).get_compiler(); + let compiler = resolve_compiler(); let is_zigcc = compiler - .path() - .file_name() - .and_then(OsStr::to_str) - .is_some_and(|name| name.starts_with("zigcc-")); + .to_str() + .is_some_and(|path| path.rsplit('/').next().is_some_and(|name| name.starts_with("zigcc-"))); let out = env::var_os("OUT_DIR").unwrap(); let mut source = env::var_os("CARGO_MANIFEST_DIR").unwrap(); @@ -62,12 +49,30 @@ fn main() { if is_static && let Some(musl_target) = musl_target { compile_zig_musl(musl_target, &source, &dest, flags); } else { - compile(&compiler, &source, &dest, flags); + run_compile(Command::new(&compiler), &source, &dest, flags); } println!("cargo::rustc-env={env_name}={}", dest.to_str().unwrap()); } } +fn resolve_compiler() -> OsString { + if let Ok(mut target) = env::var("TARGET") { + // SAFETY: replacing ASCII '-' with ASCII '_' preserves UTF-8 validity. + for byte in unsafe { target.as_bytes_mut() } { + if *byte == b'-' { + *byte = b'_'; + } + } + let mut key = OsString::from("CC_"); + key.push(&target); + println!("cargo::rerun-if-env-changed=CC_{target}"); + if let Some(cc) = env::var_os(&key).filter(|value| !value.is_empty()) { + return cc; + } + } + env::var_os("CC").filter(|value| !value.is_empty()).unwrap_or_else(|| OsString::from("cc")) +} + fn join_out(out: &OsString, name: &str) -> OsString { let mut path = out.clone(); path.push(name); @@ -80,14 +85,6 @@ fn compile_zig_musl(musl_target: &str, source: &OsString, dest: &OsString, extra run_compile(command, source, dest, extra); } -fn compile(compiler: &cc::Tool, source: &OsString, dest: &OsString, extra: &[&str]) { - let mut command = Command::new(compiler.path()); - for (key, value) in compiler.env() { - command.env(key, value); - } - run_compile(command, source, dest, extra); -} - fn run_compile(mut command: Command, source: &OsString, dest: &OsString, extra: &[&str]) { let output = command .args(["-O1", "-pthread"]) From e9eb05849869ae58720079d1edd8553546b0708e Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 18:11:44 +0800 Subject: [PATCH 31/34] test(fspy-elf-loader): drop redundant echo args test and deduplicate 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 --- .../fspy_elf_loader_tests/tests/exec_elf.rs | 66 ++++++++----------- 1 file changed, 28 insertions(+), 38 deletions(-) diff --git a/crates/fspy_elf_loader_tests/tests/exec_elf.rs b/crates/fspy_elf_loader_tests/tests/exec_elf.rs index 8c6bd84f9..47f5e14a1 100644 --- a/crates/fspy_elf_loader_tests/tests/exec_elf.rs +++ b/crates/fspy_elf_loader_tests/tests/exec_elf.rs @@ -34,18 +34,6 @@ fn echo_matches_kernel_exec() { assert_eq!(loaded.stderr, direct.stderr); } -#[test] -#[timeout(10_000)] -fn echo_preserves_empty_and_non_utf8_arguments() { - let mut command = launcher(); - command.args(["/bin/echo", "echo", ""]); - command.arg(OsStr::from_bytes(b"\xff")); - let output = output(command); - assert_eq!(output.status.code(), Some(0), "{output:?}"); - assert_eq!(output.stdout, b" \xff\n"); - assert!(output.stderr.is_empty()); -} - #[test] #[timeout(10_000)] fn initializes_dynamic_pie_runtime() { @@ -58,34 +46,45 @@ fn initializes_fixed_runtime() { check_runtime_image(FIXTURE_DYN_EXEC, elf::abi::ET_EXEC, true); } +fn configure_runtime_fixture( + command: &mut Command, + fixture: &str, + interpreter: bool, + fixed_address: bool, +) { + command.arg("").arg(OsStr::from_bytes(b"\xff")); + command.env_clear().env("FIXTURE_IMAGE", fixture).env("EMPTY", ""); + command.env("BYTES", OsStr::from_bytes(b"\xff")); + if interpreter { + command.env("EXPECT_INTERPRETER", "1"); + } + if fixed_address { + command.env("EXPECT_FIXED_ADDRESS", "1"); + } +} + +fn run_loaded_fixture(fixture: &str, interpreter: bool, fixed_address: bool) -> Output { + let mut command = launcher(); + command.args([fixture, "custom-argv-zero"]); + configure_runtime_fixture(&mut command, fixture, interpreter, fixed_address); + output(command) +} + fn check_runtime_image(fixture: &str, image_type: u16, interpreter: bool) { assert_image(fixture, image_type, interpreter); - let configure = |command: &mut Command| { - command.arg("").arg(OsStr::from_bytes(b"\xff")); - command.env_clear().env("FIXTURE_IMAGE", fixture).env("EMPTY", ""); - command.env("BYTES", OsStr::from_bytes(b"\xff")); - if interpreter { - command.env("EXPECT_INTERPRETER", "1"); - } - if image_type == elf::abi::ET_EXEC { - command.env("EXPECT_FIXED_ADDRESS", "1"); - } - }; + let fixed_address = image_type == elf::abi::ET_EXEC; // Run each fixture through kernel execve first so fixture/toolchain issues // are distinguished from loader regressions. let mut direct = Command::new(fixture); direct.arg0("custom-argv-zero").stderr(Stdio::piped()); - configure(&mut direct); + configure_runtime_fixture(&mut direct, fixture, interpreter, fixed_address); let direct = output(direct); assert_eq!(direct.status.code(), Some(37), "kernel exec: {direct:?}"); assert_eq!(direct.stdout, b"runtime-ok\n"); assert!(direct.stderr.is_empty(), "kernel exec: {direct:?}"); - let mut loaded = launcher(); - loaded.args([fixture, "custom-argv-zero"]); - configure(&mut loaded); - let loaded = output(loaded); + let loaded = run_loaded_fixture(fixture, interpreter, fixed_address); assert_eq!(loaded.status.code(), Some(37), "loader exec: {loaded:?}"); assert_eq!(loaded.stdout, direct.stdout); assert_eq!(loaded.stderr, direct.stderr); @@ -221,16 +220,7 @@ fn does_not_require_section_headers() { write_u64(&mut bytes, offset_of!(libc::Elf64_Ehdr, e_shoff), u64::MAX); let file = tempfile::NamedTempFile::new().unwrap(); std::fs::write(file.path(), bytes).unwrap(); - let path = file.path().to_str().unwrap(); - let mut command = launcher(); - command.args([path, "custom-argv-zero", ""]).arg(OsStr::from_bytes(b"\xff")); - command - .env_clear() - .env("FIXTURE_IMAGE", path) - .env("EMPTY", "") - .env("BYTES", OsStr::from_bytes(b"\xff")) - .env("EXPECT_INTERPRETER", "1"); - let output = output(command); + let output = run_loaded_fixture(file.path().to_str().unwrap(), true, false); assert_eq!(output.status.code(), Some(37), "{output:?}"); assert_eq!(output.stdout, b"runtime-ok\n"); assert!(output.stderr.is_empty(), "{output:?}"); From 7ab5e99cef5b561f5932997ec1f8d80f7495a867 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 18:22:26 +0800 Subject: [PATCH 32/34] chore(fspy-elf-loader): format README and revert residual param.rs diff 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 --- crates/fspy_elf_loader/README.md | 16 ++++++++-------- crates/fspy_nostd/src/param.rs | 6 ++---- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/crates/fspy_elf_loader/README.md b/crates/fspy_elf_loader/README.md index af63ac7dd..f245f2ff1 100644 --- a/crates/fspy_elf_loader/README.md +++ b/crates/fspy_elf_loader/README.md @@ -21,10 +21,10 @@ the kernel will not, once it never sees the target. Native little-endian ELF64 on x86-64 and AArch64. `PT_GNU_STACK` must be non-executable. `ET_EXEC` that overlaps any retained mapping is rejected. -| | `PT_INTERP` | no `PT_INTERP` | -| --- | --- | --- | -| `ET_DYN` | dynamic PIE: enter ld.so, `AT_BASE` = interp bias | static-PIE / ld.so: enter `e_entry`, `AT_BASE` = 0 | -| `ET_EXEC` | dynamic non-PIE: same as dynamic PIE | traditional static: enter `e_entry`, `AT_BASE` = 0 | +| | `PT_INTERP` | no `PT_INTERP` | +| --------- | ------------------------------------------------- | -------------------------------------------------- | +| `ET_DYN` | dynamic PIE: enter ld.so, `AT_BASE` = interp bias | static-PIE / ld.so: enter `e_entry`, `AT_BASE` = 0 | +| `ET_EXEC` | dynamic non-PIE: same as dynamic PIE | traditional static: enter `e_entry`, `AT_BASE` = 0 | All four cells load. With an interpreter, map both images and enter the interpreter even though `AT_ENTRY` names the executable. Without one, map only @@ -33,10 +33,10 @@ the executable. The launcher is itself a static `ET_EXEC` at a high fixed address so the low 4 GiB stays free for non-PIE targets: -| Arch | Base | -| --- | --- | -| x86-64 | `0x5500_0000_0000` (85 TiB) | -| AArch64 | `0x0002_0000_0000` (8 GiB) | +| Arch | Base | +| ------- | --------------------------- | +| x86-64 | `0x5500_0000_0000` (85 TiB) | +| AArch64 | `0x0002_0000_0000` (8 GiB) | These sit in current LLVM Linux ASan/TSan application regions; GCC 12's AArch64 TSan still rejects the 8 GiB mapping. The addresses are conventions, not diff --git a/crates/fspy_nostd/src/param.rs b/crates/fspy_nostd/src/param.rs index c94709a81..8272e0a50 100644 --- a/crates/fspy_nostd/src/param.rs +++ b/crates/fspy_nostd/src/param.rs @@ -33,8 +33,6 @@ mod linux { /// larger pages. const MAX_PROBE_PAGE: usize = 1 << 20; - static CACHE: AtomicUsize = AtomicUsize::new(0); - /// Returns the size of a memory page, or 0 if it cannot be determined. /// /// Discovered from the kernel with a handful of raw syscalls, once per @@ -48,6 +46,7 @@ mod linux { /// this operation" (an allocator refuses the allocation). #[must_use] pub fn page_size() -> usize { + static CACHE: AtomicUsize = AtomicUsize::new(0); let cached = CACHE.load(Ordering::Relaxed); if cached != 0 { return cached; @@ -127,8 +126,7 @@ mod linux { #[test] fn probe_is_stable_and_cached() { - let probed = probe_page_size(); - assert_eq!(probed, page_size()); + assert_eq!(probe_page_size(), page_size()); assert_eq!(page_size(), page_size()); #[cfg(target_arch = "x86_64")] assert_eq!(page_size(), 4096); From cd3bdf08b6a9bab22f6edda7189da5efea7b68f3 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 18:34:11 +0800 Subject: [PATCH 33/34] fix(fspy-elf-loader): embed launcher bytes in launcher_image test 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 --- crates/fspy_elf_loader_tests/tests/launcher_image.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/fspy_elf_loader_tests/tests/launcher_image.rs b/crates/fspy_elf_loader_tests/tests/launcher_image.rs index dc447c436..036fd7e5e 100644 --- a/crates/fspy_elf_loader_tests/tests/launcher_image.rs +++ b/crates/fspy_elf_loader_tests/tests/launcher_image.rs @@ -1,13 +1,15 @@ use elf::{ElfBytes, abi, endian::LittleEndian, file::Class}; -const LAUNCHER: &str = env!("CARGO_BIN_FILE_FSPY_ELF_LOADER_TEST_LAUNCHER"); +// Embed the artifact bytes at compile time so cross-compiled test archives +// (such as Windows nextest archives built on Linux) do not depend on the +// build host's path at runtime. +const LAUNCHER: &[u8] = include_bytes!(env!("CARGO_BIN_FILE_FSPY_ELF_LOADER_TEST_LAUNCHER")); // Inspect the real artifact on every host, including macOS and Windows. // Linux execution tests separately check startup and fixed-address collisions. #[test] fn launcher_uses_high_fixed_addresses_without_runtime_relocations() { - let bytes = std::fs::read(LAUNCHER).unwrap(); - let image = ElfBytes::::minimal_parse(&bytes).unwrap(); + let image = ElfBytes::::minimal_parse(LAUNCHER).unwrap(); assert_eq!(image.ehdr.class, Class::ELF64); assert_eq!(image.ehdr.e_type, abi::ET_EXEC); // Keep the entire image inside a sanitizer application region: x86-64 From 3279a125b0b46710eff7edb4a52c9e54619283ca Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 18:38:31 +0800 Subject: [PATCH 34/34] fix(fspy-nostd): read runtime CARGO_MANIFEST_DIR in no_global_alloc test 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 --- crates/fspy_nostd/tests/no_global_alloc.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/fspy_nostd/tests/no_global_alloc.rs b/crates/fspy_nostd/tests/no_global_alloc.rs index 122d72c2f..2cc4334ab 100644 --- a/crates/fspy_nostd/tests/no_global_alloc.rs +++ b/crates/fspy_nostd/tests/no_global_alloc.rs @@ -1,8 +1,12 @@ -use std::process::Command; +use std::{ffi::OsString, process::Command}; #[test] fn global_allocator_is_checked_at_link_time() { - let source = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/support/no_global_alloc.rs"); + // Prefer runtime CARGO_MANIFEST_DIR so cross-compiled nextest archives + // remapped onto another host (such as Windows CI) find the fixture file. + let mut source = std::env::var_os("CARGO_MANIFEST_DIR") + .unwrap_or_else(|| OsString::from(env!("CARGO_MANIFEST_DIR"))); + source.push("/tests/support/no_global_alloc.rs"); // Compile and link freestanding fixtures, but never execute them. Both // targets are installed by rust-toolchain.toml; no Linux VM is needed. for target in ["aarch64-unknown-none-softfloat", "x86_64-unknown-none"] { @@ -16,7 +20,8 @@ fn global_allocator_is_checked_at_link_time() { // --cfg selects the fixture's operation. Abort avoids an unwind // runtime, and --no-pie matches our fixed-address launcher. let output = Command::new("rustc") - .args([source, "--edition=2024", "--target", target]) + .arg(&source) + .args(["--edition=2024", "--target", target]) .args(["--cfg", operation, "-C", "panic=abort", "-C"]) .arg(["opt-level=", optimization].concat()) .args(["-C", "link-arg=--no-pie", "-o"])