From 4efcc9c6422eb5bc2869390c05b4aa7326df0d21 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 18 Nov 2026 03:47:40 +0000 Subject: [PATCH 1/3] fix(fspy-elf-loader): match Linux PT_LOAD and PT_INTERP loading Map zero-filesz loads like elf_map so a mid-page BSS segment does not wipe the previous page. Padzero whenever filesz is not page-aligned, including filesz==memsz. Accept padded PT_INTERP paths and unordered non-overlapping PT_LOADs. Clear leftover GPRs in the enter stubs. Co-authored-by: Cursor Grok 4.6 Co-authored-by: Charles Wang --- crates/fspy_elf_loader/src/image.rs | 101 ++++++++------ crates/fspy_elf_loader/src/image/tests.rs | 157 +++++++++++++++++++--- crates/fspy_elf_loader/src/lib.rs | 25 +++- 3 files changed, 221 insertions(+), 62 deletions(-) diff --git a/crates/fspy_elf_loader/src/image.rs b/crates/fspy_elf_loader/src/image.rs index eebf5fc34..e9e8f9d90 100644 --- a/crates/fspy_elf_loader/src/image.rs +++ b/crates/fspy_elf_loader/src/image.rs @@ -111,7 +111,12 @@ impl File { // SAFETY: the file remains unchanged and mapped read-only. let bytes = unsafe { self.view.bytes() }.get(start..end).expect("truncated PT_INTERP"); - let path = CStr::from_units_with_nul(bytes).expect("invalid PT_INTERP path"); + // Linux requires only that the last byte is NUL, then treats + // the slice as a C string. Linkers may pad with extra NULs. + assert!(bytes.last() == Some(&0), "unterminated PT_INTERP"); + let len = bytes.iter().position(|byte| *byte == 0).unwrap() + 1; + let path = + CStr::from_units_with_nul(&bytes[..len]).expect("invalid PT_INTERP path"); assert!(!path.as_units().is_empty(), "empty PT_INTERP path"); result = Some(path); } @@ -119,41 +124,56 @@ impl File { result } + fn assert_disjoint_load(&self, index: usize, start: usize, end: usize) { + for (other_index, other) in self.segments().iter().enumerate() { + if other_index > index && other.p_type == abi::PT_LOAD && other.p_memsz != 0 { + let other_start = word(other.p_vaddr); + let other_end = add(other_start, word(other.p_memsz)); + assert!(end <= other_start || other_end <= start, "overlapping ELF segments"); + } + } + } + pub fn map(&self, page: usize) -> Image { // First validate the segments and find their page-rounded span. // mmap operates on whole pages, even when ELF segments do not. let mut low = usize::MAX; let mut high = 0; let mut alignment = page; - let mut previous_end = 0; - for segment in self.segments().iter() { + for (index, segment) in self.segments().iter().enumerate() { if segment.p_type == abi::PT_GNU_STACK { assert!(segment.p_flags & abi::PF_X == 0, "executable stacks are unsupported"); } - if segment.p_type != abi::PT_LOAD { - continue; - } - let start = word(segment.p_vaddr); - let end = add(start, word(segment.p_memsz)); - let file_end = add(word(segment.p_offset), word(segment.p_filesz)); - assert!(segment.p_filesz <= segment.p_memsz, "ELF filesz exceeds memsz"); - assert!(file_end <= self.view.len, "truncated ELF segment"); - // Our MVP rejects overlapping byte ranges. Page-rounded ranges - // can still overlap, so mapping below must preserve header order. - assert!(start >= previous_end, "overlapping or unordered ELF segments"); - previous_end = end; - // ELF treats alignment 0 and 1 as no extra constraint. File and - // memory offsets must agree within a page for file-backed mmap. - let align = word(segment.p_align).max(1); - assert!(align.is_power_of_two(), "invalid segment alignment"); - assert_eq!(start % align, word(segment.p_offset) % align, "incongruent ELF alignment"); - assert_eq!(start % page, word(segment.p_offset) % page, "incongruent ELF page offsets"); - alignment = alignment.max(align); - if segment.p_memsz == 0 { - continue; + if segment.p_type == abi::PT_LOAD { + let start = word(segment.p_vaddr); + let end = add(start, word(segment.p_memsz)); + let file_end = add(word(segment.p_offset), word(segment.p_filesz)); + assert!(segment.p_filesz <= segment.p_memsz, "ELF filesz exceeds memsz"); + assert!(file_end <= self.view.len, "truncated ELF segment"); + // Byte ranges must not overlap. Header order need not match + // vaddr order; mapping below still walks headers so a later + // MAP_FIXED can share a page with an earlier load. + if segment.p_memsz != 0 { + self.assert_disjoint_load(index, start, end); + low = low.min(start & !sub(page, 1)); + high = high.max(align_up(end, page)); + } + // ELF treats alignment 0 and 1 as no extra constraint. File + // and memory offsets must agree within a page for mmap. + let align = word(segment.p_align).max(1); + assert!(align.is_power_of_two(), "invalid segment alignment"); + assert_eq!( + start % align, + word(segment.p_offset) % align, + "incongruent ELF alignment" + ); + assert_eq!( + start % page, + word(segment.p_offset) % page, + "incongruent ELF page offsets" + ); + alignment = alignment.max(align); } - low = low.min(start & !sub(page, 1)); - high = high.max(align_up(end, page)); } let span = high.checked_sub(low).expect("ELF has no loadable memory"); // Reserve the whole image, including holes, before replacing pages @@ -228,17 +248,21 @@ impl File { protection |= ProtFlags::EXEC; } let fixed = MapFlags::PRIVATE | MapFlags::FIXED; - if segment.p_filesz != 0 { + // Linux elf_map skips a zero-length mapping, which happens only when + // filesz is 0 and vaddr is page-aligned. A zero-filesz load that + // starts mid-page still maps that shared page from the file so a + // later MAP_FIXED does not anonymous-wipe the previous load's bytes. + let file_len = sub(align_up(file_end, page), page_start); + if file_len != 0 { // Round both the file offset and address down by the same amount. // For example, an offset ending in 0x340 needs those first 0x340 // bytes of its page mapped too. Round the end up to cover the tail. // PRIVATE keeps BSS writes and later relocations out of the file. - let len = sub(align_up(file_end, page), page_start); // SAFETY: caller owns the entire reservation being replaced. unsafe { mm::mmap( ptr::with_exposed_provenance_mut(page_start), - len, + file_len, protection, fixed, self.fd.as_fd(), @@ -246,18 +270,18 @@ impl File { ) } .expect("cannot map ELF segment"); - if file_end < end && !file_end.is_multiple_of(page) { + // Zero through the page boundary, not just p_memsz: leftover file + // bytes after filesz==memsz, and the BSS tail of filesz(image.bias + page + 0x100).read(), 0xa5); + assert_eq!(ptr::with_exposed_provenance::(image.bias + page + 0x2ff).read(), 0xa5); + let tail = core::slice::from_raw_parts( + ptr::with_exposed_provenance::(image.bias + page + 0x300), + page - 0x300, + ); + assert!(tail.iter().all(|byte| *byte == 0), "filesz==memsz must still padzero"); + } + } +} + +#[test] +fn preserves_previous_load_when_bss_only_starts_mid_page() { + let page = fspy_nostd::param::page_size(); + for memory_size in [0x180, page + 0x180] { + let mut bytes = std::vec![0xa5; 3 * page]; + write_header(&mut bytes, 2, 0x200); + load(&mut bytes, 0, 0, page + 0x200, page + 0x200, abi::PF_R | abi::PF_X, page); + load(&mut bytes, 1, page + 0x200, 0, memory_size, abi::PF_R | abi::PF_W, page); + let image = map_bytes(&bytes); + // SAFETY: both LOADs are mapped readable; the first occupies the + // shared page below the BSS-only vaddr. + unsafe { + assert_eq!( + ptr::with_exposed_provenance::(image.bias + page + 0x80).read(), + 0xa5, + "anonymous MAP_FIXED of a filesz==0 LOAD must not wipe the previous segment" + ); + assert_eq!(ptr::with_exposed_provenance::(image.bias + page + 0x1ff).read(), 0xa5); + let zero_start = image.bias + page + 0x200; + let zero_end = align_up(zero_start + memory_size, page); + let zeroed = core::slice::from_raw_parts( + ptr::with_exposed_provenance::(zero_start), + zero_end - zero_start, + ); + assert!(zeroed.iter().all(|byte| *byte == 0)); + } + } +} + +#[test] +fn maps_unordered_non_overlapping_loads() { + let page = fspy_nostd::param::page_size(); + let mut bytes = std::vec![0; 3 * page]; + write_header(&mut bytes, 2, 0x200); + // Higher vaddr first: Linux still loads in header order. + load(&mut bytes, 0, 2 * page, 0x40, 0x40, abi::PF_R | abi::PF_W, page); + load(&mut bytes, 1, 0, page, page, abi::PF_R | abi::PF_X, page); + bytes[2 * page] = 0x11; + bytes[0x200] = 0x22; + let image = map_bytes(&bytes); + assert_eq!(image.entry, image.bias + 0x200); + // SAFETY: both disjoint LOADs are mapped readable. + unsafe { + assert_eq!(ptr::with_exposed_provenance::(image.bias + 2 * page).read(), 0x11); + assert_eq!(ptr::with_exposed_provenance::(image.entry).read(), 0x22); + } +} + +#[test] +#[should_panic(expected = "overlapping ELF segments")] +fn rejects_overlapping_load_segments() { + let page = fspy_nostd::param::page_size(); + let mut bytes = std::vec![0xa5; 2 * page]; + write_header(&mut bytes, 2, 0x80); + load(&mut bytes, 0, 0, 0x200, 0x200, abi::PF_R | abi::PF_X, page); + load(&mut bytes, 1, 0x100, 0x200, 0x200, abi::PF_R | abi::PF_W, page); + map_bytes(&bytes); +} + +#[test] +fn accepts_pt_interp_padded_with_extra_nuls() { + let file = File::new(open_bytes(&interp_image(b"ld.so\0\0\0"))); + let path = file.interpreter().unwrap(); + assert_eq!(path.as_units(), b"ld.so"); +} + +#[test] +#[should_panic(expected = "unterminated PT_INTERP")] +fn rejects_unterminated_pt_interp() { + let _ = File::new(open_bytes(&interp_image(b"ld.so"))).interpreter(); +} + +#[test] +#[should_panic(expected = "empty PT_INTERP path")] +fn rejects_empty_pt_interp() { + let _ = File::new(open_bytes(&interp_image(b"\0\0\0"))).interpreter(); +} + fn fixture(page: usize, memory_size: usize, flags: u32) -> std::vec::Vec { let mut bytes = std::vec![0xa5; 3 * page]; + write_header(&mut bytes, 2, 0x200); + load(&mut bytes, 0, 0, page + 0x100, page + 0x100, abi::PF_R | abi::PF_X, page); + load(&mut bytes, 1, page + 0x200, 0x100, memory_size, flags, page); + bytes +} + +fn interp_image(path: &[u8]) -> std::vec::Vec { + let start = 64 + 56; + let mut bytes = std::vec![0; start + path.len()]; + write_header(&mut bytes, 1, 0); + let header = &mut bytes[64..120]; + header[..4].copy_from_slice(&abi::PT_INTERP.to_le_bytes()); + for (field, value) in [(8, start), (32, path.len()), (40, path.len()), (48, 1)] { + header[field..field + 8].copy_from_slice(&u64::try_from(value).unwrap().to_le_bytes()); + } + bytes[start..start + path.len()].copy_from_slice(path); + bytes +} + +fn write_header(bytes: &mut [u8], phnum: u16, entry: u64) { bytes[..64].fill(0); bytes[..7].copy_from_slice(b"\x7fELF\x02\x01\x01"); bytes[16..18].copy_from_slice(&abi::ET_DYN.to_le_bytes()); bytes[18..20].copy_from_slice(&MACHINE.to_le_bytes()); bytes[20..24].copy_from_slice(&1_u32.to_le_bytes()); - bytes[24..32].copy_from_slice(&0x200_u64.to_le_bytes()); + bytes[24..32].copy_from_slice(&entry.to_le_bytes()); bytes[32..40].copy_from_slice(&64_u64.to_le_bytes()); bytes[52..54].copy_from_slice(&64_u16.to_le_bytes()); bytes[54..56].copy_from_slice(&56_u16.to_le_bytes()); - bytes[56..58].copy_from_slice(&2_u16.to_le_bytes()); - segment(&mut bytes, 0, 0, page + 0x100, page + 0x100, abi::PF_R | abi::PF_X, page); - segment(&mut bytes, 1, page + 0x200, 0x100, memory_size, flags, page); - bytes + bytes[56..58].copy_from_slice(&phnum.to_le_bytes()); } -fn segment( +fn load( bytes: &mut [u8], index: usize, start: usize, @@ -87,14 +197,25 @@ fn segment( flags: u32, page: usize, ) { - let offset = 64 + index * 56; - let header = &mut bytes[offset..offset + 56]; + let header = &mut bytes[64 + index * 56..64 + index * 56 + 56]; header.fill(0); header[..4].copy_from_slice(&abi::PT_LOAD.to_le_bytes()); header[4..8].copy_from_slice(&flags.to_le_bytes()); - for (offset, value) in + for (field, value) in [(8, start), (16, start), (32, file_size), (40, memory_size), (48, 2 * page)] { - header[offset..offset + 8].copy_from_slice(&u64::try_from(value).unwrap().to_le_bytes()); + header[field..field + 8].copy_from_slice(&u64::try_from(value).unwrap().to_le_bytes()); } } + +fn map_bytes(bytes: &[u8]) -> Image { + File::new(open_bytes(bytes)).map(fspy_nostd::param::page_size()) +} + +fn open_bytes(bytes: &[u8]) -> OwnedFd { + let file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(file.path(), bytes).unwrap(); + let path = std::ffi::CString::new(file.path().as_os_str().as_encoded_bytes()).unwrap(); + let path = CStr::from_units_with_nul(path.as_bytes_with_nul()).unwrap(); + fs::openat(fspy_nostd::CWD, path, fs::OFlags::RDONLY, fs::Mode::empty()).unwrap() +} diff --git a/crates/fspy_elf_loader/src/lib.rs b/crates/fspy_elf_loader/src/lib.rs index fa6a373ca..05e18df95 100644 --- a/crates/fspy_elf_loader/src/lib.rs +++ b/crates/fspy_elf_loader/src/lib.rs @@ -133,9 +133,17 @@ pub unsafe fn exec_elf<'a>( #[cfg(target_arch = "aarch64")] #[unsafe(naked)] unsafe extern "C" fn enter(_entry: usize, _stack: *mut usize) -> ! { - // X0 holds entry and X1 holds the new SP. Save entry in scratch register - // X16 before clearing X0; clear X30 because there is no caller to return to. - core::arch::naked_asm!("mov x16, x0", "mov sp, x1", "mov x0, xzr", "mov x30, xzr", "br x16"); + // X0 holds entry and X1 holds the new SP. Linux start_thread zeros GPRs; + // clear the ones this stub dirties. X16 must keep the entry for BR. + core::arch::naked_asm!( + "mov x16, x0", + "mov sp, x1", + "mov x0, xzr", + "mov x1, xzr", + "mov x29, xzr", + "mov x30, xzr", + "br x16", + ); } #[cfg(target_arch = "x86_64")] @@ -143,6 +151,13 @@ unsafe extern "C" fn enter(_entry: usize, _stack: *mut usize) -> ! { unsafe extern "C" fn enter(_entry: usize, _stack: *mut usize) -> ! { // RDI holds entry and RSI holds the new RSP. RDX is the optional // dynamic-linker finalizer (an exit callback); there is none yet. - // Clear RBP to mark the end of the frame-pointer chain. - core::arch::naked_asm!("mov rsp, rsi", "xor edx, edx", "xor ebp, ebp", "jmp rdi"); + // Clear RBP to mark the end of the frame-pointer chain. RSI held SP. + // RDI must keep the entry for JMP. + core::arch::naked_asm!( + "mov rsp, rsi", + "xor esi, esi", + "xor edx, edx", + "xor ebp, ebp", + "jmp rdi" + ); } From eb69983a67758f199536e9649f9f3e15c73283f5 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 20 Nov 2026 01:41:07 +0000 Subject: [PATCH 2/3] feat(fspy-elf-loader): load static ELF images without PT_INTERP Treat PT_INTERP as optional. Map only the executable when it is absent, set AT_BASE to 0, and enter e_entry. Add cc -static and -static-pie runtime fixtures covering traditional static and static-PIE. Co-authored-by: Cursor Grok 4.6 Co-authored-by: Charles Wang --- crates/fspy_elf_loader/README.md | 6 +- crates/fspy_elf_loader/src/image/tests.rs | 7 + crates/fspy_elf_loader/src/lib.rs | 54 ++--- crates/fspy_elf_loader/src/stack.rs | 10 +- crates/fspy_elf_loader_tests/README.md | 2 +- crates/fspy_elf_loader_tests/build.rs | 49 ++++- .../fixtures/static_runtime.c | 186 ++++++++++++++++++ .../fspy_elf_loader_tests/src/bin/fixture.rs | 11 +- .../fspy_elf_loader_tests/tests/exec_elf.rs | 29 ++- 9 files changed, 306 insertions(+), 48 deletions(-) create mode 100644 crates/fspy_elf_loader_tests/fixtures/static_runtime.c diff --git a/crates/fspy_elf_loader/README.md b/crates/fspy_elf_loader/README.md index 16af9b929..b57756ded 100644 --- a/crates/fspy_elf_loader/README.md +++ b/crates/fspy_elf_loader/README.md @@ -10,7 +10,11 @@ This crate handles loading an ELF program and transferring execution to it. The The current implementation is a proof of concept for evaluating compatibility. It does not yet provide a complete replacement for Linux exec. -It loads native ELF64 dynamic executables on AArch64 and x86-64, including PIE (`ET_DYN`) and fixed-address (`ET_EXEC`) images. Fixed-address images are rejected if their address range overlaps any existing mapping. Static executables remain unsupported. +It loads native ELF64 executables on AArch64 and x86-64, including PIE +(`ET_DYN`) and fixed-address (`ET_EXEC`) images, with or without `PT_INTERP`. +Fixed-address images are rejected if their address range overlaps any existing +mapping. Images with `PT_INTERP` enter the dynamic linker; images without it +enter the executable and receive `AT_BASE` 0. The freestanding launcher is a static fixed-address executable with no startup relocation: diff --git a/crates/fspy_elf_loader/src/image/tests.rs b/crates/fspy_elf_loader/src/image/tests.rs index 8460ff5a7..58c48ca0d 100644 --- a/crates/fspy_elf_loader/src/image/tests.rs +++ b/crates/fspy_elf_loader/src/image/tests.rs @@ -135,6 +135,13 @@ fn rejects_overlapping_load_segments() { map_bytes(&bytes); } +#[test] +fn reports_no_interpreter_when_pt_interp_is_absent() { + let page = fspy_nostd::param::page_size(); + let file = File::new(open_bytes(&fixture(page, 0x180, abi::PF_R | abi::PF_W))); + assert!(file.interpreter().is_none()); +} + #[test] fn accepts_pt_interp_padded_with_extra_nuls() { let file = File::new(open_bytes(&interp_image(b"ld.so\0\0\0"))); diff --git a/crates/fspy_elf_loader/src/lib.rs b/crates/fspy_elf_loader/src/lib.rs index 05e18df95..c2c55f259 100644 --- a/crates/fspy_elf_loader/src/lib.rs +++ b/crates/fspy_elf_loader/src/lib.rs @@ -6,6 +6,10 @@ //! fixes addresses through relocations, and enters the executable's startup //! code. That startup code eventually calls the application's `main`. //! +//! For a static executable there is no `PT_INTERP`. The kernel maps only the +//! executable and enters its `e_entry`. `AT_BASE` is 0. Static-PIE images are +//! `ET_DYN` without an interpreter; their CRT applies `RELATIVE` relocations. +//! //! We implement the mapping, stack, and entry steps after the kernel has //! already executed our freestanding loader. We leave its mappings and signal //! handlers in place. Calling another kernel exec here would discard them. @@ -25,8 +29,9 @@ mod stack; /// Loads an ELF executable into the current process and enters it. /// /// Takes ownership of a private executable descriptor and closes it after -/// mapping. Loads the executable and its `PT_INTERP`, builds an initial stack, -/// and transfers control to the interpreter entry point. +/// mapping. Loads the executable and, when present, its `PT_INTERP`. Builds an +/// initial stack and transfers control to the interpreter, or to the +/// executable when there is no interpreter. /// /// `execfn` is the original execution name used for `AT_EXECFN`; it need not /// match `argv[0]`. Arguments and environment entries are copied to the new @@ -42,9 +47,9 @@ mod stack; /// Loading failures terminate the process; they cannot return to the program /// that executed the loader. /// -/// Currently supports native little-endian ELF64 dynamic executables on -/// `AArch64` and x86-64, with an ELF interpreter and a non-executable stack. -/// Both PIE (`ET_DYN`) and fixed-address (`ET_EXEC`) executables are supported. +/// Currently supports native little-endian ELF64 executables on `AArch64` and +/// x86-64, with a non-executable stack. Both PIE (`ET_DYN`) and fixed-address +/// (`ET_EXEC`) images are supported, with or without `PT_INTERP`. /// Fixed-address images must not overlap any existing process mappings. /// The new stack has a fixed 8 MiB capacity and a guard page. Existing loader /// mappings, the old stack, and kernel process metadata (including `/proc` @@ -85,18 +90,21 @@ pub unsafe fn exec_elf<'a>( let executable = image::File::new(elf_file); // PT_INTERP names a second ELF file. Loading it here lets us delegate // dynamic linking and libc startup to the program's own interpreter. - let interpreter = executable.interpreter().expect("executable has no PT_INTERP"); - let interpreter = fspy_nostd::fs::openat( - fspy_nostd::CWD, - interpreter, - fspy_nostd::fs::OFlags::RDONLY | fspy_nostd::fs::OFlags::CLOEXEC, - fspy_nostd::fs::Mode::empty(), - ) - .expect("cannot open ELF interpreter"); - let interpreter = image::File::new(interpreter); - assert!(interpreter.interpreter().is_none(), "nested PT_INTERP is unsupported"); + // Static and static-PIE images omit it; the executable is the startup image. + let interpreter = executable.interpreter().map(|path| { + let fd = fspy_nostd::fs::openat( + fspy_nostd::CWD, + path, + fspy_nostd::fs::OFlags::RDONLY | fspy_nostd::fs::OFlags::CLOEXEC, + fspy_nostd::fs::Mode::empty(), + ) + .expect("cannot open ELF interpreter"); + let file = image::File::new(fd); + assert!(file.interpreter().is_none(), "nested PT_INTERP is unsupported"); + file + }); let executable_image = executable.map(page_size); - let interpreter_image = interpreter.map(page_size); + let interpreter_image = interpreter.as_ref().map(|file| file.map(page_size)); // SAFETY: the caller supplies live auxiliary payloads from this process. let stack = unsafe { stack::build( @@ -105,21 +113,23 @@ pub unsafe fn exec_elf<'a>( envp, inherited_auxv.iter().copied(), &executable_image, - &interpreter_image, + interpreter_image.as_ref(), page_size, ) }; - // The interpreter must run first, even though AT_ENTRY on the new stack - // points at the executable. The interpreter uses that value to hand off - // after dynamic linking; it does not call the application's main itself. - let entry = interpreter_image.entry; + // With PT_INTERP, the interpreter runs first even though AT_ENTRY points + // at the executable. It uses that value to hand off after linking. + // Without PT_INTERP, AT_BASE is 0 and the executable's e_entry starts. + let entry = interpreter_image.as_ref().map_or(executable_image.entry, |image| image.entry); // File mappings keep their backing storage alive after close. Release // only our parsing views and descriptors, then retain the execution maps // so Rust destructors cannot unmap code the target is about to use. drop(interpreter); drop(executable); executable_image.retain(); - interpreter_image.retain(); + if let Some(image) = interpreter_image { + image.retain(); + } // SAFETY: the images and stack are initialized and retained. The caller // permits abandoning the current stack and entering the trusted image. unsafe { enter(entry, stack) } diff --git a/crates/fspy_elf_loader/src/stack.rs b/crates/fspy_elf_loader/src/stack.rs index c27d485e5..39b7adc77 100644 --- a/crates/fspy_elf_loader/src/stack.rs +++ b/crates/fspy_elf_loader/src/stack.rs @@ -154,7 +154,7 @@ pub unsafe fn build<'a>( envp: impl Iterator>, inherited: impl Iterator, image: &Image, - interpreter: &Image, + interpreter: Option<&Image>, page: usize, ) -> *mut usize { let mut stack = Builder::new(page); @@ -199,14 +199,14 @@ pub unsafe fn build<'a>( } stack.aux(key, entry.value); } - // Describe the main executable even though we enter the interpreter first: - // PHDR/PHENT/PHNUM locate and size its header table; ENTRY is its startup - // address. BASE identifies the interpreter's load bias for its own linking. + // PHDR/PHENT/PHNUM locate and size the executable's header table; ENTRY + // is its startup address. With PT_INTERP we enter the interpreter first + // and BASE is that image's load bias. Without one, BASE is 0 as on Linux. stack.aux(abi::AT_PHDR, image.phdr.expect("program headers are not mapped by PT_LOAD")); stack.aux(abi::AT_PHENT, 56); stack.aux(abi::AT_PHNUM, image.phnum); stack.aux(abi::AT_ENTRY, image.entry); - stack.aux(abi::AT_BASE, interpreter.bias); + stack.aux(abi::AT_BASE, interpreter.map_or(0, |image| image.bias)); stack.aux(abi::AT_FLAGS, 0); let execfn = stack.string(execfn); // Execution name and argv[0] are independent: callers can choose a custom diff --git a/crates/fspy_elf_loader_tests/README.md b/crates/fspy_elf_loader_tests/README.md index 10f208f77..33db4fc0f 100644 --- a/crates/fspy_elf_loader_tests/README.md +++ b/crates/fspy_elf_loader_tests/README.md @@ -4,7 +4,7 @@ Integration tests for [`fspy_elf_loader`](../fspy_elf_loader/README.md). The tests check whether programs start and behave as expected through the custom loader. They help catch compatibility regressions as its scope grows. -The default suite covers dynamic PIE and fixed-address executables, including rejection of a target overlapping the launcher. With Node.js on `PATH`, run `cargo test -p fspy_elf_loader_tests -- --include-ignored` on Linux to also compare a real Node program with normal execution. +The default suite covers dynamic and static PIE and fixed-address executables, including rejection of a target overlapping the launcher. Static fixtures are compiled with `cc -static` and `cc -static-pie`. With Node.js on `PATH`, run `cargo test -p fspy_elf_loader_tests -- --include-ignored` on Linux to also compare a real Node program with normal execution. The launcher artifact is checked on every host for a static fixed-address layout at 85 TiB on x86-64 or 8 GiB on AArch64, with no dynamic relocation diff --git a/crates/fspy_elf_loader_tests/build.rs b/crates/fspy_elf_loader_tests/build.rs index 3cd8b7487..7fdfa6ec7 100644 --- a/crates/fspy_elf_loader_tests/build.rs +++ b/crates/fspy_elf_loader_tests/build.rs @@ -1,7 +1,48 @@ +use std::{ + env, + ffi::OsString, + process::{Command, Stdio}, +}; + fn main() { - if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("linux") { - // Keep the same runtime checks in PIE and fixed-address executables. - // The linker driver must retain dynamic linking while disabling PIE. - println!("cargo::rustc-link-arg-bin=fixture_exec=-no-pie"); + if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("linux") { + return; } + // Keep the same runtime checks in PIE and fixed-address executables. + // The linker driver must retain dynamic linking while disabling PIE. + println!("cargo::rustc-link-arg-bin=fixture_exec=-no-pie"); + println!("cargo::rerun-if-changed=fixtures/static_runtime.c"); + + let out = env::var_os("OUT_DIR").unwrap(); + let mut source = env::var_os("CARGO_MANIFEST_DIR").unwrap(); + source.push("/fixtures/static_runtime.c"); + let static_bin = join_out(&out, "/fixture_static"); + let static_pie = join_out(&out, "/fixture_static_pie"); + compile(&source, &static_bin, &["-static"]); + compile(&source, &static_pie, &["-static-pie"]); + println!("cargo::rustc-env=FIXTURE_STATIC={}", static_bin.to_str().unwrap()); + println!("cargo::rustc-env=FIXTURE_STATIC_PIE={}", static_pie.to_str().unwrap()); +} + +fn join_out(out: &OsString, name: &str) -> OsString { + let mut path = out.clone(); + path.push(name); + path +} + +fn compile(source: &OsString, dest: &OsString, extra: &[&str]) { + let output = Command::new("cc") + .args(["-O1", "-pthread"]) + .args(extra) + .arg("-o") + .arg(dest) + .arg(source) + .stderr(Stdio::piped()) + .output() + .expect("cannot invoke cc"); + assert!( + output.status.success(), + "cannot compile static runtime fixture: {}", + str::from_utf8(&output.stderr).unwrap_or("non-utf8 cc diagnostics") + ); } diff --git a/crates/fspy_elf_loader_tests/fixtures/static_runtime.c b/crates/fspy_elf_loader_tests/fixtures/static_runtime.c new file mode 100644 index 000000000..95c6a6ae9 --- /dev/null +++ b/crates/fspy_elf_loader_tests/fixtures/static_runtime.c @@ -0,0 +1,186 @@ +/* Runtime checks for static and static-PIE images loaded by exec_elf. + * + * Protocol matches src/bin/fixture.rs: argv[0]="custom-argv-zero", argv[1]="", + * argv[2]=0xff, EMPTY="", BYTES=0xff, FIXTURE_IMAGE=AT_EXECFN, stdout + * "runtime-ok\n", exit 37. AT_BASE must be 0 (no interpreter). + */ + +#define _GNU_SOURCE + +#include +#include +#include +#include +#include +#include + +static char bss[128 * 1024]; +static int data = 42; +static __thread int tls = 17; + +static void fail(const char *message) { + write(STDERR_FILENO, message, strlen(message)); + write(STDERR_FILENO, "\n", 1); + _exit(2); +} + +static void *thread_main(void *argument) { + if (tls != 17) { + fail("thread tls"); + } + *(int *)argument = 1; + return NULL; +} + +static unsigned long load_bias(unsigned long at_phdr, unsigned long phnum, const Elf64_Phdr *ph) { + unsigned long i; + for (i = 0; i < phnum; i++) { + if (ph[i].p_type == PT_PHDR) { + return at_phdr - (unsigned long)ph[i].p_vaddr; + } + } + /* GNU ld omits PT_PHDR on some static images. ELF64 headers start at 0. */ + unsigned char *ehdr = (unsigned char *)(at_phdr - 64); + if (ehdr[0] != 0x7f || ehdr[1] != 'E' || ehdr[2] != 'L' || ehdr[3] != 'F') { + fail("elf header"); + } + unsigned long e_phoff; + memcpy(&e_phoff, ehdr + 32, sizeof e_phoff); + if (e_phoff != 64) { + fail("e_phoff"); + } + for (i = 0; i < phnum; i++) { + if (ph[i].p_type == PT_LOAD && ph[i].p_offset == 0) { + return at_phdr - e_phoff - (unsigned long)ph[i].p_vaddr; + } + } + fail("no load at file start"); + return 0; +} + +int main(int argc, char **argv) { + unsigned long i; + pthread_t thread; + int started = 0; + char *heap; + unsigned long at_phdr; + unsigned long phnum; + unsigned long phent; + unsigned long entry; + unsigned long bias; + const Elf64_Phdr *ph; + const char *image; + + if (argc != 3) { + fail("argc"); + } + if (strcmp(argv[0], "custom-argv-zero") != 0) { + fail("argv0"); + } + if (argv[1][0] != '\0') { + fail("argv1"); + } + if ((unsigned char)argv[2][0] != 0xff || argv[2][1] != '\0') { + fail("argv2"); + } + if (getenv("EMPTY") == NULL || getenv("EMPTY")[0] != '\0') { + fail("EMPTY"); + } + { + const char *bytes = getenv("BYTES"); + if (bytes == NULL || (unsigned char)bytes[0] != 0xff || bytes[1] != '\0') { + fail("BYTES"); + } + } + for (i = 0; i < sizeof bss; i++) { + if (bss[i] != 0) { + fail("bss"); + } + } + bss[sizeof bss - 1] = 9; + if (data != 42) { + fail("data"); + } + data = 43; + if (tls != 17) { + fail("tls"); + } + tls = 23; + if (pthread_create(&thread, NULL, thread_main, &started) != 0) { + fail("pthread_create"); + } + if (pthread_join(thread, NULL) != 0 || started != 1) { + fail("pthread_join"); + } + if (tls != 23) { + fail("tls after join"); + } + + heap = malloc(128 * 1024); + if (heap == NULL) { + fail("malloc"); + } + memset(heap, 7, 128 * 1024); + for (i = 0; i < 128 * 1024; i++) { + if ((unsigned char)heap[i] != 7) { + fail("heap"); + } + } + free(heap); + + if (getauxval(AT_BASE) != 0) { + fail("AT_BASE"); + } + at_phdr = getauxval(AT_PHDR); + phnum = getauxval(AT_PHNUM); + phent = getauxval(AT_PHENT); + entry = getauxval(AT_ENTRY); + if (phent != sizeof(Elf64_Phdr) || at_phdr == 0 || phnum == 0 || entry == 0) { + fail("auxv"); + } + ph = (const Elf64_Phdr *)at_phdr; + bias = load_bias(at_phdr, phnum, ph); + if (getenv("EXPECT_FIXED_ADDRESS") != NULL && bias != 0) { + fail("relocated fixed image"); + } + { + int found_entry = 0; + for (i = 0; i < phnum; i++) { + unsigned long start; + unsigned long end; + if (ph[i].p_type != PT_LOAD || (ph[i].p_flags & PF_X) == 0) { + continue; + } + start = bias + (unsigned long)ph[i].p_vaddr; + end = start + (unsigned long)ph[i].p_memsz; + if (entry >= start && entry < end) { + found_entry = 1; + } + } + if (!found_entry) { + fail("AT_ENTRY"); + } + } + image = getenv("FIXTURE_IMAGE"); + if (image == NULL || strcmp((const char *)getauxval(AT_EXECFN), image) != 0) { + fail("AT_EXECFN"); + } + { + const unsigned char *random = (const unsigned char *)getauxval(AT_RANDOM); + int nonzero = 0; + if (random == NULL) { + fail("AT_RANDOM"); + } + for (i = 0; i < 16; i++) { + if (random[i] != 0) { + nonzero = 1; + } + } + if (!nonzero) { + fail("AT_RANDOM zero"); + } + } + + write(STDOUT_FILENO, "runtime-ok\n", 11); + _exit(37); +} diff --git a/crates/fspy_elf_loader_tests/src/bin/fixture.rs b/crates/fspy_elf_loader_tests/src/bin/fixture.rs index eb8a594e3..6b99288e2 100644 --- a/crates/fspy_elf_loader_tests/src/bin/fixture.rs +++ b/crates/fspy_elf_loader_tests/src/bin/fixture.rs @@ -59,11 +59,12 @@ fn main() { ..bias + usize::try_from(ph.p_vaddr + ph.p_memsz).unwrap()) .contains(&entry) })); - let interpreter = std::slice::from_raw_parts( - std::ptr::with_exposed_provenance::(aux(libc::AT_BASE)), - 4, - ); - assert_eq!(interpreter, b"\x7fELF"); + let base = aux(libc::AT_BASE); + if base != 0 { + let interpreter = + std::slice::from_raw_parts(std::ptr::with_exposed_provenance::(base), 4); + assert_eq!(interpreter, b"\x7fELF"); + } let random = std::slice::from_raw_parts( std::ptr::with_exposed_provenance::(aux(libc::AT_RANDOM)), 16, diff --git a/crates/fspy_elf_loader_tests/tests/exec_elf.rs b/crates/fspy_elf_loader_tests/tests/exec_elf.rs index 1f77b4625..bcb31f8f9 100644 --- a/crates/fspy_elf_loader_tests/tests/exec_elf.rs +++ b/crates/fspy_elf_loader_tests/tests/exec_elf.rs @@ -13,11 +13,13 @@ use ntest::timeout; const LAUNCHER: &str = env!("CARGO_BIN_FILE_FSPY_ELF_LOADER_fspy_elf_loader_test_launcher"); const FIXTURE: &str = env!("CARGO_BIN_EXE_fixture"); const FIXTURE_EXEC: &str = env!("CARGO_BIN_EXE_fixture_exec"); +const FIXTURE_STATIC: &str = env!("FIXTURE_STATIC"); +const FIXTURE_STATIC_PIE: &str = env!("FIXTURE_STATIC_PIE"); #[test] #[timeout(10_000)] fn echo_matches_kernel_exec() { - assert_dynamic_image("/bin/echo", elf::abi::ET_DYN); + assert_image("/bin/echo", elf::abi::ET_DYN, true); let mut direct = Command::new("/bin/echo"); direct.args(["hello", "world"]); let mut loaded = launcher(); @@ -57,7 +59,11 @@ fn initializes_fixed_runtime() { } fn check_runtime(fixture: &str, image_type: u16) { - assert_dynamic_image(fixture, image_type); + check_runtime_image(fixture, image_type, true); +} + +fn check_runtime_image(fixture: &str, image_type: u16, interpreter: bool) { + assert_image(fixture, image_type, interpreter); let mut command = launcher(); command.args([fixture, "custom-argv-zero", ""]); command.arg(OsStr::from_bytes(b"\xff")); @@ -74,12 +80,14 @@ fn check_runtime(fixture: &str, image_type: u16) { #[test] #[timeout(10_000)] -fn rejects_unsupported_static_image() { - let mut command = launcher(); - command.args([LAUNCHER, "target-argv-zero"]); - let output = output(command); - assert_eq!(output.status.code(), Some(101), "{output:?}"); - assert!(str::from_utf8(&output.stderr).unwrap().contains("executable has no PT_INTERP")); +fn initializes_static_runtime() { + check_runtime_image(FIXTURE_STATIC, elf::abi::ET_EXEC, false); +} + +#[test] +#[timeout(10_000)] +fn initializes_static_pie_runtime() { + check_runtime_image(FIXTURE_STATIC_PIE, elf::abi::ET_DYN, false); } #[test] @@ -222,11 +230,12 @@ fn launcher() -> Command { command } -fn assert_dynamic_image(path: &str, image_type: u16) { +fn assert_image(path: &str, image_type: u16, interpreter: bool) { let bytes = std::fs::read(path).unwrap(); let elf = elf::ElfBytes::::minimal_parse(&bytes).unwrap(); assert_eq!(elf.ehdr.e_type, image_type, "unexpected fixture image type: {path}"); - assert!(elf.segments().unwrap().iter().any(|ph| ph.p_type == elf::abi::PT_INTERP)); + let has_interp = elf.segments().unwrap().iter().any(|ph| ph.p_type == elf::abi::PT_INTERP); + assert_eq!(has_interp, interpreter, "unexpected PT_INTERP: {path}"); } fn output(mut command: Command) -> Output { From bf0640a9cb507829d38a0d9438050dccf88a591e Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 20 Nov 2026 01:54:02 +0000 Subject: [PATCH 3/3] fix(fspy-nostd): keep allocator guard off Windows std links The undefined __fspy_global_allocator_must_not_be_used symbol is for freestanding Linux/none binaries. Linking it into fspy_preload_windows fails MSVC because the rlib object is retained. Also align cargo-shear with the rustc-only allocator fixture and skip lib doctests that rustdoc compiles with std. Co-authored-by: Cursor Grok 4.6 Co-authored-by: Charles Wang --- crates/fspy_elf_loader/Cargo.toml | 3 +++ crates/fspy_nostd/Cargo.toml | 7 +++++++ crates/fspy_nostd/src/entry.rs | 5 +---- crates/fspy_nostd/src/lib.rs | 1 + 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/crates/fspy_elf_loader/Cargo.toml b/crates/fspy_elf_loader/Cargo.toml index 4d2395d4e..62551f55c 100644 --- a/crates/fspy_elf_loader/Cargo.toml +++ b/crates/fspy_elf_loader/Cargo.toml @@ -25,5 +25,8 @@ path = "tests/support/launcher.rs" test = false bench = false +[lib] +doctest = false + [lints] workspace = true diff --git a/crates/fspy_nostd/Cargo.toml b/crates/fspy_nostd/Cargo.toml index 879a13da5..e104cacc0 100644 --- a/crates/fspy_nostd/Cargo.toml +++ b/crates/fspy_nostd/Cargo.toml @@ -29,8 +29,15 @@ windows-sys = { workspace = true, features = [ "Win32_System_Memory", ] } +[lib] +doctest = false + [lints] workspace = true [dev-dependencies] tempfile = { workspace = true } + +[package.metadata.cargo-shear] +# Compiled by rustc from tests/no_global_alloc.rs, not as a crate module. +ignored-paths = ["tests/support/no_global_alloc.rs"] diff --git a/crates/fspy_nostd/src/entry.rs b/crates/fspy_nostd/src/entry.rs index 2879e3ebd..e741e7acd 100644 --- a/crates/fspy_nostd/src/entry.rs +++ b/crates/fspy_nostd/src/entry.rs @@ -6,13 +6,10 @@ /// accept any stack lifetime; it cannot require `InitialStack<'static>`. /// /// ```compile_fail,E0308 -/// #![no_std] -/// #![no_main] -/// /// fn run(_: fspy_nostd::env::InitialStack<'static>) -> ! { /// loop {} /// } -/// fspy_nostd::main!(run); +/// const _: for<'a> fn(fspy_nostd::env::InitialStack<'a>) -> ! = run; /// ``` /// /// Supports `AArch64` and x86-64. The executable must use `#![no_main]` and diff --git a/crates/fspy_nostd/src/lib.rs b/crates/fspy_nostd/src/lib.rs index e10fda1ca..fbd6b36f8 100644 --- a/crates/fspy_nostd/src/lib.rs +++ b/crates/fspy_nostd/src/lib.rs @@ -13,6 +13,7 @@ mod entry; mod error; #[cfg(any(target_os = "linux", target_os = "none", target_os = "macos"))] mod fd; +#[cfg(any(target_os = "linux", target_os = "none"))] #[doc(hidden)] pub mod no_global_alloc; #[cfg(any(target_os = "linux", target_os = "none"))]