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/.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/Cargo.lock b/Cargo.lock index ec2ead5fd..6a5597c97 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1468,6 +1468,35 @@ dependencies = [ "toml", ] +[[package]] +name = "fspy_elf_loader" +version = "0.1.0" +dependencies = [ + "elf", + "fspy_nostd", + "linux-raw-sys 0.12.1", + "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_test_launcher", + "libc", + "ntest", + "tempfile", +] + [[package]] name = "fspy_nostd" version = "0.0.0" @@ -1478,6 +1507,7 @@ dependencies = [ "libc", "linux-raw-sys 0.12.1", "syscalls", + "tempfile", "windows-sys 0.61.2", ] @@ -5161,6 +5191,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_elf_loader/Cargo.toml b/crates/fspy_elf_loader/Cargo.toml new file mode 100644 index 000000000..154943b2f --- /dev/null +++ b/crates/fspy_elf_loader/Cargo.toml @@ -0,0 +1,22 @@ +[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 + +[target.'cfg(any(target_os = "linux", target_os = "none"))'.dependencies] +elf = { workspace = true } +fspy_nostd = { workspace = true } +linux-raw-sys = { workspace = true, features = ["auxvec", "no_std"] } + +[target.'cfg(target_os = "linux")'.dev-dependencies] +tempfile = { workspace = true } + +[lib] +doctest = false + +[lints] +workspace = true diff --git a/crates/fspy_elf_loader/README.md b/crates/fspy_elf_loader/README.md new file mode 100644 index 000000000..f245f2ff1 --- /dev/null +++ b/crates/fspy_elf_loader/README.md @@ -0,0 +1,84 @@ +# fspy_elf_loader + +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. + +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. + +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. + +## Support + +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 | + +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. + +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) | + +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. diff --git a/crates/fspy_elf_loader/src/image.rs b/crates/fspy_elf_loader/src/image.rs new file mode 100644 index 000000000..d5c844d75 --- /dev/null +++ b/crates/fspy_elf_loader/src/image.rs @@ -0,0 +1,354 @@ +//! 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; + +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")] +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(); + } + + #[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 { + 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 >= 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() }; + // 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..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. + // 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!(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!( + 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) * PHDR_SIZE); + 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 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() { + 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"); + // 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); + } + } + 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; + 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 { + 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; 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 % page, + word(segment.p_offset) % page, + "incongruent ELF page offsets" + ); + alignment = alignment.max(align); + } + } + 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. + 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. + // 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; + // 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. + // SAFETY: caller owns the entire reservation being replaced. + unsafe { + mm::mmap( + ptr::with_exposed_provenance_mut(page_start), + file_len, + protection, + fixed, + self.fd.as_fd(), + segment.p_offset & !u64::try_from(sub(page, 1)).unwrap(), + ) + } + .expect("cannot map ELF segment"); + // Zero through the page boundary (Linux padzero) when the segment + // has BSS (memsz > 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); + 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; + } + } + } + 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"); + } + } + } + } + } + let anonymous_start = align_up(file_end, page); + let anonymous_end = align_up(end, page); + if anonymous_start < anonymous_end { + // Remaining BSS pages have no file bytes. Anonymous pages start + // at zero; mapping the file past its end could instead 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..42d0d5673 --- /dev/null +++ b/crates/fspy_elf_loader/src/image/tests.rs @@ -0,0 +1,330 @@ +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 image = map_bytes(&bytes); + assert_eq!(image.bias % (2 * page), 0); + 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() + .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); + } + } +} + +#[test] +fn zeroes_spare_file_bytes_on_writable_segment_when_filesz_equals_memsz() { + let page = fspy_nostd::param::page_size(); + 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's page is mapped readable directly from the file. + unsafe { + assert_eq!( + ptr::with_exposed_provenance::(image.bias + page + 0x300).read(), + 0xa5, + "non-writable filesz==memsz must not COW-zero its tail page" + ); + } + } +} + +#[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(); + 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] +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. + 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. + 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() { + 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 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"))); + 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 +} + +#[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 = EHDR_SIZE + PHDR_SIZE; + let mut bytes = std::vec![0; start + path.len()]; + write_header(&mut bytes, 1, 0); + 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) { + 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( + bytes: &mut [u8], + index: usize, + start: usize, + file_size: usize, + memory_size: usize, + flags: u32, + page: usize, +) { + 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 { + 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 new file mode 100644 index 000000000..8125f6919 --- /dev/null +++ b/crates/fspy_elf_loader/src/lib.rs @@ -0,0 +1,210 @@ +//! 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`. +//! +//! 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. +#![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. +/// +/// Takes ownership of a private executable descriptor and closes it after +/// 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 +/// 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 +/// 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. +/// +/// 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` +/// 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 +/// destructors. Any retained handlers, mappings, or other process state must +/// remain valid while the target runs. +/// +/// # 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: &[AuxEntry], +) -> ! { + 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. + // 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.is_dynamic(), "fixed-address PT_INTERP is unsupported"); + assert!(file.interpreter().is_none(), "nested PT_INTERP is unsupported"); + file + }); + let executable_image = executable.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( + execfn, + argv, + envp, + inherited_auxv.iter().copied(), + &executable_image, + interpreter_image.as_ref(), + page_size, + ) + }; + // 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(); + 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) } +} + +// 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. 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", + ); +} + +#[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. + // Match Linux ELF_PLAT_INIT by zeroing GPRs; RDI keeps the entry for JMP. + core::arch::naked_asm!( + "mov rsp, rsi", + "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/mapping.rs b/crates/fspy_elf_loader/src/mapping.rs new file mode 100644 index 000000000..9d63f8d0e --- /dev/null +++ b/crates/fspy_elf_loader/src/mapping.rs @@ -0,0 +1,121 @@ +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 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 + // 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) { + // Switching SP or jumping does not transfer Rust ownership. Suppress + // Drop here so it cannot release memory needed after the handoff. + core::mem::forget(self); + } +} + +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..67752906d --- /dev/null +++ b/crates/fspy_elf_loader/src/stack.rs @@ -0,0 +1,361 @@ +//! 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. 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::{align_of, size_of}, + ptr, +}; + +use fspy_nostd::{ + CStr, Thin, + env::AuxEntry, + mm::{self, MprotectFlags}, +}; +use linux_raw_sys::auxvec as abi; + +use crate::{ + image::{Image, PHDR_SIZE}, + mapping::{Mapping, add, sub}, +}; + +// 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, + // Offsets from mapping.ptr: first usable byte, staged word count, and payload start. + start: usize, + 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. + // 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, 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"); + // 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 { + 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. + 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.word_count; + self.push(0); + 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_mut()[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.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_mut()[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 = 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"); + // 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(source, target, len); + ptr::write_bytes(source, 0, len.min(sub(start, self.start))); + 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: Option<&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 { + 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_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 => { + 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 + // 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_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); + } + // 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); + } + // 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, 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)); + 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())); + } + } + } + } + + #[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(); + } +} 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_test_launcher/build.rs b/crates/fspy_elf_loader_test_launcher/build.rs new file mode 100644 index 000000000..99b5bec3c --- /dev/null +++ b/crates/fspy_elf_loader_test_launcher/build.rs @@ -0,0 +1,18 @@ +fn main() { + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("none") { + // 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={argument}"); + } + } +} diff --git a/crates/fspy_elf_loader_test_launcher/src/main.rs b/crates/fspy_elf_loader_test_launcher/src/main.rs new file mode 100644 index 000000000..29cde1486 --- /dev/null +++ b/crates/fspy_elf_loader_test_launcher/src/main.rs @@ -0,0 +1,36 @@ +#![cfg_attr(target_os = "none", no_std)] +#![cfg_attr(target_os = "none", no_main)] + +#[cfg(not(target_os = "none"))] +const fn main() {} + +#[cfg(target_os = "none")] +mod freestanding { + use fspy_nostd::{ + CWD, + fs::{Mode, OFlags, openat}, + }; + + 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. + #[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"); + 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()) + } + } +} diff --git a/crates/fspy_elf_loader_tests/Cargo.toml b/crates/fspy_elf_loader_tests/Cargo.toml new file mode 100644 index 000000000..0e7c174bb --- /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 + +[dev-dependencies] +elf = { workspace = true } + +[target.'cfg(target_os = "linux")'.dev-dependencies] +libc = { workspace = true } +ntest = { workspace = true } +tempfile = { 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" } + +[target.'cfg(target_arch = "x86_64")'.dev-dependencies] +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_test_launcher"] diff --git a/crates/fspy_elf_loader_tests/README.md b/crates/fspy_elf_loader_tests/README.md new file mode 100644 index 000000000..7401bebe8 --- /dev/null +++ b/crates/fspy_elf_loader_tests/README.md @@ -0,0 +1,19 @@ +# fspy_elf_loader_tests + +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 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. 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 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. diff --git a/crates/fspy_elf_loader_tests/build.rs b/crates/fspy_elf_loader_tests/build.rs new file mode 100644 index 000000000..994ad4197 --- /dev/null +++ b/crates/fspy_elf_loader_tests/build.rs @@ -0,0 +1,103 @@ +use std::{ + env, + ffi::OsString, + process::{Command, Stdio}, +}; + +fn main() { + if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("linux") { + return; + } + println!("cargo::rerun-if-changed=fixtures/runtime.c"); + println!("cargo::rerun-if-env-changed=CC"); + + let compiler = resolve_compiler(); + let is_zigcc = compiler + .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(); + 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. + // 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, 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); + if is_static && let Some(musl_target) = musl_target { + compile_zig_musl(musl_target, &source, &dest, flags); + } else { + 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); + 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 run_compile(mut command: Command, source: &OsString, dest: &OsString, extra: &[&str]) { + let output = command + .args(["-O1", "-pthread"]) + .args(extra) + .arg("-o") + .arg(dest) + .arg(source) + .stderr(Stdio::piped()) + .output() + .expect("cannot invoke C compiler"); + assert!( + output.status.success(), + "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/runtime.c b/crates/fspy_elf_loader_tests/fixtures/runtime.c new file mode 100644 index 000000000..167282321 --- /dev/null +++ b/crates/fspy_elf_loader_tests/fixtures/runtime.c @@ -0,0 +1,233 @@ +/* Runtime checks for all four Linux ELF64 cells loaded by exec_elf: + * dynamic PIE, dynamic ET_EXEC, traditional static, and static-PIE. + * + * 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 + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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_all(STDERR_FILENO, message, strlen(message)); + write_all(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. */ + const Elf64_Ehdr *ehdr = (const Elf64_Ehdr *)(at_phdr - sizeof *ehdr); + if (memcmp(ehdr->e_ident, ELFMAG, SELFMAG) != 0) { + fail("elf header"); + } + 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 - (unsigned long)ehdr->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_base; + 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); + + 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); + 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"); + } + } + + { + 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_all(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 new file mode 100644 index 000000000..47f5e14a1 --- /dev/null +++ b/crates/fspy_elf_loader_tests/tests/exec_elf.rs @@ -0,0 +1,265 @@ +// 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, + mem::{offset_of, size_of}, + os::unix::{ffi::OsStrExt as _, process::CommandExt as _}, + process::{Command, Output, Stdio}, +}; + +use ntest::timeout; + +const LAUNCHER: &str = env!("CARGO_BIN_FILE_FSPY_ELF_LOADER_TEST_LAUNCHER"); +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] +#[timeout(10_000)] +fn echo_matches_kernel_exec() { + let mut direct = Command::new("/bin/echo"); + direct.args(["hello", "world"]); + let mut loaded = launcher(); + // 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:?}"); + 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 initializes_dynamic_pie_runtime() { + check_runtime_image(FIXTURE_DYN_PIE, elf::abi::ET_DYN, true); +} + +#[test] +#[timeout(10_000)] +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 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_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 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); +} + +#[test] +#[timeout(10_000)] +fn initializes_static_runtime() { + check_runtime_image(FIXTURE_STATIC_EXEC, 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] +#[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_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 + .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; + write_u64(&mut bytes, offset_of!(libc::Elf64_Ehdr, e_entry), entry); + for (index, ph) in loads { + 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(); + 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] +#[timeout(10_000)] +fn rejects_malformed_images() { + 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 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", base[..size_of::()].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), "{case}: {output:?}"); + assert!( + str::from_utf8(&output.stderr).unwrap().contains("panicked at"), + "{case}: {output:?}" + ); + } +} + +#[test] +#[timeout(10_000)] +fn does_not_require_section_headers() { + let mut bytes = std::fs::read(FIXTURE_DYN_PIE).unwrap(); + // The ELF loader must not use section metadata, even if it is unusable. + 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 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:?}"); +} + +#[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_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}"); + 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 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") +} 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..036fd7e5e --- /dev/null +++ b/crates/fspy_elf_loader_tests/tests/launcher_image.rs @@ -0,0 +1,41 @@ +use elf::{ElfBytes, abi, endian::LittleEndian, file::Class}; + +// 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 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 + // 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()); +} diff --git a/crates/fspy_nostd/Cargo.toml b/crates/fspy_nostd/Cargo.toml index 6ad5ef3b0..0c6af81ff 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`. @@ -33,5 +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/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/entry.rs b/crates/fspy_nostd/src/entry.rs new file mode 100644 index 000000000..e741e7acd --- /dev/null +++ b/crates/fspy_nostd/src/entry.rs @@ -0,0 +1,59 @@ +/// 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 +/// fn run(_: fspy_nostd::env::InitialStack<'static>) -> ! { +/// loop {} +/// } +/// const _: for<'a> fn(fspy_nostd::env::InitialStack<'a>) -> ! = 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. +/// 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 $(,)?) => { + $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..a3d7d5b7a --- /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/error.rs b/crates/fspy_nostd/src/error.rs index e6d3d9af4..08db08466 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"))] @@ -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); @@ -51,6 +52,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 { @@ -84,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(); @@ -94,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..fbd6b36f8 100644 --- a/crates/fspy_nostd/src/lib.rs +++ b/crates/fspy_nostd/src/lib.rs @@ -8,9 +8,16 @@ #![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; +#[cfg(any(target_os = "linux", target_os = "none"))] +#[doc(hidden)] +pub mod no_global_alloc; +#[cfg(any(target_os = "linux", target_os = "none"))] +mod panic; #[cfg(windows)] mod windows; @@ -18,17 +25,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/mm.rs b/crates/fspy_nostd/src/mm.rs index 4c5acc8c7..37a8a036f 100644 --- a/crates/fspy_nostd/src/mm.rs +++ b/crates/fspy_nostd/src/mm.rs @@ -53,6 +53,14 @@ 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; + /// 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; } } 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/src/panic.rs b/crates/fspy_nostd/src/panic.rs new file mode 100644 index 000000000..07b3e89e9 --- /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. [`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 +/// 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) } +} 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..2cc4334ab --- /dev/null +++ b/crates/fspy_nostd/tests/no_global_alloc.rs @@ -0,0 +1,51 @@ +use std::{ffi::OsString, process::Command}; + +#[test] +fn global_allocator_is_checked_at_link_time() { + // 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"] { + // 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") + .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"]) + .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 {} +} 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_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)] 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 { 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"]