Use HostFd to manage the lifetime of host OS resources

This commit is contained in:
Tate, Hongliang Tian 2020-11-18 14:54:35 +00:00 committed by Zongmin.Gu
parent 83ce318f6c
commit 34288a5e37
4 changed files with 16 additions and 28 deletions

@ -49,13 +49,6 @@ extern "C" {
fn occlum_ocall_eventfd(ret: *mut i32, init_val: u32, flags: i32) -> sgx_status_t; fn occlum_ocall_eventfd(ret: *mut i32, init_val: u32, flags: i32) -> sgx_status_t;
} }
impl Drop for EventFile {
fn drop(&mut self) {
let ret = unsafe { libc::ocall::close(self.host_fd.to_raw() as i32) };
assert!(ret == 0);
}
}
impl File for EventFile { impl File for EventFile {
fn read(&self, buf: &mut [u8]) -> Result<usize> { fn read(&self, buf: &mut [u8]) -> Result<usize> {
let (buf_ptr, buf_len) = buf.as_mut().as_mut_ptr_and_len(); let (buf_ptr, buf_len) = buf.as_mut().as_mut_ptr_and_len();

@ -5,7 +5,16 @@ use super::*;
/// A unique fd from the host OS. /// A unique fd from the host OS.
/// ///
/// The uniqueness property is important both /// There are two benefits of using `HostFd` instead of `FileDesc`.
///
/// 1. Uniqueness. Each instance of `HostFd` is guaranteed to have a different
/// value. The uniqueness property makes it possible to use `HostFd` as keys of
/// a hash table.
///
/// 2. Resource Acquisition Is Initialization (RAII). The acquisition and release
/// of the host resource represented by a host fd is bound to the lifetime
/// of the corresponding instance of `HostFd`. This makes resource management
/// simpler and more robust.
#[derive(Debug, PartialEq, Eq, Hash)] #[derive(Debug, PartialEq, Eq, Hash)]
pub struct HostFd(FileDesc); pub struct HostFd(FileDesc);
@ -22,11 +31,12 @@ impl HostFd {
impl Drop for HostFd { impl Drop for HostFd {
fn drop(&mut self) { fn drop(&mut self) {
HOST_FD_REGISTRY let raw_fd = self.to_raw();
.lock() HOST_FD_REGISTRY.lock().unwrap().unregister(raw_fd).unwrap();
.unwrap() // Note that close MUST be done after unregistering
.unregister(self.to_raw()) unsafe {
.unwrap(); libc::ocall::close(raw_fd as i32);
}
} }
} }

@ -180,11 +180,3 @@ impl HostFileEpoller {
&self.host_epoll_fd &self.host_epoll_fd
} }
} }
impl Drop for HostFileEpoller {
fn drop(&mut self) {
unsafe {
libc::ocall::close(self.host_epoll_fd.to_raw() as i32);
}
}
}

@ -134,13 +134,6 @@ impl HostSocket {
} }
} }
impl Drop for HostSocket {
fn drop(&mut self) {
let ret = unsafe { libc::ocall::close(self.host_fd.to_raw() as i32) };
assert!(ret == 0);
}
}
pub trait HostSocketType { pub trait HostSocketType {
fn as_host_socket(&self) -> Result<&HostSocket>; fn as_host_socket(&self) -> Result<&HostSocket>;
} }