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..d726c90f8 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,136 @@ 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 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"))] + { + 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 +249,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 +261,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 {