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
83 changes: 83 additions & 0 deletions library/std/src/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1598,6 +1598,89 @@ impl Dir {
.open_file(path.as_ref(), &OpenOptions::new().read(true).0)
.map(|f| File { inner: f })
}

/// Attempts to open a file according to `opts` relative to this directory.
///
/// # Errors
///
/// This function will return an error if `path` does not point to an existing file.
/// Other errors may also be returned according to [`OpenOptions::open`].
///
/// # Examples
///
/// ```no_run
/// #![feature(dirfd)]
/// use std::{fs::{Dir, OpenOptions}, io::{self, Write}};
///
/// fn main() -> io::Result<()> {
/// let dir = Dir::open("foo")?;
/// let mut opts = OpenOptions::new();
/// opts.read(true).write(true);
/// let mut f = dir.open_file_with("bar.txt", &opts)?;
/// f.write(b"Hello, world!")?;
/// let contents = io::read_to_string(f)?;
/// assert_eq!(contents, "Hello, world!");
/// Ok(())
/// }
/// ```
#[unstable(feature = "dirfd", issue = "120426")]
pub fn open_file_with<P: AsRef<Path>>(&self, path: P, opts: &OpenOptions) -> io::Result<File> {
self.inner.open_file(path.as_ref(), &opts.0).map(|f| File { inner: f })
}

/// Attempts to remove a file relative to this directory.
///
/// # Errors
///
/// This function will return an error if `path` does not point to an existing file.
/// Other errors may also be returned according to [`OpenOptions::open`].
///
/// # Examples
///
/// ```no_run
/// #![feature(dirfd)]
/// use std::fs::Dir;
///
/// fn main() -> std::io::Result<()> {
/// let dir = Dir::open("foo")?;
/// dir.remove_file("bar.txt")?;
/// Ok(())
/// }
/// ```
#[unstable(feature = "dirfd", issue = "120426")]
pub fn remove_file<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
self.inner.remove_file(path.as_ref())
}

/// Attempts to rename a file or directory relative to this directory to a new name, replacing
/// the destination file if present.
///
/// # Errors
///
/// This function will return an error if `from` does not point to an existing file or directory.
/// Other errors may also be returned according to [`OpenOptions::open`].
///
/// # Examples
///
/// ```no_run
/// #![feature(dirfd)]
/// use std::fs::Dir;
///
/// fn main() -> std::io::Result<()> {
/// let dir = Dir::open("foo")?;
/// dir.rename("bar.txt", &dir, "quux.txt")?;
/// Ok(())
/// }
/// ```
#[unstable(feature = "dirfd", issue = "120426")]
pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(
&self,
from: P,
to_dir: &Self,
to: Q,
) -> io::Result<()> {
self.inner.rename(from.as_ref(), &to_dir.inner, to.as_ref())
}
}

