From 350018ce4335ba60ad722852f4004f90674f69e9 Mon Sep 17 00:00:00 2001 From: Pedro Henrique Penna Date: Wed, 25 Nov 2026 08:27:21 -0800 Subject: [PATCH 1/6] virtiofs: let a new microVM object take the last node ID A microVM MKDIR, MKNOD, SYMLINK, or CREATE that reserved the last node ID that the node table hands out, u64::MAX - 1, made its object on the host and then failed with ENOSPC (microsoft/nvx#2135). The guest saw the request fail while the object stayed on the host, and every retry under another name left another object behind. A restore reaches that state, since it accepts any next node ID above the saved ones; live requests would need some 2^64 allocations. These requests reserve the node ID of their object before they make it, so that a full table refuses them before the host changes, and insert the object's node with that ID afterwards. InodeReservation::insert checked that insert against the microVM limits with InodeMap::preflight_microvm_insert, which, for a node of its own, also requires that the table can hand out its next node ID. The reservation has already taken that ID, so the check asked about the ID after it: after a reservation of u64::MAX - 1, the table's next node ID is u64::MAX, which it never hands out, and the insert failed although it needed no other ID. The check dates from the microVM profile (dbf0fa400); before 301937559 made u64::MAX - 1 the last node ID, it failed this way after a reservation of u64::MAX. FileReservation::insert checks only the handle limit, so handles are not affected. Check a reserved insert with the new InodeMap::preflight_microvm_reserved_insert, which checks the inode and alias limits as before but not the next node ID. The checks that run before the host changes, and inserts without a reservation, such as a LOOKUP's, are unchanged. microvm::fs_tests::a_created_object_takes_the_last_node_id restores a state whose next node ID is u64::MAX - 1 and checks, for each of the four requests, that the request returns node u64::MAX - 1, which a LOOKUP of the new name returns too, that the next such request fails with ENOSPC and leaves nothing on the host, and that the state then saves the node and the next node ID u64::MAX, and restores. On 1633b3797, MKDIR fails the test with ENOSPC; a probe there showed each of the four requests failing with ENOSPC twice in a row, each time leaving its object on the host, and the state saving no node, on Windows and on a Linux KVM host. With the fix, the test and the rest of cargo nextest -p virtiofs pass on both. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- vm/devices/virtio/virtiofs/src/lib.rs | 2 +- .../virtio/virtiofs/src/microvm/fs_tests.rs | 81 +++++++++++++++++++ .../virtio/virtiofs/src/microvm/limits.rs | 39 ++++++++- 3 files changed, 119 insertions(+), 3 deletions(-) diff --git a/vm/devices/virtio/virtiofs/src/lib.rs b/vm/devices/virtio/virtiofs/src/lib.rs index 9677b92da21..1262b720128 100644 --- a/vm/devices/virtio/virtiofs/src/lib.rs +++ b/vm/devices/virtio/virtiofs/src/lib.rs @@ -1017,7 +1017,7 @@ impl InodeReservation<'_> { fn insert(mut self, inode: VirtioFsInode) -> lx::Result<(Arc, u64)> { let mut inodes = self.inodes.write(); if self.microvm { - inodes.preflight_microvm_insert(&inode)?; + inodes.preflight_microvm_reserved_insert(&inode)?; } let result = inodes.insert_reserved(&self.reservation, inode)?; self.committed = true; diff --git a/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs b/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs index 53579836c46..653b220aa4a 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs @@ -3,7 +3,9 @@ //! Tests for microVM filesystem persistence and limits. +use super::policy_tests::create; use super::policy_tests::lookup; +use super::policy_tests::mkdir; use super::policy_tests::name; use super::policy_tests::open; use super::policy_tests::read_node; @@ -46,6 +48,7 @@ use fuse::protocol::fuse_dirent_align; use fuse::protocol::fuse_direntplus; use fuse::protocol::fuse_in_header; use fuse::protocol::fuse_init_in; +use fuse::protocol::fuse_mknod_in; use fuse::protocol::fuse_read_in; use fuse::protocol::fuse_release_in; use std::path::Path; @@ -175,6 +178,84 @@ fn largest_restored_next_node_id_is_never_handed_out() { .unwrap(); } +/// A saved state may also hold the last node ID that the node table hands +/// out, `u64::MAX - 1`. `MKDIR`, `MKNOD`, `SYMLINK`, and `CREATE` reserve the +/// node ID of the object that they make before they make it on the host, so +/// the object takes that ID even though the table can hand out no other: the +/// reply returns the object's node rather than fail and leave the object on +/// the host without one. The next request that makes an object then fails +/// with `ENOSPC` before it changes the host, and the state saves the node and +/// the next node ID `u64::MAX`, which a restore accepts. +#[test] +fn a_created_object_takes_the_last_node_id() { + for operation in ["MKDIR", "MKNOD", "SYMLINK", "CREATE"] { + let temporary_directory = tempdir().unwrap(); + let root_path = temporary_directory.path(); + let profile = MicroVmVirtioFsProfile::from_attachment( + MICROVM_ATTACHMENT_ID.to_owned(), + microvm_root_identity(root_path).unwrap(), + false, + Vec::new(), + ) + .unwrap(); + let source = VirtioFs::new_microvm(root_path, profile.clone()).unwrap(); + let mut state = source + .save_microvm_state(&profile, SessionState::default()) + .unwrap(); + state.next_node_id = u64::MAX - 1; + let fs = VirtioFs::new_microvm(root_path, profile.clone()).unwrap(); + let session = Session::new(fs.clone()); + fs.restore_microvm_state(&profile, state, &session).unwrap(); + + let make = |object: &str| -> lx::Result { + let parent = request(FUSE_ROOT_ID); + match operation { + "MKDIR" => mkdir(&fs, FUSE_ROOT_ID, object), + "MKNOD" => { + let arg = fuse_mknod_in { + mode: lx::S_IFREG | 0o644, + rdev: 0, + umask: 0, + padding: 0, + }; + Ok(fs.mknod(&parent, name(object), &arg)?.nodeid) + } + "SYMLINK" => Ok(fs.symlink(&parent, name(object), name("target"))?.nodeid), + "CREATE" => { + let (node_id, fh) = create(&fs, FUSE_ROOT_ID, object)?; + release(&fs, node_id, fh); + Ok(node_id) + } + _ => unreachable!(), + } + }; + let on_host = |object: &str| root_path.join(object).symlink_metadata().is_ok(); + + assert_eq!(make("first"), Ok(u64::MAX - 1), "{operation}"); + assert!(on_host("first"), "{operation}"); + assert_eq!(lookup(&fs, "first"), Ok(u64::MAX - 1), "{operation}"); + assert_eq!(make("second"), Err(lx::Error::ENOSPC), "{operation}"); + assert!(!on_host("second"), "{operation}"); + + let state = fs + .save_microvm_state(&profile, SessionState::default()) + .unwrap(); + assert_eq!(state.next_node_id, u64::MAX, "{operation}"); + assert!( + state + .inodes + .iter() + .any(|inode| inode.node_id == u64::MAX - 1), + "{operation}" + ); + let restored = VirtioFs::new_microvm(root_path, profile.clone()).unwrap(); + let session = Session::new(restored.clone()); + restored + .restore_microvm_state(&profile, state, &session) + .unwrap(); + } +} + /// A reset or `FUSE_DESTROY` ends a restored session as it ends a new one, so /// a remounting guest gets nodes from 2 and handles from 1 again, even after a /// restore whose tables were full. diff --git a/vm/devices/virtio/virtiofs/src/microvm/limits.rs b/vm/devices/virtio/virtiofs/src/microvm/limits.rs index 2fe439d296a..1e8bc79ca74 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/limits.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/limits.rs @@ -28,6 +28,33 @@ impl InodeMap { } pub(crate) fn preflight_microvm_insert(&self, inode: &VirtioFsInode) -> lx::Result<()> { + self.preflight_microvm_insert_with(inode, false) + } + + /// Checks an insert of `inode` with the node ID that a reservation holds + /// (see [`InodeMap::insert_reserved`]). + /// + /// Unlike [`Self::preflight_microvm_insert`], this does not check that the + /// table can hand out another node ID, since the insert takes none: a + /// request that reserved the last node ID, `u64::MAX - 1`, must still be + /// able to insert the node of the object that it has made on the host, + /// rather than fail and leave that object there without a node. The + /// inode and alias limits apply as to any insert. + pub(crate) fn preflight_microvm_reserved_insert( + &self, + inode: &VirtioFsInode, + ) -> lx::Result<()> { + self.preflight_microvm_insert_with(inode, true) + } + + /// Checks an insert of `inode`, whose node, if it adds one, takes the node + /// ID that a reservation holds if `reserved`, and otherwise the table's + /// next node ID. + fn preflight_microvm_insert_with( + &self, + inode: &VirtioFsInode, + reserved: bool, + ) -> lx::Result<()> { let path = inode.clone_path(); Self::validate_microvm_alias_path(&path)?; // The insert aliases the inode under the dedup key only if it reuses @@ -35,12 +62,20 @@ impl InodeMap { if let Some(existing) = self.reused(inode) { return self.preflight_microvm_alias_add(existing, &path); } - self.preflight_microvm_new_inode(&path) + self.preflight_microvm_node(&path, reserved) } pub(crate) fn preflight_microvm_new_inode(&self, path: &Path) -> lx::Result<()> { + self.preflight_microvm_node(path, false) + } + + /// Checks a new node at `path` against the inode and alias limits and, + /// unless a reservation holds its node ID (`reserved`), checks that the + /// table can hand out its next node ID. + fn preflight_microvm_node(&self, path: &Path, reserved: bool) -> lx::Result<()> { Self::validate_microvm_alias_path(path)?; - if self.inodes_by_node_id.values.len() >= MAX_INODES || !self.inodes_by_node_id.can_insert() + if self.inodes_by_node_id.values.len() >= MAX_INODES + || (!reserved && !self.inodes_by_node_id.can_insert()) { return Err(lx::Error::ENOSPC); } From 770bc61e7b2c683b092bffb5c8cd83b8696cf54a Mon Sep 17 00:00:00 2001 From: Pedro Henrique Penna Date: Wed, 25 Nov 2026 08:31:28 -0800 Subject: [PATCH 2/6] virtiofs: restore microVM handles opened with access mode 3 A microVM guest that opened a virtio-fs file with access mode 3 and held it open could save the VM's state, but its restore failed with "saved handle has invalid access mode", on read-write and read-only shares alike (microsoft/nvx#2125). Linux's open(2) reserves access mode 3 to check for read and write permission and return a descriptor that can neither read nor write, and the guest's FUSE client sends that access mode to FUSE_OPEN, which accepts it. The restore disagreed with FUSE_OPEN about such a handle twice. reopen_flags rejected access mode 3 outright, and validate_microvm_state took every access mode other than O_RDONLY for one that writes, so a read-only share or child, or a node outside the writable paths, could not restore the handle even without that rejection. FUSE_OPEN gives the handle there, since check_open_readonly refuses only the opens that opens_for_writing names: those for O_WRONLY or O_RDWR, or with O_TRUNC. reopen_flags now keeps every access mode, and the validation takes a handle for one that writes as opens_for_writing takes the open that reopens it, which drops O_TRUNC, so only O_WRONLY and O_RDWR need a writable node. A restored handle keeps access mode 3, so it still neither reads nor writes. The format of the saved state is unchanged. a_handle_that_neither_reads_nor_writes_survives_save_and_restore opens a file with access mode 3 on a read-write share, on a read-only share, and outside the writable paths of a read-write share, saves and restores the state, and expects the restored handle to serve its node and to fail reads and writes with EBADF. At feature/microvm/dev 1633b3797, the restore fails with "saved handle has invalid access mode" on Windows 11 (NTFS) and Azure Linux 3 (kernel 6.18, tmpfs). Without that check alone, it fails with "read-only microVM profile cannot restore a writable handle" on the read-only share, and with "microVM access policy cannot restore a writable handle outside its writable paths" outside the writable paths. With the fix, the test passes on both hosts, and so do the other tests of the virtiofs package. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../virtio/virtiofs/src/microvm/fs_tests.rs | 63 +++++++++++++++++++ .../virtio/virtiofs/src/microvm/state.rs | 9 ++- 2 files changed, 67 insertions(+), 5 deletions(-) diff --git a/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs b/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs index 653b220aa4a..0c992679e47 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs @@ -4,13 +4,16 @@ //! Tests for microVM filesystem persistence and limits. use super::policy_tests::create; +use super::policy_tests::error; use super::policy_tests::lookup; use super::policy_tests::mkdir; use super::policy_tests::name; use super::policy_tests::open; +use super::policy_tests::owned; use super::policy_tests::read_node; use super::policy_tests::release; use super::policy_tests::request; +use super::policy_tests::write; use super::profile::MICROVM_ATTACHMENT_ID; use super::profile::MICROVM_FUSE_MAJOR; use super::profile::MICROVM_FUSE_MAX_WRITE; @@ -41,6 +44,7 @@ use fuse::SessionInfoState; use fuse::SessionState; use fuse::protocol::FUSE_ASYNC_READ; use fuse::protocol::FUSE_DIRECT_IO_ALLOW_MMAP_FLAG2; +use fuse::protocol::FUSE_GETATTR_FH; use fuse::protocol::FUSE_INIT; use fuse::protocol::FUSE_INIT_EXT; use fuse::protocol::FUSE_ROOT_ID; @@ -1200,6 +1204,65 @@ fn readonly_profile_rejects_a_writable_saved_handle() { assert!(validate_microvm_state(&state, &profile).is_err()); } +/// Linux's access mode 3 opens a file for neither reading nor writing, so +/// `FUSE_OPEN` gives such a handle of a file that the guest may not write too: +/// on a read-only share, and outside the writable paths of a read-write share. +/// A restore must reopen that handle with the same access, as it reopens the +/// handles of the other access modes. +#[test] +fn a_handle_that_neither_reads_nor_writes_survives_save_and_restore() { + let cases: [(bool, &[&str]); 3] = [(false, &[]), (true, &[]), (false, &["out"])]; + for (read_only, writable_paths) in cases { + let case = format!("read_only={read_only}, writable_paths={writable_paths:?}"); + let temporary_directory = tempdir().unwrap(); + let root_path = temporary_directory.path(); + std::fs::create_dir(root_path.join("out")).unwrap(); + std::fs::write(root_path.join("file"), b"data").unwrap(); + let profile = MicroVmVirtioFsProfile::from_attachment_with_policy( + MICROVM_ATTACHMENT_ID.to_owned(), + microvm_root_identity(root_path).unwrap(), + read_only, + Vec::new(), + Vec::new(), + owned(writable_paths), + ) + .unwrap(); + let source = VirtioFs::new_microvm(root_path, profile.clone()).unwrap(); + let node_id = lookup(&source, "file").unwrap(); + let fh = open(&source, node_id, lx::O_NOACCESS).unwrap(); + let state = source + .save_microvm_state(&profile, SessionState::default()) + .unwrap(); + + let destination = VirtioFs::new_microvm(root_path, profile.clone()).unwrap(); + let session = Session::new(destination.clone()); + if let Err(error) = destination.restore_microvm_state(&profile, state, &session) { + panic!("{case}: {error:#}"); + } + destination + .get_attr(&request(node_id), FUSE_GETATTR_FH, fh) + .unwrap(); + let mut read = fuse_read_in::new_zeroed(); + read.fh = fh; + read.size = 64; + assert_eq!( + error(destination.read(&request(node_id), &read)), + lx::Error::EBADF, + "{case}" + ); + assert_eq!( + error(write(&destination, node_id, fh, b"guest")), + lx::Error::EBADF, + "{case}" + ); + assert_eq!( + std::fs::read(root_path.join("file")).unwrap(), + b"data", + "{case}" + ); + } +} + #[test] fn saved_parent_alias_is_rejected_before_reopen() { let temporary_directory = tempdir().unwrap(); diff --git a/vm/devices/virtio/virtiofs/src/microvm/state.rs b/vm/devices/virtio/virtiofs/src/microvm/state.rs index 1a1d7ddbab7..6d3b0c448fb 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/state.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/state.rs @@ -31,6 +31,7 @@ use super::saved_state::SavedState; use crate::FuseNegotiation; use crate::file::VirtioFsFile; use crate::inode::VirtioFsVolume; +use crate::opens_for_writing; use anyhow::Context; use fuse::SessionInfoState; use fuse::SessionState; @@ -526,7 +527,9 @@ pub(crate) fn validate_microvm_state( "saved handle has an unsupported object kind" ); let reopen_flags = reopen_flags(handle.open_flags)?; - let writable_handle = reopen_flags & lx::O_ACCESS_MASK as u32 != lx::O_RDONLY as u32; + // As for `FUSE_OPEN`, only an open for writing needs a writable node: + // access mode 3 opens the file for neither reading nor writing. + let writable_handle = opens_for_writing(reopen_flags as i32); if readonly { anyhow::ensure!( !writable_handle, @@ -610,10 +613,6 @@ pub(crate) fn reopen_flags(saved: u32) -> anyhow::Result { "saved handle has unsupported open flags {:#x}", saved ); - anyhow::ensure!( - saved & lx::O_ACCESS_MASK as u32 != lx::O_NOACCESS as u32, - "saved handle has invalid access mode" - ); Ok(saved & !(lx::O_CREAT as u32 | lx::O_EXCL as u32 | lx::O_TRUNC as u32)) } From c7f6a04fd7515441959b9b7a303bafd407179e85 Mon Sep 17 00:00:00 2001 From: Pedro Henrique Penna Date: Wed, 25 Nov 2026 08:22:46 -0800 Subject: [PATCH 3/6] lxutil: reject xattr names longer than an NTFS EA name allows On Windows, lxutil stores a Linux xattr as an NTFS extended attribute named `LX.` and the xattr's name. FILE_GET_EA_INFORMATION and FILE_FULL_EA_INFORMATION give that EA name's length in one byte, but lxutil's limit on xattr names, LX_UTIL_XATTR_NAME_MAX, was u16::MAX - 3 bytes, and lxutil wrote the length with `as u8`, which kept only its low 8 bits (microsoft/nvx#2137). A FUSE_GETXATTR of a 262-byte name that starts with `user.a`, which a guest can send by building the request itself, thus queried the 9-byte EA name `LX.user.a`, 265 bytes modulo 256, and returned the value of the `user.a` attribute. Names of 252 to 261 bytes failed with EINVAL or ENODATA, depending on the operation and the length, rather than with ERANGE, and XATTR_CREATE of the 262-byte name failed with EEXIST. NTFS accepts EA names of at most 254 bytes, so lxutil can store xattr names of at most 251 bytes. LX_UTIL_XATTR_NAME_MAX is now that length. set_name, like get and set, accepts a name of exactly that length rather than rejecting it with `>=`, and returns the EA name's length as the u8 that the headers hold. get, set, and remove thus fail every longer name with ERANGE before it reaches NTFS, as Linux fails names longer than its 255 bytes. The documentation of LxVolume's xattr methods now gives the limit. xattr_name_length sets `user.a`; sets, reads, and removes an attribute whose name has the longest length that the platform allows, 251 bytes on Windows and 255 on Linux; expects every longer name, up to 262 bytes, to fail with ERANGE in get, get of the size, set with no flag, with XATTR_CREATE, and with XATTR_REPLACE, and remove; and expects `user.a` to keep its value. At feature/microvm/dev 1633b3797, it fails on Windows 11 Enterprise (build 26300, NTFS) at the first longer name, whose get failed with EINVAL. A one-off test there, not committed, showed the rest: every operation on a 252- or 253-byte name failed with EINVAL; on 254- to 261-byte names, get, XATTR_REPLACE, and remove failed with ENODATA, and set and XATTR_CREATE with EINVAL; and the 262-byte name read `secret`, the value of `user.a`, failed XATTR_CREATE with EEXIST, and failed set, XATTR_REPLACE, and remove with EINVAL. With the fix, the lxutil tests pass on Windows 11 and on Azure Linux 3 (kernel 6.18, ext4). Linux builds do not compile xattr.rs, so the fix leaves Linux's behavior as it was. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- vm/devices/support/fs/lxutil/src/lib.rs | 117 +++++++++++++++--- .../support/fs/lxutil/src/windows/xattr.rs | 31 +++-- 2 files changed, 119 insertions(+), 29 deletions(-) diff --git a/vm/devices/support/fs/lxutil/src/lib.rs b/vm/devices/support/fs/lxutil/src/lib.rs index 835e8356f84..ed0d464abb9 100644 --- a/vm/devices/support/fs/lxutil/src/lib.rs +++ b/vm/devices/support/fs/lxutil/src/lib.rs @@ -500,10 +500,10 @@ impl LxVolume { /// Extended attribute names are not case sensitive. They are stored as upper case in NTFS but /// `list_xattr` will report them as lower case for greater compatibility with Linux. /// - /// Extended attribute names are prefixed with "LX.", and have a slightly shorter maximum length - /// limit than Linux. Attribute values are prefixed with a 4-byte header to allow for "empty" - /// values, which NTFS does not normally allow. `get_xattr` and `list_xattr` will strip these - /// prefixes. + /// Extended attribute names are prefixed with "LX.", so they can be at most 251 bytes long + /// rather than 255 as on Linux; longer names fail with `ERANGE`. Attribute values are prefixed + /// with a 4-byte header to allow for "empty" values, which NTFS does not normally allow. + /// `get_xattr` and `list_xattr` will strip these prefixes. /// /// Security for accessing the various attribute namespaces is not enforced. /// @@ -531,10 +531,10 @@ impl LxVolume { /// Extended attribute names are not case sensitive. They are stored as upper case in NTFS but /// `list_xattr` will report them as lower case for greater compatibility with Linux. /// - /// Extended attribute names are prefixed with "LX.", and have a slightly shorter maximum length - /// limit than Linux. Attribute values are prefixed with a 4-byte header to allow for "empty" - /// values, which NTFS does not normally allow. `get_xattr` and `list_xattr` will strip these - /// prefixes. + /// Extended attribute names are prefixed with "LX.", so they can be at most 251 bytes long + /// rather than 255 as on Linux; longer names fail with `ERANGE`. Attribute values are prefixed + /// with a 4-byte header to allow for "empty" values, which NTFS does not normally allow. + /// `get_xattr` and `list_xattr` will strip these prefixes. /// /// Security for accessing the various attribute namespaces is not enforced. pub fn get_xattr( @@ -557,10 +557,10 @@ impl LxVolume { /// Extended attribute names are not case sensitive. They are stored as upper case in NTFS but /// `list_xattr` will report them as lower case for greater compatibility with Linux. /// - /// Extended attribute names are prefixed with "LX.", and have a slightly shorter maximum length - /// limit than Linux. Attribute values are prefixed with a 4-byte header to allow for "empty" - /// values, which NTFS does not normally allow. `get_xattr` and `list_xattr` will strip these - /// prefixes. + /// Extended attribute names are prefixed with "LX.", so they can be at most 251 bytes long + /// rather than 255 as on Linux; longer names fail with `ERANGE`. Attribute values are prefixed + /// with a 4-byte header to allow for "empty" values, which NTFS does not normally allow. + /// `get_xattr` and `list_xattr` will strip these prefixes. /// /// Security for accessing the various attribute namespaces is not enforced. pub fn list_xattr(&self, path: impl AsRef, list: Option<&mut [u8]>) -> lx::Result { @@ -574,10 +574,10 @@ impl LxVolume { /// Extended attribute names are not case sensitive. They are stored as upper case in NTFS but /// `list_xattr` will report them as lower case for greater compatibility with Linux. /// - /// Extended attribute names are prefixed with "LX.", and have a slightly shorter maximum length - /// limit than Linux. Attribute values are prefixed with a 4-byte header to allow for "empty" - /// values, which NTFS does not normally allow. `get_xattr` and `list_xattr` will strip these - /// prefixes. + /// Extended attribute names are prefixed with "LX.", so they can be at most 251 bytes long + /// rather than 255 as on Linux; longer names fail with `ERANGE`. Attribute values are prefixed + /// with a 4-byte header to allow for "empty" values, which NTFS does not normally allow. + /// `get_xattr` and `list_xattr` will strip these prefixes. /// /// Security for accessing the various attribute namespaces is not enforced. pub fn remove_xattr( @@ -2550,6 +2550,91 @@ mod tests { assert_eq!(&buffer[..3], b"baz"); } + #[test] + fn xattr_name_length() { + // Linux allows names of up to 255 bytes. On Windows, an attribute is an NTFS extended + // attribute named "LX." and the attribute's name, and NTFS allows EA names of up to 254 + // bytes. + const NAME_MAX: usize = if cfg!(windows) { 251 } else { 255 }; + + fn name(len: usize) -> Vec { + let mut name = b"user.a".to_vec(); + name.resize(len, b'x'); + name + } + + let env = TestEnv::new(); + env.create_file("testfile", "test"); + env.volume + .set_xattr("testfile", "user.a", b"secret", 0) + .unwrap(); + + // An attribute with the longest name can be set, read, and removed. + let longest = name(NAME_MAX); + let longest = lx::LxStr::from_bytes(&longest); + env.volume + .set_xattr("testfile", longest, b"long", 0) + .unwrap(); + + let mut value = [0u8; 16]; + let size = env + .volume + .get_xattr("testfile", longest, Some(&mut value)) + .unwrap(); + + assert_eq!(&value[..size], b"long"); + env.volume.remove_xattr("testfile", longest).unwrap(); + let err = env.volume.get_xattr("testfile", longest, None).unwrap_err(); + + assert_eq!(err.value(), lx::ENODATA); + + // A longer name fails with ERANGE, rather than reaching an attribute whose name it starts + // with. + for len in NAME_MAX + 1..=262 { + let long = name(len); + let long = lx::LxStr::from_bytes(&long); + let results = [ + ( + "get", + env.volume + .get_xattr("testfile", long, Some(&mut value)) + .map(drop), + ), + ( + "get size", + env.volume.get_xattr("testfile", long, None).map(drop), + ), + ("set", env.volume.set_xattr("testfile", long, b"long", 0)), + ( + "create", + env.volume + .set_xattr("testfile", long, b"long", lx::XATTR_CREATE), + ), + ( + "replace", + env.volume + .set_xattr("testfile", long, b"long", lx::XATTR_REPLACE), + ), + ("remove", env.volume.remove_xattr("testfile", long)), + ]; + + for (operation, result) in results { + assert_eq!( + result.map_err(|err| err.value()), + Err(lx::ERANGE), + "{operation} of a {len}-byte name" + ); + } + } + + let size = env + .volume + .get_xattr("testfile", "user.a", Some(&mut value)) + .unwrap(); + + assert_eq!(&value[..size], b"secret"); + } + // This test is disabled in CI on Windows only, because it requires NTFS support for setting // the case sensitive directory attribute, which is only enabled if the WSL optional component // is installed. diff --git a/vm/devices/support/fs/lxutil/src/windows/xattr.rs b/vm/devices/support/fs/lxutil/src/windows/xattr.rs index 18cf8bb1e88..817feef615f 100644 --- a/vm/devices/support/fs/lxutil/src/windows/xattr.rs +++ b/vm/devices/support/fs/lxutil/src/windows/xattr.rs @@ -15,7 +15,11 @@ const LX_UTIL_CASE_SENSITIVE: &str = "system.wsl_case_sensitive"; const LX_UTIL_XATTR_NAME_PREFIX: &str = "LX."; const LX_UTIL_XATTR_NAME_PREFIX_LENGTH: usize = LX_UTIL_XATTR_NAME_PREFIX.len(); -const LX_UTIL_XATTR_NAME_MAX: usize = u16::MAX as usize - LX_UTIL_XATTR_NAME_PREFIX_LENGTH; + +/// The longest EA name, prefix included, that NTFS accepts. `EaNameLength` is one byte, and NTFS +/// rejects a name of 255 bytes. +const LX_UTILP_EA_NAME_MAX: usize = 254; +const LX_UTIL_XATTR_NAME_MAX: usize = LX_UTILP_EA_NAME_MAX - LX_UTIL_XATTR_NAME_PREFIX_LENGTH; const LX_UTILP_XATTR_QUERY_RESTART_SCAN: i32 = 0x1; const LX_UTILP_XATTR_QUERY_RETURN_SINGLE_ENTRY: i32 = 0x2; @@ -114,26 +118,27 @@ pub fn get_system(handle: &OwnedHandle, name: &str, value: Option<&mut [u8]>) -> Ok(1) } -/// Copy the Linux EA attribute prefix and the specified name into the start of the provided buffer. -fn set_name(name: &str, buffer: &mut [u8]) -> lx::Result { +/// Copy the Linux EA attribute prefix and the specified name into the start of the provided buffer, +/// and return the length of the resulting EA name. +fn set_name(name: &str, buffer: &mut [u8]) -> lx::Result { let name_bytes = name.as_bytes(); - if name_bytes.len() >= LX_UTIL_XATTR_NAME_MAX { + if name_bytes.len() > LX_UTIL_XATTR_NAME_MAX { return Err(lx::Error::ERANGE); } - let total_required = LX_UTIL_XATTR_NAME_PREFIX_LENGTH + name_bytes.len() + 1; + let ea_name_len = LX_UTIL_XATTR_NAME_PREFIX_LENGTH + name_bytes.len(); + let total_required = ea_name_len + 1; if buffer.len() < total_required { return Err(lx::Error::ERANGE); } buffer[..LX_UTIL_XATTR_NAME_PREFIX_LENGTH] .copy_from_slice(LX_UTIL_XATTR_NAME_PREFIX.as_bytes()); - buffer[LX_UTIL_XATTR_NAME_PREFIX_LENGTH..LX_UTIL_XATTR_NAME_PREFIX_LENGTH + name_bytes.len()] - .copy_from_slice(name_bytes); - buffer[LX_UTIL_XATTR_NAME_PREFIX_LENGTH + name_bytes.len()] = 0; + buffer[LX_UTIL_XATTR_NAME_PREFIX_LENGTH..ea_name_len].copy_from_slice(name_bytes); + buffer[ea_name_len] = 0; - Ok(LX_UTIL_XATTR_NAME_PREFIX_LENGTH + name_bytes.len()) + ea_name_len.try_into().map_err(|_| lx::Error::ERANGE) } /// Queries an EA on a file. @@ -167,7 +172,7 @@ fn query_ea( let header = FileGetEaInformation { next_entry_offset: Unalign::new(0), - ea_name_length: name_len as u8, + ea_name_length: name_len, }; buffer[..size_of::()].copy_from_slice(header.as_bytes()); Some(buffer) @@ -354,13 +359,13 @@ pub fn set(handle: &OwnedHandle, name: &str, value: &[u8], flags: i32) -> lx::Re let ea_info = FileFullEaInformation { next_entry_offset: Unalign::new(0), flags: 0, - ea_name_length: name_len as u8, + ea_name_length: name_len, ea_value_length: Unalign::new(value_size as u16), }; buffer[..size_of::()].copy_from_slice(ea_info.as_bytes()); // Set the EA value header. - let ea_value_start = size_of::() + name_len + 1; + let ea_value_start = size_of::() + usize::from(name_len) + 1; buffer[ea_value_start..ea_value_start + 4] .copy_from_slice(&LX_UTILP_EA_VALUE_HEADER.to_le_bytes()); @@ -492,7 +497,7 @@ pub fn remove(handle: &OwnedHandle, name: &str) -> lx::Result<()> { let ea_info = FileFullEaInformation { next_entry_offset: Unalign::new(0), flags: 0, - ea_name_length: name_len as u8, + ea_name_length: name_len, ea_value_length: Unalign::new(0), // Zero length to remove the attribute }; buf[..size_of::()].copy_from_slice(ea_info.as_bytes()); From e61fa53264090bd63f3cc2baeb80145c63488819 Mon Sep 17 00:00:00 2001 From: Pedro Henrique Penna Date: Wed, 25 Nov 2026 08:23:11 -0800 Subject: [PATCH 4/6] lxutil: fail an empty symlink target with ENOENT on Windows On Windows, LxVolume::symlink and symlink_stat accepted an empty target (microsoft/nvx#2126), which Linux's symlink(2) fails with ENOENT. On a volume that does not confine paths, the empty target names the link's own directory, so symlink_helper chose an NT directory link and called create_nt_link_reparse_buffer. That sized its buffer as the REPARSE_DATA_BUFFER up to the PathBuffer of its symbolic link part, 20 bytes, plus the target twice, but wrote the whole 24-byte struct at its start: with an empty target, 4 bytes past the end of the heap allocation. Where the process may not create NT links, setting that reparse point then failed, and the volume fell back to a WSL-style link to the empty target, as a volume that confines paths makes directly. A virtio-fs guest could thus overflow the host's heap and get a symbolic link to nothing on a direct share, and a virtio-9p guest the same, since both devices pass the guest's target to the volume unchanged. A microVM share already refused an empty target itself. symlink_helper now fails an empty target with ENOENT before it checks the link's path or creates anything, as symlink(2) does, and create_nt_link_reparse_buffer, whose write of the struct relies on a target that is not empty, refuses an empty one with ENOENT too, so that the write stays within the buffer whatever its caller passes. symlink_rejects_an_empty_target checks that symlink and symlink_stat fail with ENOENT and leave no link, with and without confine_paths; nt_link_reparse_buffer_refuses_an_empty_target checks the guard of create_nt_link_reparse_buffer; and virtiofs's direct_symlink_rejects_an_empty_target checks that a guest SYMLINK with an empty target on a direct share fails with ENOENT and leaves no link on the host. At feature/microvm/dev 1633b3797, on Windows 11 (NTFS, a process that may not create NT links), all three fail: the first and the last create a symbolic link to the empty target, and the second gets a 20-byte buffer. An AddressSanitizer build of the first, with windows_hook_rtl_allocators, reports a heap-buffer-overflow there: a 24-byte write 0 bytes after a 20-byte region, in create_nt_link_reparse_buffer. With the fix, the three pass, and so do lxutil's other tests, also under AddressSanitizer. On Linux, whose kernel refuses an empty target, and where none of the changed code builds, the first and the last pass with and without the fix. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- vm/devices/support/fs/lxutil/src/lib.rs | 33 +++++++++++++++++++ .../support/fs/lxutil/src/windows/mod.rs | 19 +++++++++++ .../support/fs/lxutil/src/windows/util.rs | 9 ++++- vm/devices/virtio/virtiofs/src/lib.rs | 17 ++++++++++ 4 files changed, 77 insertions(+), 1 deletion(-) diff --git a/vm/devices/support/fs/lxutil/src/lib.rs b/vm/devices/support/fs/lxutil/src/lib.rs index ed0d464abb9..23fd1e14bc3 100644 --- a/vm/devices/support/fs/lxutil/src/lib.rs +++ b/vm/devices/support/fs/lxutil/src/lib.rs @@ -1835,6 +1835,39 @@ mod tests { ); } + /// Like Linux's `symlink(2)`, creating a symbolic link to an empty target + /// fails with `ENOENT` and creates nothing. On Windows, the empty target, + /// which names the link's own directory, would otherwise get an NT link + /// from a volume that does not confine paths, and a WSL-style link from + /// one that does. + #[test] + fn symlink_rejects_an_empty_target() { + for confine_paths in [false, true] { + let env = TestEnv::with_options(LxVolumeOptions::new().confine_paths(confine_paths)); + env.create_file("testdir/testfile", "test"); + let link = Path::from_lx("testdir/link").unwrap(); + assert_eq!( + env.volume + .symlink(&link, "", LxCreateOptions::new(0, 0, 0)) + .unwrap_err(), + lx::Error::ENOENT, + "confine_paths={confine_paths}" + ); + assert_eq!( + env.volume + .symlink_stat(&link, "", LxCreateOptions::new(0, 0, 0)) + .unwrap_err(), + lx::Error::ENOENT, + "confine_paths={confine_paths}" + ); + assert_eq!( + env.volume.lstat(&link).unwrap_err(), + lx::Error::ENOENT, + "confine_paths={confine_paths}" + ); + } + } + #[test] fn symlink_ancestors_are_not_walked() { fn expect_traversal_error(result: lx::Result) { diff --git a/vm/devices/support/fs/lxutil/src/windows/mod.rs b/vm/devices/support/fs/lxutil/src/windows/mod.rs index 1e2bd19ed4d..6ded3682a73 100644 --- a/vm/devices/support/fs/lxutil/src/windows/mod.rs +++ b/vm/devices/support/fs/lxutil/src/windows/mod.rs @@ -848,6 +848,13 @@ impl LxVolume { mut options: super::LxCreateOptions, ) -> lx::Result { assert!(path.is_relative() && !path.as_os_str().is_empty()); + + // Linux has no symbolic link with an empty target: symlink(2) fails one with ENOENT, + // before it looks at the link's path, so do the same before creating anything. + if target.is_empty() { + return Err(lx::Error::ENOENT); + } + self.check_sandbox_enforcement(path)?; // Handle filesystems that do not support reparse points. @@ -2026,6 +2033,18 @@ mod tests { assert_eq!(volume.read_link(path).unwrap(), target); } + /// An NT link's reparse buffer starts with a whole `REPARSE_DATA_BUFFER`, + /// which extends past the start of the link's names, so the buffer of an + /// empty target could not hold it, and is refused with `ENOENT`, as Linux + /// refuses the target. + #[test] + fn nt_link_reparse_buffer_refuses_an_empty_target() { + assert_eq!( + util::create_nt_link_reparse_buffer(ffi::OsStr::new(""), 0).unwrap_err(), + lx::Error::ENOENT + ); + } + #[test] fn no_follow_stat_fallbacks() { for (query_by_name, stat_info) in [(true, true), (false, true), (false, false)] { diff --git a/vm/devices/support/fs/lxutil/src/windows/util.rs b/vm/devices/support/fs/lxutil/src/windows/util.rs index a49c6b073a8..f3959f95ebb 100644 --- a/vm/devices/support/fs/lxutil/src/windows/util.rs +++ b/vm/devices/support/fs/lxutil/src/windows/util.rs @@ -604,6 +604,12 @@ pub fn file_info_to_stat( // Create the reparse buffer for an NT symlink. pub fn create_nt_link_reparse_buffer(target: &ffi::OsStr, flags: u32) -> lx::Result> { + // The whole REPARSE_DATA_BUFFER written below extends past the start of the names, so the + // buffer can hold it only if the target is not empty. Linux fails an empty target with ENOENT. + if target.is_empty() { + return Err(lx::Error::ENOENT); + } + let mut link_target: windows::UnicodeString = target.try_into().map_err(|_| lx::Error::EINVAL)?; @@ -619,7 +625,8 @@ pub fn create_nt_link_reparse_buffer(target: &ffi::OsStr, flags: u32) -> lx::Res let mut reparse = vec![0; local_size]; - // SAFETY: The buffer is large enough to hold the reparse data. + // SAFETY: The buffer is large enough to hold the reparse data, since the + // target is not empty: its two copies reach past the end of the struct. // This is necessary because unfortunately the Windows types don't // implement the necessary traits to use zerocopy. unsafe { diff --git a/vm/devices/virtio/virtiofs/src/lib.rs b/vm/devices/virtio/virtiofs/src/lib.rs index 1262b720128..463f7b83d34 100644 --- a/vm/devices/virtio/virtiofs/src/lib.rs +++ b/vm/devices/virtio/virtiofs/src/lib.rs @@ -2158,6 +2158,23 @@ mod tests { assert!(fs.get_inode(FUSE_ROOT_ID).is_ok()); } + /// A guest SYMLINK with an empty target fails with `ENOENT`, as Linux's + /// `symlink(2)` does, and creates nothing on the host. A microVM share + /// refuses it before it reaches the host (see `symlink_tests`); a direct + /// share leaves it to the host volume. + #[test] + fn direct_symlink_rejects_an_empty_target() { + let root = tempfile::tempdir().unwrap(); + let fs = VirtioFs::new(root.path(), None).unwrap(); + + assert_eq!( + fs.symlink(&request(FUSE_ROOT_ID), "link".as_ref(), "".as_ref()) + .unwrap_err(), + lx::Error::ENOENT + ); + assert!(std::fs::symlink_metadata(root.path().join("link")).is_err()); + } + /// Returns a direct file system of `root`, or a writable microVM one if /// `microvm`, whose root holds the regular file `file`, which the guest /// has looked up once, with the file's node ID. From 5af753b17035f548039cab531027a3cc635ac4fa Mon Sep 17 00:00:00 2001 From: Pedro Henrique Penna Date: Wed, 25 Nov 2026 08:26:42 -0800 Subject: [PATCH 5/6] virtiofs: reopen a microVM handle with O_DIRECT on restore A microVM guest that holds a file on a virtio-fs share open with O_DIRECT could save the VM's state, but not restore it: restore_microvm_state refused the saved handle with "saved handle has unsupported open flags 0x4002" for O_RDWR | O_DIRECT, and with 0x4041 for a file that FUSE_CREATE created with O_WRONLY | O_DIRECT (microsoft/nvx#2128). The Linux FUSE client passes the open's O_DIRECT in the flags of both requests. FUSE_OPEN and FUSE_CREATE accept O_DIRECT, keep it in the flags that the handle records, which the save stores, and pass it to the host open: Linux opens the host file with it, and Windows ignores it. reopen_flags, which validates a saved handle's flags before a restore and gives those with which the restore reopens it, refused any flag outside its list, which lacked O_DIRECT. It now keeps O_DIRECT, so that a restore reopens the handle as the guest opened it, and the handle keeps the host's O_DIRECT semantics: on a Linux filesystem that enforces O_DIRECT's alignment, such as ext4, the restored handle performs block-aligned I/O and refuses unaligned I/O with EINVAL, as the saved one did, where a handle reopened without O_DIRECT would have accepted both. handles_opened_with_o_direct_restore_with_it first checks that reopen_flags keeps O_DIRECT and the access of the flags that FUSE_OPEN and FUSE_CREATE record, and drops O_CREAT. It then opens a file with FUSE_OPEN and O_RDWR | O_DIRECT, creates one with FUSE_CREATE and O_WRONLY | O_CREAT | O_DIRECT, saves the state, restores it into a new attachment, and expects each handle to be reopened with O_DIRECT and its access. Linux lets a filesystem refuse O_DIRECT, as tmpfs did before Linux 6.6, so on Linux the test skips that round trip when the host refuses an open of the file with O_DIRECT that it tries outside the server; on Windows, which ignores O_DIRECT, it always runs it. At feature/microvm/dev 1633b3797, the test fails at its first check, since reopen_flags refuses 0x4002, and without that check, its round trip fails at the restore, with 0x4002 on Windows 11 Enterprise (NTFS) and 0x4041 on Azure Linux 3 (kernel 6.18, x86_64, ext4), whichever handle the restore checks first. With the fix, it passes on both without skipping, as do the other tests of the virtiofs package. On the Linux host's ext4, a one-off test, not committed, read and wrote 4 KiB at offset 0 and 512 bytes at offset 512 through the O_DIRECT handle and failed reads and writes of 100 bytes at offsets 0 and 1 with EINVAL; after the restore, the handle still read 4 KiB at offset 0 and failed a read of 100 bytes at offset 1 with EINVAL. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../virtio/virtiofs/src/microvm/fs_tests.rs | 84 +++++++++++++++++++ .../virtiofs/src/microvm/policy_tests.rs | 2 +- .../virtio/virtiofs/src/microvm/state.rs | 1 + 3 files changed, 86 insertions(+), 1 deletion(-) diff --git a/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs b/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs index 0c992679e47..23fd46919e8 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs @@ -4,6 +4,7 @@ //! Tests for microVM filesystem persistence and limits. use super::policy_tests::create; +use super::policy_tests::create_with_flags; use super::policy_tests::error; use super::policy_tests::lookup; use super::policy_tests::mkdir; @@ -1163,6 +1164,89 @@ fn saved_negotiation_must_match_the_exact_microvm_policy() { assert!(validate_microvm_state(&state, &profile).is_err()); } +/// The guest's FUSE client passes `O_DIRECT` in the flags of `FUSE_OPEN` and +/// `FUSE_CREATE`, which the server accepts, keeps in the handle's open flags, +/// and passes to the host open. A restore reopens such a handle with +/// `O_DIRECT` and the access that the guest opened it with, rather than refuse +/// the saved state. +#[test] +fn handles_opened_with_o_direct_restore_with_it() { + // The flags that FUSE_OPEN and FUSE_CREATE record for the handles below, + // and those with which a restore reopens them, whatever the host + // filesystem. + for (saved, reopened) in [ + (lx::O_RDWR | lx::O_DIRECT, lx::O_RDWR | lx::O_DIRECT), + ( + lx::O_WRONLY | lx::O_CREAT | lx::O_DIRECT, + lx::O_WRONLY | lx::O_DIRECT, + ), + ] { + assert_eq!( + reopen_flags(saved as u32).unwrap(), + reopened as u32, + "{saved:#x}" + ); + } + + let temporary_directory = tempdir().unwrap(); + let root_path = temporary_directory.path(); + std::fs::write(root_path.join("opened"), b"data").unwrap(); + // Linux lets a filesystem refuse O_DIRECT, as tmpfs did before Linux 6.6. + #[cfg(target_os = "linux")] + { + use std::os::unix::fs::OpenOptionsExt; + + let probe = std::fs::OpenOptions::new() + .read(true) + .custom_flags(lx::O_DIRECT) + .open(root_path.join("opened")); + match probe { + Err(error) if error.kind() == std::io::ErrorKind::InvalidInput => { + eprintln!("skipping: the host filesystem refuses O_DIRECT: {error}"); + return; + } + probe => drop(probe.unwrap()), + } + } + let profile = MicroVmVirtioFsProfile::from_attachment( + MICROVM_ATTACHMENT_ID.to_owned(), + microvm_root_identity(root_path).unwrap(), + false, + Vec::new(), + ) + .unwrap(); + let source = VirtioFs::new_microvm(root_path, profile.clone()).unwrap(); + let opened = lookup(&source, "opened").unwrap(); + let opened_fh = open(&source, opened, lx::O_RDWR | lx::O_DIRECT).unwrap(); + let (created, created_fh) = create_with_flags( + &source, + FUSE_ROOT_ID, + "created", + lx::O_WRONLY | lx::O_CREAT | lx::O_DIRECT, + ) + .unwrap(); + let state = source + .save_microvm_state(&profile, SessionState::default()) + .unwrap(); + + let destination = VirtioFs::new_microvm(root_path, profile.clone()).unwrap(); + let session = Session::new(destination.clone()); + destination + .restore_microvm_state(&profile, state, &session) + .unwrap(); + for (node_id, fh, access) in [ + (opened, opened_fh, lx::O_RDWR), + (created, created_fh, lx::O_WRONLY), + ] { + let file = destination.get_file(node_id, fh).unwrap(); + assert_eq!( + file.open_flags(), + (access | lx::O_DIRECT) as u32, + "node {node_id}" + ); + } +} + #[test] fn reopen_flags_preserve_safe_status_bits_and_reject_effects() { const O_NONBLOCK: u32 = 0x800; diff --git a/vm/devices/virtio/virtiofs/src/microvm/policy_tests.rs b/vm/devices/virtio/virtiofs/src/microvm/policy_tests.rs index b90ec29322e..209dbd9ebdf 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/policy_tests.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/policy_tests.rs @@ -102,7 +102,7 @@ pub(super) fn create(fs: &VirtioFs, parent: u64, file_name: &str) -> lx::Result< /// Creates and opens a file with the open flags `flags`, and returns its node /// ID and handle. -fn create_with_flags( +pub(super) fn create_with_flags( fs: &VirtioFs, parent: u64, file_name: &str, diff --git a/vm/devices/virtio/virtiofs/src/microvm/state.rs b/vm/devices/virtio/virtiofs/src/microvm/state.rs index 6d3b0c448fb..9c5cc01870d 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/state.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/state.rs @@ -599,6 +599,7 @@ pub(crate) fn reopen_flags(saved: u32) -> anyhow::Result { | lx::O_EXCL as u32 | lx::O_TRUNC as u32 | lx::O_APPEND as u32 + | lx::O_DIRECT as u32 | lx::O_DIRECTORY as u32 | lx::O_NOFOLLOW as u32 | lx::O_NOATIME as u32 From 9822f732ae72c1e0dce91590842c0c395624a745 Mon Sep 17 00:00:00 2001 From: Pedro Henrique Penna Date: Wed, 25 Nov 2026 08:29:48 -0800 Subject: [PATCH 6/6] lxutil: hard-link to one-character names on Windows On a Windows host, LxVolume::link and LxVolume::link_stat failed with EOVERFLOW, and created no link, when the new name was one UTF-16 unit long, such as `x`, although longer names worked (microsoft/nvx#2136). A guest's `ln file x` on a virtio-fs share of a Windows directory thus failed, and so would one on a Plan 9 share, which links through the same LxVolume::link. create_link passes NtSetInformationFile a FILE_LINK_INFORMATION built from a header that mirrors the structure up to FileName, 20 bytes with an alignment of 1, followed by the name. NtSetInformationFile refuses a buffer shorter than sizeof(FILE_LINK_INFORMATION), which counts the first FileName unit and the trailing padding, 24 bytes on 64-bit Windows, with STATUS_INFO_LENGTH_MISMATCH, which lxutil maps to EOVERFLOW. A name of one unit made a buffer of 22 bytes. rename does not fail this way: its header starts with the 4-byte union of FILE_RENAME_INFORMATION, so its buffer rounds up to 24 bytes. create_link now pads the name with NULs until the buffer is as long as the structure, as pal's hard_link_relative already sizes its own. FileNameLength still counts only the name, so the link gets exactly that name. link_to_a_one_character_name links a file to `a` through link and to `b` through link_stat, and expects both names to reach the file, with link counts of 2 and 3. Without the fix, its first link fails with EOVERFLOW on Windows 11 Enterprise (build 26300, NTFS); with it, the test passes there, as do the other tests of the lxutil and virtiofs packages. A one-off test, not committed, of the issue's reproduction, a FUSE_LINK through VirtioFs of a file to `xy` and then to `x`, with the standard and the microVM profile, got EOVERFLOW for `x`, and left no host file, at feature/microvm/dev 1633b3797, and a link count of 3 with the fix. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- vm/devices/support/fs/lxutil/src/lib.rs | 19 +++++++++++++++++++ .../support/fs/lxutil/src/windows/util.rs | 9 +++++++++ 2 files changed, 28 insertions(+) diff --git a/vm/devices/support/fs/lxutil/src/lib.rs b/vm/devices/support/fs/lxutil/src/lib.rs index 23fd1e14bc3..66387b2c345 100644 --- a/vm/devices/support/fs/lxutil/src/lib.rs +++ b/vm/devices/support/fs/lxutil/src/lib.rs @@ -2398,6 +2398,25 @@ mod tests { assert_eq!(stat2.link_count, 3); } + #[test] + fn link_to_a_one_character_name() { + let env = TestEnv::new(); + env.create_file("testfile", "test"); + let stat = env.volume.lstat("testfile").unwrap(); + + // On Windows, a name of one UTF-16 unit makes the shortest + // FILE_LINK_INFORMATION buffer. + env.volume.link("testfile", "a").unwrap(); + let stat2 = env.volume.lstat("a").unwrap(); + assert_eq!(stat2.inode_nr, stat.inode_nr); + assert_eq!(stat2.link_count, 2); + + let stat2 = env.volume.link_stat("testfile", "b").unwrap(); + assert_eq!(stat2.inode_nr, stat.inode_nr); + assert_eq!(stat2.link_count, 3); + assert_eq!(fs::read(env.root_dir.path().join("b")).unwrap(), b"test"); + } + #[test] fn stat_fs() { let env = TestEnv::new(); diff --git a/vm/devices/support/fs/lxutil/src/windows/util.rs b/vm/devices/support/fs/lxutil/src/windows/util.rs index f3959f95ebb..c15755f1a69 100644 --- a/vm/devices/support/fs/lxutil/src/windows/util.rs +++ b/vm/devices/support/fs/lxutil/src/windows/util.rs @@ -1202,6 +1202,15 @@ pub fn create_link( HeaderVec::::with_capacity(link, new_path.len()); buffer.extend_tail_from_slice(new_path.as_slice()); + // NtSetInformationFile fails with STATUS_INFO_LENGTH_MISMATCH for a buffer + // shorter than the whole FILE_LINK_INFORMATION, whose size counts the first + // FileName unit and the trailing padding (24 bytes on 64-bit Windows), while + // the header above stops at FileName. Pad a name of one UTF-16 unit with a + // NUL that FileNameLength leaves out. + while buffer.total_byte_len() < size_of::() { + buffer.push_tail(0); + } + set_information_file(handle, &buffer)?; Ok(())