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.

25 changes: 23 additions & 2 deletions crates/fspy_nostd/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down Expand Up @@ -87,22 +94,36 @@ 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 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;
}
Expand Down
3 changes: 2 additions & 1 deletion crates/fspy_nostd/src/fd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
}
Expand Down
94 changes: 91 additions & 3 deletions crates/fspy_nostd/src/fs/linux.rs
Original file line number Diff line number Diff line change
@@ -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`.
Expand All @@ -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<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 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 = 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<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 = 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<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
23 changes: 21 additions & 2 deletions crates/fspy_nostd/src/fs/mac.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand All @@ -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<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 +80,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
72 changes: 72 additions & 0 deletions crates/fspy_nostd/src/fs/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<crate::Thin>::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::<crate::Thin>::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");
}
35 changes: 33 additions & 2 deletions crates/fspy_nostd/src/fs/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand All @@ -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;
}
Expand All @@ -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<R>(dirfd: BorrowedFd<'_>, path: CStr<'_, R>, mode: AccessFlags) -> Result<()> {
imp::faccessat(dirfd, path, mode)
}

/// Opens `path` relative to `dirfd` and returns its owned descriptor.
///
/// # Errors
Expand Down
Loading
Loading