From 7953cc2006faab0d678c26df18f3c0b795a78586 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aurimas=20Bla=C5=BEulionis?= <0x60@pm.me> Date: Tue, 28 Nov 2023 20:08:28 +0000 Subject: [PATCH] Close FdWaker handle when on close function call --- mfio/src/backend/fd.rs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/mfio/src/backend/fd.rs b/mfio/src/backend/fd.rs index a058b0e..4943cd9 100644 --- a/mfio/src/backend/fd.rs +++ b/mfio/src/backend/fd.rs @@ -1,3 +1,4 @@ +use core::mem::ManuallyDrop; use core::sync::atomic::{AtomicU8, Ordering}; use core::task::{RawWaker, RawWakerVTable, Waker}; use std::fs::File; @@ -18,7 +19,7 @@ impl From for FdWakerOwner { fn from(fd: F) -> Self { Self(FdWaker( BaseArc::new(FdWakerInner { - fd, + fd: ManuallyDrop::new(fd), flags: Default::default(), }) .into_raw(), @@ -86,7 +87,11 @@ impl FdWaker { pub fn close(&self) { let inner = unsafe { &*self.0 }; - inner.flags.fetch_or(0b100, Ordering::AcqRel); + if inner.flags.fetch_or(0b100, Ordering::AcqRel) & 0b100 == 0 { + // SAFETY: we are attesting exclusive access to the + let fd = unsafe { &mut (*self.0.cast_mut()).fd }; + unsafe { ManuallyDrop::drop(fd) } + } } pub fn into_raw_waker(self) -> RawWaker { @@ -125,10 +130,18 @@ impl FdWaker { } struct FdWakerInner { - fd: F, + fd: ManuallyDrop, flags: AtomicU8, } +impl Drop for FdWakerInner { + fn drop(&mut self) { + if *self.flags.get_mut() & 0b100 == 0 { + unsafe { ManuallyDrop::drop(&mut self.fd) } + } + } +} + impl AsRef for FdWakerInner { fn as_ref(&self) -> &AtomicU8 { &self.flags