From a299a10874c77a0115b85a4cf076af0a52ada435 Mon Sep 17 00:00:00 2001 From: Bo Chen Date: Fri, 14 Apr 2023 17:14:31 -0700 Subject: [PATCH] vmm: Implement Clone and Drop for VmConfig The custom 'clone' duplicates 'preserved_fds' so that the validation logic can be safely carried out on the clone of the VmConfig. The custom 'drop' ensures 'preserved_fds' are safely closed when the holding VmConfig instance is destroyed. Signed-off-by: Bo Chen --- vmm/src/config.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++ vmm/src/vm_config.rs | 2 +- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/vmm/src/config.rs b/vmm/src/config.rs index 1f95c82e8..a70b8630f 100644 --- a/vmm/src/config.rs +++ b/vmm/src/config.rs @@ -2120,6 +2120,50 @@ impl VmConfig { } } +impl Clone for VmConfig { + fn clone(&self) -> Self { + VmConfig { + cpus: self.cpus.clone(), + memory: self.memory.clone(), + payload: self.payload.clone(), + disks: self.disks.clone(), + net: self.net.clone(), + rng: self.rng.clone(), + balloon: self.balloon.clone(), + fs: self.fs.clone(), + pmem: self.pmem.clone(), + serial: self.serial.clone(), + console: self.console.clone(), + devices: self.devices.clone(), + user_devices: self.user_devices.clone(), + vdpa: self.vdpa.clone(), + vsock: self.vsock.clone(), + #[cfg(target_arch = "x86_64")] + sgx_epc: self.sgx_epc.clone(), + numa: self.numa.clone(), + platform: self.platform.clone(), + tpm: self.tpm.clone(), + preserved_fds: self + .preserved_fds + .as_ref() + // SAFETY: FFI call with valid FDs + .map(|fds| fds.iter().map(|fd| unsafe { libc::dup(*fd) }).collect()), + ..*self + } + } +} + +impl Drop for VmConfig { + fn drop(&mut self) { + if let Some(mut fds) = self.preserved_fds.take() { + for fd in fds.drain(..) { + // SAFETY: FFI call with valid FDs + unsafe { libc::close(fd) }; + } + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/vmm/src/vm_config.rs b/vmm/src/vm_config.rs index d26a85c06..56add7ac8 100644 --- a/vmm/src/vm_config.rs +++ b/vmm/src/vm_config.rs @@ -563,7 +563,7 @@ pub struct TpmConfig { pub socket: PathBuf, } -#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] +#[derive(Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct VmConfig { #[serde(default)] pub cpus: CpusConfig,