From 3cf58a5234ed824435825c9f87187f5129219724 Mon Sep 17 00:00:00 2001 From: Pedro Henrique Penna Date: Fri, 6 Nov 2026 21:26:57 -0800 Subject: [PATCH] microVM: publish the outcome report below long Windows paths On Windows, a microVM whose --microvm-report path exceeded MAX_PATH ran to its end but failed to publish its outcome report: "failed to publish the microVM report: The system cannot find the path specified. (os error 3)". tempfile's persist_noclobber marks and renames the staging file with SetFileAttributesW and MoveFileExW on the paths as given, and without the extended-length \\?\ prefix those refuse a path of 260 or more UTF-16 code units. NVX keeps the report in the sandbox's store, so a long state root, such as one below a long TEMP (microsoft/nvx#1253), lost the report of every VM, and a template capture its generation. On Windows, publish the report through the extended-length form of its path: the staging file is created in that form of the parent, and tempfile passes both paths to Win32 as they are. pal::windows::fs gains extended_length_path, which resolves a path as Win32 does and adds the prefix from 248 code units on, keeping shorter, verbatim, device, NT, and empty paths as they are. That is the encoding with which the secure file and directory creation of microsoft/openvmm#4916 take long paths, and secure_create_path now takes it from there. Paths below the limits keep their form, so other reports are published as before. Tests: a report below a parent of 300 or more UTF-16 code units is published, a second report does not replace it, and neither leaves a staging file; without the change, the first publication fails with os error 3. extended_length_path prefixes resolved disk and UNC paths from 248 code units and keeps verbatim, NT, device, and empty paths, as the existing tests of secure_create_path check of its encoding. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- openvmm/openvmm_entry/src/microvm/report.rs | 34 +++++++++- support/pal/src/windows/fs.rs | 75 +++++++++++++++++++++ support/pal/src/windows/security.rs | 47 +++---------- 3 files changed, 115 insertions(+), 41 deletions(-) diff --git a/openvmm/openvmm_entry/src/microvm/report.rs b/openvmm/openvmm_entry/src/microvm/report.rs index 83ca586b647..847fbbb663e 100644 --- a/openvmm/openvmm_entry/src/microvm/report.rs +++ b/openvmm/openvmm_entry/src/microvm/report.rs @@ -217,7 +217,14 @@ impl MicrovmReportPlan { && teardown.auxiliary_workers_stopped, }, }; - let parent = self.path.parent().unwrap_or(Path::new(".")); + // `tempfile` publishes the report with Win32 functions that take a path + // beyond the legacy MAX_PATH limits only in its extended-length form. + #[cfg(windows)] + let path = pal::windows::fs::extended_length_path(&self.path) + .context("failed to resolve the microVM report path")?; + #[cfg(not(windows))] + let path = self.path; + let parent = path.parent().unwrap_or(Path::new(".")); let mut temporary = tempfile::NamedTempFile::new_in(parent) .context("failed to create the microVM report staging file")?; serde_json::to_writer_pretty(temporary.as_file_mut(), &report) @@ -231,7 +238,7 @@ impl MicrovmReportPlan { .sync_all() .context("failed to flush the microVM report")?; temporary - .persist_noclobber(&self.path) + .persist_noclobber(&path) .map_err(|error| error.error) .context("failed to publish the microVM report")?; Ok(()) @@ -426,4 +433,27 @@ mod tests { let error = validate_destination(&path).unwrap_err(); assert!(error.to_string().contains("destination already exists")); } + + #[cfg(windows)] + #[test] + fn reports_are_published_below_long_paths() { + use std::os::windows::ffi::OsStrExt; + + // The report's path exceeds the legacy MAX_PATH limits of the Win32 + // functions with which `tempfile` publishes it. + let directory = tempfile::tempdir().unwrap(); + let mut parent = directory.path().to_path_buf(); + while parent.as_os_str().encode_wide().count() < 300 { + parent.push("long-report-parent-component"); + } + fs_err::create_dir_all(&parent).unwrap(); + let path = parent.join("outcome.json"); + test_plan(path.clone()).write(&Ok(0)).unwrap(); + assert_eq!(read_report(&path)["outcome"]["category"], "success"); + + // A second report replaces nothing, and neither leaves a staging file. + test_plan(path.clone()).write(&Ok(1)).unwrap_err(); + assert_eq!(read_report(&path)["outcome"]["category"], "success"); + assert_eq!(fs_err::read_dir(&parent).unwrap().count(), 1); + } } diff --git a/support/pal/src/windows/fs.rs b/support/pal/src/windows/fs.rs index 6ed3d32cfc1..85f4f805ac0 100644 --- a/support/pal/src/windows/fs.rs +++ b/support/pal/src/windows/fs.rs @@ -6,12 +6,18 @@ pub mod sparse; use super::chk_status; use super::dos_to_nt_path; +use std::ffi::OsString; use std::ffi::c_void; use std::fs; use std::io; use std::mem::zeroed; +use std::os::windows::ffi::OsStrExt; +use std::os::windows::ffi::OsStringExt; use std::os::windows::io::AsRawHandle; +use std::path::Component; use std::path::Path; +use std::path::PathBuf; +use std::path::Prefix; use std::ptr::null_mut; use widestring::U16CString; use windows_sys::Wdk::Foundation::OBJECT_ATTRIBUTES; @@ -96,13 +102,82 @@ pub fn is_unix_socket(path: &Path) -> io::Result { && data.dwReserved0 == IO_REPARSE_TAG_AF_UNIX) } +/// Returns `path` in a form that the Win32 file functions take whatever its +/// length. Without the extended-length `\\?\` prefix, `CreateDirectoryW` +/// refuses a path of 248 or more UTF-16 code units, and the other functions, +/// such as `CreateFileW` and `MoveFileExW`, one of 260 or more. +/// +/// The path is resolved, as Win32 resolves it, before the prefix is added, +/// since the file system takes an extended-length path as given, and a path +/// shorter than 248 code units keeps its resolved form. Win32 also takes an NT +/// path, `\??\...`, as given, and refuses an empty path itself, so both keep +/// their form, as do verbatim and device paths. +pub fn extended_length_path(path: &Path) -> io::Result { + let raw = path.as_os_str(); + if raw.is_empty() || raw.encode_wide().take(4).eq(r"\??\".encode_utf16()) { + return Ok(path.to_path_buf()); + } + let path = std::path::absolute(path)?; + if path.as_os_str().encode_wide().count() < 248 { + return Ok(path); + } + let (prefix, skip) = match path.components().next() { + Some(Component::Prefix(prefix)) => match prefix.kind() { + Prefix::Disk(_) => (r"\\?\", 0), + Prefix::UNC(..) => (r"\\?\UNC\", 2), + _ => ("", 0), + }, + _ => ("", 0), + }; + let extended = prefix + .encode_utf16() + .chain(path.as_os_str().encode_wide().skip(skip)) + .collect::>(); + Ok(OsString::from_wide(&extended).into()) +} + #[cfg(test)] mod tests { use super::*; + use test_with_tracing::test; #[test] fn test_query_stat_lx() { let result = query_stat_lx_by_name(r"C:\\".as_ref()).unwrap(); assert_ne!(0, result.FileId); } + + #[test] + fn extended_length_paths_prefix_resolved_long_paths() { + let extended = |path: &str| extended_length_path(Path::new(path)).unwrap(); + let name = |length| "a".repeat(length); + + // Disk and UNC paths take the prefix from 248 UTF-16 code units, once + // resolved. + let short = format!(r"C:\{}", name(244)); + let long = format!(r"C:\{}", name(245)); + assert_eq!(extended(&short), Path::new(&short)); + assert_eq!(extended(&long), Path::new(&format!(r"\\?\{long}"))); + let long = format!(r"\\server\share\{}", name(233)); + assert_eq!( + extended(&long), + Path::new(&format!(r"\\?\UNC\{}", &long[2..])) + ); + assert_eq!( + extended(&format!("C:/{}/./child/../leaf", name(300))), + Path::new(&format!(r"\\?\C:\{}\leaf", name(300))) + ); + let relative = std::env::current_dir().unwrap().join(name(300)); + assert_eq!(extended(&name(300)), extended(relative.to_str().unwrap())); + + // Verbatim, NT, device, and empty paths keep their form. + for path in [ + format!(r"\\?\C:\{}", name(300)), + format!(r"\??\C:\{}", name(300)), + format!(r"\\.\C:\{}", name(300)), + String::new(), + ] { + assert_eq!(extended(&path), Path::new(&path)); + } + } } diff --git a/support/pal/src/windows/security.rs b/support/pal/src/windows/security.rs index b2a1cfac825..ef4490755eb 100644 --- a/support/pal/src/windows/security.rs +++ b/support/pal/src/windows/security.rs @@ -11,9 +11,7 @@ use std::io::ErrorKind; use std::marker::PhantomData; use std::ops::Deref; use std::os::windows::prelude::*; -use std::path::Component; use std::path::Path; -use std::path::Prefix; use std::ptr::NonNull; use std::ptr::null_mut; use std::str::FromStr; @@ -391,44 +389,13 @@ where } } -/// Encodes `path` for the Win32 creation functions. Without the extended-length -/// `\\?\` prefix, `CreateDirectoryW` refuses a path of 248 or more UTF-16 code -/// units and `CreateFileW` one of 260 or more. -/// -/// The path is resolved, as Win32 resolves it, before the prefix is added, -/// since the file system takes an extended-length path as given. Win32 also -/// takes an NT path, `\??\...`, as given, and refuses an empty path itself, so -/// both keep their form. +/// Encodes `path` for the Win32 creation functions, in the form that +/// [`extended_length_path`](super::fs::extended_length_path) returns, which +/// they take whatever its length. fn secure_create_path(path: &Path) -> std::io::Result { - fn encode(path: &Path) -> std::io::Result { - U16CString::from_os_str(path.as_os_str()) - .map_err(|error| std::io::Error::new(ErrorKind::InvalidInput, error)) - } - - let raw = path.as_os_str(); - if raw.is_empty() || raw.encode_wide().take(4).eq(r"\??\".encode_utf16()) { - return encode(path); - } - let path = std::path::absolute(path)?; - let name = encode(&path)?; - if name.len() < 248 { - return Ok(name); - } - let (prefix, skip) = match path.components().next() { - Some(Component::Prefix(prefix)) => match prefix.kind() { - Prefix::Disk(_) => (r"\\?\", 0), - Prefix::UNC(..) => (r"\\?\UNC\", 2), - _ => ("", 0), - }, - _ => ("", 0), - }; - U16CString::from_vec( - prefix - .encode_utf16() - .chain(name.as_slice().iter().copied().skip(skip)) - .collect::>(), - ) - .map_err(|error| std::io::Error::new(ErrorKind::InvalidInput, error)) + let path = super::fs::extended_length_path(path)?; + U16CString::from_os_str(path.as_os_str()) + .map_err(|error| std::io::Error::new(ErrorKind::InvalidInput, error)) } /// Creates a directory with `security_descriptor` applied atomically. @@ -497,7 +464,9 @@ mod tests { use std::io::Write; use std::os::windows::ffi::OsStrExt; use std::os::windows::ffi::OsStringExt; + use std::path::Component; use std::path::PathBuf; + use std::path::Prefix; use test_with_tracing::test; use widestring::U16CStr; use windows_sys::Win32::Foundation::LocalFree;