Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Abort a process when FD ownership is violated #124210

Merged
merged 3 commits into from
Apr 28, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
15 changes: 14 additions & 1 deletion library/std/src/os/fd/owned.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,20 @@ impl Drop for OwnedFd {
// something like EINTR), we might close another valid file descriptor
// opened after we closed ours.
#[cfg(not(target_os = "hermit"))]
let _ = libc::close(self.fd);
{
use crate::sys::os::errno;
// ideally this would use assert_unsafe_precondition!, but that's only in core
if cfg!(debug_assertions) {
the8472 marked this conversation as resolved.
Show resolved Hide resolved
// close() can bubble up error codes from FUSE which can send semantically
// inappropriate error codes including EBADF.
// So we check file flags instead which live on the file descriptor and not the underlying file.
// The downside is that it costs an extra syscall, so we only do it for debug.
if libc::fcntl(self.fd, libc::F_GETFD) == -1 && errno() == libc::EBADF {
rtabort!("IO Safety violation: owned file descriptor already closed");
}
}
let _ = libc::close(self.fd);
}
#[cfg(target_os = "hermit")]
let _ = hermit_abi::close(self.fd);
}
Expand Down
21 changes: 21 additions & 0 deletions library/std/src/sys/pal/unix/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -870,6 +870,27 @@ impl Iterator for ReadDir {

impl Drop for Dir {
fn drop(&mut self) {
// ideally this would use assert_unsafe_precondition!, but that's only in core
#[cfg(all(
debug_assertions,
not(any(
target_os = "redox",
target_os = "nto",
target_os = "vita",
target_os = "hurd",
))
))]
{
use crate::sys::os::errno;
// close() can bubble up error codes from FUSE which can send semantically
// inappropriate error codes including EBADF.
// So we check file flags instead which live on the file descriptor and not the underlying file.
// The downside is that it costs an extra syscall, so we only do it for debug.
let fd = unsafe { libc::dirfd(self.0) };
if unsafe { libc::fcntl(fd, libc::F_GETFD) } == -1 && errno() == libc::EBADF {
rtabort!("IO Safety violation: DIR*'s owned file descriptor already closed");
}
}
let r = unsafe { libc::closedir(self.0) };
assert!(
r == 0 || crate::io::Error::last_os_error().is_interrupted(),
Expand Down
Loading