impl AsInner<fs_imp::Dir> for Dir {
Expand Down
49 changes: 49 additions & 0 deletions library/std/src/fs/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ use rand::RngCore;

#[cfg(not(miri))]
use super::Dir;
#[cfg(not(miri))]
use crate::fs::exists;
use crate::fs::{self, File, FileTimes, OpenOptions, TryLockError};
#[cfg(not(miri))]
use crate::io;
Expand Down Expand Up @@ -2555,3 +2557,50 @@ fn test_dir_read_file() {
let buf = check!(io::read_to_string(f));
assert_eq!("bar", &buf);
}

#[test]
// FIXME: libc calls fail on miri
#[cfg(not(miri))]
fn test_dir_write_file() {
let tmpdir = tmpdir();
let dir = check!(Dir::open(tmpdir.path()));
let mut f = check!(dir.open_file_with("foo.txt", &OpenOptions::new().write(true).create(true)));
check!(f.write(b"bar"));
check!(f.flush());
drop(f);
let mut f = check!(File::open(tmpdir.join("foo.txt")));
let mut buf = [0u8; 3];
check!(f.read_exact(&mut buf));
assert_eq!(b"bar", &buf);
}

#[test]
// FIXME: libc calls fail on miri
#[cfg(not(miri))]
fn test_dir_remove_file() {
let tmpdir = tmpdir();
let mut f = check!(File::create(tmpdir.join("foo.txt")));
check!(f.write(b"bar"));
check!(f.flush());
drop(f);
let dir = check!(Dir::open(tmpdir.path()));
check!(dir.remove_file("foo.txt"));
assert!(!matches!(exists(tmpdir.join("foo.txt")), Ok(true)));
}

#[test]
// FIXME: libc calls fail on miri
#[cfg(not(miri))]
fn test_dir_rename_file() {
let tmpdir = tmpdir();
let mut f = check!(File::create(tmpdir.join("foo.txt")));
check!(f.write(b"bar"));
check!(f.flush());
drop(f);
let dir = check!(Dir::open(tmpdir.path()));
check!(dir.rename("foo.txt", &dir, "baz.txt"));
let mut f = check!(File::open(tmpdir.join("baz.txt")));
let mut buf = [0u8; 3];
check!(f.read_exact(&mut buf));
assert_eq!(b"bar", &buf);
}
9 changes: 9 additions & 0 deletions library/std/src/sys/fs/common.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#![allow(dead_code)] // not used on all platforms

use crate::fs::{remove_file, rename};
use crate::io::{self, Error, ErrorKind};
use crate::path::{Path, PathBuf};
use crate::sys::fs::{File, OpenOptions};
Expand Down Expand Up @@ -72,6 +73,14 @@ impl Dir {
pub fn open_file(&self, path: &Path, opts: &OpenOptions) -> io::Result<File> {
File::open(&self.path.join(path), &opts)
}

pub fn remove_file(&self, path: &Path) -> io::Result<()> {
remove_file(self.path.join(path))
}

pub fn rename(&self, from: &Path, to_dir: &Self, to: &Path) -> io::Result<()> {
rename(self.path.join(from), to_dir.path.join(to))
}
}

impl fmt::Debug for Dir {
Expand Down
32 changes: 30 additions & 2 deletions library/std/src/sys/fs/unix/dir.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use libc::c_int;
use libc::{c_int, renameat, unlinkat};

cfg_select! {
not(
Expand Down Expand Up @@ -27,7 +27,7 @@ use crate::sys::fd::FileDesc;
use crate::sys::fs::OpenOptions;
use crate::sys::fs::unix::{File, debug_path_fd};
use crate::sys::helpers::run_path_with_cstr;
use crate::sys::{AsInner, FromInner, IntoInner, cvt_r};
use crate::sys::{AsInner, FromInner, IntoInner, cvt, cvt_r};
use crate::{fmt, fs, io};

pub struct Dir(OwnedFd);
Expand All @@ -41,6 +41,16 @@ impl Dir {
run_path_with_cstr(path.as_ref(), &|path| self.open_file_c(path, &opts))
}

pub fn remove_file(&self, path: &Path) -> io::Result<()> {
run_path_with_cstr(path, &|path| self.remove_c(path, false))
}

pub fn rename(&self, from: &Path, to_dir: &Self, to: &Path) -> io::Result<()> {
run_path_with_cstr(from, &|from| {
run_path_with_cstr(to, &|to| self.rename_c(from, to_dir, to))
})
}

pub fn open_with_c(path: &CStr, opts: &OpenOptions) -> io::Result<Self> {
let flags = libc::O_CLOEXEC
| libc::O_DIRECTORY
Expand All @@ -61,6 +71,24 @@ impl Dir {
})?;
Ok(File(unsafe { FileDesc::from_raw_fd(fd) }))
}

fn remove_c(&self, path: &CStr, remove_dir: bool) -> io::Result<()> {
cvt(unsafe {
unlinkat(
self.0.as_raw_fd(),
path.as_ptr(),
if remove_dir { libc::AT_REMOVEDIR } else { 0 },
)
})
.map(|_| ())
}

fn rename_c(&self, from: &CStr, to_dir: &Self, to: &CStr) -> io::Result<()> {
cvt(unsafe {
renameat(self.0.as_raw_fd(), from.as_ptr(), to_dir.0.as_raw_fd(), to.as_ptr())
})
.map(|_| ())
}
}

impl fmt::Debug for Dir {
Expand Down
113 changes: 61 additions & 52 deletions library/std/src/sys/fs/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1318,6 +1318,66 @@ pub fn unlink(path: &WCStr) -> io::Result<()> {
}
}

/// Renames a file using NtSetInformationFile and FileRenameInformation. If to_dir is None, passes a
/// null pointer, which uses the directory `from` is already in (or it's ignored if `to` is an
/// absolute path).
fn nt_rename(from: impl AsHandle, to: &[u16], to_dir: Option<&Handle>) -> io::Result<()> {
let handle = from.as_handle();

const too_long_err: io::Error =
io::const_error!(io::ErrorKind::InvalidFilename, "Filename too long");
let struct_size = to
.len()
.checked_mul(2)
.and_then(|x| x.checked_add(offset_of!(c::FILE_RENAME_INFORMATION, FileName)))
.ok_or(too_long_err)?;
let layout = Layout::from_size_align(struct_size, align_of::<c::FILE_RENAME_INFORMATION>())
.map_err(|_| too_long_err)?;
let struct_size = u32::try_from(struct_size).map_err(|_| too_long_err)?;
let to_byte_len = u32::try_from(to.len() * 2).map_err(|_| too_long_err)?;

let file_rename_info;
// SAFETY: We allocate enough memory for a full FILE_RENAME_INFORMATION struct and the filename.
unsafe {
file_rename_info = alloc(layout).cast::<c::FILE_RENAME_INFORMATION>();
if file_rename_info.is_null() {
return Err(io::ErrorKind::OutOfMemory.into());
}

(&raw mut (*file_rename_info).Anonymous).write(c::FILE_RENAME_INFORMATION_0 {
Flags: c::FILE_RENAME_FLAG_REPLACE_IF_EXISTS | c::FILE_RENAME_FLAG_POSIX_SEMANTICS,
});

(&raw mut (*file_rename_info).RootDirectory)
.write(to_dir.map(Handle::as_raw_handle).unwrap_or_else(ptr::null_mut));
// Don't include the NULL in the size
(&raw mut (*file_rename_info).FileNameLength).write(to_byte_len);

to.as_ptr().copy_to_nonoverlapping(
(&raw mut (*file_rename_info).FileName).cast::<u16>(),
to.len(),
);
}

let status = unsafe {
c::NtSetInformationFile(
handle.as_raw_handle(),
&mut c::IO_STATUS_BLOCK::default(),
file_rename_info.cast::<c_void>(),
struct_size,
c::FileRenameInformation,
)
};
unsafe { dealloc(file_rename_info.cast::<u8>(), layout) };
if c::nt_success(status) {
// SAFETY: nt_success guarantees that handle is no longer null
Ok(())
} else {
Err(WinError::new(unsafe { c::RtlNtStatusToDosError(status) }))
}
.io_result()
}

pub fn rename(old: &WCStr, new: &WCStr) -> io::Result<()> {
if unsafe { c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING) } == 0 {
let err = api::get_last_error();
Expand All @@ -1330,58 +1390,7 @@ pub fn rename(old: &WCStr, new: &WCStr) -> io::Result<()> {
opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
let Ok(f) = File::open_native(&old, &opts) else { return Err(err).io_result() };

// Calculate the layout of the `FILE_RENAME_INFO` we pass to `SetFileInformation`
// This is a dynamically sized struct so we need to get the position of the last field to calculate the actual size.
let Ok(new_len_without_nul_in_bytes): Result<u32, _> =
((new.count_bytes() - 1) * 2).try_into()
else {
return Err(err).io_result();
};
let offset: u32 = offset_of!(c::FILE_RENAME_INFO, FileName).try_into().unwrap();
let struct_size = offset + new_len_without_nul_in_bytes + 2;
let layout =
Layout::from_size_align(struct_size as usize, align_of::<c::FILE_RENAME_INFO>())
.unwrap();

let file_rename_info;
// SAFETY: We allocate enough memory for a full FILE_RENAME_INFO struct and a filename.
unsafe {
file_rename_info = alloc(layout).cast::<c::FILE_RENAME_INFO>();
if file_rename_info.is_null() {
return Err(io::ErrorKind::OutOfMemory.into());
}

(&raw mut (*file_rename_info).Anonymous).write(c::FILE_RENAME_INFO_0 {
Flags: c::FILE_RENAME_FLAG_REPLACE_IF_EXISTS
| c::FILE_RENAME_FLAG_POSIX_SEMANTICS,
});

(&raw mut (*file_rename_info).RootDirectory).write(ptr::null_mut());
// Don't include the NULL in the size
(&raw mut (*file_rename_info).FileNameLength).write(new_len_without_nul_in_bytes);

new.as_ptr().copy_to_nonoverlapping(
(&raw mut (*file_rename_info).FileName).cast::<u16>(),
new.count_bytes(),
);
}

let result = unsafe {
c::SetFileInformationByHandle(
f.as_raw_handle(),
c::FileRenameInfoEx,
file_rename_info.cast::<c_void>(),
struct_size,
)
};
unsafe { dealloc(file_rename_info.cast::<u8>(), layout) };
if result == 0 {
if api::get_last_error() == WinError::DIR_NOT_EMPTY {
return Err(WinError::DIR_NOT_EMPTY).io_result();
} else {
return Err(err).io_result();
}
}
nt_rename(f.handle, new.as_slice(), None)?;
} else {
return Err(err).io_result();
}
Expand Down
Loading
Loading