diff --git a/Cargo.lock b/Cargo.lock index 287106eb353..ac52ac65f05 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1162,6 +1162,7 @@ dependencies = [ "signature", "symcrypt", "thiserror 2.0.16", + "widestring", "windows 0.62.0", "windows-result 0.4.0", "x509-cert", @@ -1798,6 +1799,7 @@ dependencies = [ "tempfile", "thiserror 2.0.16", "vm_resource", + "widestring", "windows-sys 0.61.0", "zerocopy", ] @@ -2266,7 +2268,6 @@ dependencies = [ "vmcore", "vmm_core", "watchdog_core", - "wchar", "zerocopy", ] @@ -3480,7 +3481,6 @@ dependencies = [ "ucs2 0.0.0", "uefi_nvram_storage", "vmcore", - "wchar", "zerocopy", ] @@ -3752,6 +3752,7 @@ dependencies = [ "static_assertions", "tempfile", "virt", + "widestring", "zerocopy", ] @@ -3780,6 +3781,7 @@ dependencies = [ "vmbus_channel", "vmbus_ring", "vmcore", + "widestring", "zerocopy", ] @@ -4645,6 +4647,7 @@ name = "make_imc_hive" version = "0.0.0" dependencies = [ "anyhow", + "widestring", "windows-sys 0.61.0", ] @@ -5322,6 +5325,7 @@ dependencies = [ "vmbus_core", "vmbus_ring", "vmcore", + "widestring", "zerocopy", ] @@ -8804,6 +8808,7 @@ dependencies = [ "test_with_tracing", "tracing", "tracing-subscriber", + "widestring", "windows-sys 0.61.0", ] @@ -9388,7 +9393,6 @@ dependencies = [ "ucs2 0.0.0", "uefi_specs", "vmcore", - "wchar", "zerocopy", ] @@ -9402,7 +9406,7 @@ dependencies = [ "open_enum", "static_assertions", "ucs2 0.0.0", - "wchar", + "widestring", "zerocopy", ] @@ -10055,6 +10059,7 @@ dependencies = [ "test_with_tracing", "thiserror 2.0.16", "tracing", + "widestring", "windows 0.62.0", "zerocopy", ] @@ -11903,26 +11908,6 @@ dependencies = [ "vmcore", ] -[[package]] -name = "wchar" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8be48fe4c433c0d4aa71bb8759c5f7b1da6dacb1b99998566ebe16503f6a59c" -dependencies = [ - "wchar-impl", -] - -[[package]] -name = "wchar-impl" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "075c93156fed21f9dab57af5e81604d0fdb67432c919a8c1f78bb979f06a3d25" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "web-time" version = "1.1.0" @@ -11963,6 +11948,7 @@ dependencies = [ "criterion", "guid", "pal", + "widestring", "windows-sys 0.61.0", ] diff --git a/Cargo.toml b/Cargo.toml index 4b84d232a5f..9da1cb826ab 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -563,7 +563,6 @@ serde_json = { version = "1.0", default-features = false } serde_yaml = "0.9" toml_edit = "0.23" urlencoding = "2.1.3" -wchar = "0.11" widestring = "1.0" # We add the derive feature here since the vast majority of our crates use it. zerocopy = { version = "0.8.25", features = ["derive"]} diff --git a/openhcl/underhill_attestation/src/jwt.rs b/openhcl/underhill_attestation/src/jwt.rs index c62183f6e11..0419ca661b6 100644 --- a/openhcl/underhill_attestation/src/jwt.rs +++ b/openhcl/underhill_attestation/src/jwt.rs @@ -338,9 +338,7 @@ mod tests { // UTF-16 string let data = "UTF-16 encoded" .encode_utf16() - .collect::>() - .iter() - .flat_map(|character| character.to_ne_bytes()) + .flat_map(u16::to_ne_bytes) .collect::>(); let result = string_from_utf8_preserve_invalid_bytes(data.as_slice()); assert_eq!(result, "U\0T\0F\0-\x001\x006\0 \0e\0n\0c\0o\0d\0e\0d\0"); diff --git a/petri/make_imc_hive/Cargo.toml b/petri/make_imc_hive/Cargo.toml index 2db82412ea6..7e411416b6a 100644 --- a/petri/make_imc_hive/Cargo.toml +++ b/petri/make_imc_hive/Cargo.toml @@ -10,6 +10,7 @@ rust-version.workspace = true windows-sys = { workspace = true, features = ["Wdk_System_OfflineRegistry", "Win32_Foundation", "Win32_Security", "Win32_System_Registry"] } anyhow.workspace = true +widestring.workspace = true [lints] workspace = true diff --git a/petri/make_imc_hive/src/windows/offreg.rs b/petri/make_imc_hive/src/windows/offreg.rs index a73e8e6a47f..d95282cbf92 100644 --- a/petri/make_imc_hive/src/windows/offreg.rs +++ b/petri/make_imc_hive/src/windows/offreg.rs @@ -6,11 +6,13 @@ // UNSAFETY: needed for the FFI bindings. #![expect(unsafe_code)] +use std::ffi::OsStr; use std::ops::Deref; -use std::os::windows::ffi::OsStrExt; use std::path::Path; use std::ptr::null; use std::ptr::null_mut; +use widestring::U16CString; +use widestring::U16String; use windows_sys::Wdk::System::OfflineRegistry::ORCloseHive; use windows_sys::Wdk::System::OfflineRegistry::ORCloseKey; use windows_sys::Wdk::System::OfflineRegistry::ORCreateHive; @@ -36,11 +38,7 @@ impl Hive { } pub fn save(&self, path: &Path) -> std::io::Result<()> { - let path16 = path - .as_os_str() - .encode_wide() - .chain([0]) - .collect::>(); + let path16 = wide(path)?; // SAFETY: calling as documented with owned key and null-terminated // path. @@ -104,7 +102,7 @@ pub struct Key(ORHKEY); impl Key { pub fn create_key(&self, name: &str) -> anyhow::Result { let mut new_key = null_mut(); - let name16 = name.encode_utf16().chain([0]).collect::>(); + let name16 = wide(name)?; // SAFETY: calling as documented with owned key and null-terminated // path. unsafe { @@ -122,7 +120,7 @@ impl Key { } pub fn set_dword(&self, name: &str, dword: u32) -> std::io::Result<()> { - let name16 = name.encode_utf16().chain([0]).collect::>(); + let name16 = wide(name)?; // SAFETY: calling as documented with owned key and null-terminated // name. unsafe { @@ -138,8 +136,8 @@ impl Key { } pub fn set_sz(&self, name: &str, value: &str) -> std::io::Result<()> { - let name16 = name.encode_utf16().chain([0]).collect::>(); - let value16 = value.encode_utf16().chain([0]).collect::>(); + let name16 = wide(name)?; + let value16 = wide(value)?; // SAFETY: calling as documented with owned key and null-terminated // name and value. unsafe { @@ -148,15 +146,15 @@ impl Key { name16.as_ptr(), REG_SZ, value16.as_ptr().cast(), - value16.len() as u32 * 2, + value16.as_slice_with_nul().len() as u32 * 2, ))?; } Ok(()) } pub fn set_expand_sz(&self, name: &str, value: &str) -> std::io::Result<()> { - let name16 = name.encode_utf16().chain([0]).collect::>(); - let value16 = value.encode_utf16().chain([0]).collect::>(); + let name16 = wide(name)?; + let value16 = wide(value)?; // SAFETY: calling as documented with owned key and null-terminated // name and value. unsafe { @@ -165,7 +163,7 @@ impl Key { name16.as_ptr(), REG_EXPAND_SZ, value16.as_ptr().cast(), - value16.len() as u32 * 2, + value16.as_slice_with_nul().len() as u32 * 2, ))?; } Ok(()) @@ -176,12 +174,12 @@ impl Key { name: &str, value: impl IntoIterator, ) -> std::io::Result<()> { - let name16 = name.encode_utf16().chain([0]).collect::>(); - let value16 = value - .into_iter() - .flat_map(|s| s.encode_utf16().chain([0])) - .chain([0]) - .collect::>(); + let name16 = wide(name)?; + let mut value16 = U16String::new(); + for s in value { + value16.push_slice(wide(s)?.as_slice_with_nul()); + } + value16.push_char('\0'); // SAFETY: calling as documented with owned key and null-terminated // name and value. unsafe { @@ -197,6 +195,10 @@ impl Key { } } +fn wide(s: impl AsRef) -> std::io::Result { + U16CString::from_os_str(s).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e)) +} + fn chk(err: u32) -> std::io::Result<()> { if err != 0 { return Err(std::io::Error::from_raw_os_error(err as i32)); diff --git a/support/crypto/Cargo.toml b/support/crypto/Cargo.toml index 218889c1357..ee9a3c6f1d0 100644 --- a/support/crypto/Cargo.toml +++ b/support/crypto/Cargo.toml @@ -80,6 +80,7 @@ jiff.workspace = true thiserror.workspace = true [target.'cfg(windows)'.dependencies] +widestring.workspace = true windows = { workspace = true, features = [ "Win32_Foundation", "Win32_Security_Cryptography", diff --git a/support/crypto/src/aes_256_gcm/win.rs b/support/crypto/src/aes_256_gcm/win.rs index b6b4fa7e972..0c1b8129804 100644 --- a/support/crypto/src/aes_256_gcm/win.rs +++ b/support/crypto/src/aes_256_gcm/win.rs @@ -6,6 +6,7 @@ use super::*; use crate::win::*; use std::sync::LazyLock; +use widestring::U16CStr; use windows::Win32::Security::Cryptography::BCRYPT_ALG_HANDLE; use windows::Win32::Security::Cryptography::BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO; use windows::Win32::Security::Cryptography::BCRYPT_CHAIN_MODE_GCM; @@ -29,12 +30,11 @@ static AES_256_GCM: LazyLock> = LazyLock::new( .map(|()| AlgHandle(handle)) .map_err(|e| err(e, "opening the AES algorithm provider"))?; - let mut chaining_mode = BCRYPT_CHAIN_MODE_GCM.as_wide().to_vec(); - chaining_mode.push(0); + let chaining_mode = U16CStr::from_ptr_str(BCRYPT_CHAIN_MODE_GCM.as_ptr()); windows::Win32::Security::Cryptography::BCryptSetProperty( handle.0.into(), windows::Win32::Security::Cryptography::BCRYPT_CHAINING_MODE, - chaining_mode.as_bytes(), + chaining_mode.as_slice_with_nul().as_bytes(), 0, ) .ok() diff --git a/support/crypto/src/aes_kwp/win.rs b/support/crypto/src/aes_kwp/win.rs index 01c9d3cb5e1..c66d1004141 100644 --- a/support/crypto/src/aes_kwp/win.rs +++ b/support/crypto/src/aes_kwp/win.rs @@ -10,6 +10,7 @@ use super::AesKeyWrapErrorInner; use super::kwp; use crate::win::*; use std::sync::LazyLock; +use widestring::U16CStr; use windows::Win32::Foundation::NTE_BAD_DATA; use windows::Win32::Security::Cryptography::BCRYPT_ALG_HANDLE; use windows::Win32::Security::Cryptography::BCRYPT_CHAIN_MODE_ECB; @@ -35,12 +36,11 @@ static AES_ECB: LazyLock> = LazyLock::new(|| .map(|()| AlgHandle(handle)) .map_err(|e| err(e, "opening the AES algorithm provider"))?; - let mut chaining_mode = BCRYPT_CHAIN_MODE_ECB.as_wide().to_vec(); - chaining_mode.push(0); + let chaining_mode = U16CStr::from_ptr_str(BCRYPT_CHAIN_MODE_ECB.as_ptr()); windows::Win32::Security::Cryptography::BCryptSetProperty( handle.0.into(), windows::Win32::Security::Cryptography::BCRYPT_CHAINING_MODE, - chaining_mode.as_bytes(), + chaining_mode.as_slice_with_nul().as_bytes(), 0, ) .ok() diff --git a/support/crypto/src/x509/win.rs b/support/crypto/src/x509/win.rs index 2121ad0d723..a18d2d7fe79 100644 --- a/support/crypto/src/x509/win.rs +++ b/support/crypto/src/x509/win.rs @@ -14,6 +14,7 @@ use crate::win::decode_object; use crate::win::encode_object; use std::ffi::c_void; use std::ptr::NonNull; +use widestring::U16CString; use windows::Win32::Security::Cryptography::BCRYPT_KEY_HANDLE; use windows::Win32::Security::Cryptography::CERT_AUTHORITY_KEY_ID2_INFO; use windows::Win32::Security::Cryptography::CERT_CONTEXT; @@ -373,8 +374,7 @@ impl X509CertificateInner { if written == 0 { return Err(last_err("formatting the issuer distinguished name")); } - let len = buf.iter().position(|&c| c == 0).unwrap_or(buf.len()); - Ok(String::from_utf16_lossy(&buf[..len])) + Ok(U16CString::from_vec_truncate(buf).to_string_lossy()) } pub fn serial_number(&self) -> Result, X509Error> { @@ -468,9 +468,7 @@ impl X509CertificateInner { if written == 0 { return Err(last_err("reading the subject common name")); } - // Strip trailing NUL. - let len = buf.iter().position(|&c| c == 0).unwrap_or(buf.len()); - Ok(Some(String::from_utf16_lossy(&buf[..len]))) + Ok(Some(U16CString::from_vec_truncate(buf).to_string_lossy())) } #[cfg(any(test, feature = "test_helpers"))] @@ -689,28 +687,31 @@ fn encode_x500_name( use windows::Win32::Security::Cryptography::CERT_RDN_UTF8_STRING; use windows::Win32::Security::Cryptography::szOID_COUNTRY_NAME; - let mut rdn_entries: Vec<(PCSTR, Vec)> = vec![ - (szOID_COUNTRY_NAME, country.encode_utf16().collect()), + let mut rdn_entries: Vec<_> = [ + (szOID_COUNTRY_NAME, country), ( windows::Win32::Security::Cryptography::szOID_STATE_OR_PROVINCE_NAME, - state.encode_utf16().collect(), + state, ), ( windows::Win32::Security::Cryptography::szOID_LOCALITY_NAME, - locality.encode_utf16().collect(), + locality, ), ( windows::Win32::Security::Cryptography::szOID_ORGANIZATION_NAME, - organization.encode_utf16().collect(), + organization, ), - (szOID_COMMON_NAME, common_name.encode_utf16().collect()), - ]; + (szOID_COMMON_NAME, common_name), + ] + .into_iter() + .map(|(oid, value)| (oid, widestring::U16String::from_str(value))) + .collect(); rdn_entries.retain(|(_, value)| !value.is_empty()); // Build CERT_RDN_ATTR list and one CERT_RDN per attribute (each in its // own RDN so the resulting DN is fully ordered). let mut attrs: Vec = Vec::with_capacity(rdn_entries.len()); - for (oid, bytes) in &mut rdn_entries { + for (oid, value) in &mut rdn_entries { attrs.push(CERT_RDN_ATTR { pszObjId: windows::core::PSTR(oid.0.cast_mut()), dwValueType: if *oid == szOID_COUNTRY_NAME { @@ -719,8 +720,8 @@ fn encode_x500_name( CERT_RDN_UTF8_STRING.0 as u32 }, Value: CRYPT_INTEGER_BLOB { - cbData: (bytes.len() * size_of::()) as u32, - pbData: bytes.as_mut_ptr().cast(), + cbData: (value.len() * size_of::()) as u32, + pbData: value.as_mut_ptr().cast(), }, }); } diff --git a/support/hvs_file/src/reader.rs b/support/hvs_file/src/reader.rs index bee1b034f04..0b35cc49d0f 100644 --- a/support/hvs_file/src/reader.rs +++ b/support/hvs_file/src/reader.rs @@ -368,17 +368,20 @@ impl HvsFileReader { }); } // Data format: u32 size_in_bytes, then UTF-16LE data - if entry.data.len() < 4 { + let Some((byte_len, data)) = entry.data.split_first_chunk::<4>() else { return Ok(String::new()); - } - let byte_len = u32::from_le_bytes(entry.data[..4].try_into().unwrap_or_default()) as usize; - let utf16_bytes = &entry.data[4..4 + byte_len.min(entry.data.len() - 4)]; - let utf16: Vec = utf16_bytes - .chunks_exact(2) - .map(|c| u16::from_le_bytes([c[0], c[1]])) + }; + let byte_len = u32::from_le_bytes(*byte_len) as usize; + let utf16 = data[..byte_len.min(data.len())] + .as_chunks() + .0 + .iter() + .map(|&c| u16::from_le_bytes(c)); + let mut s: String = char::decode_utf16(utf16) + .map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER)) .collect(); - let s = String::from_utf16_lossy(&utf16); - Ok(s.trim_end_matches('\0').to_string()) + s.truncate(s.trim_end_matches('\0').len()); + Ok(s) } /// Reads a boolean value. diff --git a/support/hvs_file/src/writer.rs b/support/hvs_file/src/writer.rs index 4041ae4ebe8..89bb211b9e3 100644 --- a/support/hvs_file/src/writer.rs +++ b/support/hvs_file/src/writer.rs @@ -314,9 +314,7 @@ impl HvsFileWriter { Value::Bool(v) => (KeyType::BOOL, 0u8, (v as i32).to_le_bytes().to_vec()), Value::String(s) => { let mut data = vec![0u8; 4]; - for ch in s.encode_utf16().chain(core::iter::once(0)) { - data.extend_from_slice(&ch.to_le_bytes()); - } + data.extend(s.encode_utf16().chain([0]).flat_map(u16::to_le_bytes)); let byte_len = (data.len() - 4) as u32; data[..4].copy_from_slice(&byte_len.to_le_bytes()); (KeyType::STRING, 0u8, data) diff --git a/support/pal/src/windows.rs b/support/pal/src/windows.rs index 3371b97da4d..6d1433e1940 100644 --- a/support/pal/src/windows.rs +++ b/support/pal/src/windows.rs @@ -48,6 +48,7 @@ use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::time::Duration; use widestring::U16CString; +use widestring::U16String; use widestring::Utf16Str; use windows_sys::Wdk::Storage::FileSystem::NtCreateDirectoryObject; use windows_sys::Wdk::Storage::FileSystem::NtOpenDirectoryObject; @@ -607,8 +608,8 @@ impl<'a> TryFrom<&'a OsStr> for UnicodeString { type Error = StringTooLong; fn try_from(value: &'a OsStr) -> std::result::Result { // FUTURE: figure out how to do this without a second allocation. - let value16: Vec<_> = value.encode_wide().collect(); - Self::new(&value16) + let value16 = U16String::from_os_str(value); + Self::new(value16.as_slice()) } } @@ -1201,23 +1202,28 @@ pub fn disable_hard_error_dialog() { #[cfg(test)] mod tests { use super::*; + use test_with_tracing::test; + use widestring::u16str; #[test] fn test_dos_to_nt_path() { let pathu = dos_to_nt_path("c:\\foo").unwrap(); - assert!( - pathu - .as_slice() - .iter() - .copied() - .eq("\\??\\c:\\foo".encode_utf16()) - ); + assert_eq!(pathu.as_slice(), u16str!("\\??\\c:\\foo").as_slice()); } #[test] fn test_alloc_unicode_string() { let s: UnicodeString = "abc".try_into().unwrap(); - assert!(s.as_slice().iter().copied().eq("abc".encode_utf16())); + assert_eq!(s.as_slice(), u16str!("abc").as_slice()); + } + + #[test] + fn test_alloc_unicode_string_preserves_code_units() { + let value = [b'a' as u16, 0, 0xd83d, 0xde80, 0xd800]; + let value = U16String::from_vec(value); + let s = UnicodeString::try_from(value.to_os_string().as_os_str()).unwrap(); + assert_eq!(s.as_slice(), value.as_slice()); + assert_eq!(s.length(), size_of_val(value.as_slice())); } #[test] diff --git a/support/pal/src/windows/fs/relative.rs b/support/pal/src/windows/fs/relative.rs index 8908b97df94..6a554d71113 100644 --- a/support/pal/src/windows/fs/relative.rs +++ b/support/pal/src/windows/fs/relative.rs @@ -12,8 +12,6 @@ use crate::windows::chk_status; use std::cell::UnsafeCell; use std::fs; use std::io; -use std::os::windows::ffi::OsStrExt; -use std::os::windows::ffi::OsStringExt; use std::os::windows::io::AsHandle; use std::os::windows::io::AsRawHandle; use std::os::windows::io::FromRawHandle; @@ -21,6 +19,9 @@ use std::ptr; use std::ptr::null_mut; use std::sync::atomic::AtomicI32; use std::sync::atomic::Ordering; +use widestring::U16Str; +use widestring::U16String; +use widestring::u16str; use windows_sys::Wdk::Storage::FileSystem as ntioapi; use windows_sys::Win32::Foundation::OBJ_CASE_INSENSITIVE; use windows_sys::Win32::Foundation::STATUS_NO_MORE_FILES; @@ -104,15 +105,15 @@ fn ensure_synchronous(file: &fs::File) -> io::Result<()> { Ok(()) } -fn validate_relative_component(name: &std::ffi::OsStr, description: &str) -> io::Result> { - let name: Vec = name.encode_wide().collect(); +fn validate_relative_component(name: &std::ffi::OsStr, description: &str) -> io::Result { + let name = U16String::from_os_str(name); // Native relative opens do not apply Win32 dot-component normalization, // but dot names still violate this API's single-component contract. if name.is_empty() - || name.contains(&0) - || name.as_slice() == ['.' as u16] - || name.as_slice() == ['.' as u16, '.' as u16] - || name.iter().any(|character| { + || name.as_slice().contains(&0) + || name == u16str!(".") + || name == u16str!("..") + || name.as_slice().iter().any(|character| { *character == b'/' as u16 || *character == b'\\' as u16 || *character == b':' as u16 }) { @@ -181,7 +182,7 @@ fn open_relative_file( create_disposition: u32, ) -> io::Result { let name = validate_relative_component(name, "file")?; - let name = UnicodeString::new(&name) + let name = UnicodeString::new(name.as_slice()) .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "file name is too long"))?; let mut attributes = ObjectAttributes::new(); attributes @@ -354,7 +355,7 @@ pub fn directory_entry_names(directory: &fs::File) -> io::Result()) }; - let name = std::ffi::OsString::from_wide(name); + let name = U16Str::from_slice(name).to_os_string(); if name != "." && name != ".." { names.push(name); } @@ -518,7 +519,7 @@ mod tests { (*entry).FileNameLength as usize / size_of::(), ) }; - Some(String::from_utf16(name).unwrap()) + Some(U16Str::from_slice(name).to_string().unwrap()) } #[test] @@ -544,6 +545,13 @@ mod tests { } } + #[test] + fn relative_name_preserves_unpaired_surrogates() { + let name = U16String::from_vec([b'f' as u16, 0xd800]); + let validated = validate_relative_component(&name.to_os_string(), "file").unwrap(); + assert_eq!(validated, name); + } + #[test] fn relative_file_lifecycle_uses_the_opened_directory() { let root = TestDirectory::new(); diff --git a/support/pal/src/windows/process.rs b/support/pal/src/windows/process.rs index 03d7fa356e9..1e52548668c 100644 --- a/support/pal/src/windows/process.rs +++ b/support/pal/src/windows/process.rs @@ -13,6 +13,7 @@ use std::os::windows::prelude::*; use std::ptr::null; use std::ptr::null_mut; use widestring::U16CString; +use widestring::U16String; use windows_sys::Win32::Foundation::ERROR_INVALID_PARAMETER; use windows_sys::Win32::Foundation::HANDLE_FLAG_INHERIT; use windows_sys::Win32::Foundation::SetHandleInformation; @@ -608,9 +609,9 @@ impl Stdio<'_> { #[derive(Debug)] pub struct Builder<'a> { creation_flags: u32, - command_line: Vec, - application_name: Option>, - current_directory: Option>, + command_line: U16String, + application_name: Option, + current_directory: Option, handles: Vec>, jobs: Vec>, stdin: Stdio<'a>, @@ -624,24 +625,12 @@ pub struct Builder<'a> { child_process_policy: ChildProcessPolicy, } -fn wstr(s: &OsStr) -> Vec { - s.encode_wide().collect() -} - /// Null terminates a wide string, ensuring that there are no internal null characters. -fn null_terminate(v: Vec) -> Result { +fn null_terminate(v: U16String) -> Result { U16CString::from_vec(v) .map_err(|_| io::Error::from_raw_os_error(ERROR_INVALID_PARAMETER as i32)) } -fn ensure_no_null(v: &OsStr) -> Result<(), io::Error> { - if v.encode_wide().all(|x| x != 0) { - Ok(()) - } else { - Err(io::Error::from_raw_os_error(ERROR_INVALID_PARAMETER as i32)) - } -} - fn ptr_or_null(v: &Option) -> *const T where U: AsRef<[T]>, @@ -710,7 +699,7 @@ impl<'a> Builder<'a> { pub fn new(command_line: impl AsRef) -> Self { Self { creation_flags: 0, - command_line: wstr(command_line.as_ref()), + command_line: U16String::from_os_str(&command_line), application_name: None, current_directory: None, handles: Vec::new(), @@ -728,7 +717,7 @@ impl<'a> Builder<'a> { } pub fn application_name(&mut self, path: impl AsRef) -> &mut Self { - self.application_name = Some(wstr(path.as_ref())); + self.application_name = Some(U16String::from_os_str(&path)); self } @@ -924,16 +913,20 @@ impl<'a> Builder<'a> { } } } - let mut block = Vec::new(); + let mut block = U16String::new(); for (key, val) in env { - ensure_no_null(&key)?; - block.extend(key.encode_wide()); - block.push('=' as u16); - ensure_no_null(&val)?; - block.extend(val.encode_wide()); - block.push(0); + let mut entry = U16String::from_os_str(&key); + entry.push_char('='); + entry.push_os_str(val); + // Reject every NUL, including a trailing one that + // `null_terminate` would accept as the terminator. + if entry.as_slice().contains(&0) { + return Err(io::Error::from_raw_os_error(ERROR_INVALID_PARAMETER as i32)); + } + block.push(entry); + block.push_char('\0'); } - block.push(0); + block.push_char('\0'); env_block = Some(block); } @@ -1017,8 +1010,43 @@ pub(crate) fn terminate(exit_code: i32) -> ! { #[cfg(test)] mod tests { + use super::Builder; use super::EmptyProcess; use super::empty_process; + use test_with_tracing::test; + + #[test] + fn test_unicode_environment_block() { + let value = "value-\u{1f680}"; + let command_line = format!( + r#"cmd.exe /d /c if "%PAL_WIDE_VALUE%:%PAL_SECOND_VALUE%"=="{value}:other" (exit /b 42) else (exit /b 1)"# + ); + let mut builder = Builder::new(command_line); + builder + .env_clear() + .env("PAL_WIDE_VALUE", value) + .env("PAL_SECOND_VALUE", "other"); + let process = builder.spawn().unwrap(); + process.wait(); + assert_eq!(process.exit_code(), 42); + } + + #[test] + fn test_environment_rejects_interior_nul() { + for (key, value) in [ + ("nul\0key", "value"), + ("key", "nul\0value"), + ("key", "value\0"), + ] { + let mut builder = Builder::new("unused"); + builder.env_clear().env(key, value); + let error = builder.spawn().unwrap_err(); + assert_eq!( + error.raw_os_error(), + Some(windows_sys::Win32::Foundation::ERROR_INVALID_PARAMETER as i32) + ); + } + } #[test] fn test_empty() { diff --git a/support/pal/src/windows/security.rs b/support/pal/src/windows/security.rs index 83e3e575dad..907ce6f51e6 100644 --- a/support/pal/src/windows/security.rs +++ b/support/pal/src/windows/security.rs @@ -646,17 +646,16 @@ pub fn process_user_sid(process_id: u32) -> std::io::Result { #[cfg(test)] mod tests { use super::*; - use std::ffi::OsString; use std::fs; use std::fs::OpenOptions; use std::io; use std::io::Read; use std::io::Seek; use std::io::Write; - use std::os::windows::ffi::OsStringExt; use std::path::PathBuf; use test_with_tracing::test; use widestring::U16CStr; + use widestring::u16str; use windows_sys::Win32::Foundation::ERROR_NO_TOKEN; use windows_sys::Win32::Foundation::LocalFree; use windows_sys::Win32::Security::Authorization::ConvertSecurityDescriptorToStringSecurityDescriptorW; @@ -860,12 +859,7 @@ mod tests { fn rejects_paths_with_interior_nul() { let root = TestDirectory::new(); let descriptor = protected_descriptor(); - let path = root.join(OsString::from_wide(&[ - b'n' as u16, - 0, - b'u' as u16, - b'l' as u16, - ])); + let path = root.join(u16str!("n\0ul").to_os_string()); assert_eq!( create_directory_with_security(&path, &descriptor) diff --git a/support/ucs2/src/lib.rs b/support/ucs2/src/lib.rs index 3b6492f21bf..376901c27d4 100644 --- a/support/ucs2/src/lib.rs +++ b/support/ucs2/src/lib.rs @@ -106,12 +106,11 @@ impl From for std::borrow::Cow<'_, Ucs2LeSlice> { impl<'a> From<&'a str> for Ucs2LeVec { fn from(s: &'a str) -> Ucs2LeVec { - let mut s = s + let s = s .encode_utf16() - .flat_map(|w| [w as u8, (w >> 8) as u8]) + .chain([0]) + .flat_map(u16::to_le_bytes) .collect::>(); - s.push(0); - s.push(0); // SAFETY: UTF-8 str has been converted into a valid null-terminated UCS-2 Le string Ucs2LeVec(s) } @@ -160,11 +159,7 @@ impl Ucs2LeSlice { // Unlike UTF-8 or UTF-16, UCS-2 doesn't require any complex semantic // validation, as all values from 0 to 0xFFFF are valid codepoints. - let mut buf_as_u16_iter = buf - .chunks_exact(2) - .map(|c| u16::from_le_bytes(c.try_into().unwrap())); - - match buf_as_u16_iter.position(|c| c == 0) { + match buf.as_chunks().0.iter().position(|c| *c == [0, 0]) { None => Err(Ucs2ParseError::MissingNullTerm), // SAFETY: buf has been validated to contain valid data Some(idx) => Ok(unsafe { Ucs2LeSlice::from_slice_unchecked(&buf[..(idx + 1) * 2]) }), @@ -205,14 +200,10 @@ impl Ucs2LeSlice { // // Properly converting UCS-2 to UTF-8/16 is a bit more subtle, and // handling this properly will require a PR in its own right. - String::from_utf16_lossy( - &self - .0 - .chunks_exact(2) - .map(|c| u16::from_le_bytes(c.try_into().unwrap())) - .take_while(|b| *b != 0) - .collect::>(), - ) + let units = self.0.as_chunks().0.iter().map(|&c| u16::from_le_bytes(c)); + char::decode_utf16(units.take_while(|&c| c != 0)) + .map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER)) + .collect() } } @@ -254,7 +245,7 @@ mod test { // Too bad UEFI doesn't support proper UTF-16... imagine if we could use // Emoji as nvram variable names 👀 s.encode_utf16() - .flat_map(|b| b.to_le_bytes().into_iter()) + .flat_map(u16::to_le_bytes) .collect::>() } @@ -314,4 +305,22 @@ mod test { let res = Ucs2LeSlice::from_slice_with_nul(&s16); assert!(matches!(res, Err(Ucs2ParseError::MissingNullTerm))) } + + #[test] + fn from_str_encodes_little_endian_with_null() { + let s = Ucs2LeVec::from("hi\u{1f680}"); + assert_eq!( + s.as_bytes(), + [b'h', 0, b'i', 0, 0x3d, 0xd8, 0x80, 0xde, 0, 0] + ); + assert_eq!(s.to_string(), "hi\u{1f680}"); + } + + #[test] + fn display_replaces_unpaired_surrogates() { + let raw = [b'a', 0, 0x00, 0xd8, b'b', 0, 0, 0]; + let s = Ucs2LeSlice::from_slice_with_nul(&raw).unwrap(); + assert_eq!(s.to_string(), "a\u{fffd}b"); + assert_eq!(format!("{s:?}"), "\"a\u{fffd}b\""); + } } diff --git a/vm/devices/firmware/firmware_uefi/Cargo.toml b/vm/devices/firmware/firmware_uefi/Cargo.toml index 62ebe45f55d..38fe68bbe52 100644 --- a/vm/devices/firmware/firmware_uefi/Cargo.toml +++ b/vm/devices/firmware/firmware_uefi/Cargo.toml @@ -52,7 +52,6 @@ zerocopy.workspace = true [dev-dependencies] parking_lot.workspace = true test_with_tracing.workspace = true -wchar.workspace = true [lints] workspace = true diff --git a/vm/devices/firmware/firmware_uefi/src/service/nvram/mod.rs b/vm/devices/firmware/firmware_uefi/src/service/nvram/mod.rs index 254dc7fd6a6..6202733682b 100644 --- a/vm/devices/firmware/firmware_uefi/src/service/nvram/mod.rs +++ b/vm/devices/firmware/firmware_uefi/src/service/nvram/mod.rs @@ -712,12 +712,12 @@ mod tests { use firmware_uefi_custom_vars::ApplyDeltaError; use pal_async::async_test; use ucs2::Ucs2LeSlice; + use ucs2::Ucs2LeVec; use uefi_nvram_specvars::signature_list::SignatureData; use uefi_nvram_specvars::signature_list::SignatureList; use uefi_nvram_storage::EFI_TIME; use uefi_nvram_storage::NvramStorage; use uefi_nvram_storage::in_memory::InMemoryNvram; - use wchar::wchz; const TEST_SIGNATURE_OWNER: Guid = guid::guid!("00000000-0000-0000-0000-000000000001"); @@ -792,7 +792,7 @@ mod tests { attributes: u32, data: &[u8], ) -> EfiStatus { - let name = wchz!(u16, "var").as_bytes(); + let name: &[u8] = &Ucs2LeVec::from("var").into_inner(); gm.write_at(0x2000, name).unwrap(); gm.write_at(0x3000, data).unwrap(); gm.write_plain( @@ -830,7 +830,7 @@ mod tests { .with_non_volatile(true) .with_bootservice_access(true) .with_runtime_access(true); - let data = vec![0x5a; 32 * 1024 - 48 - wchz!(u16, "var").as_bytes().len()]; + let data = vec![0x5a; 32 * 1024 - 48 - Ucs2LeVec::from("var").as_bytes().len()]; nvram.services.prepare_for_boot(); for &vendor in &vendors { @@ -892,7 +892,7 @@ mod tests { .await, EfiStatus::INVALID_PARAMETER ); - let name = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "var").as_bytes()).unwrap(); + let name: &Ucs2LeSlice = &Ucs2LeVec::from("var"); let (stored_attributes, stored_data) = nvram .services .get_variable_ucs2(vendors[0], name) @@ -1083,7 +1083,7 @@ mod tests { ); // A legal request still passes the gate and is stored. - let name = wchz!(u16, "TestVar"); + let name = Ucs2LeVec::from("TestVar"); let name_addr = 0x2000; let data_addr = 0x2200; let data = b"test"; @@ -1194,7 +1194,7 @@ mod tests { #[async_test] async fn invalid_templates_are_ignored_after_first_boot_without_secure_boot() { let mut storage = InMemoryNvram::new(); - let name = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "existing").as_bytes()).unwrap(); + let name: &Ucs2LeSlice = &Ucs2LeVec::from("existing"); storage .set_variable(name, Guid::default(), 0, vec![1], EFI_TIME::default()) .await @@ -1215,7 +1215,7 @@ mod tests { #[async_test] async fn invalid_base_template_is_ignored_after_first_boot_with_secure_boot() { let mut storage = InMemoryNvram::new(); - let name = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "existing").as_bytes()).unwrap(); + let name: &Ucs2LeSlice = &Ucs2LeVec::from("existing"); storage .set_variable(name, Guid::default(), 0, vec![1], EFI_TIME::default()) .await diff --git a/vm/devices/firmware/firmware_uefi/src/service/nvram/spec_services/mod.rs b/vm/devices/firmware/firmware_uefi/src/service/nvram/spec_services/mod.rs index f1aaacbf33f..dc878c833e7 100644 --- a/vm/devices/firmware/firmware_uefi/src/service/nvram/spec_services/mod.rs +++ b/vm/devices/firmware/firmware_uefi/src/service/nvram/spec_services/mod.rs @@ -1485,14 +1485,12 @@ mod save_restore { mod test { use super::*; use uefi_nvram_storage::in_memory::InMemoryNvram; - // TODO: wchz returns UTF-16 strings, _not_ UCS-2 strings. This works fine + // TODO: Ucs2LeVec::from encodes UTF-16, _not_ UCS-2. This works fine // when using english variable names, but things will _not_ work as expected // if one tries to use any particularly "exotic" chars (that cannot be // represented in UCS-2). use pal_async::async_test; - use wchar::wchz; - - use zerocopy::IntoBytes; + use ucs2::Ucs2LeVec; /// Extension trait around `NvramServices` that makes it easier to use the /// API outside the context of the UEFI device @@ -1569,10 +1567,10 @@ mod test { nvram.prepare_for_boot(); - let name1 = wchz!(u16, "var1").as_bytes(); - let name2 = wchz!(u16, "var2").as_bytes(); - let name3 = wchz!(u16, "var3").as_bytes(); - let name4 = wchz!(u16, "var4").as_bytes(); + let name1: &[u8] = &Ucs2LeVec::from("var1").into_inner(); + let name2: &[u8] = &Ucs2LeVec::from("var2").into_inner(); + let name3: &[u8] = &Ucs2LeVec::from("var3").into_inner(); + let name4: &[u8] = &Ucs2LeVec::from("var4").into_inner(); let dummy_data = b"dummy data".to_vec(); @@ -1619,7 +1617,7 @@ mod test { assert_eq!(data, Some(dummy_data.clone())); // access them sequentially - let mut name = Some(wchz!(u16, "").as_bytes().into()); + let mut name = Some(Ucs2LeVec::from("").into_inner()); name = nvram.get_next_test_var(name).await.unwrap_efi_success(); assert_eq!(name, Some(name1.into())); @@ -1643,7 +1641,7 @@ mod test { // try to set non-runtime access var let NvramResult(_, status, err) = nvram .set_test_var( - wchz!(u16, "non-volatile").as_bytes(), + Ucs2LeVec::from("non-volatile").as_bytes(), no_runtime_attr, &dummy_data, ) @@ -1673,7 +1671,7 @@ mod test { assert!(matches!(err, Some(NvramError::InvalidRuntimeAccess))); // access them sequentially - let mut name = Some(wchz!(u16, "").as_bytes().into()); + let mut name = Some(Ucs2LeVec::from("").into_inner()); name = nvram.get_next_test_var(name).await.unwrap_efi_success(); assert_eq!(name, Some(name1.into())); @@ -1697,7 +1695,7 @@ mod test { nvram.prepare_for_boot(); - let name = wchz!(u16, "TestVar").as_bytes(); + let name: &[u8] = &Ucs2LeVec::from("TestVar").into_inner(); let dummy_data = b"test data".to_vec(); // Create a variable with specific attributes @@ -1747,7 +1745,7 @@ mod test { nvram.prepare_for_boot(); - let name = wchz!(u16, "RegularVar").as_bytes(); + let name: &[u8] = &Ucs2LeVec::from("RegularVar").into_inner(); let dummy_data = b"regular data".to_vec(); // Create a regular (non-authenticated) variable @@ -1798,7 +1796,7 @@ mod test { nvram.prepare_for_boot(); - let name = wchz!(u16, "TestVar").as_bytes(); + let name: &[u8] = &Ucs2LeVec::from("TestVar").into_inner(); let dummy_data = b"test data".to_vec(); // Create a regular variable @@ -1832,7 +1830,7 @@ mod test { nvram.prepare_for_boot(); - let name = wchz!(u16, "ZeroDataVar").as_bytes(); + let name: &[u8] = &Ucs2LeVec::from("ZeroDataVar").into_inner(); let dummy_data = b"some data".to_vec(); // Create a variable @@ -1864,8 +1862,8 @@ mod test { nvram.prepare_for_boot(); - let name1 = wchz!(u16, "RuntimeVar").as_bytes(); - let name2 = wchz!(u16, "BootVar").as_bytes(); + let name1: &[u8] = &Ucs2LeVec::from("RuntimeVar").into_inner(); + let name2: &[u8] = &Ucs2LeVec::from("BootVar").into_inner(); let dummy_data = b"data".to_vec(); // Create runtime-accessible variable @@ -1923,7 +1921,7 @@ mod test { nvram.prepare_for_boot(); - let name = wchz!(u16, "AppendVar").as_bytes(); + let name: &[u8] = &Ucs2LeVec::from("AppendVar").into_inner(); let initial_data = b"initial".to_vec(); let append_data = b"appended".to_vec(); diff --git a/vm/devices/firmware/hcl_compat_uefi_nvram_storage/Cargo.toml b/vm/devices/firmware/hcl_compat_uefi_nvram_storage/Cargo.toml index f8e20331a54..1904075769f 100644 --- a/vm/devices/firmware/hcl_compat_uefi_nvram_storage/Cargo.toml +++ b/vm/devices/firmware/hcl_compat_uefi_nvram_storage/Cargo.toml @@ -31,7 +31,6 @@ tracing.workspace = true zerocopy.workspace = true [dev-dependencies] pal_async.workspace = true -wchar.workspace = true [lints] workspace = true diff --git a/vm/devices/firmware/hcl_compat_uefi_nvram_storage/src/lib.rs b/vm/devices/firmware/hcl_compat_uefi_nvram_storage/src/lib.rs index 903963006e0..78c1fd313b8 100644 --- a/vm/devices/firmware/hcl_compat_uefi_nvram_storage/src/lib.rs +++ b/vm/devices/firmware/hcl_compat_uefi_nvram_storage/src/lib.rs @@ -509,7 +509,6 @@ mod test { use pal_async::async_test; use ucs2::Ucs2LeVec; use uefi_nvram_storage::in_memory::impl_agnostic_tests; - use wchar::wchz; /// An ephemeral implementation of [`StorageBackend`] backed by an in-memory /// buffer. Useful for tests, stateless VM scenarios. @@ -628,7 +627,7 @@ mod test { #[async_test] async fn storage_limit_rejects_writes_without_mutation() { - let name = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "var").as_bytes()).unwrap(); + let name: &Ucs2LeSlice = &Ucs2LeVec::from("var"); let timestamp = EFI_TIME::default(); let vendors: [Guid; 4] = std::array::from_fn(|_| Guid::new_random()); let entry_overhead = size_of::() + name.as_bytes().len(); @@ -717,11 +716,11 @@ mod test { let mut storage = EphemeralStorageBackend::default(); let vendor1 = Guid::new_random(); - let name1 = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "var1").as_bytes()).unwrap(); + let name1: &Ucs2LeSlice = &Ucs2LeVec::from("var1"); let vendor2 = Guid::new_random(); - let name2 = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "var2").as_bytes()).unwrap(); + let name2: &Ucs2LeSlice = &Ucs2LeVec::from("var2"); let vendor3 = Guid::new_random(); - let name3 = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "var3").as_bytes()).unwrap(); + let name3: &Ucs2LeSlice = &Ucs2LeVec::from("var3"); let attr = 0x1234; let data = vec![0x1, 0x2, 0x3, 0x4, 0x5]; let timestamp = EFI_TIME::default(); @@ -770,7 +769,7 @@ mod test { use vmcore::save_restore::SaveRestore; let vendor = Guid::new_random(); - let name = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "var").as_bytes()).unwrap(); + let name: &Ucs2LeSlice = &Ucs2LeVec::from("var"); let timestamp = EFI_TIME::default(); let mut source = HclCompatNvram::new(EphemeralStorageBackend::default(), None); diff --git a/vm/devices/firmware/uefi_nvram_storage/Cargo.toml b/vm/devices/firmware/uefi_nvram_storage/Cargo.toml index e05398a9627..e480de96090 100644 --- a/vm/devices/firmware/uefi_nvram_storage/Cargo.toml +++ b/vm/devices/firmware/uefi_nvram_storage/Cargo.toml @@ -22,7 +22,6 @@ vmcore = { workspace = true, optional = true } async-trait.workspace = true thiserror.workspace = true -wchar.workspace = true zerocopy.workspace = true [dev-dependencies] pal_async.workspace = true diff --git a/vm/devices/firmware/uefi_nvram_storage/src/in_memory.rs b/vm/devices/firmware/uefi_nvram_storage/src/in_memory.rs index a74b03b884f..f3b30f40b36 100644 --- a/vm/devices/firmware/uefi_nvram_storage/src/in_memory.rs +++ b/vm/devices/firmware/uefi_nvram_storage/src/in_memory.rs @@ -273,13 +273,12 @@ pub mod impl_agnostic_tests { use crate::NvramStorage; use guid::Guid; use ucs2::Ucs2LeSlice; - use wchar::wchz; + use ucs2::Ucs2LeVec; use zerocopy::FromZeros; - use zerocopy::IntoBytes; pub async fn test_single_variable(nvram: &mut dyn NvramStorage) { let vendor = Guid::new_random(); - let name = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "var1").as_bytes()).unwrap(); + let name: &Ucs2LeSlice = &Ucs2LeVec::from("var1"); let attr = 0x1234; let data = vec![0x1, 0x2, 0x3, 0x4, 0x5]; let data1 = vec![0xa, 0xb, 0xc]; @@ -320,11 +319,11 @@ pub mod impl_agnostic_tests { pub async fn test_next(nvram: &mut dyn NvramStorage) { let vendor1 = Guid::new_random(); - let name1 = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "var1").as_bytes()).unwrap(); + let name1: &Ucs2LeSlice = &Ucs2LeVec::from("var1"); let vendor2 = Guid::new_random(); - let name2 = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "var2").as_bytes()).unwrap(); + let name2: &Ucs2LeSlice = &Ucs2LeVec::from("var2"); let vendor3 = Guid::new_random(); - let name3 = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "var3").as_bytes()).unwrap(); + let name3: &Ucs2LeSlice = &Ucs2LeVec::from("var3"); let attr = 0x1234; let data = vec![0x1, 0x2, 0x3, 0x4, 0x5]; let timestamp = EFI_TIME::new_zeroed(); @@ -411,11 +410,11 @@ pub mod impl_agnostic_tests { pub async fn test_multiple_variable(nvram: &mut dyn NvramStorage) { let vendor1 = Guid::new_random(); - let name1 = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "var1").as_bytes()).unwrap(); + let name1: &Ucs2LeSlice = &Ucs2LeVec::from("var1"); let vendor2 = Guid::new_random(); - let name2 = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "var2").as_bytes()).unwrap(); + let name2: &Ucs2LeSlice = &Ucs2LeVec::from("var2"); let vendor3 = Guid::new_random(); - let name3 = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "var3").as_bytes()).unwrap(); + let name3: &Ucs2LeSlice = &Ucs2LeVec::from("var3"); let attr = 0x1234; let data = vec![0x1, 0x2, 0x3, 0x4, 0x5]; let timestamp = EFI_TIME::new_zeroed(); diff --git a/vm/devices/firmware/uefi_specs/Cargo.toml b/vm/devices/firmware/uefi_specs/Cargo.toml index 05fefb89c61..f3dfdee0c6f 100644 --- a/vm/devices/firmware/uefi_specs/Cargo.toml +++ b/vm/devices/firmware/uefi_specs/Cargo.toml @@ -11,7 +11,7 @@ default = [] inspect = ["dep:inspect"] # The NVRAM variable-name helpers, which need `ucs2`. -std = ["dep:ucs2", "dep:wchar"] +std = ["dep:ucs2", "dep:widestring"] [dependencies] guid.workspace = true @@ -21,7 +21,7 @@ ucs2 = { workspace = true, optional = true } bitfield-struct.workspace = true static_assertions.workspace = true -wchar = { workspace = true, optional = true } +widestring = { workspace = true, optional = true } zerocopy.workspace = true [dev-dependencies] diff --git a/vm/devices/firmware/uefi_specs/src/lib.rs b/vm/devices/firmware/uefi_specs/src/lib.rs index 93f7540e27a..faa2a439c61 100644 --- a/vm/devices/firmware/uefi_specs/src/lib.rs +++ b/vm/devices/firmware/uefi_specs/src/lib.rs @@ -26,7 +26,10 @@ macro_rules! defn_nvram_var { ( $guid, - Ucs2LeSlice::from_slice_with_nul(wchar::wchz!(u16, $name).as_bytes()).unwrap(), + Ucs2LeSlice::from_slice_with_nul( + widestring::u16cstr!($name).as_slice_with_nul().as_bytes(), + ) + .unwrap(), ) } }; diff --git a/vm/devices/firmware/uefi_specs/src/uefi/nvram.rs b/vm/devices/firmware/uefi_specs/src/uefi/nvram.rs index 64339594b44..40f0ed958f1 100644 --- a/vm/devices/firmware/uefi_specs/src/uefi/nvram.rs +++ b/vm/devices/firmware/uefi_specs/src/uefi/nvram.rs @@ -180,10 +180,9 @@ pub fn is_secure_boot_policy_var(vendor: Guid, name: &ucs2::Ucs2LeSlice) -> bool /// UEFI spec 3.3 - Table 3-1 /// -/// Due to the Rust compiler not having built-in support for defining -/// wide-string literals, and me not wanting to yak-shave a proc macro -/// implementation that emits valid Utf16LeSlices at compile time, these -/// "constants" are actually methods that can only be called at runtime. +/// The UTF-16 literals are generated at compile time, but validation as +/// [`ucs2::Ucs2LeSlice`] happens at runtime, so these helpers are functions +/// rather than constants. #[cfg(feature = "std")] pub mod vars { use guid::Guid; diff --git a/vm/devices/get/test_igvm_agent_rpc_server/Cargo.toml b/vm/devices/get/test_igvm_agent_rpc_server/Cargo.toml index c89cc9bfdd2..2e6ec46e0d2 100644 --- a/vm/devices/get/test_igvm_agent_rpc_server/Cargo.toml +++ b/vm/devices/get/test_igvm_agent_rpc_server/Cargo.toml @@ -17,6 +17,7 @@ parking_lot.workspace = true test_igvm_agent_lib.workspace = true tracing.workspace = true tracing-subscriber = { workspace = true, features = ["env-filter"] } +widestring.workspace = true windows-sys = { workspace = true, features = [ "Win32_Foundation", "Win32_System_Memory", diff --git a/vm/devices/get/test_igvm_agent_rpc_server/src/rpc/handlers.rs b/vm/devices/get/test_igvm_agent_rpc_server/src/rpc/handlers.rs index 98560a62f10..11863d0c15f 100644 --- a/vm/devices/get/test_igvm_agent_rpc_server/src/rpc/handlers.rs +++ b/vm/devices/get/test_igvm_agent_rpc_server/src/rpc/handlers.rs @@ -7,6 +7,8 @@ use std::ffi::c_void; use std::mem::size_of; use std::ptr; use std::slice; +use widestring::U16CStr; +use widestring::U16Str; use windows_sys::Win32::Foundation::E_FAIL; use windows_sys::Win32::Foundation::E_INVALIDARG; use windows_sys::Win32::Foundation::E_OUTOFMEMORY; @@ -143,27 +145,16 @@ fn read_utf16(ptr: *const u16) -> Option { return None; } + // Truncate if no null terminator is found within MAX_LEN. + // // SAFETY: The caller (RPC runtime) is responsible for providing valid pointers. // This is a test server, so we trust the RPC infrastructure to provide valid data. - unsafe { - let mut len = 0usize; - - // Scan for null terminator with bounds checking - while len < MAX_LEN { - if *ptr.add(len) == 0 { - break; - } - len += 1; - } - - // If we hit MAX_LEN without finding a null terminator, truncate - if len == MAX_LEN { - len = MAX_LEN - 1; - } - - let slice = slice::from_raw_parts(ptr, len); - String::from_utf16(slice).ok() - } + let s = unsafe { + U16CStr::from_ptr_truncate(ptr, MAX_LEN - 1) + .map(U16CStr::as_ustr) + .unwrap_or_else(|_| U16Str::from_ptr(ptr, MAX_LEN - 1)) + }; + s.to_string().ok() } /// Entry point that services `RpcIGVmAttest` requests for the test agent. diff --git a/vm/devices/get/test_igvm_agent_rpc_server/src/rpc/server.rs b/vm/devices/get/test_igvm_agent_rpc_server/src/rpc/server.rs index df47c522bfb..294c82bf848 100644 --- a/vm/devices/get/test_igvm_agent_rpc_server/src/rpc/server.rs +++ b/vm/devices/get/test_igvm_agent_rpc_server/src/rpc/server.rs @@ -2,11 +2,11 @@ // Licensed under the MIT License. use core::ffi::c_void; -use std::ffi::OsStr; -use std::os::windows::ffi::OsStrExt; use std::ptr; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; +use widestring::U16CStr; +use widestring::u16cstr; use windows_sys::Win32::Foundation::FALSE; use windows_sys::Win32::Foundation::TRUE; use windows_sys::Win32::System::Console::CTRL_BREAK_EVENT; @@ -26,8 +26,8 @@ use windows_sys::Win32::System::Rpc::RpcServerUnregisterIf; use windows_sys::Win32::System::Rpc::RpcServerUseProtseqEpW; use windows_sys::core::BOOL; -pub const PROTOCOL_SEQUENCE: &str = "ncalrpc"; -pub const ENDPOINT: &str = "IGVM_AGENT_RPC_SERVER"; +pub const PROTOCOL_SEQUENCE: &U16CStr = u16cstr!("ncalrpc"); +pub const ENDPOINT: &U16CStr = u16cstr!("IGVM_AGENT_RPC_SERVER"); pub type RpcInterfaceHandle = *mut c_void; @@ -36,10 +36,6 @@ unsafe extern "C" { pub static IGVmAgentRpcApi_v1_0_s_ifspec: RpcInterfaceHandle; } -fn to_wide(s: &str) -> Vec { - OsStr::new(s).encode_wide().chain([0]).collect() -} - /// # SAFETY /// The callback for the passing through FFI unsafe extern "system" fn rpc_bind_callback( @@ -97,16 +93,18 @@ impl Drop for ConsoleHandlerGuard { } fn register_protocol_and_interface() -> Result<(), String> { - tracing::info!(protocol = %PROTOCOL_SEQUENCE, endpoint = %ENDPOINT, "registering RPC protocol"); - let mut protocol_seq = to_wide(PROTOCOL_SEQUENCE); - let mut endpoint = to_wide(ENDPOINT); + tracing::info!( + protocol = %PROTOCOL_SEQUENCE.display(), + endpoint = %ENDPOINT.display(), + "registering RPC protocol" + ); // SAFETY: Make an FFI call. let status = unsafe { RpcServerUseProtseqEpW( - protocol_seq.as_mut_ptr(), + PROTOCOL_SEQUENCE.as_ptr(), RPC_C_PROTSEQ_MAX_REQS_DEFAULT, - endpoint.as_mut_ptr(), + ENDPOINT.as_ptr(), ptr::null_mut(), ) }; diff --git a/vm/devices/hyperv_ic/Cargo.toml b/vm/devices/hyperv_ic/Cargo.toml index 63c89f84f90..aee0ba3789f 100644 --- a/vm/devices/hyperv_ic/Cargo.toml +++ b/vm/devices/hyperv_ic/Cargo.toml @@ -29,6 +29,7 @@ futures.workspace = true futures-concurrency.workspace = true thiserror.workspace = true tracing.workspace = true +widestring.workspace = true zerocopy.workspace = true [dev-dependencies] diff --git a/vm/devices/hyperv_ic/src/kvp.rs b/vm/devices/hyperv_ic/src/kvp.rs index 97996f39db3..08ae34dbdc9 100644 --- a/vm/devices/hyperv_ic/src/kvp.rs +++ b/vm/devices/hyperv_ic/src/kvp.rs @@ -44,6 +44,8 @@ use vmbus_channel::simple::SaveRestoreSimpleVmbusDevice; use vmbus_channel::simple::SimpleVmbusDevice; use vmbus_ring::RingMem; use vmcore::save_restore::NoSavedState; +use widestring::U16CStr; +use widestring::U16CString; use zerocopy::FromBytes; use zerocopy::FromZeros; use zerocopy::Immutable; @@ -735,20 +737,21 @@ fn parse_str(v: &[u16], n: u32) -> anyhow::Result { anyhow::bail!("invalid string length"); } let v = v.get(..n as usize / 2).context("string length too large")?; - if v.last() != Some(&0) { - anyhow::bail!("missing null terminator"); - } - String::from_utf16(&v[..v.len() - 1]).context("invalid utf-16") + U16CStr::from_slice(v) + .context("invalid null terminator")? + .to_string() + .context("invalid utf-16") } fn write_str(v: &mut [u16], s: &str) -> anyhow::Result { - let mut i = 0; - for (s, d) in s.encode_utf16().zip(&mut *v) { - *d = s; - i += 1; - } - *v.get_mut(i).context("string too long")? = 0; - Ok((i + 1) as u32 * 2) + // `U16CString::from_str` would accept a trailing NUL as the terminator. + anyhow::ensure!(!s.contains('\0'), "string contains a null character"); + let s = U16CString::from_str_truncate(s); + let s = s.as_slice_with_nul(); + v.get_mut(..s.len()) + .context("string too long")? + .copy_from_slice(s); + Ok(size_of_val(s) as u32) } fn write_value(buf: &mut [u8], v: &Value) -> anyhow::Result<(proto::ValueType, u32)> { diff --git a/vm/devices/hyperv_ic/src/kvp_tests.rs b/vm/devices/hyperv_ic/src/kvp_tests.rs index e2376804f3e..9fa5ed395ea 100644 --- a/vm/devices/hyperv_ic/src/kvp_tests.rs +++ b/vm/devices/hyperv_ic/src/kvp_tests.rs @@ -71,3 +71,28 @@ async fn stop_between_rejected_responses_keeps_kvp_negotiation(driver: DefaultDr stop_with_timeout(&mut task, &driver).await; } } + +#[test] +fn string_round_trip_fills_buffer_exactly() { + let mut buf = [0xffff; 4]; + // The surrogate pair and terminator exactly fill the buffer. + let n = write_str(&mut buf, "a\u{1f680}").unwrap(); + assert_eq!(n, 8); + assert_eq!(parse_str(&buf, n).unwrap(), "a\u{1f680}"); + assert!(write_str(&mut buf, "abcd").is_err()); +} + +#[test] +fn malformed_strings_are_rejected() { + let mut buf = [0; 8]; + for s in ["a\0b", "a\0", "\0"] { + assert!(write_str(&mut buf, s).is_err(), "{s:?}"); + } + + let guest = [b'a' as u16, 0, b'b' as u16, 0]; + assert_eq!(parse_str(&guest, 4).unwrap(), "a"); + // Interior null, odd length, too long, and missing terminator. + for n in [8, 3, 10, 2] { + assert!(parse_str(&guest, n).is_err(), "{n}"); + } +} diff --git a/vm/devices/net/netvsp/Cargo.toml b/vm/devices/net/netvsp/Cargo.toml index 4f7d7ecec42..c15ff8b2194 100644 --- a/vm/devices/net/netvsp/Cargo.toml +++ b/vm/devices/net/netvsp/Cargo.toml @@ -35,6 +35,7 @@ static_assertions.workspace = true thiserror.workspace = true tracelimit.workspace = true tracing.workspace = true +widestring.workspace = true zerocopy.workspace = true hvdef.workspace = true diff --git a/vm/devices/net/netvsp/src/lib.rs b/vm/devices/net/netvsp/src/lib.rs index ccfef2fdcf9..14f2d75e9d3 100644 --- a/vm/devices/net/netvsp/src/lib.rs +++ b/vm/devices/net/netvsp/src/lib.rs @@ -3618,9 +3618,9 @@ impl Adapter { } rndisprot::Oid::OID_GEN_MAXIMUM_SEND_PACKETS => writer.write(u32::MAX.as_bytes())?, rndisprot::Oid::OID_GEN_FRIENDLY_NAME => { - let name16: Vec = "Network Device".encode_utf16().collect(); + let name16 = widestring::u16str!("Network Device").as_slice(); let mut name = rndisprot::FriendlyName::new_zeroed(); - name.name[..name16.len()].copy_from_slice(&name16); + name.name[..name16.len()].copy_from_slice(name16); writer.write(name.as_bytes())? } rndisprot::Oid::OID_802_3_PERMANENT_ADDRESS diff --git a/vm/devices/storage/disk_vhdmp/Cargo.toml b/vm/devices/storage/disk_vhdmp/Cargo.toml index 47243f07e77..d1bde8a0df6 100644 --- a/vm/devices/storage/disk_vhdmp/Cargo.toml +++ b/vm/devices/storage/disk_vhdmp/Cargo.toml @@ -20,6 +20,7 @@ mesh.workspace = true futures.workspace = true blocking.workspace = true thiserror.workspace = true +widestring.workspace = true windows-sys = { workspace = true, features = ["Win32_Storage_Vhd", "Win32_System_IO"] } zerocopy.workspace = true diff --git a/vm/devices/storage/disk_vhdmp/src/lib.rs b/vm/devices/storage/disk_vhdmp/src/lib.rs index 1986b7219ab..4e65e2fa51d 100644 --- a/vm/devices/storage/disk_vhdmp/src/lib.rs +++ b/vm/devices/storage/disk_vhdmp/src/lib.rs @@ -25,6 +25,7 @@ use vm_resource::ResolveResource; use vm_resource::ResourceId; use vm_resource::declare_static_resolver; use vm_resource::kind::DiskHandleKind; +use widestring::U16CString; mod scsi; @@ -394,6 +395,11 @@ mod virtdisk { /// Handle for an open VHD file. pub struct Vhd(fs::File); +fn wide_path(path: &Path) -> std::io::Result { + U16CString::from_os_str(path) + .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e)) +} + fn chk_win32(err: u32) -> std::io::Result<()> { if err == 0 { Ok(()) @@ -444,8 +450,7 @@ impl OpenOptions { }, }, }; - let mut path16: Vec<_> = path.as_os_str().encode_wide().collect(); - path16.push(0); + let path16 = wide_path(path)?; let mut handle = std::ptr::null_mut(); // SAFETY: All structs are correctly initialized, the path has a null @@ -481,8 +486,7 @@ impl OpenOptions { impl Vhd { /// Create a new dynamic VHD pub fn create_dynamic(path: &Path, max_size_mb: u64, vhdx: bool) -> std::io::Result { - let mut path16: Vec<_> = path.as_os_str().encode_wide().collect(); - path16.push(0); + let path16 = wide_path(path)?; let mut storage_type = virtdisk::VIRTUAL_STORAGE_TYPE { DeviceId: if vhdx { @@ -539,11 +543,9 @@ impl Vhd { pub fn create_diff(path: &Path, parent_path: &Path) -> std::io::Result { let mut storage_type = virtdisk::VIRTUAL_STORAGE_TYPE::default(); - let mut path16: Vec<_> = path.as_os_str().encode_wide().collect(); - path16.push(0); + let path16 = wide_path(path)?; - let mut parent_path16: Vec<_> = parent_path.as_os_str().encode_wide().collect(); - parent_path16.push(0); + let parent_path16 = wide_path(parent_path)?; // Use a unique ID for each open to avoid virtual disk sharing // within VHDMP. In the future, consider taking this as a parameter diff --git a/vm/devices/storage/vhdx/Cargo.toml b/vm/devices/storage/vhdx/Cargo.toml index 656dc05b4a0..07a84664b5b 100644 --- a/vm/devices/storage/vhdx/Cargo.toml +++ b/vm/devices/storage/vhdx/Cargo.toml @@ -24,6 +24,7 @@ zerocopy.workspace = true test_with_tracing.workspace = true [target.'cfg(windows)'.dev-dependencies] +widestring.workspace = true windows = { workspace = true, features = [ "Win32_Storage_Vhd", "Win32_Foundation", diff --git a/vm/devices/storage/vhdx/src/locator.rs b/vm/devices/storage/vhdx/src/locator.rs index 006a286b7ae..f317d6330f1 100644 --- a/vm/devices/storage/vhdx/src/locator.rs +++ b/vm/devices/storage/vhdx/src/locator.rs @@ -70,20 +70,10 @@ fn decode_utf16le(data: &[u8], offset: usize, length: usize) -> Option { return None; } let slice = &data[offset..end]; - if has_embedded_null(slice) { - return None; - } - let u16s: Vec = slice - .chunks_exact(2) - .map(|c| u16::from_le_bytes([c[0], c[1]])) - .collect(); - String::from_utf16(&u16s).ok() -} - -/// Check that a UTF-16LE byte slice does not contain embedded null characters. -fn has_embedded_null(data: &[u8]) -> bool { - data.chunks_exact(2) - .any(|c| u16::from_le_bytes([c[0], c[1]]) == 0) + let units = slice.as_chunks().0.iter().map(|&c| u16::from_le_bytes(c)); + char::decode_utf16(units) + .map(|c| c.ok().filter(|&c| c != '\0')) + .collect() } impl ParentLocator { diff --git a/vm/devices/storage/vhdx/tests/native_cross_validation.rs b/vm/devices/storage/vhdx/tests/native_cross_validation.rs index f9dda203ced..885aa6e73cc 100644 --- a/vm/devices/storage/vhdx/tests/native_cross_validation.rs +++ b/vm/devices/storage/vhdx/tests/native_cross_validation.rs @@ -30,6 +30,7 @@ use vhdx::ReadRange; use vhdx::TrimMode; use vhdx::TrimRequest; use vhdx::WriteRange; +use widestring::U16CString; use windows::Win32::Foundation::CloseHandle; use windows::Win32::Foundation::HANDLE; @@ -169,18 +170,6 @@ const VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT: windows::core::GUID = windows::core data4: [0x90, 0x1F, 0x71, 0x41, 0x5A, 0x66, 0x34, 0x5B], }; -// --------------------------------------------------------------------- -// Path helper -// --------------------------------------------------------------------- - -fn to_wide(path: &Path) -> Vec { - use std::os::windows::ffi::OsStrExt; - path.as_os_str() - .encode_wide() - .chain(std::iter::once(0)) - .collect() -} - // --------------------------------------------------------------------- // NativeVhdx — RAII wrapper around Windows virtual disk APIs // --------------------------------------------------------------------- @@ -198,7 +187,7 @@ impl NativeVhdx { VendorId: VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT, }; - let wide = to_wide(path); + let wide = U16CString::from_os_str(path).unwrap(); let mut params = CREATE_VIRTUAL_DISK_PARAMETERS { Version: CREATE_VIRTUAL_DISK_VERSION_2, @@ -240,7 +229,7 @@ impl NativeVhdx { VendorId: VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT, }; - let wide = to_wide(path); + let wide = U16CString::from_os_str(path).unwrap(); let params = OPEN_VIRTUAL_DISK_PARAMETERS { Version: OPEN_VIRTUAL_DISK_VERSION_2, @@ -1137,8 +1126,8 @@ impl NativeVhdx { VendorId: VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT, }; - let wide = to_wide(path); - let parent_wide = to_wide(parent_path); + let wide = U16CString::from_os_str(path).unwrap(); + let parent_wide = U16CString::from_os_str(parent_path).unwrap(); let mut params = CREATE_VIRTUAL_DISK_PARAMETERS { Version: CREATE_VIRTUAL_DISK_VERSION_2, diff --git a/vm/devices/support/fs/lxutil/src/windows/mod.rs b/vm/devices/support/fs/lxutil/src/windows/mod.rs index 59dc86bf020..b38c5b5ed1a 100644 --- a/vm/devices/support/fs/lxutil/src/windows/mod.rs +++ b/vm/devices/support/fs/lxutil/src/windows/mod.rs @@ -244,7 +244,7 @@ impl LxVolume { assert!(path.is_relative()); // NTFS interprets ':' as a stream separator, which this API does not support. // Linux filename colons are escaped by PathExt/PathBufExt before opening. - if path.as_os_str().encode_wide().any(|c| c == b':' as u16) { + if path.as_os_str().as_encoded_bytes().contains(&b':') { return Err(lx::Error::EINVAL); } self.check_sandbox_enforcement(path)?; @@ -1537,6 +1537,9 @@ mod tests { use crate::LxCreateOptions; use crate::LxVolumeOptions; use test_with_tracing::test; + use widestring::U16CString; + use widestring::U16String; + use widestring::u16cstr; fn set_host_attributes(path: &Path, attributes: u32) { let file = std::fs::OpenOptions::new() @@ -1718,10 +1721,13 @@ mod tests { .unwrap(); // Version 3: package family, application ID, executable, and application type. let mut data = 3u32.to_le_bytes().to_vec(); - for field in ["test-package", "test-package!app", r"C:\unused.exe", "0"] { - for value in field.encode_utf16().chain([0]) { - data.extend_from_slice(&value.to_le_bytes()); - } + for field in [ + u16cstr!("test-package"), + u16cstr!("test-package!app"), + u16cstr!(r"C:\unused.exe"), + u16cstr!("0"), + ] { + data.extend_from_slice(field.as_slice_with_nul().as_bytes()); } let mut reparse = W32Ss::IO_REPARSE_TAG_APPEXECLINK.to_le_bytes().to_vec(); reparse.extend_from_slice(&u16::try_from(data.len()).unwrap().to_le_bytes()); @@ -2219,9 +2225,9 @@ mod tests { ) .open(link) .unwrap(); - let mut substitute = ffi::OsString::from(r"\??\"); - substitute.push(target); - let substitute: Vec = substitute.encode_wide().collect(); + let mut substitute = U16String::from_str(r"\??\"); + substitute.push_os_str(target); + let substitute = U16CString::from_ustr(substitute).unwrap(); let length = u16::try_from(substitute.len() * 2).unwrap(); // Mount-point data has four name fields, followed by two terminated names. let mut reparse = Vec::new(); @@ -2229,9 +2235,9 @@ mod tests { for value in [8 + length + 4, 0, 0, length, length + 2, 0] { reparse.extend_from_slice(&value.to_le_bytes()); } - for value in substitute.into_iter().chain([0, 0]) { - reparse.extend_from_slice(&value.to_le_bytes()); - } + reparse.extend_from_slice(substitute.as_slice_with_nul().as_bytes()); + // The print name is empty. + reparse.extend_from_slice(u16cstr!("").as_slice_with_nul().as_bytes()); util::set_reparse_point(&handle.into(), &reparse).unwrap(); }); } diff --git a/vm/devices/support/fs/lxutil/src/windows/readdir.rs b/vm/devices/support/fs/lxutil/src/windows/readdir.rs index 755f65223bd..f9cc7773fb5 100644 --- a/vm/devices/support/fs/lxutil/src/windows/readdir.rs +++ b/vm/devices/support/fs/lxutil/src/windows/readdir.rs @@ -10,11 +10,11 @@ use bitfield_struct::bitfield; use pal::windows::UnicodeString; use pal::windows::UnicodeStringRef; use std::ffi; -use std::os::windows::ffi::OsStringExt; use std::os::windows::io::AsRawHandle; use std::os::windows::io::FromRawHandle; use std::os::windows::io::OwnedHandle; use std::ptr; +use widestring::U16Str; use windows::Wdk::Storage::FileSystem; use windows::Wdk::Storage::FileSystem::FILE_INFORMATION_CLASS; use windows::Wdk::System::Threading; @@ -903,7 +903,8 @@ impl DirEntrySource for WindowsDirEntrySource<'_> { // Cache the policy decision from the enumeration snapshot, // without reopening or querying each child. let visible = if self.state.options.sandbox { - let name = ffi::OsString::from_wide(file_info.file_name.as_slice()); + let name = + U16Str::from_slice(file_info.file_name.as_slice()).to_os_string(); match self.state.check_sandbox_name(&name).and_then(|()| { self.state .check_sandbox_attributes(file_info.file_attributes) diff --git a/vm/devices/support/fs/lxutil/src/windows/symlink.rs b/vm/devices/support/fs/lxutil/src/windows/symlink.rs index 2ab3e46714e..7e2c43c3694 100644 --- a/vm/devices/support/fs/lxutil/src/windows/symlink.rs +++ b/vm/devices/support/fs/lxutil/src/windows/symlink.rs @@ -76,11 +76,9 @@ fn translate_absolute_target( if substitute_name.len() < 6 { return Err(lx::Error::EIO); } - let name = if substitute_name[substitute_name.len() - 1] == 0 { - &substitute_name[..substitute_name.len() - 1] - } else { - &substitute_name[..substitute_name.len()] - }; + let name = substitute_name + .strip_suffix(&[0]) + .unwrap_or(substitute_name); let name = match String::from_utf16(name) { Ok(name) => name, Err(_) => return Err(lx::Error::EIO), diff --git a/vm/devices/support/fs/lxutil/src/windows/util.rs b/vm/devices/support/fs/lxutil/src/windows/util.rs index 5facd3b55d8..332bfb8d966 100644 --- a/vm/devices/support/fs/lxutil/src/windows/util.rs +++ b/vm/devices/support/fs/lxutil/src/windows/util.rs @@ -27,6 +27,8 @@ use std::path::Path; use std::ptr; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; +use widestring::U16CString; +use widestring::U16String; use zerocopy::Immutable; use zerocopy::IntoBytes; use zerocopy::KnownLayout; @@ -440,9 +442,8 @@ pub fn get_attributes( // Determine if a name is a reserved legacy DOS device name pub fn is_dos_device_name(name: &ffi::OsStr) -> lx::Result { - let nameu = widestring::U16CString::from_os_str(name).map_err(|_| lx::Error::EINVAL)?; - if unsafe { FileSystem::RtlIsDosDeviceName_U(PCWSTR(nameu.as_slice_with_nul().as_ptr())) } == 0 - { + let nameu = U16CString::from_os_str(name).map_err(|_| lx::Error::EINVAL)?; + if unsafe { FileSystem::RtlIsDosDeviceName_U(PCWSTR(nameu.as_ptr())) } == 0 { Ok(false) } else { Ok(true) @@ -1095,7 +1096,7 @@ pub fn create_link( link_root: &OwnedHandle, new_path: &Path, ) -> lx::Result<()> { - let new_path: Vec = new_path.as_os_str().encode_wide().collect(); + let new_path = U16String::from_os_str(new_path); // This matches the public definition of FILE_LINK_INFORMATION in ntifs.h, with the variable length payload field // at the end removed. u8 arrays are used for fields to remove the need for padding and repr(packed). @@ -1126,6 +1127,7 @@ pub fn create_link( ); let file_name_length: u32 = new_path + .as_slice() .as_bytes() .len() .try_into() @@ -1181,14 +1183,13 @@ pub fn rename( target_path: &Path, flags: fs::RenameFlags, ) -> lx::Result<()> { - // If necessary, escape the path, then convert it into a Vec - let target_name: Vec = if flags.escape_name() { - path::path_from_lx(target_path.as_os_str().as_encoded_bytes())? - .as_os_str() - .encode_wide() - .collect() + // If necessary, escape the path before converting it to UTF-16. + let target_name = if flags.escape_name() { + U16String::from_os_str( + path::path_from_lx(target_path.as_os_str().as_encoded_bytes())?.as_os_str(), + ) } else { - target_path.as_os_str().encode_wide().collect() + U16String::from_os_str(target_path) }; // Create the union field of FILE_RENAME_INFORMATION--if POSIX semantics are enabled, @@ -1270,6 +1271,7 @@ pub fn rename( ); let file_name_length: u32 = target_name + .as_slice() .as_bytes() .len() .try_into() diff --git a/vm/loader/snp_bootshim/src/efi/tables.rs b/vm/loader/snp_bootshim/src/efi/tables.rs index 5d50a20da8a..ec5e3a339a4 100644 --- a/vm/loader/snp_bootshim/src/efi/tables.rs +++ b/vm/loader/snp_bootshim/src/efi/tables.rs @@ -379,8 +379,8 @@ mod tests { assert_eq!(st.configuration_table, address(&efi.configuration_tables)); assert_eq!(st.number_of_table_entries, 4); assert_eq!( - &efi.firmware_vendor[..8], - &"OpenVMM\0".encode_utf16().collect::>()[..] + efi.firmware_vendor.as_slice(), + "OpenVMM\0".encode_utf16().collect::>() ); assert_eq!(efi.loaded_image.load_options, 6 * MB); assert_eq!(efi.loaded_image.image_base, MB); diff --git a/vm/whp/Cargo.toml b/vm/whp/Cargo.toml index ee9b9c63b8a..2c406a265c2 100644 --- a/vm/whp/Cargo.toml +++ b/vm/whp/Cargo.toml @@ -9,6 +9,7 @@ rust-version.workspace = true [target.'cfg(windows)'.dependencies] guid.workspace = true pal.workspace = true +widestring.workspace = true windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_System_Power"] } [target.'cfg(windows)'.dev-dependencies] diff --git a/vm/whp/src/lib.rs b/vm/whp/src/lib.rs index 2662a514bc0..0747d1e7c0a 100644 --- a/vm/whp/src/lib.rs +++ b/vm/whp/src/lib.rs @@ -30,6 +30,7 @@ use std::os::windows::prelude::*; use std::ptr::NonNull; use std::ptr::null; use std::ptr::null_mut; +use widestring::U16CString; use windows_sys::Win32::Foundation::ERROR_BAD_PATHNAME; use windows_sys::Win32::Foundation::LUID; use windows_sys::Win32::System::Power::DEVICE_POWER_STATE; @@ -960,12 +961,13 @@ impl VpciResource { VirtualFunctionIndex: *index, Reserved: 0, }; - let mut path16: Vec<_> = path.encode_utf16().collect(); - path16.push(0); + let path16 = + U16CString::from_str(path).map_err(|_| WHvError::ERROR_BAD_PATHNAME)?; + let path16 = path16.as_slice_with_nul(); if path16.len() > sriov.PnpInstanceId.len() { return Err(WHvError::ERROR_BAD_PATHNAME); } - sriov.PnpInstanceId[..path16.len()].copy_from_slice(&path16); + sriov.PnpInstanceId[..path16.len()].copy_from_slice(path16); std::slice::from_raw_parts( std::ptr::from_ref(&sriov).cast(), size_of_val(&sriov), diff --git a/vmm_core/hyperv_dump/Cargo.toml b/vmm_core/hyperv_dump/Cargo.toml index 3b4b94764ef..d61e9993d29 100644 --- a/vmm_core/hyperv_dump/Cargo.toml +++ b/vmm_core/hyperv_dump/Cargo.toml @@ -17,6 +17,7 @@ zerocopy.workspace = true [dev-dependencies] pal.workspace = true tempfile.workspace = true +widestring.workspace = true [lints] workspace = true diff --git a/vmm_core/hyperv_dump/tests/cross_validate.rs b/vmm_core/hyperv_dump/tests/cross_validate.rs index 1c0635d647b..0178a0e7edc 100644 --- a/vmm_core/hyperv_dump/tests/cross_validate.rs +++ b/vmm_core/hyperv_dump/tests/cross_validate.rs @@ -21,6 +21,7 @@ use std::ffi::c_void; use std::io::Cursor; use std::path::PathBuf; use std::sync::OnceLock; +use widestring::U16CString; mod dll { use std::ffi::c_void; @@ -88,12 +89,7 @@ fn setup_dll_search_path_inner() -> bool { let dll_dir = version_dir.join(arch); let dll_path = dll_dir.join("vmsavedstatedumpprovider.dll"); if dll_path.exists() { - let wide_dir: Vec = dll_dir - .to_str() - .unwrap() - .encode_utf16() - .chain(std::iter::once(0)) - .collect(); + let wide_dir = U16CString::from_os_str(&dll_dir).unwrap(); // SAFETY: Calling SetDllDirectoryW with a valid null-terminated // wide string to add the SDK directory to the DLL search path. unsafe { @@ -207,12 +203,7 @@ fn load_and_verify(vmrs_data: &[u8], expected_vp_count: u32, _test_name: &str) { std::io::Write::write_all(&mut tmp, vmrs_data).unwrap(); let vmrs_path = tmp.path(); - let wide_path: Vec = vmrs_path - .to_str() - .unwrap() - .encode_utf16() - .chain(std::iter::once(0)) - .collect(); + let wide_path = U16CString::from_os_str(vmrs_path).unwrap(); // SAFETY: Calling VmSavedStateDumpProvider FFI functions with valid // pointers. The handle is obtained from LoadSavedStateFile and released @@ -353,12 +344,7 @@ fn dll_validates_large_memory() { // Verify the DLL can load the file. let vmrs_path = tmp.path(); - let wide_path: Vec = vmrs_path - .to_str() - .unwrap() - .encode_utf16() - .chain(std::iter::once(0)) - .collect(); + let wide_path = U16CString::from_os_str(vmrs_path).unwrap(); // SAFETY: Calling VmSavedStateDumpProvider FFI functions with valid // pointers. The handle is obtained from LoadSavedStateFile and released