A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Simplify metadata/file-type handling in `filesystem::primitives` (#14356)
Alex Crichton1a57ed471503
diff --git a/crates/wasi/src/filesystem/primitives/file_type.rs b/crates/wasi/src/filesystem/primitives/file_type.rsindex 20ebf31f2b..bbfdbe501a 100644--- a/crates/wasi/src/filesystem/primitives/file_type.rs+++ b/crates/wasi/src/filesystem/primitives/file_type.rs@@ -1,22 +1,6 @@//! The `FileType` struct.-use crate::filesystem::primitives::ImplFileTypeExt;--/// `FileType`'s inner state.-#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]-enum Inner {- /// A directory.- Dir,-- /// A file.- File,-- /// An unknown entity.- Unknown,-- /// A `FileTypeExt` type.- Ext(ImplFileTypeExt),-}+use std::fs;/// A structure representing a type of file with accessors for each file type.///@@ -26,41 +10,30 @@ enum Inner {/// We need to define our own version because the libstd `FileType` doesn't/// have a public constructor that we can use./// </details>-#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]-#[repr(transparent)]-pub struct FileType(Inner);--impl FileType {- /// Creates a `FileType` for which `is_dir()` returns `true`.- #[inline]- pub const fn dir() -> Self {- Self(Inner::Dir)- }-- /// Creates a `FileType` for which `is_file()` returns `true`.- #[inline]- pub const fn file() -> Self {- Self(Inner::File)- }-- /// Creates a `FileType` for which `is_unknown()` returns `true`.- #[inline]- pub const fn unknown() -> Self {- Self(Inner::Unknown)- }+#[derive(Debug, Copy, Clone, Eq, PartialEq)]+pub enum FileType {+ Std(fs::FileType),+ #[cfg(unix)]+ Unix(rustix::fs::FileType),+}- /// Creates a `FileType` from extension type.- #[inline]- pub(crate) const fn ext(ext: ImplFileTypeExt) -> Self {- Self(Inner::Ext(ext))+impl From<fs::FileType> for FileType {+ fn from(std: fs::FileType) -> Self {+ Self::Std(std)}+}+impl FileType {/// Tests whether this file type represents a directory.////// This corresponds to [`std::fs::FileType::is_dir`].#[inline]pub fn is_dir(&self) -> bool {- self.0 == Inner::Dir+ match self {+ Self::Std(std) => std.is_dir(),+ #[cfg(unix)]+ Self::Unix(unix) => unix.is_dir(),+ }}/// Tests whether this file type represents a regular file.@@ -68,7 +41,11 @@ impl FileType {/// This corresponds to [`std::fs::FileType::is_file`].#[inline]pub fn is_file(&self) -> bool {- self.0 == Inner::File+ match self {+ Self::Std(std) => std.is_file(),+ #[cfg(unix)]+ Self::Unix(unix) => unix.is_file(),+ }}/// Tests whether this file type represents a symbolic link.@@ -76,48 +53,10 @@ impl FileType {/// This corresponds to [`std::fs::FileType::is_symlink`].#[inline]pub fn is_symlink(&self) -> bool {- if let Inner::Ext(ext) = self.0 {- ext.is_symlink()- } else {- false+ match self {+ Self::Std(std) => std.is_symlink(),+ #[cfg(unix)]+ Self::Unix(unix) => unix.is_symlink(),}}}--/// Unix-specific extensions for [`FileType`].-///-/// This corresponds to [`std::os::unix::fs::FileTypeExt`].-#[cfg(any(unix, target_os = "vxworks"))]-pub trait FileTypeExt {- /// Returns `true` if this file type is a block device.- fn is_block_device(&self) -> bool;- /// Returns `true` if this file type is a character device.- fn is_char_device(&self) -> bool;-}--#[cfg(any(unix, target_os = "vxworks"))]-impl FileTypeExt for FileType {- #[inline]- fn is_block_device(&self) -> bool {- self.0 == Inner::Ext(ImplFileTypeExt::block_device())- }-- #[inline]- fn is_char_device(&self) -> bool {- self.0 == Inner::Ext(ImplFileTypeExt::char_device())- }-}--/// Extension trait to allow `is_block_device` etc. to be exposed by-/// the `cap-fs-ext` crate.-///-/// This is hidden from the main API since this functionality isn't present in-/// `std`. Use `cap_fs_ext::FileTypeExt` instead of calling this directly.-#[cfg(windows)]-#[doc(hidden)]-pub trait _WindowsFileTypeExt {- fn is_block_device(&self) -> bool;- fn is_char_device(&self) -> bool;- fn is_fifo(&self) -> bool;- fn is_socket(&self) -> bool;-}diff --git a/crates/wasi/src/filesystem/primitives/metadata.rs b/crates/wasi/src/filesystem/primitives/metadata.rsindex d2ed46c228..9fadc31692 100644--- a/crates/wasi/src/filesystem/primitives/metadata.rs+++ b/crates/wasi/src/filesystem/primitives/metadata.rs@@ -1,4 +1,4 @@-use crate::filesystem::primitives::{FileType, ImplFileTypeExt, ImplMetadataExt};+use crate::filesystem::primitives::FileType;use std::time::SystemTime;use std::{fs, io};@@ -11,44 +11,39 @@ use std::{fs, io};/// have a public constructor that we can use./// </details>#[derive(Debug, Clone)]-pub struct Metadata {- pub(crate) file_type: FileType,- pub(crate) len: u64,- pub(crate) modified: Option<SystemTime>,- pub(crate) accessed: Option<SystemTime>,- pub(crate) created: Option<SystemTime>,- pub(crate) ext: ImplMetadataExt,+pub(crate) enum Metadata {+ Std(fs::Metadata),+ #[cfg(unix)]+ Stat(rustix::fs::Stat),+ #[cfg(target_os = "linux")]+ Statx(rustix::fs::Statx),+}++impl From<fs::Metadata> for Metadata {+ fn from(std: fs::Metadata) -> Self {+ Self::Std(std)+ }}-#[allow(clippy::len_without_is_empty)]impl Metadata {/// Constructs a new instance of `Self` from the given [`std::fs::File`].#[inline]pub fn from_file(file: &fs::File) -> io::Result<Self> {- let std = file.metadata()?;- let ext = ImplMetadataExt::from(file, &std)?;- let file_type = ImplFileTypeExt::from(file, &std)?;- Ok(Self::from_parts(std, ext, file_type))- }-- #[inline]- fn from_parts(std: fs::Metadata, ext: ImplMetadataExt, file_type: FileType) -> Self {- Self {- file_type,- len: std.len(),- modified: std.modified().ok(),- accessed: std.accessed().ok(),- created: std.created().ok(),- ext,- }+ file.metadata().map(Metadata::Std)}/// Returns the file type for this metadata.////// This corresponds to [`std::fs::Metadata::file_type`].#[inline]- pub const fn file_type(&self) -> FileType {- self.file_type+ pub fn file_type(&self) -> FileType {+ match self {+ Metadata::Std(m) => FileType::from(m.file_type()),+ #[cfg(unix)]+ Metadata::Stat(m) => FileType::from_raw_mode(m.st_mode.into()),+ #[cfg(target_os = "linux")]+ Metadata::Statx(m) => FileType::from_raw_mode(m.stx_mode.into()),+ }}/// Returns `true` if this metadata is for a directory.@@ -56,15 +51,21 @@ impl Metadata {/// This corresponds to [`std::fs::Metadata::is_dir`].#[inline]pub fn is_dir(&self) -> bool {- self.file_type.is_dir()+ self.file_type().is_dir()}/// Returns the size of the file, in bytes, this metadata is for.////// This corresponds to [`std::fs::Metadata::len`].#[inline]- pub const fn len(&self) -> u64 {- self.len+ pub fn len(&self) -> u64 {+ match self {+ Metadata::Std(m) => m.len(),+ #[cfg(unix)]+ Metadata::Stat(m) => u64::try_from(m.st_size).unwrap(),+ #[cfg(target_os = "linux")]+ Metadata::Statx(m) => m.stx_size,+ }}/// Returns the last modification time listed in this metadata.@@ -72,12 +73,27 @@ impl Metadata {/// This corresponds to [`std::fs::Metadata::modified`].#[inline]pub fn modified(&self) -> io::Result<SystemTime> {- self.modified.ok_or_else(|| {- io::Error::new(- io::ErrorKind::Other,- "modified time metadata not available on this platform",+ match self {+ Metadata::Std(m) => m.modified(),+ #[cfg(unix)]+ Metadata::Stat(m) => super::unix::system_time_from_rustix(+ m.st_mtime,+ m.st_mtime_nsec.try_into().unwrap(),)- })+ .ok_or_else(time_unavailable),+ #[cfg(target_os = "linux")]+ Metadata::Statx(m) => {+ if m.stx_mask & rustix::fs::StatxFlags::MTIME.bits() != 0 {+ super::unix::system_time_from_rustix(+ m.stx_mtime.tv_sec,+ m.stx_mtime.tv_nsec.into(),+ )+ .ok_or_else(time_unavailable)+ } else {+ Err(time_unavailable())+ }+ }+ }}/// Returns the last access time of this metadata.@@ -85,12 +101,27 @@ impl Metadata {/// This corresponds to [`std::fs::Metadata::accessed`].#[inline]pub fn accessed(&self) -> io::Result<SystemTime> {- self.accessed.ok_or_else(|| {- io::Error::new(- io::ErrorKind::Other,- "accessed time metadata not available on this platform",+ match self {+ Metadata::Std(m) => m.accessed(),+ #[cfg(unix)]+ Metadata::Stat(m) => super::unix::system_time_from_rustix(+ m.st_atime,+ m.st_atime_nsec.try_into().unwrap(),)- })+ .ok_or_else(time_unavailable),+ #[cfg(target_os = "linux")]+ Metadata::Statx(m) => {+ if m.stx_mask & rustix::fs::StatxFlags::ATIME.bits() != 0 {+ super::unix::system_time_from_rustix(+ m.stx_atime.tv_sec,+ m.stx_atime.tv_nsec.into(),+ )+ .ok_or_else(time_unavailable)+ } else {+ Err(time_unavailable())+ }+ }+ }}/// Returns the creation time listed in this metadata.@@ -98,129 +129,46 @@ impl Metadata {/// This corresponds to [`std::fs::Metadata::created`].#[inline]pub fn created(&self) -> io::Result<SystemTime> {- self.created.ok_or_else(|| {- io::Error::new(- io::ErrorKind::Other,- "created time metadata not available on this platform",- )- })- }-- /// `MetadataExt` requires nightly to be implemented, but we sometimes- /// just need the file attributes.- #[cfg(windows)]- #[inline]- pub(crate) fn file_attributes(&self) -> u32 {- self.ext.file_attributes()+ match self {+ Metadata::Std(m) => m.created(),+ #[cfg(unix)]+ Metadata::Stat(m) => {+ cfg_select! {+ any(target_os = "freebsd", target_vendor = "apple") => {+ super::unix::system_time_from_rustix(+ m.st_birthtime,+ m.st_birthtime_nsec.try_into().unwrap(),+ )+ .ok_or_else(time_unavailable)+ }+ _ => {+ // `stat.st_ctime` is the latest status change; we want+ // the creation.+ let _ = &m;+ Err(time_unavailable())+ }+ }+ }+ #[cfg(target_os = "linux")]+ Metadata::Statx(m) => {+ if m.stx_mask & rustix::fs::StatxFlags::BTIME.bits() != 0 {+ super::unix::system_time_from_rustix(+ m.stx_btime.tv_sec,+ m.stx_btime.tv_nsec.into(),+ )+ .ok_or_else(time_unavailable)+ } else {+ Err(time_unavailable())+ }+ }+ }}}-/// Unix-specific extensions for [`MetadataExt`].-///-/// This corresponds to [`std::os::unix::fs::MetadataExt`].-#[cfg(any(unix, target_os = "vxworks"))]-pub trait MetadataExt {- /// Returns the ID of the device containing the file.- fn dev(&self) -> u64;- /// Returns the inode number.- fn ino(&self) -> u64;- /// Returns the number of hard links pointing to this file.- fn nlink(&self) -> u64;- #[cfg(target_os = "vxworks")]- fn attrib(&self) -> u8;-}--/// WASI-specific extensions for [`MetadataExt`].-///-/// This corresponds to [`std::os::wasi::fs::MetadataExt`].-#[cfg(target_os = "wasi")]-pub trait MetadataExt {- /// Returns the ID of the device containing the file.- fn dev(&self) -> u64;- /// Returns the inode number.- fn ino(&self) -> u64;- /// Returns the number of hard links pointing to this file.- fn nlink(&self) -> u64;-}--/// Windows-specific extensions to [`Metadata`].-///-/// This corresponds to [`std::os::windows::fs::MetadataExt`].-#[cfg(windows)]-pub trait MetadataExt {- /// Returns the value of the `dwFileAttributes` field of this metadata.- fn file_attributes(&self) -> u32;-}-#[cfg(unix)]-impl MetadataExt for Metadata {- #[inline]- fn dev(&self) -> u64 {- crate::filesystem::primitives::MetadataExt::dev(&self.ext)- }-- #[inline]- fn ino(&self) -> u64 {- crate::filesystem::primitives::MetadataExt::ino(&self.ext)- }-- #[inline]- fn nlink(&self) -> u64 {- crate::filesystem::primitives::MetadataExt::nlink(&self.ext)- }-}--#[cfg(target_os = "wasi")]-impl MetadataExt for Metadata {- #[inline]- fn dev(&self) -> u64 {- crate::filesystem::primitives::MetadataExt::dev(&self.ext)- }-- #[inline]- fn ino(&self) -> u64 {- crate::filesystem::primitives::MetadataExt::ino(&self.ext)- }-- #[inline]- fn nlink(&self) -> u64 {- crate::filesystem::primitives::MetadataExt::nlink(&self.ext)- }-}--#[cfg(target_os = "vxworks")]-impl MetadataExt for Metadata {- #[inline]- fn dev(&self) -> u64 {- self.ext.dev()- }-- #[inline]- fn ino(&self) -> u64 {- self.ext.ino()- }-- #[inline]- fn nlink(&self) -> u64 {- self.ext.nlink()- }-}--#[cfg(windows)]-impl MetadataExt for Metadata {- #[inline]- fn file_attributes(&self) -> u32 {- self.ext.file_attributes()- }-}--/// Extension trait to allow `volume_serial_number` etc. to be exposed by-/// the `cap-fs-ext` crate.-///-/// This is hidden from the main API since this functionality isn't present in-/// `std`. Use `cap_fs_ext::MetadataExt` instead of calling this directly.-#[cfg(windows)]-#[doc(hidden)]-pub trait _WindowsByHandle {- fn number_of_links(&self) -> Option<u32>;+fn time_unavailable() -> io::Error {+ io::Error::new(+ io::ErrorKind::Other,+ "time metadata not available on this platform",+ )}diff --git a/crates/wasi/src/filesystem/primitives/mod.rs b/crates/wasi/src/filesystem/primitives/mod.rsindex be4f6721be..b0a1fa30bb 100644--- a/crates/wasi/src/filesystem/primitives/mod.rs+++ b/crates/wasi/src/filesystem/primitives/mod.rs@@ -16,6 +16,7 @@clippy::allow_attributes_without_reason,reason = "preexisting from when cap-primitives was imported")]+#![allow(clippy::useless_conversion, reason = "typedefs are platform-specific")]use std::path::{Component, Path, PathBuf};use std::{fs, io};@@ -42,19 +43,13 @@ mod windows;#[cfg(windows)]use self::windows as sys;-#[cfg(windows)]-use file_type::_WindowsFileTypeExt;use maybe_owned_file::MaybeOwnedFile;use open_parent::open_parent;use open_unchecked_error::*;use sys::*;pub(crate) use file_type::FileType;-#[cfg(any(unix, target_os = "vxworks"))]-pub(crate) use file_type::FileTypeExt;-#[cfg(windows)]-pub(crate) use metadata::_WindowsByHandle;-pub(crate) use metadata::{Metadata, MetadataExt};+pub(crate) use metadata::Metadata;pub(crate) use open_options::*;pub(crate) use sys::open_ambient_dir;pub(crate) use sys::read_dir;diff --git a/crates/wasi/src/filesystem/primitives/tests/file_type_ext.rs b/crates/wasi/src/filesystem/primitives/tests/file_type_ext.rsindex d61114e75a..e518aece54 100644--- a/crates/wasi/src/filesystem/primitives/tests/file_type_ext.rs+++ b/crates/wasi/src/filesystem/primitives/tests/file_type_ext.rs@@ -1,8 +1,6 @@// This file contains tests for `FileTypeExt`.use super::sys_common::io::tmpdir;-#[cfg(unix)]-use crate::filesystem::primitives::FileTypeExt;use crate::filesystem::primitives::{Metadata, OpenOptions, open, open_ambient_dir};use std::path::Path;diff --git a/crates/wasi/src/filesystem/primitives/tests/fs_additional.rs b/crates/wasi/src/filesystem/primitives/tests/fs_additional.rsindex 8d308b9c98..fbc4bd25f6 100644--- a/crates/wasi/src/filesystem/primitives/tests/fs_additional.rs+++ b/crates/wasi/src/filesystem/primitives/tests/fs_additional.rs@@ -947,11 +947,11 @@ fn check_metadata(std: &std::fs::Metadata, cap: &p::Metadata) {{assert_eq!(std::os::unix::fs::FileTypeExt::is_block_device(&std.file_type()),- p::FileTypeExt::is_block_device(&cap.file_type())+ cap.file_type().is_block_device());assert_eq!(std::os::unix::fs::FileTypeExt::is_char_device(&std.file_type()),- p::FileTypeExt::is_char_device(&cap.file_type())+ cap.file_type().is_char_device());}@@ -1006,9 +1006,9 @@ fn check_metadata(std: &std::fs::Metadata, cap: &p::Metadata) {#[cfg(unix)]{use std::os::unix::fs::MetadataExt;- assert_eq!(std.dev(), p::MetadataExt::dev(cap));- assert_eq!(std.ino(), p::MetadataExt::ino(cap));- assert_eq!(std.nlink(), p::MetadataExt::nlink(cap));+ assert_eq!(std.dev(), cap.dev());+ assert_eq!(std.ino(), cap.ino());+ assert_eq!(std.nlink(), cap.nlink());}}diff --git a/crates/wasi/src/filesystem/primitives/tests/metadata_ext.rs b/crates/wasi/src/filesystem/primitives/tests/metadata_ext.rsindex 6d4fae861f..25405c1c8e 100644--- a/crates/wasi/src/filesystem/primitives/tests/metadata_ext.rs+++ b/crates/wasi/src/filesystem/primitives/tests/metadata_ext.rs@@ -6,9 +6,7 @@use super::helpers as h;use super::sys_common::io::tmpdir;use super::sys_common::symlink_supported;-use crate::filesystem::primitives::{- FollowSymlinks, Metadata, MetadataExt, hard_link, open_ambient_dir, stat,-};+use crate::filesystem::primitives::{FollowSymlinks, Metadata, hard_link, open_ambient_dir, stat};use std::path::Path;#[test]diff --git a/crates/wasi/src/filesystem/primitives/unix/file_type_ext.rs b/crates/wasi/src/filesystem/primitives/unix/file_type_ext.rsdeleted file mode 100644index 72504cc1b4..0000000000--- a/crates/wasi/src/filesystem/primitives/unix/file_type_ext.rs+++ /dev/null@@ -1,114 +0,0 @@-use crate::filesystem::primitives::FileType;-use rustix::fs::RawMode;-use std::{fs, io};--/// A type that implements `FileTypeExt` for this platform.-#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]-pub(crate) enum ImplFileTypeExt {- Symlink,- BlockDevice,- CharDevice,- Fifo,- Socket,-}--impl ImplFileTypeExt {- /// Constructs a new instance of `FileType` from the given- /// [`std::fs::File`] and [`std::fs::FileType`].- #[inline]- #[allow(clippy::unnecessary_wraps)]- pub(crate) fn from(_file: &fs::File, metadata: &fs::Metadata) -> io::Result<FileType> {- // On `rustix`-style platforms, the `Metadata` has everything we need.- Ok(Self::from_just_metadata(metadata))- }-- /// Constructs a new instance of `FileType` from the given- /// [`std::fs::Metadata`].- #[inline]- pub(crate) fn from_just_metadata(metadata: &fs::Metadata) -> FileType {- let std = metadata.file_type();- Self::from_std(std)- }-- /// Constructs a new instance of `Self` from the given- /// [`std::fs::FileType`].- #[inline]- pub(crate) fn from_std(std: fs::FileType) -> FileType {- use rustix::fs::FileTypeExt;- if std.is_file() {- FileType::file()- } else if std.is_dir() {- FileType::dir()- } else if std.is_symlink() {- FileType::ext(Self::Symlink)- } else if std.is_block_device() {- FileType::ext(Self::BlockDevice)- } else if std.is_char_device() {- FileType::ext(Self::CharDevice)- } else {- #[cfg(not(target_os = "wasi"))]- if std.is_fifo() {- return FileType::ext(Self::Fifo);- }- #[cfg(not(target_os = "wasi"))]- if std.is_socket() {- return FileType::ext(Self::Socket);- }- FileType::unknown()- }- }-- /// Constructs a new instance of `FileType` from the given- /// [`RawMode`].- #[inline]- pub(crate) const fn from_raw_mode(mode: RawMode) -> FileType {- match rustix::fs::FileType::from_raw_mode(mode) {- rustix::fs::FileType::RegularFile => FileType::file(),- rustix::fs::FileType::Directory => FileType::dir(),- rustix::fs::FileType::Symlink => FileType::ext(Self::symlink()),- #[cfg(not(target_os = "wasi"))]- rustix::fs::FileType::Fifo => FileType::ext(Self::fifo()),- rustix::fs::FileType::CharacterDevice => FileType::ext(Self::char_device()),- rustix::fs::FileType::BlockDevice => FileType::ext(Self::block_device()),- #[cfg(not(target_os = "wasi"))]- rustix::fs::FileType::Socket => FileType::ext(Self::socket()),- _ => FileType::unknown(),- }- }-- /// Creates a `FileType` for which `is_symlink()` returns `true`.- #[inline]- pub(crate) const fn symlink() -> Self {- Self::Symlink- }-- /// Creates a `FileType` for which `is_block_device()` returns `true`.- #[inline]- pub(crate) const fn block_device() -> Self {- Self::BlockDevice- }-- /// Creates a `FileType` for which `is_char_device()` returns `true`.- #[inline]- pub(crate) const fn char_device() -> Self {- Self::CharDevice- }-- /// Creates a `FileType` for which `is_fifo()` returns `true`.- #[inline]- pub(crate) const fn fifo() -> Self {- Self::Fifo- }-- /// Creates a `FileType` for which `is_socket()` returns `true`.- #[inline]- pub(crate) const fn socket() -> Self {- Self::Socket- }-- /// Tests whether this file type represents a symbolic link.- #[inline]- pub(crate) fn is_symlink(&self) -> bool {- *self == Self::Symlink- }-}diff --git a/crates/wasi/src/filesystem/primitives/unix/freebsd.rs b/crates/wasi/src/filesystem/primitives/unix/freebsd.rsindex 0328cd95ba..1964a278e8 100644--- a/crates/wasi/src/filesystem/primitives/unix/freebsd.rs+++ b/crates/wasi/src/filesystem/primitives/unix/freebsd.rs@@ -1,7 +1,5 @@use crate::filesystem::primitives::unix::{compute_oflags, to_timespec};-use crate::filesystem::primitives::{- FollowSymlinks, ImplMetadataExt, Metadata, OpenOptions, errors,-};+use crate::filesystem::primitives::{FollowSymlinks, Metadata, OpenOptions, errors};use rustix::fs::{AtFlags, CWD, Mode, OFlags, RawMode, Timestamps, openat, statat, unlinkat, utimensat,};@@ -114,7 +112,7 @@ pub(crate) fn stat_fast(} else {AtFlags::SYMLINK_NOFOLLOW};- let stat = ImplMetadataExt::from_rustix(statat(start, path, flags)?);+ let stat = Metadata::Stat(statat(start, path, flags)?);Ok(Some(stat))}diff --git a/crates/wasi/src/filesystem/primitives/unix/is_same_file.rs b/crates/wasi/src/filesystem/primitives/unix/is_same_file.rsindex dc74f1d99c..42d7ad07da 100644--- a/crates/wasi/src/filesystem/primitives/unix/is_same_file.rs+++ b/crates/wasi/src/filesystem/primitives/unix/is_same_file.rs@@ -1,4 +1,4 @@-use crate::filesystem::primitives::{Metadata, MetadataExt};+use crate::filesystem::primitives::Metadata;use std::{fs, io};/// Determine if `a` and `b` refer to the same inode on the same device.diff --git a/crates/wasi/src/filesystem/primitives/unix/linux.rs b/crates/wasi/src/filesystem/primitives/unix/linux.rsindex 97d2cf3af0..e6629c16bc 100644--- a/crates/wasi/src/filesystem/primitives/unix/linux.rs+++ b/crates/wasi/src/filesystem/primitives/unix/linux.rs@@ -1,6 +1,6 @@use crate::filesystem::primitives::unix::{compute_oflags, to_timespec};use crate::filesystem::primitives::{- FollowSymlinks, ImplMetadataExt, Metadata, OpenOptions, OpenOptionsExt, errors, open,+ FollowSymlinks, Metadata, OpenOptions, OpenOptionsExt, errors, open,};use rustix::fs::{AtFlags, Mode, OFlags, RawMode, ResolveFlags, Timestamps, openat2, statat, utimensat,@@ -162,7 +162,7 @@ pub(crate) fn stat_fast(// If `fstat` with `O_PATH` isn't supported, use `statat` with// `AT_EMPTY_PATH`.Ok(Some(- statat(file, "", AtFlags::EMPTY_PATH).map(ImplMetadataExt::from_rustix)?,+ statat(file, "", AtFlags::EMPTY_PATH).map(Metadata::Stat)?,))}Err(err) => match Errno::from_io_error(&err) {diff --git a/crates/wasi/src/filesystem/primitives/unix/metadata_ext.rs b/crates/wasi/src/filesystem/primitives/unix/metadata_ext.rsdeleted file mode 100644index 8e4400ebf9..0000000000--- a/crates/wasi/src/filesystem/primitives/unix/metadata_ext.rs+++ /dev/null@@ -1,181 +0,0 @@-#![allow(clippy::useless_conversion)]--use crate::filesystem::primitives::{ImplFileTypeExt, Metadata};-use rustix::fs::{RawMode, Stat};-#[cfg(target_os = "linux")]-use rustix::fs::{Statx, StatxFlags, makedev};-use std::time::{Duration, SystemTime};-use std::{fs, io};--#[derive(Debug, Clone)]-pub(crate) struct ImplMetadataExt {- dev: u64,- ino: u64,- nlink: u64,-}--impl ImplMetadataExt {- /// Constructs a new instance of `Self` from the given [`std::fs::File`]- /// and [`std::fs::Metadata`].- #[inline]- #[allow(clippy::unnecessary_wraps)]- pub(crate) fn from(_file: &fs::File, std: &fs::Metadata) -> io::Result<Self> {- // On `rustix`-style platforms, the `Metadata` has everything we need.- Ok(Self::from_just_metadata(std))- }-- /// Constructs a new instance of `Self` from the given- /// [`std::fs::Metadata`].- #[inline]- pub(crate) fn from_just_metadata(std: &fs::Metadata) -> Self {- use rustix::fs::MetadataExt;- Self {- dev: std.dev(),- ino: std.ino(),- nlink: std.nlink(),- }- }-- /// Constructs a new instance of `Metadata` from the given `Stat`.- #[inline]- #[allow(unused_comparisons)] // NB: rust-lang/rust#115823 requires this here instead of on `st_dev` processing below- pub(crate) fn from_rustix(stat: Stat) -> Metadata {- Metadata {- file_type: ImplFileTypeExt::from_raw_mode(stat.st_mode as RawMode),- len: u64::try_from(stat.st_size).unwrap(),-- #[cfg(not(target_os = "wasi"))]- modified: system_time_from_rustix(- stat.st_mtime.try_into().unwrap(),- stat.st_mtime_nsec as _,- ),- #[cfg(not(target_os = "wasi"))]- accessed: system_time_from_rustix(- stat.st_atime.try_into().unwrap(),- stat.st_atime_nsec as _,- ),-- #[cfg(target_os = "wasi")]- modified: system_time_from_rustix(stat.st_mtim.tv_sec, stat.st_mtim.tv_nsec as _),- #[cfg(target_os = "wasi")]- accessed: system_time_from_rustix(stat.st_atim.tv_sec, stat.st_atim.tv_nsec as _),-- #[cfg(any(- target_os = "freebsd",- target_os = "openbsd",- target_os = "netbsd",- target_os = "macos",- target_os = "ios",- target_os = "tvos",- target_os = "watchos",- target_os = "visionos",- ))]- created: system_time_from_rustix(- stat.st_birthtime.try_into().unwrap(),- stat.st_birthtime_nsec as _,- ),-- // `stat.st_ctime` is the latest status change; we want the creation.- #[cfg(not(any(- target_os = "freebsd",- target_os = "openbsd",- target_os = "macos",- target_os = "ios",- target_os = "tvos",- target_os = "watchos",- target_os = "visionos",- target_os = "netbsd"- )))]- created: None,-- ext: Self {- // The type of `st_dev` is `dev_t` which is signed on some- // platforms and unsigned on other platforms. A `u64` is enough- // to work for all unsigned platforms, and for signed platforms- // perform a sign extension to `i64` and then view that as an- // unsigned 64-bit number instead.- //- // Note that the `unused_comparisons` is ignored here for- // platforms where it's unsigned since the first branch here- // will never be taken.- dev: if stat.st_dev < 0 {- i64::try_from(stat.st_dev).unwrap() as u64- } else {- u64::try_from(stat.st_dev).unwrap()- },- ino: stat.st_ino.into(),- nlink: u64::from(stat.st_nlink),- },- }- }-- /// Constructs a new instance of `Metadata` from the given `Statx`.- #[cfg(target_os = "linux")]- #[inline]- pub(crate) fn from_rustix_statx(statx: Statx) -> Metadata {- Metadata {- file_type: ImplFileTypeExt::from_raw_mode(RawMode::from(statx.stx_mode)),- len: u64::try_from(statx.stx_size).unwrap(),- modified: if statx.stx_mask & StatxFlags::MTIME.bits() != 0 {- system_time_from_rustix(statx.stx_mtime.tv_sec, statx.stx_mtime.tv_nsec as _)- } else {- None- },- accessed: if statx.stx_mask & StatxFlags::ATIME.bits() != 0 {- system_time_from_rustix(statx.stx_atime.tv_sec, statx.stx_atime.tv_nsec as _)- } else {- None- },- created: if statx.stx_mask & StatxFlags::BTIME.bits() != 0 {- system_time_from_rustix(statx.stx_btime.tv_sec, statx.stx_btime.tv_nsec as _)- } else {- None- },-- ext: Self {- dev: makedev(statx.stx_dev_major, statx.stx_dev_minor),- ino: statx.stx_ino.into(),- nlink: u64::from(statx.stx_nlink),- },- }- }-}--#[allow(clippy::similar_names)]-fn system_time_from_rustix(sec: i64, nsec: u64) -> Option<SystemTime> {- if sec >= 0 {- SystemTime::UNIX_EPOCH.checked_add(Duration::new(u64::try_from(sec).unwrap(), nsec as _))- } else {- SystemTime::UNIX_EPOCH- .checked_sub(Duration::new(sec.unsigned_abs(), 0))- .map(|t| t.checked_add(Duration::new(0, nsec as u32)))- .flatten()- }-}--impl crate::filesystem::primitives::MetadataExt for ImplMetadataExt {- #[inline]- fn dev(&self) -> u64 {- self.dev- }-- #[inline]- fn ino(&self) -> u64 {- self.ino- }-- #[inline]- fn nlink(&self) -> u64 {- self.nlink- }-}--/// It should be possible to represent times before the Epoch.-/// https://github.com/bytecodealliance/cap-std/issues/328-#[test]-fn negative_time() {- let system_time = system_time_from_rustix(-1, 1).unwrap();- let d = SystemTime::UNIX_EPOCH.duration_since(system_time).unwrap();- assert_eq!(d.as_secs(), 0);- assert_eq!(d.subsec_nanos(), 999999999);-}diff --git a/crates/wasi/src/filesystem/primitives/unix/mod.rs b/crates/wasi/src/filesystem/primitives/unix/mod.rsindex 18cae07dca..b9ff935f3a 100644--- a/crates/wasi/src/filesystem/primitives/unix/mod.rs+++ b/crates/wasi/src/filesystem/primitives/unix/mod.rs@@ -1,21 +1,20 @@use crate::filesystem::primitives::{- FileType, FollowSymlinks, MaybeOwnedFile, OpenOptions, open, open_parent,+ FileType, FollowSymlinks, MaybeOwnedFile, Metadata, OpenOptions, open, open_parent,};-use rustix::fs::{AtFlags, Dir, utimensat};+use rustix::fs::{AtFlags, Dir, RawMode, utimensat};use rustix::io::Errno;use std::ffi::OsString;use std::fs;use std::io;use std::os::unix::ffi::{OsStrExt, OsStringExt};+use std::os::unix::fs::{FileTypeExt, MetadataExt};use std::path::{Component, Path, PathBuf};-use std::time::SystemTime;+use std::time::{Duration, SystemTime};mod create_dir_unchecked;mod dir_utils;-mod file_type_ext;mod hard_link_unchecked;mod is_same_file;-mod metadata_ext;mod oflags;mod open_options_ext;mod open_unchecked;@@ -45,11 +44,9 @@ pub(crate) use self::linux::*;pub(crate) use create_dir_unchecked::create_dir_unchecked;pub(crate) use dir_utils::*;-pub(crate) use file_type_ext::ImplFileTypeExt;pub(crate) use hard_link_unchecked::hard_link_unchecked;#[allow(unused_imports)]pub(crate) use is_same_file::{is_different_file, is_different_file_metadata, is_same_file};-pub(crate) use metadata_ext::ImplMetadataExt;pub(crate) use open_options_ext::ImplOpenOptionsExt;pub(crate) use open_unchecked::open_unchecked;pub(crate) use read_link_unchecked::read_link_unchecked;@@ -190,7 +187,7 @@ pub(crate) fn read_dir(};- let file_type = ImplFileTypeExt::from_raw_mode(raw_mode);+ let file_type = FileType::from_raw_mode(raw_mode.into());return Ok(Some((OsString::from_vec(file_name.to_vec()), file_type)));}})();@@ -201,3 +198,95 @@ pub(crate) fn read_dir(}}))}++#[allow(clippy::similar_names)]+pub(super) fn system_time_from_rustix(sec: i64, nsec: u64) -> Option<SystemTime> {+ if sec >= 0 {+ SystemTime::UNIX_EPOCH.checked_add(Duration::new(u64::try_from(sec).unwrap(), nsec as _))+ } else {+ SystemTime::UNIX_EPOCH+ .checked_sub(Duration::new(sec.unsigned_abs(), 0))+ .map(|t| t.checked_add(Duration::new(0, nsec as u32)))+ .flatten()+ }+}++impl Metadata {+ #[inline]+ pub fn dev(&self) -> u64 {+ match self {+ Metadata::Std(m) => m.dev(),+ #[allow(unused_comparisons, reason = "platform-specific typedef")]+ Metadata::Stat(m) => {+ // The type of `st_dev` is `dev_t` which is signed on some+ // platforms and unsigned on other platforms. A `u64` is enough+ // to work for all unsigned platforms, and for signed platforms+ // perform a sign extension to `i64` and then view that as an+ // unsigned 64-bit number instead.+ //+ // Note that the `unused_comparisons` is ignored here for+ // platforms where it's unsigned since the first branch here+ // will never be taken.+ if m.st_dev < 0 {+ i64::try_from(m.st_dev).unwrap().cast_unsigned()+ } else {+ u64::try_from(m.st_dev).unwrap()+ }+ }+ #[cfg(target_os = "linux")]+ Metadata::Statx(m) => rustix::fs::makedev(m.stx_dev_major, m.stx_dev_minor),+ }+ }++ #[inline]+ pub fn ino(&self) -> u64 {+ match self {+ Metadata::Std(m) => m.ino(),+ Metadata::Stat(m) => m.st_ino,+ #[cfg(target_os = "linux")]+ Metadata::Statx(m) => m.stx_ino,+ }+ }++ #[inline]+ pub fn nlink(&self) -> u64 {+ match self {+ Metadata::Std(m) => m.nlink(),+ Metadata::Stat(m) => m.st_nlink.into(),+ #[cfg(target_os = "linux")]+ Metadata::Statx(m) => m.stx_nlink.into(),+ }+ }+}++impl FileType {+ pub(super) fn from_raw_mode(raw_mode: RawMode) -> Self {+ Self::Unix(rustix::fs::FileType::from_raw_mode(raw_mode))+ }++ pub fn is_char_device(&self) -> bool {+ match self {+ Self::Std(std) => std.is_char_device(),+ #[cfg(unix)]+ Self::Unix(unix) => unix.is_char_device(),+ }+ }++ pub fn is_block_device(&self) -> bool {+ match self {+ Self::Std(std) => std.is_block_device(),+ #[cfg(unix)]+ Self::Unix(unix) => unix.is_block_device(),+ }+ }+}++/// It should be possible to represent times before the Epoch.+/// https://github.com/bytecodealliance/cap-std/issues/328+#[test]+fn negative_time() {+ let system_time = system_time_from_rustix(-1, 1).unwrap();+ let d = SystemTime::UNIX_EPOCH.duration_since(system_time).unwrap();+ assert_eq!(d.as_secs(), 0);+ assert_eq!(d.subsec_nanos(), 999999999);+}diff --git a/crates/wasi/src/filesystem/primitives/unix/stat_unchecked.rs b/crates/wasi/src/filesystem/primitives/unix/stat_unchecked.rsindex 25bf59a620..19cc7a35ad 100644--- a/crates/wasi/src/filesystem/primitives/unix/stat_unchecked.rs+++ b/crates/wasi/src/filesystem/primitives/unix/stat_unchecked.rs@@ -1,4 +1,4 @@-use crate::filesystem::primitives::{FollowSymlinks, ImplMetadataExt, Metadata};+use crate::filesystem::primitives::{FollowSymlinks, Metadata};use rustix::fs::{AtFlags, statat};use std::path::Path;use std::{fs, io};@@ -50,7 +50,7 @@ pub(crate) fn stat_unchecked(if state == 0 {STATX_STATE.store(2, Ordering::Relaxed);}- return Ok(ImplMetadataExt::from_rustix_statx(statx));+ return Ok(Metadata::Statx(statx));}Err(rustix::io::Errno::NOSYS) => STATX_STATE.store(1, Ordering::Relaxed),Err(rustix::io::Errno::PERM) if state == 0 => {@@ -75,5 +75,5 @@ pub(crate) fn stat_unchecked(}}- Ok(statat(start, path, atflags).map(ImplMetadataExt::from_rustix)?)+ Ok(statat(start, path, atflags).map(Metadata::Stat)?)}diff --git a/crates/wasi/src/filesystem/primitives/windows/file_type_ext.rs b/crates/wasi/src/filesystem/primitives/windows/file_type_ext.rsdeleted file mode 100644index 084b805dc1..0000000000--- a/crates/wasi/src/filesystem/primitives/windows/file_type_ext.rs+++ /dev/null@@ -1,92 +0,0 @@-use crate::filesystem::primitives::FileType;-use std::{fs, io};--/// A type that implements `FileTypeExt` for this platform.-#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]-pub(crate) enum ImplFileTypeExt {- CharacterDevice,- Fifo,- SymlinkUnknown,-}--impl ImplFileTypeExt {- /// Constructs a new instance of `Self` from the given [`std::fs::File`]- /// and [`std::fs::Metadata`].- pub(crate) fn from(file: &fs::File, metadata: &fs::Metadata) -> io::Result<FileType> {- // Check for the things we can do with just metadata.- let file_type = Self::from_just_metadata(metadata);- if file_type != FileType::unknown() {- return Ok(file_type);- }-- // Use the open file to check for one of the exotic file types.- let file_type = winx::winapi_util::file::typ(file)?;- if file_type.is_char() {- return Ok(FileType::ext(ImplFileTypeExt::CharacterDevice));- }- if file_type.is_pipe() {- return Ok(FileType::ext(ImplFileTypeExt::Fifo));- }-- Ok(FileType::unknown())- }-- /// Constructs a new instance of `Self` from the given- /// [`std::fs::Metadata`].- #[inline]- pub(crate) fn from_just_metadata(metadata: &fs::Metadata) -> FileType {- let std = metadata.file_type();- Self::from_std(std)- }-- /// Constructs a new instance of `Self` from the given- /// [`std::fs::FileType`].- #[inline]- pub(crate) fn from_std(std: fs::FileType) -> FileType {- if std.is_file() {- return FileType::file();- }- if std.is_dir() {- return FileType::dir();- }-- if std.is_symlink() {- return FileType::ext(Self::SymlinkUnknown);- }-- FileType::unknown()- }-- #[inline]- pub(crate) fn is_symlink(&self) -> bool {- match self {- Self::SymlinkUnknown => true,- _ => false,- }- }-}--#[doc(hidden)]-impl crate::filesystem::primitives::_WindowsFileTypeExt- for crate::filesystem::primitives::FileType-{- #[inline]- fn is_block_device(&self) -> bool {- false- }-- #[inline]- fn is_char_device(&self) -> bool {- *self == FileType::ext(ImplFileTypeExt::CharacterDevice)- }-- #[inline]- fn is_fifo(&self) -> bool {- *self == FileType::ext(ImplFileTypeExt::Fifo)- }-- #[inline]- fn is_socket(&self) -> bool {- false- }-}diff --git a/crates/wasi/src/filesystem/primitives/windows/metadata_ext.rs b/crates/wasi/src/filesystem/primitives/windows/metadata_ext.rsdeleted file mode 100644index 3d164c8321..0000000000--- a/crates/wasi/src/filesystem/primitives/windows/metadata_ext.rs+++ /dev/null@@ -1,53 +0,0 @@-#![allow(clippy::useless_conversion)]--use crate::filesystem::primitives::MetadataExt;-use std::{fs, io};--#[derive(Debug, Clone)]-pub(crate) struct ImplMetadataExt {- file_attributes: u32,- number_of_links: Option<u32>,-}--impl ImplMetadataExt {- /// Constructs a new instance of `Self` from the given [`std::fs::File`]- /// and [`std::fs::Metadata`].- #[inline]- pub(crate) fn from(file: &fs::File, std: &fs::Metadata) -> io::Result<Self> {- let fileinfo = winx::winapi_util::file::information(file)?;- let t64: u64 = fileinfo.number_of_links();- let t32: u32 = t64.try_into().unwrap();-- Ok(Self::from_parts(std, Some(t32)))- }-- #[inline]- fn from_parts(std: &fs::Metadata, number_of_links: Option<u32>) -> Self {- use std::os::windows::fs::MetadataExt;- Self {- file_attributes: std.file_attributes(),- number_of_links,- }- }-- /// `MetadataExt` requires nightly to be implemented, but we sometimes- /// just need the file attributes.- #[inline]- pub(crate) fn file_attributes(&self) -> u32 {- self.file_attributes- }-}--impl MetadataExt for ImplMetadataExt {- fn file_attributes(&self) -> u32 {- self.file_attributes- }-}--#[doc(hidden)]-impl crate::filesystem::primitives::_WindowsByHandle for crate::filesystem::primitives::Metadata {- #[inline]- fn number_of_links(&self) -> Option<u32> {- self.ext.number_of_links- }-}diff --git a/crates/wasi/src/filesystem/primitives/windows/mod.rs b/crates/wasi/src/filesystem/primitives/windows/mod.rsindex d36e12db3b..307decd70e 100644--- a/crates/wasi/src/filesystem/primitives/windows/mod.rs+++ b/crates/wasi/src/filesystem/primitives/windows/mod.rs@@ -1,10 +1,11 @@+use crate::filesystem::primitives::Metadata;+use std::os::windows::fs::MetadataExt;+mod create_dir_unchecked;mod create_file_at_w;mod dir_utils;-mod file_type_ext;mod get_path;mod hard_link_unchecked;-mod metadata_ext;mod oflags;mod open_fast;mod open_options_ext;@@ -23,9 +24,7 @@ pub(crate) mod errors;pub(crate) use create_dir_unchecked::*;pub(crate) use dir_utils::*;-pub(crate) use file_type_ext::*;pub(crate) use hard_link_unchecked::*;-pub(crate) use metadata_ext::*;pub(crate) use open_fast::*;pub(crate) use open_options_ext::*;pub(crate) use open_unchecked::*;@@ -48,3 +47,10 @@ pub(crate) fn file_path(file: &std::fs::File) -> Option<std::path::PathBuf> {}pub(super) use oflags::*;++impl Metadata {+ pub(super) fn file_attributes(&self) -> u32 {+ let Metadata::Std(std) = self;+ std.file_attributes()+ }+}diff --git a/crates/wasi/src/filesystem/primitives/windows/read_dir.rs b/crates/wasi/src/filesystem/primitives/windows/read_dir.rsindex 80dcc0a863..b8a29f8610 100644--- a/crates/wasi/src/filesystem/primitives/windows/read_dir.rs+++ b/crates/wasi/src/filesystem/primitives/windows/read_dir.rs@@ -1,6 +1,5 @@use super::get_path::concatenate;use crate::filesystem::primitives::FileType;-use crate::filesystem::primitives::windows::ImplFileTypeExt;use std::ffi::OsString;use std::path::Component;use std::{fs, io};@@ -12,7 +11,6 @@ pub(crate) fn read_dir(let iter = fs::read_dir(full_path)?;Ok(iter.map(|entry| {let entry = entry?;- let file_type = ImplFileTypeExt::from_std(entry.file_type()?);- Ok((entry.file_name(), file_type))+ Ok((entry.file_name(), entry.file_type()?.into()))}))}diff --git a/crates/wasi/src/filesystem/unix.rs b/crates/wasi/src/filesystem/unix.rsindex bfa09865d5..198abab4ad 100644--- a/crates/wasi/src/filesystem/unix.rs+++ b/crates/wasi/src/filesystem/unix.rs@@ -1,6 +1,4 @@-use crate::filesystem::primitives::{- FileType, FileTypeExt, FollowSymlinks, Metadata, MetadataExt, OpenOptions,-};+use crate::filesystem::primitives::{FileType, FollowSymlinks, Metadata, OpenOptions};use crate::filesystem::{Advice, DescriptorFlags, DescriptorStat, DescriptorType, MetadataHashValue,};diff --git a/crates/wasi/src/filesystem/windows.rs b/crates/wasi/src/filesystem/windows.rsindex ab5d9209b7..d1ba31bd97 100644--- a/crates/wasi/src/filesystem/windows.rs+++ b/crates/wasi/src/filesystem/windows.rs@@ -7,7 +7,7 @@ use crate::filesystem::{use std::fs::File;use std::io::{self, Write};use std::mem::{self, MaybeUninit};-use std::os::windows::fs::FileExt;+use std::os::windows::fs::{FileExt, MetadataExt};use std::os::windows::io::*;use std::path::Path;use std::sync::OnceLock;@@ -129,10 +129,7 @@ fn open_metadata_handle(start: &File, path: &Path, follow: FollowSymlinks) -> iopub(crate) fn stat(f: &std::fs::File) -> io::Result<DescriptorStat> {let meta = Metadata::from_file(f)?;-- let link_count = crate::filesystem::primitives::_WindowsByHandle::number_of_links(&meta)- .unwrap()- .into();+ let link_count = by_handle_info(f)?.nNumberOfLinks.into();Ok(DescriptorStat::new(&meta, link_count))}@@ -194,11 +191,9 @@ pub(crate) fn remove_file_or_symlink(start: &File, path: &Path) -> io::Result<()opts.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS);let file = crate::filesystem::primitives::open(start, path, &opts)?;- let meta = Metadata::from_file(&file)?;+ let meta = file.metadata()?;if meta.file_type().is_symlink()- && crate::filesystem::primitives::MetadataExt::file_attributes(&meta)- & FILE_ATTRIBUTE_DIRECTORY- == FILE_ATTRIBUTE_DIRECTORY+ && meta.file_attributes() & FILE_ATTRIBUTE_DIRECTORY == FILE_ATTRIBUTE_DIRECTORY{crate::filesystem::primitives::remove_dir(start, path)?;} else {