From 6730e4b07a7cdb290ac9f14ed0865beeb0925ca8 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Fri, 27 Nov 2026 08:24:39 +0800 Subject: [PATCH 1/4] feat(fspy_nostd): add Unix filesystem, I/O, and path-resolution primitives Add low-level `no_std` filesystem, I/O, and allocator-backed path resolution primitives needed by the freestanding Linux ELF/SIGSYS tracker and shared Unix exec resolver: - `fspy_nostd`: `Error::ACCES`, `pread`, `faccessat`, `stat`/`fstat`, `getcwd`, `readlinkat`/`fcntl_getpath`, plus unit tests. - `fspy_nostd_alloc`: allocator-backed `getcwd`, `fd_path`, `resolve_path_at`, and pooled bump allocator helpers, plus unit tests. - `vt_ipc_str`: `IpcStr::as_bytes` for Unix and `target_os = "none"`. - `fspy_shared`: gate host dev-dependencies on `not(target_os = "none")`. Co-authored-by: Gemini 4 Neon --- .typos.toml | 2 + Cargo.lock | 1 + crates/fspy_nostd/src/error.rs | 25 +++- crates/fspy_nostd/src/fd.rs | 3 +- crates/fspy_nostd/src/fs/linux.rs | 94 +++++++++++- crates/fspy_nostd/src/fs/mac.rs | 23 ++- crates/fspy_nostd/src/fs/tests.rs | 72 ++++++++++ crates/fspy_nostd/src/fs/unix.rs | 35 ++++- crates/fspy_nostd/src/io.rs | 71 +++++++++ crates/fspy_nostd_alloc/Cargo.toml | 3 + crates/fspy_nostd_alloc/src/fs.rs | 223 +++++++++++++++++++++++++++-- crates/fspy_nostd_alloc/src/lib.rs | 84 +++++++++-- crates/fspy_shared/Cargo.toml | 4 +- crates/vt_ipc_str/src/lib.rs | 6 + 14 files changed, 612 insertions(+), 34 deletions(-) diff --git a/.typos.toml b/.typos.toml index c227ba5df..b356d1098 100644 --- a/.typos.toml +++ b/.typos.toml @@ -4,6 +4,8 @@ PUNICODE = "PUNICODE" EDN = "EDN" # Win32 spells `ERROR_FILENAME_EXCED_RANGE` this way. EXCED = "EXCED" +# POSIX errno `EACCES` (`fspy_nostd::Error::ACCES`). +ACCES = "ACCES" [files] extend-exclude = [ diff --git a/Cargo.lock b/Cargo.lock index ec8175b57..9d0c90324 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1518,6 +1518,7 @@ dependencies = [ "allocator-api2", "bump-scope", "fspy_nostd", + "tempfile", ] [[package]] diff --git a/crates/fspy_nostd/src/error.rs b/crates/fspy_nostd/src/error.rs index 08db08466..12299d0ad 100644 --- a/crates/fspy_nostd/src/error.rs +++ b/crates/fspy_nostd/src/error.rs @@ -17,11 +17,18 @@ pub struct Error(u32); #[cfg(any(target_os = "linux", target_os = "none", target_os = "macos"))] impl Error { + pub const ACCES: Self = Self(errno::ACCES); pub const BADF: Self = Self(errno::BADF); + pub const FAULT: Self = Self(errno::FAULT); pub const INTR: Self = Self(errno::INTR); pub const INVAL: Self = Self(errno::INVAL); + pub const LOOP: Self = Self(errno::LOOP); + pub const NAMETOOLONG: Self = Self(errno::NAMETOOLONG); pub const NOENT: Self = Self(errno::NOENT); + pub const NOEXEC: Self = Self(errno::NOEXEC); pub const NOMEM: Self = Self(errno::NOMEM); + pub const NOSYS: Self = Self(errno::NOSYS); + pub const NOTDIR: Self = Self(errno::NOTDIR); pub const OVERFLOW: Self = Self(errno::OVERFLOW); pub const RANGE: Self = Self(errno::RANGE); @@ -87,22 +94,36 @@ impl From for Error { #[cfg(any(target_os = "linux", target_os = "none"))] mod errno { + pub const ACCES: i32 = linux_raw_sys::errno::EACCES.cast_signed(); pub const BADF: i32 = linux_raw_sys::errno::EBADF.cast_signed(); + pub const FAULT: i32 = linux_raw_sys::errno::EFAULT.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 LOOP: i32 = linux_raw_sys::errno::ELOOP.cast_signed(); + pub const NAMETOOLONG: i32 = linux_raw_sys::errno::ENAMETOOLONG.cast_signed(); pub const NOENT: i32 = linux_raw_sys::errno::ENOENT.cast_signed(); + pub const NOEXEC: i32 = linux_raw_sys::errno::ENOEXEC.cast_signed(); + pub const NOMEM: i32 = linux_raw_sys::errno::ENOMEM.cast_signed(); + pub const NOSYS: i32 = linux_raw_sys::errno::ENOSYS.cast_signed(); + pub const NOTDIR: i32 = linux_raw_sys::errno::ENOTDIR.cast_signed(); pub const OVERFLOW: i32 = linux_raw_sys::errno::EOVERFLOW.cast_signed(); pub const RANGE: i32 = linux_raw_sys::errno::ERANGE.cast_signed(); } #[cfg(target_os = "macos")] mod errno { + pub const ACCES: i32 = libc::EACCES; pub const BADF: i32 = libc::EBADF; + pub const FAULT: i32 = libc::EFAULT; pub const INTR: i32 = libc::EINTR; pub const INVAL: i32 = libc::EINVAL; - pub const NOMEM: i32 = libc::ENOMEM; + pub const LOOP: i32 = libc::ELOOP; + pub const NAMETOOLONG: i32 = libc::ENAMETOOLONG; pub const NOENT: i32 = libc::ENOENT; + pub const NOEXEC: i32 = libc::ENOEXEC; + pub const NOMEM: i32 = libc::ENOMEM; + pub const NOSYS: i32 = libc::ENOSYS; + pub const NOTDIR: i32 = libc::ENOTDIR; pub const OVERFLOW: i32 = libc::EOVERFLOW; pub const RANGE: i32 = libc::ERANGE; } diff --git a/crates/fspy_nostd/src/fd.rs b/crates/fspy_nostd/src/fd.rs index 46a2818c6..dace4e0e7 100644 --- a/crates/fspy_nostd/src/fd.rs +++ b/crates/fspy_nostd/src/fd.rs @@ -100,7 +100,8 @@ impl OwnedFd { /// # Safety /// /// `fd` must be a valid, uniquely owned descriptor that may be closed. - pub(crate) const unsafe fn from_raw_fd(fd: RawFd) -> Self { + #[must_use] + pub const unsafe fn from_raw_fd(fd: RawFd) -> Self { debug_assert!(fd >= 0); Self { fd } } diff --git a/crates/fspy_nostd/src/fs/linux.rs b/crates/fspy_nostd/src/fs/linux.rs index 259133da2..e4b4d0b13 100644 --- a/crates/fspy_nostd/src/fs/linux.rs +++ b/crates/fspy_nostd/src/fs/linux.rs @@ -1,8 +1,8 @@ use core::{mem::MaybeUninit, slice}; use crate::{ - BorrowedFd, CStr, Error, Fat, OwnedFd, Result, Thin, - fs::{AtFlags, Mode, OFlags, Stat}, + BorrowedFd, CStr, Error, Fat, OwnedFd, RawFd, Result, Thin, + fs::{AccessFlags, AtFlags, Mode, OFlags, Stat}, }; // Linux UAPI `PATH_MAX`. @@ -11,11 +11,36 @@ pub(super) const O_RDONLY: u32 = linux_raw_sys::general::O_RDONLY; pub(super) const O_RDWR: u32 = linux_raw_sys::general::O_RDWR; pub(super) const O_CREAT: u32 = linux_raw_sys::general::O_CREAT; pub(super) const O_EXCL: u32 = linux_raw_sys::general::O_EXCL; +pub(super) const O_NOFOLLOW: u32 = linux_raw_sys::general::O_NOFOLLOW; +pub(super) const O_NONBLOCK: u32 = linux_raw_sys::general::O_NONBLOCK; pub(super) const O_CLOEXEC: u32 = linux_raw_sys::general::O_CLOEXEC; pub(super) const AT_REMOVEDIR: u32 = linux_raw_sys::general::AT_REMOVEDIR; +pub(super) const X_OK: u32 = 1; pub(super) type ModeBits = u32; pub(super) const S_IRUSR: ModeBits = linux_raw_sys::general::S_IRUSR; pub(super) const S_IWUSR: ModeBits = linux_raw_sys::general::S_IWUSR; +pub(super) const S_IFMT: ModeBits = linux_raw_sys::general::S_IFMT; +pub(super) const S_IFREG: ModeBits = linux_raw_sys::general::S_IFREG; + +#[expect(clippy::needless_pass_by_value, reason = "CStr is a borrowed value type")] +pub(super) fn faccessat( + dirfd: BorrowedFd<'_>, + path: CStr<'_, R>, + mode: AccessFlags, +) -> Result<()> { + // SAFETY: `dirfd` remains borrowed and `path` is NUL-terminated for the + // syscall. + unsafe { + syscalls::syscall!( + syscalls::Sysno::faccessat, + dirfd.as_raw_fd(), + path.as_ptr(), + mode.bits() + ) + } + .map_err(Error::from)?; + Ok(()) +} #[expect(clippy::needless_pass_by_value, reason = "CStr is a borrowed value type")] pub(super) fn openat( @@ -69,7 +94,70 @@ pub(super) fn fstat(fd: BorrowedFd<'_>) -> Result { .map_err(Error::from)?; // SAFETY: a successful `fstat` initialized the complete structure. let raw = unsafe { raw.assume_init() }; - Ok(Stat { st_size: raw.st_size }) + Ok(Stat { st_size: raw.st_size, st_mode: raw.st_mode }) +} + +/// Duplicates `fd` to the lowest available descriptor greater than or equal to +/// `min_fd`, leaving `FD_CLOEXEC` clear on the duplicate. +/// +/// # Errors +/// +/// Returns the error reported by `fcntl`. +pub fn fcntl_dupfd(fd: BorrowedFd<'_>, min_fd: RawFd) -> Result { + // SAFETY: `fd` remains borrowed and `F_DUPFD` takes one integer argument. + let dup = unsafe { + syscalls::syscall!( + syscalls::Sysno::fcntl, + fd.as_raw_fd(), + linux_raw_sys::general::F_DUPFD, + min_fd + ) + } + .map_err(Error::from)?; + + let dup = i32::try_from(dup).map_err(|_| Error::OVERFLOW)?; + + // SAFETY: a successful `F_DUPFD` returns a new owned descriptor. + Ok(unsafe { OwnedFd::from_raw_fd(dup) }) +} + +/// Duplicates `fd` to the lowest available descriptor greater than or equal to +/// `min_fd`, setting `FD_CLOEXEC` on the duplicate. +/// +/// # Errors +/// +/// Returns the error reported by `fcntl`. +pub fn fcntl_dupfd_cloexec(fd: BorrowedFd<'_>, min_fd: RawFd) -> Result { + // SAFETY: `fd` remains borrowed and `F_DUPFD_CLOEXEC` takes one integer argument. + let dup = unsafe { + syscalls::syscall!( + syscalls::Sysno::fcntl, + fd.as_raw_fd(), + linux_raw_sys::general::F_DUPFD_CLOEXEC, + min_fd + ) + } + .map_err(Error::from)?; + + let dup = i32::try_from(dup).map_err(|_| Error::OVERFLOW)?; + + // SAFETY: a successful `F_DUPFD_CLOEXEC` returns a new owned descriptor. + Ok(unsafe { OwnedFd::from_raw_fd(dup) }) +} + +/// Returns whether `FD_CLOEXEC` is set on `fd`. +/// +/// # Errors +/// +/// Returns the error reported by `fcntl`. +pub fn fcntl_is_cloexec(fd: BorrowedFd<'_>) -> Result { + // SAFETY: `fd` remains borrowed and `F_GETFD` takes no additional arguments. + let flags = unsafe { + syscalls::syscall!(syscalls::Sysno::fcntl, fd.as_raw_fd(), linux_raw_sys::general::F_GETFD) + } + .map_err(Error::from)?; + + Ok((flags & (linux_raw_sys::general::FD_CLOEXEC as usize)) != 0) } pub(super) fn ftruncate(fd: BorrowedFd<'_>, len: u64) -> Result<()> { diff --git a/crates/fspy_nostd/src/fs/mac.rs b/crates/fspy_nostd/src/fs/mac.rs index 943dfd417..e0928d452 100644 --- a/crates/fspy_nostd/src/fs/mac.rs +++ b/crates/fspy_nostd/src/fs/mac.rs @@ -2,7 +2,7 @@ use core::{mem::MaybeUninit, slice}; use crate::{ BorrowedFd, CStr, CWD, Error, Fat, OwnedFd, Result, Thin, - fs::{AtFlags, Mode, OFlags, Stat}, + fs::{AccessFlags, AtFlags, Mode, OFlags, Stat}, }; // Darwin UAPI `MAXPATHLEN`. @@ -12,11 +12,30 @@ pub(super) const O_RDONLY: u32 = libc::O_RDONLY.cast_unsigned(); pub(super) const O_RDWR: u32 = libc::O_RDWR.cast_unsigned(); pub(super) const O_CREAT: u32 = libc::O_CREAT.cast_unsigned(); pub(super) const O_EXCL: u32 = libc::O_EXCL.cast_unsigned(); +pub(super) const O_NOFOLLOW: u32 = libc::O_NOFOLLOW.cast_unsigned(); +pub(super) const O_NONBLOCK: u32 = libc::O_NONBLOCK.cast_unsigned(); pub(super) const O_CLOEXEC: u32 = libc::O_CLOEXEC.cast_unsigned(); pub(super) const AT_REMOVEDIR: u32 = libc::AT_REMOVEDIR.cast_unsigned(); +pub(super) const X_OK: u32 = libc::X_OK.cast_unsigned(); pub(super) type ModeBits = libc::mode_t; pub(super) const S_IRUSR: ModeBits = libc::S_IRUSR; pub(super) const S_IWUSR: ModeBits = libc::S_IWUSR; +pub(super) const S_IFMT: ModeBits = libc::S_IFMT; +pub(super) const S_IFREG: ModeBits = libc::S_IFREG; + +#[expect(clippy::needless_pass_by_value, reason = "CStr is a borrowed value type")] +pub(super) fn faccessat( + dirfd: BorrowedFd<'_>, + path: CStr<'_, R>, + mode: AccessFlags, +) -> Result<()> { + // SAFETY: `dirfd` remains borrowed and `path` is NUL-terminated for the + // call. + let result = unsafe { + libc::faccessat(dirfd.as_raw_fd(), path.as_ptr().cast(), mode.bits().cast_signed(), 0) + }; + if result == -1 { Err(Error::last_os_error()) } else { Ok(()) } +} #[expect(clippy::needless_pass_by_value, reason = "CStr is a borrowed value type")] pub(super) fn openat( @@ -61,7 +80,7 @@ pub(super) fn fstat(fd: BorrowedFd<'_>) -> Result { } // SAFETY: a successful `fstat` initialized the complete structure. let raw = unsafe { raw.assume_init() }; - Ok(Stat { st_size: raw.st_size }) + Ok(Stat { st_size: raw.st_size, st_mode: raw.st_mode }) } pub(super) fn ftruncate(fd: BorrowedFd<'_>, len: u64) -> Result<()> { diff --git a/crates/fspy_nostd/src/fs/tests.rs b/crates/fspy_nostd/src/fs/tests.rs index 87e99d9d3..ab1cef121 100644 --- a/crates/fspy_nostd/src/fs/tests.rs +++ b/crates/fspy_nostd/src/fs/tests.rs @@ -60,3 +60,75 @@ fn readlinkat_returns_the_initialized_target() { assert_eq!(target, std::fs::read_link("/proc/self/exe").unwrap().as_os_str().as_bytes()); } + +#[test] +fn faccessat_checks_existence_and_execute_permission() { + use std::{ffi::CString, fs::Permissions, os::unix::fs::PermissionsExt as _}; + + let dir = tempfile::tempdir().unwrap(); + let file_path = dir.path().join("target"); + std::fs::write(&file_path, b"x").unwrap(); + std::fs::set_permissions(&file_path, Permissions::from_mode(0o600)).unwrap(); + + let file_c = CString::new(file_path.as_os_str().as_bytes()).unwrap(); + // SAFETY: `file_c` is NUL-terminated for the duration of the test. + let file_cstr = unsafe { crate::CStr::::from_ptr(file_c.as_ptr().cast()) }; + + assert_eq!(super::faccessat(crate::CWD, file_cstr, super::AccessFlags::empty()), Ok(())); + assert_eq!( + super::faccessat(crate::CWD, file_cstr, super::AccessFlags::X_OK), + Err(Error::ACCES) + ); + + std::fs::set_permissions(&file_path, Permissions::from_mode(0o700)).unwrap(); + assert_eq!(super::faccessat(crate::CWD, file_cstr, super::AccessFlags::X_OK), Ok(())); + + let missing_path = dir.path().join("missing"); + let missing_c = CString::new(missing_path.as_os_str().as_bytes()).unwrap(); + // SAFETY: `missing_c` is NUL-terminated for the duration of the test. + let missing_cstr = unsafe { crate::CStr::::from_ptr(missing_c.as_ptr().cast()) }; + assert_eq!( + super::faccessat(crate::CWD, missing_cstr, super::AccessFlags::empty()), + Err(Error::NOENT) + ); +} + +#[test] +fn stat_distinguishes_regular_files_from_directories() { + use std::os::fd::AsRawFd as _; + + let file = tempfile::tempfile().unwrap(); + // SAFETY: `file` remains open for the call. + let file_fd = unsafe { crate::BorrowedFd::borrow_raw(file.as_raw_fd()) }; + assert!(super::fstat(file_fd).unwrap().is_regular_file()); + + let dir = tempfile::tempdir().unwrap(); + let dir_file = std::fs::File::open(dir.path()).unwrap(); + // SAFETY: `dir_file` remains open for the call. + let dir_fd = unsafe { crate::BorrowedFd::borrow_raw(dir_file.as_raw_fd()) }; + assert!(!super::fstat(dir_fd).unwrap().is_regular_file()); +} + +#[cfg(target_os = "linux")] +#[test] +fn fcntl_dupfd_duplicates_above_min_fd_without_cloexec() { + use std::{io::Write as _, os::fd::AsRawFd as _}; + + let mut file = tempfile::tempfile().unwrap(); + file.write_all(b"dup-test").unwrap(); + + // SAFETY: `file` remains open for the call. + let fd = unsafe { crate::BorrowedFd::borrow_raw(file.as_raw_fd()) }; + let dup = super::fcntl_dupfd(fd, 20).unwrap(); + + assert!(dup.as_raw_fd() >= 20); + assert!(!super::fcntl_is_cloexec(dup.as_fd()).unwrap()); + + let dup_cloexec = super::fcntl_dupfd_cloexec(fd, 25).unwrap(); + assert!(dup_cloexec.as_raw_fd() >= 25); + assert!(super::fcntl_is_cloexec(dup_cloexec.as_fd()).unwrap()); + + let mut buf = [0u8; 8]; + assert_eq!(crate::io::pread(dup.as_fd(), &mut buf, 0).unwrap(), 8); + assert_eq!(&buf, b"dup-test"); +} diff --git a/crates/fspy_nostd/src/fs/unix.rs b/crates/fspy_nostd/src/fs/unix.rs index 36c7ceeec..c5d155cc8 100644 --- a/crates/fspy_nostd/src/fs/unix.rs +++ b/crates/fspy_nostd/src/fs/unix.rs @@ -5,7 +5,7 @@ use bitflags::bitflags; #[cfg(any(target_os = "linux", target_os = "none"))] use super::linux as imp; #[cfg(any(target_os = "linux", target_os = "none"))] -pub use super::linux::readlinkat; +pub use super::linux::{fcntl_dupfd, fcntl_dupfd_cloexec, fcntl_is_cloexec, readlinkat}; #[cfg(target_os = "macos")] use super::mac as imp; #[cfg(target_os = "macos")] @@ -26,6 +26,10 @@ bitflags! { const CREATE = imp::O_CREAT; /// Fail when creating a file that already exists. const EXCL = imp::O_EXCL; + /// Do not follow a trailing symbolic link. + const NOFOLLOW = imp::O_NOFOLLOW; + /// Open in non-blocking mode. + const NONBLOCK = imp::O_NONBLOCK; /// Close the descriptor across `exec`. const CLOEXEC = imp::O_CLOEXEC; } @@ -45,17 +49,44 @@ bitflags! { /// Remove a directory rather than a non-directory entry. const REMOVEDIR = imp::AT_REMOVEDIR; } + + /// Mode bits accepted by [`faccessat`]. + /// + /// An empty flag set checks file existence (`F_OK`). + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub struct AccessFlags: u32 { + /// Check execute permission. + const X_OK = imp::X_OK; + } } -/// Metadata used by fspy's shared-memory backing files. +/// Metadata for an open file descriptor. #[derive(Clone, Copy, Debug)] pub struct Stat { pub st_size: i64, + pub(super) st_mode: ModeBits, +} + +impl Stat { + /// Returns `true` when the file is a regular file (`S_ISREG`). + #[must_use] + pub const fn is_regular_file(&self) -> bool { + (self.st_mode & imp::S_IFMT) == imp::S_IFREG + } } /// The platform's maximum pathname size, including the terminating NUL. pub const PATH_MAX: usize = imp::PATH_MAX; +/// Checks accessibility of `path` relative to `dirfd`. +/// +/// # Errors +/// +/// Returns the error reported by `faccessat`. +pub fn faccessat(dirfd: BorrowedFd<'_>, path: CStr<'_, R>, mode: AccessFlags) -> Result<()> { + imp::faccessat(dirfd, path, mode) +} + /// Opens `path` relative to `dirfd` and returns its owned descriptor. /// /// # Errors diff --git a/crates/fspy_nostd/src/io.rs b/crates/fspy_nostd/src/io.rs index bba554c2e..2814dd0dc 100644 --- a/crates/fspy_nostd/src/io.rs +++ b/crates/fspy_nostd/src/io.rs @@ -17,6 +17,38 @@ pub fn read(fd: BorrowedFd<'_>, buf: &mut [u8]) -> Result { .map_err(Error::from) } +/// Reads from `fd` starting at byte `offset` into `buf` without modifying the +/// descriptor's file offset, returning the initialized byte count. +/// +/// # Errors +/// +/// Returns [`Error::INVAL`] if `offset` exceeds `i64::MAX`, or the error +/// reported by `pread`. +pub fn pread(fd: BorrowedFd<'_>, buf: &mut [u8], offset: u64) -> Result { + let offset = i64::try_from(offset).map_err(|_| Error::INVAL)?; + #[cfg(any(target_os = "linux", target_os = "none"))] + { + // SAFETY: `fd` stays borrowed and `buf` is writable for its whole length. + unsafe { + syscalls::syscall!( + syscalls::Sysno::pread64, + fd.as_raw_fd(), + buf.as_mut_ptr(), + buf.len(), + offset + ) + } + .map_err(Error::from) + } + #[cfg(target_os = "macos")] + { + // SAFETY: `fd` stays borrowed and `buf` is writable for its whole length. + let read = + unsafe { libc::pread(fd.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len(), offset) }; + if read == -1 { Err(Error::last_os_error()) } else { Ok(read.cast_unsigned()) } + } +} + /// Writes `buf` to `fd` with a single `write(2)` and returns the number of /// bytes the kernel accepted. /// @@ -42,3 +74,42 @@ pub fn write(fd: BorrowedFd<'_>, buf: &[u8]) -> Result { if written == -1 { Err(Error::last_os_error()) } else { Ok(written.cast_unsigned()) } } } + +#[cfg(test)] +mod tests { + use std::{ + io::{Read as _, Seek as _, SeekFrom, Write as _}, + os::fd::AsRawFd as _, + }; + + use super::pread; + use crate::{BorrowedFd, Error}; + + #[test] + fn pread_reads_at_offset_without_mutating_seek_position() { + let mut file = tempfile::tempfile().unwrap(); + file.write_all(b"abcdef").unwrap(); + file.seek(SeekFrom::Start(3)).unwrap(); + + // SAFETY: `file` remains open for the duration of the calls. + let fd = unsafe { BorrowedFd::borrow_raw(file.as_raw_fd()) }; + + let mut head = [0u8; 3]; + assert_eq!(pread(fd, &mut head, 0).unwrap(), 3); + assert_eq!(&head, b"abc"); + + // Offset 0 read must not disturb the current seek position. + assert_eq!(file.stream_position().unwrap(), 3); + + let mut mid = [0u8; 2]; + assert_eq!(pread(fd, &mut mid, 2).unwrap(), 2); + assert_eq!(&mid, b"cd"); + assert_eq!(file.stream_position().unwrap(), 3); + + let mut tail = [0u8; 3]; + file.read_exact(&mut tail).unwrap(); + assert_eq!(&tail, b"def"); + + assert_eq!(pread(fd, &mut head, u64::MAX), Err(Error::INVAL)); + } +} diff --git a/crates/fspy_nostd_alloc/Cargo.toml b/crates/fspy_nostd_alloc/Cargo.toml index 1c209f66f..1273181bd 100644 --- a/crates/fspy_nostd_alloc/Cargo.toml +++ b/crates/fspy_nostd_alloc/Cargo.toml @@ -14,3 +14,6 @@ fspy_nostd = { workspace = true } [lints] workspace = true + +[dev-dependencies] +tempfile = { workspace = true } diff --git a/crates/fspy_nostd_alloc/src/fs.rs b/crates/fspy_nostd_alloc/src/fs.rs index c348b6a48..9121e270b 100644 --- a/crates/fspy_nostd_alloc/src/fs.rs +++ b/crates/fspy_nostd_alloc/src/fs.rs @@ -3,11 +3,7 @@ #[cfg(target_os = "macos")] use allocator_api2::boxed::Box; use allocator_api2::{alloc::Allocator, vec::Vec}; -#[cfg(any(target_os = "linux", target_os = "none", target_os = "macos"))] -use fspy_nostd::Thin; -#[cfg(any(target_os = "linux", target_os = "none"))] -use fspy_nostd::{BorrowedFd, CStr}; -use fspy_nostd::{Error, Fat, Result}; +use fspy_nostd::{BorrowedFd, CStr, CWD, Error, Fat, Result, Thin}; use crate::CString; @@ -103,9 +99,132 @@ fn path_buffer( Ok(unsafe { bytes.assume_init() }) } +/// Resolves the pathname associated with an open file descriptor (or [`CWD`]), +/// allocated with `allocator`. +/// +/// Returns `Ok(None)` when the descriptor is invalid or has no resolvable path +/// (`EBADF` / `ENOENT`). +/// +/// # Errors +/// +/// Returns [`Error::NOMEM`] if storage cannot be allocated, or any other OS +/// error reported while resolving the descriptor. +pub fn fd_path(allocator: A, fd: BorrowedFd<'_>) -> Result>> { + if fd.as_raw_fd() == CWD.as_raw_fd() { + return getcwd(allocator).map(Some); + } + + #[cfg(any(target_os = "linux", target_os = "none"))] + { + let Ok(raw_fd) = u32::try_from(fd.as_raw_fd()) else { + return Ok(None); + }; + let mut proc_buf = [0u8; 32]; + let proc_path = format_proc_self_fd(&mut proc_buf, raw_fd); + match readlinkat(allocator, CWD, proc_path) { + Ok(mut bytes) => { + bytes.try_reserve(1).map_err(|_| Error::NOMEM)?; + bytes.push(0); + Ok(CString::from_vec_with_nul(bytes)) + } + Err(Error::BADF | Error::NOENT) => Ok(None), + Err(err) => Err(err), + } + } + + #[cfg(target_os = "macos")] + { + match fcntl_getpath(allocator, fd) { + Ok(path) => Ok(Some(path.count())), + Err(Error::BADF | Error::NOENT) => Ok(None), + Err(err) => Err(err), + } + } +} + +/// Formats `/proc/self/fd/\0` on the stack without allocating. +#[cfg(any(target_os = "linux", target_os = "none"))] +fn format_proc_self_fd(buf: &mut [u8; 32], mut fd: u32) -> CStr<'_, Thin> { + const PREFIX: &[u8] = b"/proc/self/fd/"; + let mut digits = [0u8; 10]; + let mut num_digits = 0; + loop { + digits[num_digits] = b'0' + (fd % 10) as u8; + num_digits += 1; + fd /= 10; + if fd == 0 { + break; + } + } + let mut len = PREFIX.len(); + buf[..len].copy_from_slice(PREFIX); + for i in (0..num_digits).rev() { + buf[len] = digits[i]; + len += 1; + } + buf[len] = 0; + // SAFETY: `buf` begins with a NUL-terminated ASCII string and remains + // borrowed for the returned lifetime. + unsafe { CStr::from_ptr(buf.as_ptr()) } +} + +/// Resolves `path` relative to `dirfd`, leaking any newly allocated joined +/// pathname into `allocator`. +/// +/// Absolute paths are returned directly without allocating. Relative paths +/// (including the empty path) return `Ok(None)` when `dirfd` is `None` or +/// cannot be resolved to a path. +/// +/// # Errors +/// +/// Returns [`Error::NOMEM`] if storage cannot be allocated, or any other OS +/// error from [`fd_path`]. +pub fn resolve_path_at<'a, A: Allocator>( + allocator: &'a A, + dirfd: Option>, + path: CStr<'a, Thin>, +) -> Result>> { + let counted = path.count(); + let rel = counted.as_units(); + if rel.first() == Some(&b'/') { + return Ok(Some(counted)); + } + + let Some(dirfd) = dirfd else { + return Ok(None); + }; + + let Some(base) = fd_path(allocator, dirfd)? else { + return Ok(None); + }; + + let bytes = if rel.is_empty() { + base.into_units_with_nul() + } else { + let mut joined = base.into_units(); + let needs_sep = joined.last() != Some(&b'/'); + let extra = usize::from(needs_sep) + rel.len() + 1; + joined.try_reserve(extra).map_err(|_| Error::NOMEM)?; + if needs_sep { + joined.push(b'/'); + } + joined.extend_from_slice(rel); + joined.push(0); + joined + }; + + let leaked: &'a [u8] = bytes.leak(); + // SAFETY: `base` and `rel` contain no interior NULs, and `bytes` ends with + // exactly one NUL terminator. + Ok(Some(unsafe { CStr::from_units_with_nul_unchecked(leaked) })) +} + #[cfg(test)] mod tests { + use std::{ffi::CString as StdCString, fs::File, os::fd::AsRawFd as _}; + use allocator_api2::alloc::Global; + use fspy_nostd::{BorrowedFd, CStr, CWD, Thin}; #[test] fn getcwd_allocates_a_c_string() { @@ -126,11 +245,9 @@ mod tests { #[cfg(target_os = "macos")] #[test] fn fcntl_getpath_allocates_a_thin_c_string() { - use std::{fs::File, os::fd::AsRawFd as _}; - let root = File::open("/").unwrap(); // SAFETY: `root` remains open for the call. - let root = unsafe { fspy_nostd::BorrowedFd::borrow_raw(root.as_raw_fd()) }; + let root = unsafe { BorrowedFd::borrow_raw(root.as_raw_fd()) }; let path = super::fcntl_getpath(Global, root).unwrap(); assert_eq!(path.as_c_str().count().as_units_with_nul(), b"/\0"); @@ -140,14 +257,96 @@ mod tests { #[test] fn readlinkat_allocates_the_complete_target() { // SAFETY: the literal is NUL-terminated and lives for the call. - let path = unsafe { - fspy_nostd::CStr::::from_ptr(c"/proc/self/exe".as_ptr().cast()) - }; - let target = super::readlinkat(Global, fspy_nostd::CWD, path).unwrap(); + let path = unsafe { CStr::::from_ptr(c"/proc/self/exe".as_ptr().cast()) }; + let target = super::readlinkat(Global, CWD, path).unwrap(); assert_eq!( target.as_slice(), std::fs::read_link("/proc/self/exe").unwrap().as_os_str().as_encoded_bytes() ); } + + #[test] + fn fd_path_resolves_cwd_regular_fd_and_invalid_fd() { + let cwd_path = super::fd_path(Global, CWD).unwrap().unwrap(); + let expected_cwd = super::getcwd(Global).unwrap(); + assert_eq!(cwd_path.as_units_with_nul(), expected_cwd.as_units_with_nul()); + + let dir = tempfile::tempdir().unwrap(); + let file_path = dir.path().join("sample.txt"); + std::fs::write(&file_path, b"hi").unwrap(); + let canonical = std::fs::canonicalize(&file_path).unwrap(); + let file = File::open(&file_path).unwrap(); + // SAFETY: `file` remains open for the call. + let file_fd = unsafe { BorrowedFd::borrow_raw(file.as_raw_fd()) }; + let resolved = super::fd_path(Global, file_fd).unwrap().unwrap(); + assert_eq!(resolved.as_units(), canonical.as_os_str().as_encoded_bytes()); + + // A high descriptor number that is not open returns `Ok(None)`. + // SAFETY: passing an unopened descriptor only triggers EBADF/ENOENT. + let invalid_fd = unsafe { BorrowedFd::borrow_raw(999_999) }; + assert!(super::fd_path(Global, invalid_fd).unwrap().is_none()); + + // `try_borrow_raw(-1)` yields `None`, matching invalid caller fds. + // SAFETY: `-1` is explicitly handled by `try_borrow_raw`. + assert!(unsafe { BorrowedFd::try_borrow_raw(-1) }.is_none()); + } + + #[test] + fn resolve_path_at_handles_absolute_relative_empty_and_missing_dirfd() { + let bump = crate::pooled_bump(); + + // Absolute path returns directly without allocating. + let abs_raw = c"/usr/bin/env"; + // SAFETY: static NUL-terminated literal. + let abs = unsafe { CStr::::from_ptr(abs_raw.as_ptr().cast()) }; + let resolved_abs = super::resolve_path_at(&bump, None, abs).unwrap().unwrap(); + assert_eq!(resolved_abs.as_units(), b"/usr/bin/env"); + assert_eq!(resolved_abs.as_ptr(), abs.as_ptr()); + + // Relative path with `None` dirfd returns `Ok(None)`. + // SAFETY: static NUL-terminated literal. + let rel = unsafe { CStr::::from_ptr(c"sub/file".as_ptr().cast()) }; + assert!(super::resolve_path_at(&bump, None, rel).unwrap().is_none()); + + // Relative path with `Some(CWD)` joins against `getcwd`. + let expected_cwd = super::getcwd(Global).unwrap(); + let resolved_cwd = super::resolve_path_at(&bump, Some(CWD), rel).unwrap().unwrap(); + let mut expected = expected_cwd.as_units().to_vec(); + if expected.last() != Some(&b'/') { + expected.push(b'/'); + } + expected.extend_from_slice(b"sub/file"); + assert_eq!(resolved_cwd.as_units(), expected.as_slice()); + + // Relative path with a real directory fd. + let dir = tempfile::tempdir().unwrap(); + let canonical_dir = std::fs::canonicalize(dir.path()).unwrap(); + let dir_file = File::open(dir.path()).unwrap(); + // SAFETY: `dir_file` stays open for the calls below. + let dir_fd = unsafe { BorrowedFd::borrow_raw(dir_file.as_raw_fd()) }; + + let resolved_dir = super::resolve_path_at(&bump, Some(dir_fd), rel).unwrap().unwrap(); + let mut expected_dir = canonical_dir.as_os_str().as_encoded_bytes().to_vec(); + expected_dir.push(b'/'); + expected_dir.extend_from_slice(b"sub/file"); + assert_eq!(resolved_dir.as_units(), expected_dir.as_slice()); + + // Empty path with a directory fd returns the directory path itself. + // SAFETY: static NUL-terminated literal. + let empty = unsafe { CStr::::from_ptr(c"".as_ptr().cast()) }; + let resolved_empty = super::resolve_path_at(&bump, Some(dir_fd), empty).unwrap().unwrap(); + assert_eq!(resolved_empty.as_units(), canonical_dir.as_os_str().as_encoded_bytes()); + + // Joining against `/` does not double the leading slash. + let root_file = File::open("/").unwrap(); + // SAFETY: `root_file` stays open for the call. + let root_fd = unsafe { BorrowedFd::borrow_raw(root_file.as_raw_fd()) }; + let child = StdCString::new("etc").unwrap(); + // SAFETY: `child` is NUL-terminated for the call. + let child_cstr = unsafe { CStr::::from_ptr(child.as_ptr().cast()) }; + let resolved_root = + super::resolve_path_at(&bump, Some(root_fd), child_cstr).unwrap().unwrap(); + assert_eq!(resolved_root.as_units(), b"/etc"); + } } diff --git a/crates/fspy_nostd_alloc/src/lib.rs b/crates/fspy_nostd_alloc/src/lib.rs index bac25747e..9f6fbb40c 100644 --- a/crates/fspy_nostd_alloc/src/lib.rs +++ b/crates/fspy_nostd_alloc/src/lib.rs @@ -23,11 +23,9 @@ mod pool; #[cfg(windows)] mod virtual_alloc; -use allocator_api2::alloc::Allocator; -/// The bump interface [`pooled_bump`] returns, re-exported so callers can -/// name the bound and call its methods without a direct bump-scope -/// dependency. -pub use bump_scope::traits::BumpAllocator; +use core::{alloc::Layout, ptr::NonNull}; + +use allocator_api2::alloc::{AllocError, Allocator}; use bump_scope::{ Bump, alloc::compat::AllocatorApi2V02Compat, @@ -112,6 +110,75 @@ pub const fn page_bump() -> PageBump { Bump::unallocated() } +type RawPooledBump = Bump< + AllocatorApi2V02Compat<&'static ChunkPool>, + PooledBumpSettings, +>; + +/// A bump allocator backed by the process-wide chunk pool, created by +/// [`pooled_bump`]. +/// +/// Wraps `bump_scope::Bump` so that in unoptimized (`debug_assertions`) builds +/// the `Allocator` methods are kept out of line (`inline(never)`): `bump-scope` +/// marks its allocation helpers `#[inline(always)]`, which without LLVM stack +/// slot coloring duplicates multi-KiB stack frames into every `Vec` caller and +/// would overflow tight `SIGSYS` / `sigaltstack` / `vfork` stacks. Release +/// builds inline normally. +pub struct PooledBump(RawPooledBump); + +// SAFETY: Every method delegates directly to `bump_scope::Bump`'s `Allocator` +// implementation without altering returned pointers, layouts, or lifetimes. +unsafe impl Allocator for PooledBump { + #[cfg_attr(debug_assertions, inline(never))] + fn allocate(&self, layout: Layout) -> Result, AllocError> { + self.0.allocate(layout) + } + + #[cfg_attr(debug_assertions, inline(never))] + fn allocate_zeroed(&self, layout: Layout) -> Result, AllocError> { + self.0.allocate_zeroed(layout) + } + + #[cfg_attr(debug_assertions, inline(never))] + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + // SAFETY: forwarded directly from caller's `Allocator::deallocate` contract. + unsafe { self.0.deallocate(ptr, layout) } + } + + #[cfg_attr(debug_assertions, inline(never))] + unsafe fn grow( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + // SAFETY: forwarded directly from caller's `Allocator::grow` contract. + unsafe { self.0.grow(ptr, old_layout, new_layout) } + } + + #[cfg_attr(debug_assertions, inline(never))] + unsafe fn grow_zeroed( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + // SAFETY: forwarded directly from caller's `Allocator::grow_zeroed` contract. + unsafe { self.0.grow_zeroed(ptr, old_layout, new_layout) } + } + + #[cfg_attr(debug_assertions, inline(never))] + unsafe fn shrink( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + // SAFETY: forwarded directly from caller's `Allocator::shrink` contract. + unsafe { self.0.shrink(ptr, old_layout, new_layout) } + } +} + /// Creates a fresh bump backed by the process-wide chunk pool. /// /// Creating the bump allocates nothing; the first allocation grabs a whole @@ -126,11 +193,8 @@ pub const fn page_bump() -> PageBump { /// (see `ChunkPool` and the platform page allocators in this crate's source /// for why). #[must_use] -pub fn pooled_bump() -> impl BumpAllocator + Allocator { - Bump::< - AllocatorApi2V02Compat<&'static ChunkPool>, - PooledBumpSettings, - >::unallocated() +pub const fn pooled_bump() -> PooledBump { + PooledBump(RawPooledBump::unallocated()) } #[cfg(test)] diff --git a/crates/fspy_shared/Cargo.toml b/crates/fspy_shared/Cargo.toml index fcfff9ecd..54906fe0d 100644 --- a/crates/fspy_shared/Cargo.toml +++ b/crates/fspy_shared/Cargo.toml @@ -25,9 +25,9 @@ bytemuck = { workspace = true } omnipath = { workspace = true } winapi = { workspace = true, features = ["std"] } -[dev-dependencies] +[target.'cfg(not(target_os = "none"))'.dev-dependencies] assert2 = { workspace = true } -bstr = { workspace = true, features = ["alloc", "std"] } +bstr = { workspace = true } ctor = { workspace = true } rustc-hash = { workspace = true } vt_subprocess_test = { workspace = true } diff --git a/crates/vt_ipc_str/src/lib.rs b/crates/vt_ipc_str/src/lib.rs index 766889b35..4ea8aed7d 100644 --- a/crates/vt_ipc_str/src/lib.rs +++ b/crates/vt_ipc_str/src/lib.rs @@ -67,6 +67,12 @@ impl IpcStr { Self::wrap_ref(bytes) } + #[cfg(any(unix, target_os = "none"))] + #[must_use] + pub const fn as_bytes(&self) -> &[u8] { + &self.data + } + #[cfg(windows)] #[must_use] pub fn from_wide(wide: &[u16]) -> &Self { From 06d7fc412900220e5a961c87e94aa5b696e4cd7f Mon Sep 17 00:00:00 2001 From: wan9chi Date: Fri, 27 Nov 2026 08:45:01 +0800 Subject: [PATCH 2/4] fix(fspy_nostd_alloc): map CWD ENOENT to Ok(None) in fd_path Co-authored-by: Gemini 4 Neon --- crates/fspy_nostd_alloc/src/fs.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/fspy_nostd_alloc/src/fs.rs b/crates/fspy_nostd_alloc/src/fs.rs index 9121e270b..d726c90f8 100644 --- a/crates/fspy_nostd_alloc/src/fs.rs +++ b/crates/fspy_nostd_alloc/src/fs.rs @@ -111,7 +111,11 @@ fn path_buffer( /// error reported while resolving the descriptor. pub fn fd_path(allocator: A, fd: BorrowedFd<'_>) -> Result>> { if fd.as_raw_fd() == CWD.as_raw_fd() { - return getcwd(allocator).map(Some); + return match getcwd(allocator) { + Ok(path) => Ok(Some(path)), + Err(Error::NOENT) => Ok(None), + Err(err) => Err(err), + }; } #[cfg(any(target_os = "linux", target_os = "none"))] From 746a48daa312529573f4e6309377fea629a2b9f8 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Fri, 27 Nov 2026 17:02:02 +0800 Subject: [PATCH 3/4] refactor(fspy_nostd): tighten nostd primitives, allocators, and IpcStr decoding - Wrap `PageBump` like `PooledBump` with unconditional `#[inline(never)]` on `allocate`/`deallocate`/`grow` and drop unused `allocate_zeroed`/ `grow_zeroed`/`shrink` overrides - Avoid panicking on odd byte lengths in Windows `IpcStr::to_os_string` - Export `fspy_nostd_alloc::fs::format_proc_self_fd` for reuse - Use `linux_raw_sys::general::{PATH_MAX, X_OK}` instead of literals in `fspy_nostd::fs::linux` - Tighten `BorrowedFd::try_borrow_raw` to accept only `fd >= 0 || fd == CWD_RAW` - Remove dead/unreachable code (`mac::getcwd_small`, `Error::NOSYS`, `AtFlags::REMOVEDIR`, and unreachable `OVERFLOW` fd conversions in Linux fs) Co-authored-by: Gemini 4 Neon --- crates/fspy_nostd/src/error.rs | 3 - crates/fspy_nostd/src/fd.rs | 21 +++--- crates/fspy_nostd/src/fd/tests.rs | 24 +++++++ crates/fspy_nostd/src/fs/linux.rs | 24 ++++--- crates/fspy_nostd/src/fs/mac.rs | 23 +------ crates/fspy_nostd/src/fs/tests.rs | 10 ++- crates/fspy_nostd/src/fs/unix.rs | 9 ++- crates/fspy_nostd_alloc/src/fs.rs | 31 ++++++++- crates/fspy_nostd_alloc/src/lib.rs | 107 ++++++++++++++++++----------- crates/vt_ipc_str/src/lib.rs | 24 ++++++- 10 files changed, 183 insertions(+), 93 deletions(-) diff --git a/crates/fspy_nostd/src/error.rs b/crates/fspy_nostd/src/error.rs index 12299d0ad..b53c9eb8d 100644 --- a/crates/fspy_nostd/src/error.rs +++ b/crates/fspy_nostd/src/error.rs @@ -27,7 +27,6 @@ impl Error { pub const NOENT: Self = Self(errno::NOENT); pub const NOEXEC: Self = Self(errno::NOEXEC); pub const NOMEM: Self = Self(errno::NOMEM); - pub const NOSYS: Self = Self(errno::NOSYS); pub const NOTDIR: Self = Self(errno::NOTDIR); pub const OVERFLOW: Self = Self(errno::OVERFLOW); pub const RANGE: Self = Self(errno::RANGE); @@ -104,7 +103,6 @@ mod errno { pub const NOENT: i32 = linux_raw_sys::errno::ENOENT.cast_signed(); pub const NOEXEC: i32 = linux_raw_sys::errno::ENOEXEC.cast_signed(); pub const NOMEM: i32 = linux_raw_sys::errno::ENOMEM.cast_signed(); - pub const NOSYS: i32 = linux_raw_sys::errno::ENOSYS.cast_signed(); pub const NOTDIR: i32 = linux_raw_sys::errno::ENOTDIR.cast_signed(); pub const OVERFLOW: i32 = linux_raw_sys::errno::EOVERFLOW.cast_signed(); pub const RANGE: i32 = linux_raw_sys::errno::ERANGE.cast_signed(); @@ -122,7 +120,6 @@ mod errno { pub const NOENT: i32 = libc::ENOENT; pub const NOEXEC: i32 = libc::ENOEXEC; pub const NOMEM: i32 = libc::ENOMEM; - pub const NOSYS: i32 = libc::ENOSYS; pub const NOTDIR: i32 = libc::ENOTDIR; pub const OVERFLOW: i32 = libc::EOVERFLOW; pub const RANGE: i32 = libc::ERANGE; diff --git a/crates/fspy_nostd/src/fd.rs b/crates/fspy_nostd/src/fd.rs index dace4e0e7..a76be021a 100644 --- a/crates/fspy_nostd/src/fd.rs +++ b/crates/fspy_nostd/src/fd.rs @@ -42,23 +42,24 @@ impl BorrowedFd<'_> { } /// Borrows a descriptor argument passed by a caller, or returns `None` - /// when it is `-1`. + /// when it is neither a non-negative descriptor nor [`CWD`] (`AT_FDCWD`). /// - /// Callers can pass `-1` unchecked from a failed call such as `open`. - /// The kernel rejects it with `EBADF` wherever it uses the descriptor, - /// so it is not a caller error to report here. + /// Callers can pass `-1` (from a failed call such as `open`) or another + /// invalid negative descriptor value. The kernel rejects those with `EBADF` + /// wherever it uses the descriptor, so they are not valid borrows to + /// report here. /// /// # Safety /// - /// Any value other than `-1` must satisfy [`Self::borrow_raw`]. + /// Any non-negative `fd` must satisfy [`Self::borrow_raw`]. #[must_use] pub const unsafe fn try_borrow_raw(fd: RawFd) -> Option { - if fd == -1 { - None - } else { - // SAFETY: `fd` is not `-1`, and the caller upholds the - // remaining requirements of `borrow_raw`. + if fd >= 0 || fd == CWD_RAW { + // SAFETY: `fd` is either `CWD_RAW` (which is valid and not `-1`) or + // a non-negative descriptor upholding `borrow_raw`'s contract. Some(unsafe { Self::borrow_raw(fd) }) + } else { + None } } diff --git a/crates/fspy_nostd/src/fd/tests.rs b/crates/fspy_nostd/src/fd/tests.rs index ad6c6a74d..f66f0987e 100644 --- a/crates/fspy_nostd/src/fd/tests.rs +++ b/crates/fspy_nostd/src/fd/tests.rs @@ -96,3 +96,27 @@ fn standard_descriptors_have_the_expected_numbers() { assert_eq!(stdout.as_raw_fd(), 1); assert_eq!(stderr.as_raw_fd(), 2); } + +#[test] +fn try_borrow_raw_accepts_non_negative_and_cwd_only() { + // SAFETY: test inspects only the raw descriptor number without performing I/O. + unsafe { + assert_eq!(BorrowedFd::try_borrow_raw(0).map(BorrowedFd::as_raw_fd), Some(0)); + assert_eq!(BorrowedFd::try_borrow_raw(3).map(BorrowedFd::as_raw_fd), Some(3)); + assert_eq!(BorrowedFd::try_borrow_raw(CWD_RAW).map(BorrowedFd::as_raw_fd), Some(CWD_RAW)); + + for invalid in [-1, -3, -50, CWD_RAW - 1, CWD_RAW + 1, RawFd::MIN] { + assert!( + BorrowedFd::try_borrow_raw(invalid).is_none(), + "expected try_borrow_raw({invalid}) to return None" + ); + } + + // On Linux `AT_FDCWD` is `-100`, so `-2` is invalid; on macOS `AT_FDCWD` + // is `-2`, so `-100` is invalid. + #[cfg(any(target_os = "linux", target_os = "none"))] + assert!(BorrowedFd::try_borrow_raw(-2).is_none()); + #[cfg(target_os = "macos")] + assert!(BorrowedFd::try_borrow_raw(-100).is_none()); + } +} diff --git a/crates/fspy_nostd/src/fs/linux.rs b/crates/fspy_nostd/src/fs/linux.rs index e4b4d0b13..a67597cd4 100644 --- a/crates/fspy_nostd/src/fs/linux.rs +++ b/crates/fspy_nostd/src/fs/linux.rs @@ -5,8 +5,7 @@ use crate::{ fs::{AccessFlags, AtFlags, Mode, OFlags, Stat}, }; -// Linux UAPI `PATH_MAX`. -pub(super) const PATH_MAX: usize = 4096; +pub(super) const PATH_MAX: usize = linux_raw_sys::general::PATH_MAX as usize; pub(super) const O_RDONLY: u32 = linux_raw_sys::general::O_RDONLY; pub(super) const O_RDWR: u32 = linux_raw_sys::general::O_RDWR; pub(super) const O_CREAT: u32 = linux_raw_sys::general::O_CREAT; @@ -14,14 +13,23 @@ pub(super) const O_EXCL: u32 = linux_raw_sys::general::O_EXCL; pub(super) const O_NOFOLLOW: u32 = linux_raw_sys::general::O_NOFOLLOW; pub(super) const O_NONBLOCK: u32 = linux_raw_sys::general::O_NONBLOCK; pub(super) const O_CLOEXEC: u32 = linux_raw_sys::general::O_CLOEXEC; -pub(super) const AT_REMOVEDIR: u32 = linux_raw_sys::general::AT_REMOVEDIR; -pub(super) const X_OK: u32 = 1; +pub(super) const X_OK: u32 = linux_raw_sys::general::X_OK; pub(super) type ModeBits = u32; pub(super) const S_IRUSR: ModeBits = linux_raw_sys::general::S_IRUSR; pub(super) const S_IWUSR: ModeBits = linux_raw_sys::general::S_IWUSR; pub(super) const S_IFMT: ModeBits = linux_raw_sys::general::S_IFMT; pub(super) const S_IFREG: ModeBits = linux_raw_sys::general::S_IFREG; +#[expect( + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + reason = "successful Linux syscalls always return a non-negative c_int file descriptor" +)] +fn raw_fd_from_syscall(fd: usize) -> RawFd { + debug_assert!(i32::try_from(fd).is_ok()); + fd as RawFd +} + #[expect(clippy::needless_pass_by_value, reason = "CStr is a borrowed value type")] pub(super) fn faccessat( dirfd: BorrowedFd<'_>, @@ -62,9 +70,7 @@ pub(super) fn openat( } .map_err(Error::from)?; - // This should not fail with a well-behaved kernel: `openat` returns a - // nonnegative `c_int` file descriptor. - let fd = i32::try_from(fd).map_err(|_| Error::OVERFLOW)?; + let fd = raw_fd_from_syscall(fd); // SAFETY: a successful `openat` returns a new owned descriptor. Ok(unsafe { OwnedFd::from_raw_fd(fd) }) @@ -115,7 +121,7 @@ pub fn fcntl_dupfd(fd: BorrowedFd<'_>, min_fd: RawFd) -> Result { } .map_err(Error::from)?; - let dup = i32::try_from(dup).map_err(|_| Error::OVERFLOW)?; + let dup = raw_fd_from_syscall(dup); // SAFETY: a successful `F_DUPFD` returns a new owned descriptor. Ok(unsafe { OwnedFd::from_raw_fd(dup) }) @@ -139,7 +145,7 @@ pub fn fcntl_dupfd_cloexec(fd: BorrowedFd<'_>, min_fd: RawFd) -> Result } .map_err(Error::from)?; - let dup = i32::try_from(dup).map_err(|_| Error::OVERFLOW)?; + let dup = raw_fd_from_syscall(dup); // SAFETY: a successful `F_DUPFD_CLOEXEC` returns a new owned descriptor. Ok(unsafe { OwnedFd::from_raw_fd(dup) }) diff --git a/crates/fspy_nostd/src/fs/mac.rs b/crates/fspy_nostd/src/fs/mac.rs index e0928d452..ebfa2c7f0 100644 --- a/crates/fspy_nostd/src/fs/mac.rs +++ b/crates/fspy_nostd/src/fs/mac.rs @@ -1,4 +1,4 @@ -use core::{mem::MaybeUninit, slice}; +use core::mem::MaybeUninit; use crate::{ BorrowedFd, CStr, CWD, Error, Fat, OwnedFd, Result, Thin, @@ -15,7 +15,6 @@ pub(super) const O_EXCL: u32 = libc::O_EXCL.cast_unsigned(); pub(super) const O_NOFOLLOW: u32 = libc::O_NOFOLLOW.cast_unsigned(); pub(super) const O_NONBLOCK: u32 = libc::O_NONBLOCK.cast_unsigned(); pub(super) const O_CLOEXEC: u32 = libc::O_CLOEXEC.cast_unsigned(); -pub(super) const AT_REMOVEDIR: u32 = libc::AT_REMOVEDIR.cast_unsigned(); pub(super) const X_OK: u32 = libc::X_OK.cast_unsigned(); pub(super) type ModeBits = libc::mode_t; pub(super) const S_IRUSR: ModeBits = libc::S_IRUSR; @@ -124,29 +123,13 @@ pub fn fcntl_getpath<'buf>( } pub(super) fn getcwd(buf: &mut [MaybeUninit]) -> Result> { - let (chunks, remainder) = buf.as_chunks_mut::(); + let (chunks, _) = buf.as_chunks_mut::(); let Some(full) = chunks.first_mut() else { - return getcwd_small(remainder); + return Err(Error::RANGE); }; getcwd_full(full) } -// Keep the `PATH_MAX` scratch storage in a separate stack frame so the -// large-buffer path does not reserve it. `inline(never)` preserves that -// conditional stack allocation after optimization. -#[inline(never)] -fn getcwd_small(buf: &mut [MaybeUninit]) -> Result> { - let mut scratch = [MaybeUninit::uninit(); PATH_MAX]; - let initialized = getcwd_full(&mut scratch)?.len_with_nul(); - let buf = buf.get_mut(..initialized).ok_or(Error::RANGE)?; - - buf.copy_from_slice(&scratch[..initialized]); - // SAFETY: `getcwd_full` initialized this copied C string prefix. - let bytes = unsafe { slice::from_raw_parts(buf.as_ptr().cast(), buf.len()) }; - // SAFETY: upheld by the initialized prefix above. - Ok(unsafe { CStr::from_units_with_nul_unchecked(bytes) }) -} - /// The allocation-free fast path from Apple's [`getcwd`]: ask an open `.` /// descriptor for its path. /// diff --git a/crates/fspy_nostd/src/fs/tests.rs b/crates/fspy_nostd/src/fs/tests.rs index ab1cef121..cd3aa95fb 100644 --- a/crates/fspy_nostd/src/fs/tests.rs +++ b/crates/fspy_nostd/src/fs/tests.rs @@ -11,7 +11,8 @@ use crate::Error; )] fn getcwd_returns_current_directory() { let expected = std::env::current_dir().unwrap(); - let mut buf = vec![MaybeUninit::uninit(); expected.as_os_str().as_bytes().len() + 1]; + let len = super::PATH_MAX.max(expected.as_os_str().as_bytes().len() + 1); + let mut buf = vec![MaybeUninit::uninit(); len]; let buf_ptr = buf.as_ptr().cast::(); let actual = getcwd(&mut buf).unwrap(); @@ -28,6 +29,13 @@ fn getcwd_rejects_an_empty_buffer() { assert!(matches!(getcwd(&mut []), Err(Error::RANGE))); } +#[cfg(target_os = "macos")] +#[test] +fn getcwd_rejects_buffer_smaller_than_path_max() { + let mut buf = [MaybeUninit::uninit(); super::PATH_MAX - 1]; + assert!(matches!(getcwd(&mut buf), Err(Error::RANGE))); +} + #[cfg(target_os = "macos")] #[test] fn fcntl_getpath_returns_descriptor_path() { diff --git a/crates/fspy_nostd/src/fs/unix.rs b/crates/fspy_nostd/src/fs/unix.rs index c5d155cc8..a4f65112c 100644 --- a/crates/fspy_nostd/src/fs/unix.rs +++ b/crates/fspy_nostd/src/fs/unix.rs @@ -45,10 +45,7 @@ bitflags! { /// Options accepted by `*at` filesystem operations. #[derive(Clone, Copy, Debug, Eq, PartialEq)] - pub struct AtFlags: u32 { - /// Remove a directory rather than a non-directory entry. - const REMOVEDIR = imp::AT_REMOVEDIR; - } + pub struct AtFlags: u32 {} /// Mode bits accepted by [`faccessat`]. /// @@ -135,7 +132,9 @@ pub fn ftruncate(fd: BorrowedFd<'_>, len: u64) -> Result<()> { /// unspecified initialization state. /// /// This function performs one resolution attempt and does not allocate, grow, -/// or retry. No buffer size guarantees success, including one larger than +/// or retry. Callers should pass a buffer of at least [`PATH_MAX`] bytes +/// (smaller buffers fail with [`Error::RANGE`](crate::Error::RANGE) on macOS), +/// and no buffer size guarantees success, including one larger than /// [`PATH_MAX`]. /// /// # Errors diff --git a/crates/fspy_nostd_alloc/src/fs.rs b/crates/fspy_nostd_alloc/src/fs.rs index d726c90f8..494a60dcc 100644 --- a/crates/fspy_nostd_alloc/src/fs.rs +++ b/crates/fspy_nostd_alloc/src/fs.rs @@ -146,9 +146,14 @@ pub fn fd_path(allocator: A, fd: BorrowedFd<'_>) -> Result\0` on the stack without allocating. +/// Formats `/proc/self/fd/\0` into caller-provided stack storage without +/// allocating. +/// +/// The 32-byte buffer always fits the 14-byte prefix, up to 10 decimal digits +/// for any `u32`, and the terminating NUL byte. #[cfg(any(target_os = "linux", target_os = "none"))] -fn format_proc_self_fd(buf: &mut [u8; 32], mut fd: u32) -> CStr<'_, Thin> { +#[must_use] +pub fn format_proc_self_fd(buf: &mut [u8; 32], mut fd: u32) -> CStr<'_, Thin> { const PREFIX: &[u8] = b"/proc/self/fd/"; let mut digits = [0u8; 10]; let mut num_digits = 0; @@ -257,6 +262,28 @@ mod tests { assert_eq!(path.as_c_str().count().as_units_with_nul(), b"/\0"); } + #[cfg(target_os = "linux")] + #[test] + fn format_proc_self_fd_formats_boundary_values() { + let mut buf = [0u8; 32]; + assert_eq!( + super::format_proc_self_fd(&mut buf, 0).count().as_units_with_nul(), + b"/proc/self/fd/0\0" + ); + assert_eq!( + super::format_proc_self_fd(&mut buf, 1).count().as_units_with_nul(), + b"/proc/self/fd/1\0" + ); + assert_eq!( + super::format_proc_self_fd(&mut buf, 42).count().as_units_with_nul(), + b"/proc/self/fd/42\0" + ); + assert_eq!( + super::format_proc_self_fd(&mut buf, u32::MAX).count().as_units_with_nul(), + b"/proc/self/fd/4294967295\0" + ); + } + #[cfg(target_os = "linux")] #[test] fn readlinkat_allocates_the_complete_target() { diff --git a/crates/fspy_nostd_alloc/src/lib.rs b/crates/fspy_nostd_alloc/src/lib.rs index 9f6fbb40c..926308ec1 100644 --- a/crates/fspy_nostd_alloc/src/lib.rs +++ b/crates/fspy_nostd_alloc/src/lib.rs @@ -86,6 +86,12 @@ impl Default for &'static ChunkPool::WithGuaranteedAllocated; + +type RawPageBump = Bump, PageBumpSettings>; + /// A bump allocator drawing whole pages straight from the kernel — never /// from the chunk pool — so its memory is never recycled into other bumps. /// @@ -93,11 +99,39 @@ impl Default for &'static ChunkPool, PageBumpSettings>; +/// +/// Wraps `bump_scope::Bump` so that the `Allocator` methods stay out of line +/// (`#[inline(never)]`): `bump-scope` marks its allocation helpers +/// `#[inline(always)]`, which duplicates large stack frames into every `Vec` +/// caller and would risk overflowing tight `SIGSYS` / `sigaltstack` / `vfork` +/// stacks. +pub struct PageBump(RawPageBump); -/// [`PageBump`]'s settings: start without a chunk, so creating one -/// allocates nothing. -pub type PageBumpSettings = ::WithGuaranteedAllocated; +// SAFETY: Every method delegates directly to `bump_scope::Bump`'s `Allocator` +// implementation without altering returned pointers, layouts, or lifetimes. +unsafe impl Allocator for PageBump { + #[inline(never)] + fn allocate(&self, layout: Layout) -> Result, AllocError> { + self.0.allocate(layout) + } + + #[inline(never)] + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + // SAFETY: forwarded directly from caller's `Allocator::deallocate` contract. + unsafe { self.0.deallocate(ptr, layout) } + } + + #[inline(never)] + unsafe fn grow( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + // SAFETY: forwarded directly from caller's `Allocator::grow` contract. + unsafe { self.0.grow(ptr, old_layout, new_layout) } + } +} /// Creates an empty [`PageBump`]. /// @@ -107,7 +141,7 @@ pub type PageBumpSettings = ::WithGuarant /// permanent. #[must_use] pub const fn page_bump() -> PageBump { - Bump::unallocated() + PageBump(RawPageBump::unallocated()) } type RawPooledBump = Bump< @@ -118,34 +152,28 @@ type RawPooledBump = Bump< /// A bump allocator backed by the process-wide chunk pool, created by /// [`pooled_bump`]. /// -/// Wraps `bump_scope::Bump` so that in unoptimized (`debug_assertions`) builds -/// the `Allocator` methods are kept out of line (`inline(never)`): `bump-scope` -/// marks its allocation helpers `#[inline(always)]`, which without LLVM stack -/// slot coloring duplicates multi-KiB stack frames into every `Vec` caller and -/// would overflow tight `SIGSYS` / `sigaltstack` / `vfork` stacks. Release -/// builds inline normally. +/// Wraps `bump_scope::Bump` so that the `Allocator` methods stay out of line +/// (`#[inline(never)]`): `bump-scope` marks its allocation helpers +/// `#[inline(always)]`, which duplicates large stack frames into every `Vec` +/// caller and would risk overflowing tight `SIGSYS` / `sigaltstack` / `vfork` +/// stacks. pub struct PooledBump(RawPooledBump); // SAFETY: Every method delegates directly to `bump_scope::Bump`'s `Allocator` // implementation without altering returned pointers, layouts, or lifetimes. unsafe impl Allocator for PooledBump { - #[cfg_attr(debug_assertions, inline(never))] + #[inline(never)] fn allocate(&self, layout: Layout) -> Result, AllocError> { self.0.allocate(layout) } - #[cfg_attr(debug_assertions, inline(never))] - fn allocate_zeroed(&self, layout: Layout) -> Result, AllocError> { - self.0.allocate_zeroed(layout) - } - - #[cfg_attr(debug_assertions, inline(never))] + #[inline(never)] unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { // SAFETY: forwarded directly from caller's `Allocator::deallocate` contract. unsafe { self.0.deallocate(ptr, layout) } } - #[cfg_attr(debug_assertions, inline(never))] + #[inline(never)] unsafe fn grow( &self, ptr: NonNull, @@ -155,28 +183,6 @@ unsafe impl Allocator for PooledBump { // SAFETY: forwarded directly from caller's `Allocator::grow` contract. unsafe { self.0.grow(ptr, old_layout, new_layout) } } - - #[cfg_attr(debug_assertions, inline(never))] - unsafe fn grow_zeroed( - &self, - ptr: NonNull, - old_layout: Layout, - new_layout: Layout, - ) -> Result, AllocError> { - // SAFETY: forwarded directly from caller's `Allocator::grow_zeroed` contract. - unsafe { self.0.grow_zeroed(ptr, old_layout, new_layout) } - } - - #[cfg_attr(debug_assertions, inline(never))] - unsafe fn shrink( - &self, - ptr: NonNull, - old_layout: Layout, - new_layout: Layout, - ) -> Result, AllocError> { - // SAFETY: forwarded directly from caller's `Allocator::shrink` contract. - unsafe { self.0.shrink(ptr, old_layout, new_layout) } - } } /// Creates a fresh bump backed by the process-wide chunk pool. @@ -267,4 +273,23 @@ mod tests { let again = second_bump.allocate(layout).unwrap(); assert_eq!(again.cast::().as_ptr().addr(), first_addr); } + + #[test] + #[cfg(not(miri))] + fn page_bump_allocates_and_grows() { + let bump = page_bump(); + let small = Layout::from_size_align(64, 8).unwrap(); + let large = Layout::from_size_align(256, 8).unwrap(); + let block = bump.allocate(small).unwrap(); + // SAFETY: fresh exclusive block of at least 64 bytes. + unsafe { block.cast::().as_ptr().write_bytes(0xAB, 64) }; + // SAFETY: `block` was allocated from `bump` with `small` and `large >= small`. + let grown = unsafe { bump.grow(block.cast(), small, large) }.unwrap(); + assert!(grown.len() >= 256); + // SAFETY: first 64 bytes were preserved from the original allocation. + let prefix = unsafe { core::slice::from_raw_parts(grown.cast::().as_ptr(), 64) }; + assert!(prefix.iter().all(|&b| b == 0xAB)); + // SAFETY: `grown` was allocated from `bump` with `large`. + unsafe { bump.deallocate(grown.cast(), large) }; + } } diff --git a/crates/vt_ipc_str/src/lib.rs b/crates/vt_ipc_str/src/lib.rs index 4ea8aed7d..8fd4b2795 100644 --- a/crates/vt_ipc_str/src/lib.rs +++ b/crates/vt_ipc_str/src/lib.rs @@ -85,14 +85,21 @@ impl IpcStr { OsStr::from_bytes(&self.data) } + /// Decodes this IPC string as an [`OsString`] of native-endian UTF-16 code + /// units. + /// + /// Uses a zero-copy cast when aligned and even-length; otherwise decodes + /// complete 2-byte pairs and ignores any trailing odd byte without + /// panicking. #[cfg(windows)] #[must_use] pub fn to_os_string(&self) -> OsString { - use bytemuck::{allocation::pod_collect_to_vec, try_cast_slice}; + use bytemuck::try_cast_slice; try_cast_slice::(&self.data).map_or_else( |_| { - let wide = pod_collect_to_vec::(&self.data); + let (pairs, _) = self.data.as_chunks::<2>(); + let wide: Vec = pairs.iter().copied().map(u16::from_ne_bytes).collect(); OsString::from_wide(&wide) }, OsString::from_wide, @@ -273,4 +280,17 @@ mod tests { let decoded_wide = decoded.to_os_string().encode_wide().collect::>(); assert_eq!(decoded_wide, wide_str); } + + #[cfg(windows)] + #[test] + fn test_to_os_string_odd_byte_length_does_not_panic() { + use std::os::windows::ffi::OsStrExt; + + let odd = IpcStr::wrap_ref(&[b'a', 0, b'b']); + let decoded_wide: Vec = odd.to_os_string().encode_wide().collect(); + assert_eq!(decoded_wide, [u16::from(b'a')]); + + let single = IpcStr::wrap_ref(&[0xFF]); + assert!(single.to_os_string().is_empty()); + } } From c0d04e8d124ab2ccd088c3a82d2c094448a1b4d3 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Fri, 27 Nov 2026 18:10:34 +0800 Subject: [PATCH 4/4] fix(fspy_nostd): keep checked i32 fd conversion in raw_fd_from_syscall Co-authored-by: Gemini 4 Neon --- crates/fspy_nostd/src/fs/linux.rs | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/crates/fspy_nostd/src/fs/linux.rs b/crates/fspy_nostd/src/fs/linux.rs index a67597cd4..589b435ad 100644 --- a/crates/fspy_nostd/src/fs/linux.rs +++ b/crates/fspy_nostd/src/fs/linux.rs @@ -20,14 +20,8 @@ pub(super) const S_IWUSR: ModeBits = linux_raw_sys::general::S_IWUSR; pub(super) const S_IFMT: ModeBits = linux_raw_sys::general::S_IFMT; pub(super) const S_IFREG: ModeBits = linux_raw_sys::general::S_IFREG; -#[expect( - clippy::cast_possible_truncation, - clippy::cast_possible_wrap, - reason = "successful Linux syscalls always return a non-negative c_int file descriptor" -)] -fn raw_fd_from_syscall(fd: usize) -> RawFd { - debug_assert!(i32::try_from(fd).is_ok()); - fd as RawFd +fn raw_fd_from_syscall(fd: usize) -> Result { + RawFd::try_from(fd).map_err(|_| Error::OVERFLOW) } #[expect(clippy::needless_pass_by_value, reason = "CStr is a borrowed value type")] @@ -70,7 +64,7 @@ pub(super) fn openat( } .map_err(Error::from)?; - let fd = raw_fd_from_syscall(fd); + let fd = raw_fd_from_syscall(fd)?; // SAFETY: a successful `openat` returns a new owned descriptor. Ok(unsafe { OwnedFd::from_raw_fd(fd) }) @@ -121,7 +115,7 @@ pub fn fcntl_dupfd(fd: BorrowedFd<'_>, min_fd: RawFd) -> Result { } .map_err(Error::from)?; - let dup = raw_fd_from_syscall(dup); + let dup = raw_fd_from_syscall(dup)?; // SAFETY: a successful `F_DUPFD` returns a new owned descriptor. Ok(unsafe { OwnedFd::from_raw_fd(dup) }) @@ -145,7 +139,7 @@ pub fn fcntl_dupfd_cloexec(fd: BorrowedFd<'_>, min_fd: RawFd) -> Result } .map_err(Error::from)?; - let dup = raw_fd_from_syscall(dup); + let dup = raw_fd_from_syscall(dup)?; // SAFETY: a successful `F_DUPFD_CLOEXEC` returns a new owned descriptor. Ok(unsafe { OwnedFd::from_raw_fd(dup) })