From a8b4ea3704bceccb3d38751ac941a4a559cce5b1 Mon Sep 17 00:00:00 2001 From: The 8472 Date: Thu, 18 Apr 2024 20:03:45 +0200 Subject: [PATCH] Abort a process when FD ownership is violated When an EBADF happens then something else already touched an FD in ways it is not allowed to. At that point things can already be arbitrarily bad, e.g. clobbered mmaps. Recovery is not possible. All we can do is hasten the fire. --- library/std/src/os/fd/owned.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/library/std/src/os/fd/owned.rs b/library/std/src/os/fd/owned.rs index 010ce4e5076ba..a626415a5d16a 100644 --- a/library/std/src/os/fd/owned.rs +++ b/library/std/src/os/fd/owned.rs @@ -176,7 +176,16 @@ 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); + { + match cvt(libc::close(self.fd)) { + Err(e) if e.raw_os_error() == Some(libc::EBADF) => { + rtabort!( + "IO Safety violation: owned file descriptor already closed (EBADF)" + ); + } + _ => {} + } + } #[cfg(target_os = "hermit")] let _ = hermit_abi::close(self.fd); }