vmm: Use HashSet for VmConfig::preserved_fds

Each VM reboot re-entered the VFIO/virtio-net add paths and re-appended
the same originating fds, leaving duplicates in preserved_fds and a
double-close hazard at final teardown. Switching to HashSet makes
add_preserved_fds idempotent.

Signed-off-by: Bo Chen <bchen@crusoe.ai>
Assisted-by: Claude:Opus-4.7
This commit is contained in:
Bo Chen
2026-05-06 22:03:45 +00:00
committed by Rob Bradford
parent 5c25d82f59
commit 8fd8224ee3
3 changed files with 9 additions and 10 deletions
+6 -8
View File
@@ -3,7 +3,7 @@
// SPDX-License-Identifier: Apache-2.0
//
use std::collections::{BTreeSet, HashMap};
use std::collections::{BTreeSet, HashMap, HashSet};
#[cfg(feature = "ivshmem")]
use std::fs;
use std::path::PathBuf;
@@ -3560,16 +3560,14 @@ impl VmConfig {
/// # Safety
/// To use this safely, the caller must guarantee that the input
/// fds are all valid.
pub unsafe fn add_preserved_fds(&mut self, mut fds: Vec<i32>) {
pub unsafe fn add_preserved_fds(&mut self, fds: Vec<i32>) {
if fds.is_empty() {
return;
}
if let Some(preserved_fds) = &self.preserved_fds {
fds.append(&mut preserved_fds.clone());
}
self.preserved_fds = Some(fds);
self.preserved_fds
.get_or_insert_with(HashSet::new)
.extend(fds);
}
#[cfg(feature = "tdx")]
@@ -3627,7 +3625,7 @@ impl Clone for VmConfig {
impl Drop for VmConfig {
fn drop(&mut self) {
if let Some(mut fds) = self.preserved_fds.take() {
for fd in fds.drain(..) {
for fd in fds.drain() {
// SAFETY: FFI call with valid FDs
unsafe { libc::close(fd) };
}