Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .typos.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 20 additions & 2 deletions crates/fspy_nostd/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,17 @@ 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 NOTDIR: Self = Self(errno::NOTDIR);
pub const OVERFLOW: Self = Self(errno::OVERFLOW);
pub const RANGE: Self = Self(errno::RANGE);

Expand Down Expand Up @@ -87,22 +93,34 @@ impl From<syscalls::Errno> 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 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 NOTDIR: i32 = libc::ENOTDIR;
pub const OVERFLOW: i32 = libc::EOVERFLOW;
pub const RANGE: i32 = libc::ERANGE;
}
Expand Down
24 changes: 13 additions & 11 deletions crates/fspy_nostd/src/fd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Self> {
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
}
}

Expand Down Expand Up @@ -100,7 +101,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 }
}
Expand Down
24 changes: 24 additions & 0 deletions crates/fspy_nostd/src/fd/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
}
106 changes: 97 additions & 9 deletions crates/fspy_nostd/src/fs/linux.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,48 @@
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`.
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;
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 = 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;

fn raw_fd_from_syscall(fd: usize) -> Result<RawFd> {
RawFd::try_from(fd).map_err(|_| Error::OVERFLOW)
}

#[expect(clippy::needless_pass_by_value, reason = "CStr is a borrowed value type")]
pub(super) fn faccessat<R>(
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<R>(
Expand All @@ -37,9 +64,7 @@ pub(super) fn openat<R>(
}
.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) })
Expand Down Expand Up @@ -69,7 +94,70 @@ pub(super) fn fstat(fd: BorrowedFd<'_>) -> Result<Stat> {
.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<OwnedFd> {
// 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 = raw_fd_from_syscall(dup)?;

// 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<OwnedFd> {
// 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 = raw_fd_from_syscall(dup)?;

// 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<bool> {
// 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<()> {
Expand Down
46 changes: 24 additions & 22 deletions crates/fspy_nostd/src/fs/mac.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use core::{mem::MaybeUninit, slice};
use core::mem::MaybeUninit;

use crate::{
BorrowedFd, CStr, CWD, Error, Fat, OwnedFd, Result, Thin,
fs::{AtFlags, Mode, OFlags, Stat},
fs::{AccessFlags, AtFlags, Mode, OFlags, Stat},
};

// Darwin UAPI `MAXPATHLEN`.
Expand All @@ -12,11 +12,29 @@ 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<R>(
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<R>(
Expand Down Expand Up @@ -61,7 +79,7 @@ pub(super) fn fstat(fd: BorrowedFd<'_>) -> Result<Stat> {
}
// 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<()> {
Expand Down Expand Up @@ -105,29 +123,13 @@ pub fn fcntl_getpath<'buf>(
}

pub(super) fn getcwd(buf: &mut [MaybeUninit<u8>]) -> Result<CStr<'_, Fat>> {
let (chunks, remainder) = buf.as_chunks_mut::<PATH_MAX>();
let (chunks, _) = buf.as_chunks_mut::<PATH_MAX>();
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<u8>]) -> Result<CStr<'_, Fat>> {
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.
///
Expand Down
Loading
Loading